feat(chat): delete a chat, disband a group, Seen — and purge what everyone deleted

Delete chat is the caller's alone: the history so far vanishes for them
(chat_members.cleared_id) and a direct chat leaves their list (hidden) until a
new message arrives; the others keep theirs. What EVERY member has deleted is
deleted for real (purge): messages up to the lowest cleared_id and their files
on disk, and a direct chat both people deleted, whole. Purge also runs when a
member leaves or is removed. A group's creator disbands it for everyone
(DELETE /api/chat/rooms/:id).

Seen: rooms carry every member's read mark (reads); a mark that moves is told
to the members (chat_read, exactAudience) and never passes the newest
message. Under your newest message: Seen / Seen by … / Seen by everyone.
A room open on a tab you come back to is marked read then.
This commit is contained in:
2026-11-03 09:54:55 +07:00
parent 0016b6a427
commit c797e9868e
17 changed files with 600 additions and 59 deletions
+83 -1
View File
@@ -4,7 +4,8 @@
* a direct chat is one per pair, a group's creator alone changes it, only a
* room's members read it — an admin included —, unread counts and read marks,
* files served only to members under a sandbox CSP, a message deleted only by
* its author, local mode refused, and
* its author, "delete chat" for the caller alone, a group disbanded only by its
* creator, local mode refused, and
* every chat frame reaches exactly the users in its `to` (scope.exactAudience).
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
@@ -168,6 +169,87 @@ describe("chat", () => {
assert.equal((await call(2, "DELETE", `/rooms/${group}/messages/${sys.id}`)).status, 403);
});
it("deletes a direct chat for the caller only, until a new message", async () => {
await call(3, "POST", `/rooms/${dm}/messages`, { body: "cũ" });
const c = await call(2, "POST", `/rooms/${dm}/clear`);
assert.deepEqual(c.body, { hidden: true, purged: false });
assert.ok(!(await call(2, "GET", "/rooms")).body.rooms.some((r) => r.id === dm));
assert.deepEqual((await call(2, "GET", `/rooms/${dm}/messages`)).body.messages, []);
// The other person keeps everything.
assert.ok((await call(3, "GET", `/rooms/${dm}/messages`)).body.messages.length >= 2);
await call(3, "POST", `/rooms/${dm}/messages`, { body: "mới" });
const back = (await call(2, "GET", "/rooms")).body.rooms.find((r) => r.id === dm);
assert.equal(back.unread, 1);
assert.deepEqual(
(await call(2, "GET", `/rooms/${dm}/messages`)).body.messages.map((m) => m.body),
["mới"]
);
});
it("hides a cleared message's files from the one who cleared it", async () => {
const fd = new FormData();
fd.append("files", new Blob(["x"], { type: "text/plain" }), "b.txt");
const m = (await call(3, "POST", `/rooms/${group}/messages`, fd)).body.message;
await call(2, "POST", `/rooms/${group}/clear`);
assert.equal((await call(2, "GET", `/rooms/${group}/files/${m.files[0].id}`)).status, 404);
assert.equal((await call(3, "GET", `/rooms/${group}/files/${m.files[0].id}`)).status, 200);
// A group stays in the list after its history is cleared.
assert.ok((await call(2, "GET", "/rooms")).body.rooms.some((r) => r.id === group));
});
it("lets only a group's creator disband it, for everyone", async () => {
const g = (await call(3, "POST", "/rooms", { kind: "group", name: "Tạm", userIds: [2] })).body
.room.id;
assert.equal((await call(2, "DELETE", `/rooms/${g}`)).status, 403);
assert.equal((await call(3, "DELETE", `/rooms/${g}`)).status, 200);
assert.equal((await call(2, "GET", `/rooms/${g}/messages`)).status, 404);
assert.equal((await call(3, "DELETE", `/rooms/${dm}`)).status, 400);
});
it("deletes for real what everyone deleted, and a direct chat both deleted whole", async () => {
const { db } = require("../db");
const fd = new FormData();
fd.append("body", "bí mật");
fd.append("files", new Blob(["y"], { type: "text/plain" }), "c.txt");
const room = (await call(4, "POST", "/rooms", { kind: "dm", userId: 3 })).body.room.id;
const m = (await call(4, "POST", `/rooms/${room}/messages`, fd)).body.message;
const onDisk = path.join(TMP, "chat", String(room), m.files[0].id);
assert.ok(fs.existsSync(onDisk));
await call(4, "POST", `/rooms/${room}/clear`);
// One side only: still stored for the other.
assert.ok(db.prepare("SELECT 1 FROM chat_messages WHERE id = ?").get(m.id));
assert.ok(fs.existsSync(onDisk));
const both = await call(3, "POST", `/rooms/${room}/clear`);
assert.equal(both.body.purged, true);
assert.equal(db.prepare("SELECT 1 FROM chat_messages WHERE id = ?").get(m.id), undefined);
assert.equal(db.prepare("SELECT 1 FROM chat_rooms WHERE id = ?").get(room), undefined);
assert.ok(!fs.existsSync(onDisk));
// Opening it again starts afresh.
const again = (await call(4, "POST", "/rooms", { kind: "dm", userId: 3 })).body.room;
assert.equal(again.lastMessage, null);
});
it("purges a group's history once every member cleared it", async () => {
const { db } = require("../db");
const g = (await call(2, "POST", "/rooms", { kind: "group", userIds: [3] })).body.room.id;
const m = (await call(2, "POST", `/rooms/${g}/messages`, { body: "x" })).body.message;
await call(2, "POST", `/rooms/${g}/clear`);
assert.ok(db.prepare("SELECT 1 FROM chat_messages WHERE id = ?").get(m.id));
await call(3, "POST", `/rooms/${g}/clear`);
assert.equal(db.prepare("SELECT 1 FROM chat_messages WHERE id = ?").get(m.id), undefined);
// The group itself stays.
assert.ok((await call(2, "GET", "/rooms")).body.rooms.some((r) => r.id === g));
});
it("tells every member's read mark (seen), never past the newest message", async () => {
const r = await call(3, "POST", `/rooms/${group}/read`, { upTo: 1e9 });
const room = (await call(2, "GET", "/rooms")).body.rooms.find((x) => x.id === group);
assert.equal(room.reads[3], r.body.lastReadId);
assert.equal(room.reads[3], room.lastMessage ? room.lastMessage.id : room.reads[3]);
assert.ok(r.body.lastReadId < 1e9);
assert.deepEqual([...scope.exactAudience("chat_read", { to: [2, 3] })], [2, 3]);
});
it("refuses an empty message", async () => {
assert.equal((await call(2, "POST", `/rooms/${dm}/messages`, { body: " " })).status, 400);
});
+9
View File
@@ -1952,6 +1952,15 @@ db.exec(`
);
CREATE INDEX IF NOT EXISTS idx_chat_files_message ON chat_files(message_id);
`);
// A member's own "delete this chat": messages up to cleared_id are gone for
// them (not for anyone else), and a hidden direct chat leaves their list until
// a new message arrives. Additive.
try {
db.prepare("SELECT cleared_id, hidden FROM chat_members LIMIT 1").get();
} catch {
db.prepare("ALTER TABLE chat_members ADD COLUMN cleared_id INTEGER NOT NULL DEFAULT 0").run();
db.prepare("ALTER TABLE chat_members ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0").run();
}
// An account's own agent instructions, put before every workspace's in each
// pane it owns (server/lib/lane-sources.js, issue #67). Additive.
+128 -22
View File
@@ -5,7 +5,17 @@
* per pair of users) or a group anyone may start and name. Only a room's
* MEMBERS read or write it — an admin or analyst included, and there is no
* route that lists another user's rooms. A group's creator adds, removes and
* renames; any member may leave; anyone deletes their own messages (only). A message is text (≤ 8000 chars) and up to
* renames; any member may leave; anyone deletes their own messages (only).
* "Delete chat" is the caller's alone: the messages so far vanish for THEM
* (`cleared_id`) and a direct chat leaves their list (`hidden`) until a new
* message arrives — the other members keep everything. Only a group's creator
* disbands it, for everyone, its files included. Once EVERY member has
* deleted a stretch of history, it is deleted for real (`purge`): the
* messages up to the lowest `cleared_id` and their files, and a direct chat
* both people deleted, whole. "Seen": each room carries every member's read
* mark (`reads`), and a read that moves is told to the members (`chat_read`) —
* a mark never passes the room's newest message, so it cannot claim to have
* seen one not yet written. A message is text (≤ 8000 chars) and up to
* `MAX_FILES` files of ≤ `MAX_FILE_BYTES` each, stored once under
* `<data dir>/chat/<room id>/<random id>` — a name the server makes, never one
* from the request — and served back only to the room's members (the route
@@ -112,16 +122,16 @@ function shapeMessages(rows) {
/** One room as `me` sees it: members, newest message, unread count. */
function shapeRoom(me, r) {
const mine = sql("SELECT last_read_id FROM chat_members WHERE room_id = ? AND user_id = ?").get(
r.id,
me
);
const last = sql("SELECT * FROM chat_messages WHERE room_id = ? ORDER BY id DESC LIMIT 1").get(
r.id
);
const mine = sql(
"SELECT last_read_id, cleared_id FROM chat_members WHERE room_id = ? AND user_id = ?"
).get(r.id, me);
const cleared = mine ? mine.cleared_id : 0;
const last = sql(
"SELECT * FROM chat_messages WHERE room_id = ? AND id > ? ORDER BY id DESC LIMIT 1"
).get(r.id, cleared);
const unread = sql(
"SELECT COUNT(*) AS n FROM chat_messages WHERE room_id = ? AND id > ? AND COALESCE(user_id, -1) != ?"
).get(r.id, mine ? mine.last_read_id : 0, me).n;
).get(r.id, Math.max(mine ? mine.last_read_id : 0, cleared), me).n;
return {
id: r.id,
kind: r.kind,
@@ -132,6 +142,12 @@ function shapeRoom(me, r) {
members: memberIds(r.id),
lastMessage: last ? shapeMessages([last])[0] : null,
lastReadId: mine ? mine.last_read_id : 0,
clearedId: cleared,
reads: Object.fromEntries(
sql("SELECT user_id, last_read_id FROM chat_members WHERE room_id = ?")
.all(r.id)
.map((x) => [x.user_id, x.last_read_id])
),
unread,
};
}
@@ -140,7 +156,8 @@ function shapeRoom(me, r) {
function listRooms(me) {
return sql(
`SELECT r.* FROM chat_rooms r JOIN chat_members m ON m.room_id = r.id
WHERE m.user_id = ? ORDER BY COALESCE(r.last_message_at, r.created_at) DESC`
WHERE m.user_id = ? AND m.hidden = 0
ORDER BY COALESCE(r.last_message_at, r.created_at) DESC`
)
.all(me)
.map((r) => shapeRoom(me, r));
@@ -167,7 +184,11 @@ function openDm(me, other) {
if (!them || them.id === me) throw err("ENOUSER", "pick another user");
const key = [me, them.id].sort((a, b) => a - b).join(":");
const found = sql("SELECT * FROM chat_rooms WHERE dm_key = ?").get(key);
if (found) return { room: shapeRoom(me, found), created: false };
if (found) {
// Opened again on purpose: back in the list (its cleared history stays gone).
sql("UPDATE chat_members SET hidden = 0 WHERE room_id = ? AND user_id = ?").run(found.id, me);
return { room: shapeRoom(me, found), created: false };
}
const id = db().transaction(() => {
const { lastInsertRowid } = sql(
"INSERT INTO chat_rooms (kind, dm_key, created_by) VALUES ('dm', ?, ?)"
@@ -237,6 +258,8 @@ function updateGroup(me, roomId, { name, add, remove }) {
if (adds.length) systemLine(room.id, me, `added:${adds.join(",")}`);
if (drops.length) systemLine(room.id, me, `removed:${drops.join(",")}`);
})();
// A removed member's mark no longer holds history back.
if (drops.length) purge(room.id);
return {
room: shapeRoom(me, sql("SELECT * FROM chat_rooms WHERE id = ?").get(room.id)),
notify: [...new Set([...before, ...adds])],
@@ -251,24 +274,29 @@ function leaveGroup(me, roomId) {
db().transaction(() => {
sql("DELETE FROM chat_members WHERE room_id = ? AND user_id = ?").run(room.id, me);
if (before.length > 1) systemLine(room.id, me, "left");
else sql("DELETE FROM chat_rooms WHERE id = ?").run(room.id);
})();
if (before.length <= 1) fs.rmSync(fileDir(room.id), { recursive: true, force: true });
purge(room.id);
return { notify: before };
}
/** A page of messages, oldest first: the newest `limit`, or those before `before`. */
function messages(me, roomId, { before, limit } = {}) {
const room = roomFor(me, roomId);
const cleared = sql("SELECT cleared_id FROM chat_members WHERE room_id = ? AND user_id = ?").get(
room.id,
me
).cleared_id;
const n = Math.min(Math.max(parseInt(limit, 10) || 50, 1), 200);
const b = parseInt(before, 10);
const rows = Number.isSafeInteger(b)
? sql("SELECT * FROM chat_messages WHERE room_id = ? AND id < ? ORDER BY id DESC LIMIT ?").all(
? sql(
"SELECT * FROM chat_messages WHERE room_id = ? AND id > ? AND id < ? ORDER BY id DESC LIMIT ?"
).all(room.id, cleared, b, n)
: sql("SELECT * FROM chat_messages WHERE room_id = ? AND id > ? ORDER BY id DESC LIMIT ?").all(
room.id,
b,
cleared,
n
)
: sql("SELECT * FROM chat_messages WHERE room_id = ? ORDER BY id DESC LIMIT ?").all(room.id, n);
);
return { messages: shapeMessages(rows.reverse()), hasMore: rows.length === n };
}
@@ -322,6 +350,8 @@ function post(me, roomId, { body, files = [] }) {
sql(
"UPDATE chat_rooms SET last_message_at = (SELECT created_at FROM chat_messages WHERE id = ?) WHERE id = ?"
).run(lastInsertRowid, room.id);
// A new message brings the chat back to everyone who deleted it.
sql("UPDATE chat_members SET hidden = 0 WHERE room_id = ? AND hidden = 1").run(room.id);
// Your own message is read.
sql("UPDATE chat_members SET last_read_id = ? WHERE room_id = ? AND user_id = ?").run(
lastInsertRowid,
@@ -343,10 +373,51 @@ function markRead(me, roomId, upTo) {
const room = roomFor(me, roomId);
const n = Number(upTo);
if (!Number.isSafeInteger(n) || n < 0) throw err("EBADFIELD", "upTo: a message id");
sql(
"UPDATE chat_members SET last_read_id = MAX(last_read_id, ?) WHERE room_id = ? AND user_id = ?"
).run(n, room.id, me);
return { lastReadId: Math.max(n, 0) };
const top = sql("SELECT COALESCE(MAX(id), 0) AS id FROM chat_messages WHERE room_id = ?").get(
room.id
).id;
const { changes } = sql(
"UPDATE chat_members SET last_read_id = ? WHERE room_id = ? AND user_id = ? AND last_read_id < ?"
).run(Math.min(n, top), room.id, me, Math.min(n, top));
const now = sql("SELECT last_read_id FROM chat_members WHERE room_id = ? AND user_id = ?").get(
room.id,
me
).last_read_id;
return { lastReadId: now, moved: changes > 0, notify: memberIds(room.id) };
}
/**
* Delete for real what every member has deleted for themselves: messages up
* to the lowest `cleared_id` and their files; a direct chat both people
* deleted (hidden, nothing left) goes whole. Answers whether the room is gone.
*/
function purge(roomId) {
const room = sql("SELECT * FROM chat_rooms WHERE id = ?").get(roomId);
if (!room) return true;
const low = sql(
"SELECT MIN(cleared_id) AS low, MIN(hidden) AS allHidden FROM chat_members WHERE room_id = ?"
).get(room.id);
if (low.low == null) {
// Nobody left.
sql("DELETE FROM chat_rooms WHERE id = ?").run(room.id);
fs.rmSync(fileDir(room.id), { recursive: true, force: true });
return true;
}
if (low.low > 0) {
const files = sql("SELECT id FROM chat_files WHERE room_id = ? AND message_id <= ?").all(
room.id,
low.low
);
sql("DELETE FROM chat_messages WHERE room_id = ? AND id <= ?").run(room.id, low.low);
for (const f of files) fs.rmSync(path.join(fileDir(room.id), f.id), { force: true });
}
const left = sql("SELECT COUNT(*) AS n FROM chat_messages WHERE room_id = ?").get(room.id).n;
if (room.kind === "dm" && low.allHidden === 1 && left === 0) {
sql("DELETE FROM chat_rooms WHERE id = ?").run(room.id);
fs.rmSync(fileDir(room.id), { recursive: true, force: true });
return true;
}
return false;
}
/**
@@ -374,12 +445,44 @@ function removeMessage(me, roomId, messageId) {
return { notify: memberIds(room.id) };
}
/**
* "Delete chat" for `me` only: every message so far is gone for them; a
* direct chat also leaves their list until a new message arrives. Nobody
* else's copy changes.
*/
function clearChat(me, roomId) {
const room = roomFor(me, roomId);
const top = sql("SELECT COALESCE(MAX(id), 0) AS id FROM chat_messages WHERE room_id = ?").get(
room.id
).id;
sql(
`UPDATE chat_members SET cleared_id = ?, last_read_id = MAX(last_read_id, ?), hidden = ?
WHERE room_id = ? AND user_id = ?`
).run(top, top, room.kind === "dm" ? 1 : 0, room.id, me);
const gone = purge(room.id);
return { hidden: room.kind === "dm", purged: gone };
}
/** The group's creator deletes it for everyone, files included. Answers who to tell. */
function disbandGroup(me, roomId) {
const room = roomFor(me, roomId);
if (room.kind !== "group") throw err("EBADFIELD", "only a group can be disbanded");
if (room.created_by !== me) throw err("EFORBIDDEN", "only the group's creator disbands it", 403);
const before = memberIds(room.id);
sql("DELETE FROM chat_rooms WHERE id = ?").run(room.id);
fs.rmSync(fileDir(room.id), { recursive: true, force: true });
return { notify: before };
}
/** A file of a room `me` is in: `{path, name, type, inline}`. */
function file(me, roomId, fileId) {
const room = roomFor(me, roomId);
if (typeof fileId !== "string" || !/^[0-9a-f]{32}$/.test(fileId))
throw err("ENOTFOUND", "no such file", 404);
const f = sql("SELECT * FROM chat_files WHERE id = ? AND room_id = ?").get(fileId, room.id);
const f = sql(
`SELECT f.* FROM chat_files f JOIN chat_members m ON m.room_id = f.room_id AND m.user_id = ?
WHERE f.id = ? AND f.room_id = ? AND f.message_id > m.cleared_id`
).get(me, fileId, room.id);
const p = f && path.join(fileDir(room.id), f.id);
if (!f || !fs.existsSync(p)) throw err("ENOTFOUND", "no such file", 404);
return { path: p, name: f.name, type: f.type, inline: INLINE_TYPES.has(f.type) };
@@ -397,7 +500,10 @@ module.exports = {
messages,
post,
markRead,
purge,
removeMessage,
clearChat,
disbandGroup,
file,
roomFor,
shapeRoom,
+1 -1
View File
@@ -347,7 +347,7 @@ function exactAudience(type, data) {
const d = data && typeof data === "object" ? data : {};
// Chat (server/lib/chat.js): only the room's members, whatever their role —
// an admin reads no one else's chat. No list = nobody.
if (type === "chat_message" || type === "chat_room" || type === "chat_deleted") {
if (["chat_message", "chat_room", "chat_deleted", "chat_read"].includes(type)) {
return new Set(Array.isArray(d.to) ? d.to : []);
}
if (type === "cc_config_changed" && d.ownerId != null) return new Set([d.ownerId]);
+50
View File
@@ -59,7 +59,16 @@ const schemas = {
members: { type: "array", items: { type: "integer" } },
lastMessage: { allOf: [{ $ref: "#/components/schemas/ChatMessage" }], nullable: true },
lastReadId: { type: "integer" },
clearedId: {
type: "integer",
description: "Messages up to this id were deleted by the caller for themselves.",
},
unread: { type: "integer", description: "Messages of others after `lastReadId`." },
reads: {
type: "object",
additionalProperties: { type: "integer" },
description: "Every member's read mark by user id — what the room shows as Seen.",
},
},
},
};
@@ -145,6 +154,20 @@ const paths = {
},
},
"/api/chat/rooms/{id}": {
delete: {
tags: ["Chat"],
summary: "Disband a group",
description:
"The group's creator only (`403 EFORBIDDEN`): deletes it for every member, its files included. Broadcasts `chat_room`.",
parameters: [idParam],
responses: {
200: {
description: "Disbanded",
...json({ type: "object", properties: { ok: { type: "boolean" } } }),
},
...fail([400, 403, 404]),
},
},
patch: {
tags: ["Chat"],
summary: "Rename a group, add or remove members",
@@ -164,6 +187,31 @@ const paths = {
responses: { 200: { description: "Updated", ...roomResp }, ...fail([400, 403, 404]) },
},
},
"/api/chat/rooms/{id}/clear": {
post: {
tags: ["Chat"],
summary: "Delete a chat for yourself",
description:
"Every message so far is gone for the caller only (`clearedId`); a direct chat also leaves their list until a new message arrives. Nobody else's copy changes — but what EVERY member has deleted is deleted for real (messages, files, and a direct chat both people deleted, whole).",
parameters: [idParam],
responses: {
200: {
description: "Cleared",
...json({
type: "object",
properties: {
hidden: { type: "boolean" },
purged: {
type: "boolean",
description: "Every member has now deleted it: the chat is gone from the server.",
},
},
}),
},
...fail([404]),
},
},
},
"/api/chat/rooms/{id}/leave": {
post: {
tags: ["Chat"],
@@ -262,6 +310,8 @@ const paths = {
post: {
tags: ["Chat"],
summary: "Mark a room read up to a message",
description:
"Never moves back, never past the room's newest message. A mark that moved is told to the members as `chat_read` (`{roomId, userId, lastReadId}`).",
parameters: [idParam],
requestBody: {
required: true,
+24 -1
View File
@@ -118,6 +118,24 @@ router.post(
})
);
// Delete the chat for the caller only (their history; a direct chat leaves their list).
router.post(
"/rooms/:id/clear",
sameOriginGuard,
handle((me, req, res) => res.json(chat.clearChat(me, req.params.id)))
);
// The group's creator deletes it for everyone.
router.delete(
"/rooms/:id",
sameOriginGuard,
handle((me, req, res) => {
const { notify } = chat.disbandGroup(me, req.params.id);
tell("chat_room", { roomId: Number(req.params.id) }, notify);
res.json({ ok: true });
})
);
router.get(
"/rooms/:id/messages",
handle((me, req, res) =>
@@ -153,7 +171,12 @@ router.delete(
router.post(
"/rooms/:id/read",
sameOriginGuard,
handle((me, req, res) => res.json(chat.markRead(me, req.params.id, req.body?.upTo)))
handle((me, req, res) => {
const { lastReadId, moved, notify } = chat.markRead(me, req.params.id, req.body?.upTo);
// "Seen": the other members' views move their read marks.
if (moved) tell("chat_read", { roomId: Number(req.params.id), userId: me, lastReadId }, notify);
res.json({ lastReadId });
})
);
router.get(