Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Rooms: close a finished thread, a new reply reopens it, and bots close their own (#7574)

Milind Soniddf0295696b1
diff --git a/DESIGN.md b/DESIGN.md
index 1dcdc6cc28..92592f2fad 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -204,7 +204,10 @@ element's job and never a pixel value:
the sidebar thread row's menu behind a quiet More (hover, focus and touch),
a pin mark when pinned, and its unread or waiting dot; the thread beside the
feed has the same menu in its header, with its export. Archived threads come
- back under "Show archived threads" at the top of the feed. The header is plain
+ back under "Show archived threads" at the top of the feed. A closed thread (its
+ work done; Close in the menu, or its bot closes it) folds with its closed
+ neighbours into one quiet "4 closed threads" row that opens in place, ten at a
+ time; one with news stays a row, and a new line opens it again. The header is plain
words, so the feed is masked under it. Below 768px the room is today's single
transcript.
- **The sidebar stays open beside a side panel** while the chat keeps 440px:
diff --git a/packages/phone-protocol/src/room-threads.ts b/packages/phone-protocol/src/room-threads.ts
index 011825b1f0..491f10af8d 100644
--- a/packages/phone-protocol/src/room-threads.ts
+++ b/packages/phone-protocol/src/room-threads.ts
@@ -2,6 +2,14 @@
* server's own profile person). */
export type RoomThreadSpeaker = { botId: string } | { person: { id?: string; name?: string } };
+/** Who closed a room thread: a person who can post in the room (`id`: their person key, "owner" for the server's own
+ * profile person) or one of its bots (`id`: the bot's id). */
+export interface RoomThreadCloser {
+ kind: "person" | "bot";
+ id: string;
+ name: string;
+}
+
/** One of a room's threads as its feed shows it. `first` is the thread's first conversation line, its text clamped to
* ROOM_THREAD_FIRST_CHARS (`clipped` when cut); null while the thread has no line yet. `replies` counts the conversation
* lines after it, on every branch of the thread; `repliers` are the latest distinct speakers of those, newest first, at
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index b7d7a46ebc..ac5a800392 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -34,7 +34,7 @@ import type { WebhookAttempt, WebhookTrigger } from "./webhooks.ts";
import type { PublishedPageCard } from "./published-page.ts";
import type { InboxItem, InboxTask } from "./inbox.ts";
import type { LiveCallRecord, LiveCallState } from "./live-call-wire.ts";
-import type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";
+import type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts"; import type { RoomThreadCloser } from "./room-threads.ts";
import type { CompanionEndpointsSnapshot } from "./responses.ts";
/** What a team bot's main chat is called, beside each person's own chats. */
export const SHARED_CHAT_TITLE = "Shared chat";
@@ -820,7 +820,7 @@ export interface GroupTask {
* the global group turn limit. Direct chats do not use this limit. */
turnTimeoutMinutes?: number;
/** Epoch ms when the person archived this thread; absent while it is in the list. */ archivedAt?: number;
- /** A card in this thread waits on the person, with no turn running. */ activity?: "waiting-on-you";
+ /** A card in this thread waits on the person, with no turn running. */ activity?: "waiting-on-you"; /** Epoch ms when someone marked its work finished, with who did; both absent while it is open, and any new person's line or bot reply opens it again. Nothing is hidden from bots or search. */ closedAt?: number; closedBy?: RoomThreadCloser;
/** Epoch ms of the newest message, or createdAt when the thread has none. */
updatedAt?: number;
lastThreadOrderAt?: number;
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index 1b51542309..86596ee973 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -170,6 +170,7 @@ export const VITEST_SUBSETS = {
"server/cloud-send-arrived.test.ts",
"server/cloud-team-bot-access.e2e.test.ts",
"server/room-thread-summaries.e2e.test.ts",
+ "server/room-thread-close.e2e.test.ts",
"server/cloud-team-one-answer.e2e.test.ts",
"server/cloud-team-preference.e2e.test.ts",
"server/cloud-team-rules.e2e.test.ts",
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index dff85ce9c6..b37403d52a 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -310,6 +310,7 @@ describe("CI outputs", () => {
"server/cloud-send-arrived.test.ts",
"server/cloud-team-bot-access.e2e.test.ts",
"server/room-thread-summaries.e2e.test.ts",
+ "server/room-thread-close.e2e.test.ts",
"server/cloud-team-one-answer.e2e.test.ts",
"server/cloud-team-preference.e2e.test.ts",
"server/cloud-team-rules.e2e.test.ts",
diff --git a/scripts/testing/room-feed-ui.e2e.test.ts b/scripts/testing/room-feed-ui.e2e.test.ts
index 631f2181b2..a3628c487c 100644
--- a/scripts/testing/room-feed-ui.e2e.test.ts
+++ b/scripts/testing/room-feed-ui.e2e.test.ts
@@ -4,6 +4,8 @@
// room's current thread stays where it was. A row's menu pins, archives and deletes its thread, archived ones come back
// under Show archived threads, and the panel beside the feed renames and deletes the thread it holds. Below 768px the
// room is its single transcript.
+// Closed threads fold into one quiet row that opens ten at a time, the panel says who closed its thread and reopens it,
+// a new line opens a closed thread, and the sidebar marks a closed thread and offers Reopen.
// Needs the pinned agent-browser binary: runs when one resolves (tools directory, OMB_AGENT_BROWSER_PATH or PATH) or
// OMB_UI_E2E=1 asks for the verified download; otherwise skipped.
import { spawn } from "node:child_process";
@@ -237,3 +239,100 @@ async function until<T>(probe: () => Promise<T> | T, what: string, timeoutMs = 3
expect(existsSync(info.dataDir)).toBe(false);
}
}, LAUNCH_TIMEOUT_MS + 240_000);
+
+(enabled ? it : it.skip)("folds a room's closed threads, says who closed one beside the feed, and opens it again", async () => {
+ const { child, info } = await launch();
+ try {
+ const api = fixtureApi(info.url, { headers: { origin: info.url } });
+ const ui = (verb: string, ...args: string[]) => runControlOmb(["ui", verb, "--ui", info.ui, ...args]) as Promise<Record<string, any>>;
+ const evaluate = async (js: string) => (await ui("eval", "--js", js)).result;
+ const browser = JSON.parse(readFileSync(info.ui, "utf8")) as UiHandle;
+ const browse = (...args: string[]) => agentBrowser(browser.binary, sessionEnv(browser), args);
+ const shot = async (name: string) => {
+ for (const skin of ["midnight", "daylight"]) {
+ await evaluate(`import('/src/lib/skins.ts').then(({ applySkin }) => { applySkin(${JSON.stringify(skin)}); return true; })`);
+ await new Promise((done) => setTimeout(done, 400));
+ await ui("screenshot", "--out", join(evidenceDir, `${name}-${skin}.png`));
+ }
+ await evaluate("import('/src/lib/skins.ts').then(({ applySkin }) => { applySkin('midnight'); return true; })");
+ };
+ await browse("set", "viewport", "1440", "900");
+ const idle = () => until(async () => ((await api("GET", "/api/bots")).bots as Array<{ busy?: boolean }>).every((bot) => !bot.busy), "the bots to settle");
+
+ const room = (await api("POST", "/api/groups", {
+ memberIds: [info.botId], name: "Docs room", setup: { bulletin: "", defaultResponder: { kind: "member", botId: info.botId } },
+ })).group;
+ const lines = ["Outline the API guide", "Fix the README typo", "Rename the config page", "Update the changelog", "Plan the docs sprint"];
+ const threads: string[] = [];
+ for (const [index, text] of lines.entries()) {
+ const threadId = index === 0 ? room.threadId : (await api("POST", `/api/groups/${room.id}/tasks`, { activate: false })).task.threadId;
+ threads.push(threadId);
+ await api("POST", `/api/groups/${room.id}/messages`, { text, threadId });
+ await idle();
+ await api("POST", `/api/groups/${room.id}/read`, { threadId });
+ }
+ const tasks = async () => ((await api("GET", "/api/bots")).groups as Array<{ id: string; tasks: Array<{ threadId: string; closedAt?: number; closedBy?: { kind: string; name: string } }> }>)
+ .find((group) => group.id === room.id)!.tasks;
+ const row = (threadId: string) => `[data-feed-thread="${threadId}"]`;
+ const menuItem = (label: string) => `[...[...document.querySelectorAll('[data-thread-overlay]')].at(-1)?.querySelectorAll('button') ?? []].find((button) => button.textContent === ${JSON.stringify(label)})`;
+
+ await evaluate(`document.querySelector('[data-sidebar-group-row="${room.id}"]').click(); true`);
+ await until(() => evaluate("document.querySelectorAll('[data-feed-thread]').length === 5"), "the feed to list the room's five threads");
+ await shot("close-before");
+
+ await evaluate(`document.querySelector('${row(threads[1]!)} button[aria-expanded]').click(); true`);
+ await until(() => evaluate(`Boolean(${menuItem("Close")})`), "Close in the row's menu");
+ await evaluate(`${menuItem("Close")}.click(); true`);
+ await until(async () => (await tasks()).find((task) => task.threadId === threads[1])?.closedBy?.kind === "person", "the thread to be closed by the person");
+ for (const threadId of threads.slice(2, 4)) await api("PATCH", `/api/groups/${room.id}/tasks/${threadId}`, { closed: true });
+ await until(() => evaluate("document.querySelectorAll('[data-feed-thread]').length === 2"), "the closed threads to fold");
+ expect(await evaluate("[...document.querySelectorAll('[data-feed-fold]')].map((fold) => fold.textContent)")).toEqual(["3 closed threads"]);
+ await shot("close-folded");
+
+ await evaluate("document.querySelector('[data-feed-fold]').click(); true");
+ await until(() => evaluate("document.querySelectorAll('[data-feed-thread]').length === 5 && !document.querySelector('[data-feed-fold]')"), "the fold to open in place");
+ expect(await evaluate("[...document.querySelectorAll('[data-feed-thread]')].map((item) => Boolean(item.querySelector('[data-feed-closed]')))")).toEqual([false, true, true, true, false]);
+ await shot("close-unfolded");
+
+ await evaluate(`document.querySelector('${row(threads[2]!)} > button:first-child').click(); true`);
+ await until(() => evaluate(`document.querySelector('[data-thread-panel]')?.getAttribute('data-thread-panel') === ${JSON.stringify(threads[2])}`), "the closed thread beside the feed");
+ await until(() => evaluate("document.querySelector('[data-thread-closed]')?.textContent.startsWith('Closed by ')"), "who closed it, in the panel");
+ expect(await evaluate("document.querySelectorAll('[data-feed-thread]').length === 5 && !document.querySelector('[data-feed-fold]')")).toBe(true);
+ await shot("close-panel");
+ await browse("set", "viewport", "900", "900");
+ await new Promise((done) => setTimeout(done, 400));
+ await ui("screenshot", "--out", join(evidenceDir, "close-panel-narrow-midnight.png"));
+ await browse("set", "viewport", "1440", "900");
+ await evaluate("document.querySelector('[data-thread-reopen]').click(); true");
+ await until(async () => (await tasks()).find((task) => task.threadId === threads[2])?.closedAt === undefined, "Reopen to open the thread");
+ await until(() => evaluate("!document.querySelector('[data-thread-closed]') && !document.querySelector('[data-thread-reopen]')"), "the panel to drop its closed line");
+ await browse("click", "[data-thread-panel] header button[aria-expanded]");
+ await until(() => evaluate(`Boolean(${menuItem("Close")})`), "Close in the panel's menu");
+ await evaluate(`${menuItem("Close")}.click(); true`);
+ await until(() => evaluate("Boolean(document.querySelector('[data-thread-reopen]'))"), "the panel to show its thread closed again");
+ await evaluate("document.querySelector('[data-thread-panel] header button[aria-label=\"Close thread\"]').click(); true");
+
+ await api("POST", `/api/groups/${room.id}/messages`, { text: "One more README fix", threadId: threads[1] });
+ await until(async () => (await tasks()).find((task) => task.threadId === threads[1])?.closedAt === undefined, "a new line to open the thread");
+ await idle();
+ await until(() => evaluate(`Boolean(document.querySelector('${row(threads[1]!)}')) && !document.querySelector('${row(threads[1]!)} [data-feed-closed]')`), "the reopened thread as an ordinary row");
+
+ await browse("set", "viewport", "700", "900");
+ await until(() => evaluate("!document.querySelector('[data-room-feed]')"), "the room's transcript below 768px");
+ await evaluate(`document.querySelector('button[aria-label="Open bot list"]').click(); true`);
+ await until(() => evaluate(`Boolean(document.querySelector('[aria-label="Expand Docs room threads"], [aria-label="Collapse Docs room threads"]'))`), "the room in the bot list");
+ await evaluate(`document.querySelector('[aria-label="Expand Docs room threads"]')?.click(); true`);
+ await until(() => evaluate(`Boolean(document.querySelector('[data-sidebar-thread-row="${threads[3]}"]'))`), "the room's threads in the sidebar");
+ expect(await evaluate(`document.querySelector('[data-sidebar-thread-row="${threads[3]}"]').textContent`)).toContain("closed by");
+ await evaluate(`document.querySelector('[data-sidebar-thread-row="${threads[3]}"]').parentElement.querySelector('button[aria-expanded]').click(); true`);
+ await until(() => evaluate(`Boolean(${menuItem("Reopen")})`), "Reopen in the sidebar row's menu");
+ await shot("close-sidebar");
+ await evaluate(`${menuItem("Reopen")}.click(); true`);
+ await until(async () => (await tasks()).find((task) => task.threadId === threads[3])?.closedAt === undefined, "the sidebar's Reopen to open the thread");
+ const logs = await ui("console");
+ expect((logs.messages as Array<{ type: string; text: string }>).filter((message) => message.type === "error")).toEqual([]);
+ } finally {
+ await waitForExit(child, { signal: "SIGINT", graceMs: 30_000 });
+ expect(existsSync(info.dataDir)).toBe(false);
+ }
+}, LAUNCH_TIMEOUT_MS + 240_000);
diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.ts
index 96498ab92f..1a534cb286 100644
--- a/server/drivers/agents-call.ts
+++ b/server/drivers/agents-call.ts
@@ -433,8 +433,7 @@ export async function callTool(called: string, input: Json, context: ToolCallCon
}
if (name === LIST_THREADS_TOOL) return callListThreadsTool(args, context);
if (name === "close_thread") {
- const threadId = String(args.thread_id ?? "").trim();
- if (!threadId) return { text: "close_thread needs the thread_id from list_threads or start_thread.", isError: true };
+ const threadId = String(args.thread_id ?? "").trim() || THREAD_ID;
const r = await api(`/api/internal/threads/${encodeURIComponent(threadId)}/close`, { method: "POST", body: JSON.stringify({ fromBotId: BOT_ID, fromThreadId: THREAD_ID }) });
if (r.error) return { text: `Couldn't close that thread: ${String(r.error)}`, isError: true };
return { text: closedThreadText(r) };
diff --git a/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json b/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json
index 94a9acf279..103e71295e 100644
--- a/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json
+++ b/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json
@@ -190,10 +190,7 @@
"thread_id": {
"type": "string"
}
- },
- "required": [
- "thread_id"
- ]
+ }
}
},
{
diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.json
index d3dcbd62b3..0b88729132 100644
--- a/server/drivers/agents-catalog-goldens/full.tools-list.json
+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json
@@ -333,7 +333,7 @@
},
{
"name": "close_thread",
- "description": "Mark a thread you opened (or one of your own) as finished once you have read its result: it leaves the person's default sidebar list (still under all threads, with a note saying you closed it) and list_threads reports it as closed. Nothing is deleted — deleting stays the person's decision — and a thread that is still running cannot be closed; wait for it or leave it. Use the thread id from list_threads or from the start_thread result. If a close is refused, do not retry it.",
+ "description": "Mark a thread you opened (or one of your own) as finished once you have read its result: it leaves the person's default sidebar list (still under all threads, with a note saying you closed it) and list_threads reports it as closed. Nothing is deleted — deleting stays the person's decision — and a thread that is still running cannot be closed; wait for it or leave it. In a room thread, leave thread_id out to close the one you are in once your reply ends. If a close is refused, do not retry it.",
"inputSchema": {
"type": "object",
"additionalProperties": false,
@@ -342,10 +342,7 @@
"type": "string",
"description": "The thread id from list_threads or start_thread."
}
- },
- "required": [
- "thread_id"
- ]
+ }
}
},
{
diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.json
index bb3d0e69ea..c787c1efcc 100644
--- a/server/drivers/agents-catalog-goldens/profiles.json
+++ b/server/drivers/agents-catalog-goldens/profiles.json
@@ -1,7 +1,7 @@
{
"default": {
- "bytes": 62352,
- "sha256": "e70ca880b452f13f54840fb198d3eeacb3b859a43e1ebbdb3fcaf3c01b59c9cd",
+ "bytes": 62346,
+ "sha256": "f587cc8e42fee7cf8ca8eac3bf57a2ea21db8813a03b4d75c24b1ec31cd73418",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -62,8 +62,8 @@
]
},
"voice": {
- "bytes": 63133,
- "sha256": "ac4522edb7fa5e46303a652d30d6b95f58372561cf5b38aa59541e5828946809",
+ "bytes": 63127,
+ "sha256": "37c6c671c1ac22727d41761502d48c640949a25d277b0334b68bf38ca1071b8b",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -125,8 +125,8 @@
]
},
"shared": {
- "bytes": 64617,
- "sha256": "b4f03deebe942a2985fb1ab663754baa8e7976600f36014eabc617b06f1c63d1",
+ "bytes": 64611,
+ "sha256": "9660d3ef6fe8eec91e55ca14f4440336589e4a88c755257e581fe51ffa44c436",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -189,8 +189,8 @@
]
},
"shared+voice": {
- "bytes": 65398,
- "sha256": "502f845932f8c53eb463dda18f4e2c97bbf27f9adca406ae6176b96dd7719185",
+ "bytes": 65392,
+ "sha256": "2d49ee3afe824ffa608556e2573072bb6f692578bc9e94f7bdf76451d20926e2",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -254,8 +254,8 @@
]
},
"skills": {
- "bytes": 64775,
- "sha256": "c666a2ed0f1bfc16671737ec6508f7e85eb2006270af65b0fd0bbef5cf350bc7",
+ "bytes": 64769,
+ "sha256": "446d7a15d2d699a47f9ebb2e4fb110bfa8bb417a834083ec633af2419a989bd2",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -318,8 +318,8 @@
]
},
"skills+voice": {
- "bytes": 65556,
- "sha256": "fa2af521b9a5555093f6fd2eaf99e493f8ca2c841c67c44a505667ce9d30e7cf",
+ "bytes": 65550,
+ "sha256": "c2d1beb39ee74d7994099df2779de44a90b6806eb54dd2e2f6039ac6557e963d",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -383,8 +383,8 @@
]
},
"skills+shared": {
- "bytes": 67040,
- "sha256": "a83dcd8f817eb59e6cb45808dcb34c7444a1be1bdb26442427a3f54177670615",
+ "bytes": 67034,
+ "sha256": "65e0917b3a6e01f8cc44380fefcdc3a3ee3bca706471a8d8fc111b6890778e8b",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -449,8 +449,8 @@
]
},
"skills+shared+voice": {
- "bytes": 67821,
- "sha256": "70db0bd3fb867ccf62742779deeaf28e517e4efdffec886229e43c33d3ca4d65",
+ "bytes": 67815,
+ "sha256": "3bc3bce0be04b7e33f4e2ede456c1c401faa9cd16a773fc998da01889b476f3a",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -516,8 +516,8 @@
]
},
"non-chief": {
- "bytes": 53804,
- "sha256": "a110431ebee64f43e4bf6c9b784b854bbc6e7365826cc905637081a06d89112d",
+ "bytes": 53798,
+ "sha256": "1f33aa35bf44cddada3f0c10d2fe3a47cf498628653f03f8e7a80e4cdbd93bf8",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -571,8 +571,8 @@
]
},
"voice+non-chief": {
- "bytes": 54585,
- "sha256": "e24a68ca8244db758f64075cfe0929cff5478b7f34fa57d18bd2659eee6b7fad",
+ "bytes": 54579,
+ "sha256": "8b481b6d8952fa1e2fd98f6e7e2dd046d1e1ec183ae76e298cc3e474507f58ee",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -627,8 +627,8 @@
]
},
"shared+non-chief": {
- "bytes": 56069,
- "sha256": "4841983f2bfcb9add15b41d0ffff986c2cae524e478f3055b4ae229ffd0c469e",
+ "bytes": 56063,
+ "sha256": "d4a5fe74ce5e9fcf45c81a819b8f21042e91958073a9a7ee4724473694e32b65",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -684,8 +684,8 @@
]
},
"shared+voice+non-chief": {
- "bytes": 56850,
- "sha256": "9e4720865dc027fabb0441c7923cc3bcb34e2400e65d5c94a088e440ff4065cc",
+ "bytes": 56844,
+ "sha256": "3856165ebbf4cf2c31dc4b3477a1a4ad33b9438cfd7de65d0a1e973b035e3969",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -742,8 +742,8 @@
]
},
"skills+non-chief": {
- "bytes": 56227,
- "sha256": "db17883d5e2cf975180b369e9601061a2597e9c0b0cbf5d4321720fec30f0c24",
+ "bytes": 56221,
+ "sha256": "50ba0a87d44d82b0d71bd2f59cae4d79c459d3958d3ca76dd069cad4ffeff10f",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -799,8 +799,8 @@
]
},
"skills+voice+non-chief": {
- "bytes": 57008,
- "sha256": "33fa6d0a500462a2f6409e57a05f74fa4f21850ba6daba08783e029b7d5acab6",
+ "bytes": 57002,
+ "sha256": "fc0c127017084d14dfb07914d6e636147302cbdd7e0f4a18e26a60068f35ba9e",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -857,8 +857,8 @@
]
},
"skills+shared+non-chief": {
- "bytes": 58492,
- "sha256": "193a55498bec0c04f68d0f27c0a4ee4d4bbd0ef74b29b8e4956f4426941c58c5",
+ "bytes": 58486,
+ "sha256": "c39f9284726d177e1d6ca54807ea46de62a973d443cb5ed9f217e78a5493b9e2",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -916,8 +916,8 @@
]
},
"skills+shared+voice+non-chief": {
- "bytes": 59273,
- "sha256": "947b428fc5a5a8de59825b157450bd8dd06fc6683afee7fc43cb223203a0808f",
+ "bytes": 59267,
+ "sha256": "ed8e9754c6cf28d53f74f93bf53ee9666e3d8f4ecff0090d894f5df65039dc8c",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -976,8 +976,8 @@
]
},
"skills+shared+voice+cloud-home": {
- "bytes": 67577,
- "sha256": "9f63cf723c45613831b43cdcb6471e6274e8d81005818701baf5df87d131c987",
+ "bytes": 67571,
+ "sha256": "d94d9f46665234441a767410c4d77b89375a1542c18e37dccdbe9c0bd8f28202",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1043,8 +1043,8 @@
]
},
"skills+shared+voice+non-chief+cloud-home": {
- "bytes": 59029,
- "sha256": "f04b18b3bad8455491ded5f43b4e08c0e8d9aafe900f592463b66e5e63ea2d7e",
+ "bytes": 59023,
+ "sha256": "8857776ccde5544345fb0aea1dd413a68d7a7ad13d1c5f867c39908facddb8d2",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1103,8 +1103,8 @@
]
},
"skills+shared+voice+x": {
- "bytes": 71660,
- "sha256": "816cdc894d9debc610810cfef94df06e88560158159abdbff36cb920409acf99",
+ "bytes": 71654,
+ "sha256": "6e7f1445dce141cd07ebd4fad7b326740bbe98c1ca9e74bd06cf477113ea3f01",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1174,8 +1174,8 @@
]
},
"skills+shared+voice+x+team": {
- "bytes": 71660,
- "sha256": "816cdc894d9debc610810cfef94df06e88560158159abdbff36cb920409acf99",
+ "bytes": 71654,
+ "sha256": "6e7f1445dce141cd07ebd4fad7b326740bbe98c1ca9e74bd06cf477113ea3f01",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1245,8 +1245,8 @@
]
},
"skills+shared+voice+x+team+images": {
- "bytes": 73607,
- "sha256": "f4ffffbe49793bcf1be23c25325135379c56b770c3e8eef8e720e4af25c4ad11",
+ "bytes": 73601,
+ "sha256": "890062311ea64e1069ff04c83138da75cafabbc4562400bb115da7dfab17e8be",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1318,8 +1318,8 @@
]
},
"default+legacy-switches": {
- "bytes": 62352,
- "sha256": "e70ca880b452f13f54840fb198d3eeacb3b859a43e1ebbdb3fcaf3c01b59c9cd",
+ "bytes": 62346,
+ "sha256": "f587cc8e42fee7cf8ca8eac3bf57a2ea21db8813a03b4d75c24b1ec31cd73418",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1380,8 +1380,8 @@
]
},
"default+mausbot": {
- "bytes": 63003,
- "sha256": "a42427984d1ddcc94b0de416b1d562cdfd69580ad26e5640589c88fa52443629",
+ "bytes": 62997,
+ "sha256": "020c74aea114451ea67e44eea7edf32a17af43e66ad7466fc440b996d5386198",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1444,8 +1444,8 @@
]
},
"skills+shared+voice+mausbot": {
- "bytes": 68472,
- "sha256": "f01b237dae2749b15cffbb91e747f7c427beb2c0b287614ef5b06242d6100a62",
+ "bytes": 68466,
+ "sha256": "ed0a6eded832772e9ba14af01d83d70d83ef728159f9eb3bcf34fa18c1f5a5e6",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1513,8 +1513,8 @@
]
},
"default+no-computer-pick": {
- "bytes": 61140,
- "sha256": "797ecb9bc37085345e9cce95de62a8e98dca000c07724bb19a9ca6023d64b959",
+ "bytes": 61134,
+ "sha256": "10b34b77b4b1066dd4fef750a226a557bfb84d602adfd22cda2681b1e891c3f6",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1574,8 +1574,8 @@
]
},
"default+room": {
- "bytes": 57278,
- "sha256": "d3f1c89a65cb4724160561aa9b59e0c89758c92fff0b2656442f2d8ec24859a6",
+ "bytes": 57272,
+ "sha256": "cf5f5e0507878ab7ef5bc72ea41013f0b6cb628714c6b8abc6083284a3cdd15e",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1628,8 +1628,8 @@
]
},
"non-chief+room": {
- "bytes": 48730,
- "sha256": "48384b845f7ba0c6bc4e760f11698e1a7123dd98ff4408dc78d265883769f993",
+ "bytes": 48724,
+ "sha256": "81350def78ee9e48aefd0b404b846036521d5c2697816a9e8ba70c1247697a1c",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1675,8 +1675,8 @@
]
},
"default+images": {
- "bytes": 64299,
- "sha256": "c1444a66887273fc58bff094664b81058aace735f1bae4fdc19e3f8ebcbfb864",
+ "bytes": 64293,
+ "sha256": "6c32076891cacc05c43187ce29bed0e984e0e414c9a24d7902618260c11af673",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1739,8 +1739,8 @@
]
},
"skills+shared+voice+x+team+images+hosting": {
- "bytes": 75531,
- "sha256": "e68e9f3daf8c7573e6ddd11328a7cebe90dd4b86f1ac31ff0d164b545fc35839",
+ "bytes": 75525,
+ "sha256": "90d7f1dbed0eb33836de39b28025ce304437d1d4e80facb8aa0ad5787fca75c9",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1814,8 +1814,8 @@
]
},
"default+hosting": {
- "bytes": 64276,
- "sha256": "ada1d1f2973ac3cedcba6bfb353cc1d0ef30bd3784e49b256f536a1e92a9d102",
+ "bytes": 64270,
+ "sha256": "5289358ee714ba5c1b501590545308282824ff2928ae2ec53ebaaef8a4b3cf09",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1878,8 +1878,8 @@
]
},
"skills+shared+voice+x+team+board": {
- "bytes": 73715,
- "sha256": "dc873aa4d5289b79537daaa470f5b28bd172367fb59f1d41a1237fd37439487b",
+ "bytes": 73709,
+ "sha256": "d3124fe10b922eec06e35a34715e4d534944fc6fbc945002055cb331985d0ac2",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1952,8 +1952,8 @@
]
},
"default+room+board": {
- "bytes": 59333,
- "sha256": "16b32642ffd54aa13bd400e1a9e74b97a1dad3d7f4ead1f1841d81e75e9c1b17",
+ "bytes": 59327,
+ "sha256": "c028972269f98e3f689cf138a5de55e94580beeaeda42f038f17366d8a9ee1e8",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -2009,8 +2009,8 @@
]
},
"default+tools-off": {
- "bytes": 57916,
- "sha256": "b07fd850e835853499868d98e34c93b1415c5b1f8eff0afbeca047c72f5cadea",
+ "bytes": 57910,
+ "sha256": "06b8f84b5eefb0b2f5b002043b4dcd371f79fa70bc22ea66487e56c904e8ffe3",
"tools": [
"tool_result_read",
"list_room_targets",
diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.ts
index 69f34abe6f..143141d1e0 100644
--- a/server/drivers/agents-catalog.ts
+++ b/server/drivers/agents-catalog.ts
@@ -246,12 +246,11 @@ const TOOL_DEFINITIONS = [
{
name: "close_thread",
description:
- "Mark a thread you opened (or one of your own) as finished once you have read its result: it leaves the person's default sidebar list (still under all threads, with a note saying you closed it) and list_threads reports it as closed. Nothing is deleted — deleting stays the person's decision — and a thread that is still running cannot be closed; wait for it or leave it. Use the thread id from list_threads or from the start_thread result. If a close is refused, do not retry it.",
+ "Mark a thread you opened (or one of your own) as finished once you have read its result: it leaves the person's default sidebar list (still under all threads, with a note saying you closed it) and list_threads reports it as closed. Nothing is deleted — deleting stays the person's decision — and a thread that is still running cannot be closed; wait for it or leave it. In a room thread, leave thread_id out to close the one you are in once your reply ends. If a close is refused, do not retry it.",
inputSchema: {
type: "object",
additionalProperties: false,
properties: { thread_id: { type: "string", description: "The thread id from list_threads or start_thread." } },
- required: ["thread_id"],
},
},
RENAME_THREAD_TOOL_DEFINITION,
diff --git a/server/drivers/agents-list-threads-tool.ts b/server/drivers/agents-list-threads-tool.ts
index 3840f03b4c..378f474f88 100644
--- a/server/drivers/agents-list-threads-tool.ts
+++ b/server/drivers/agents-list-threads-tool.ts
@@ -35,6 +35,11 @@ export async function callListThreadsTool(args: Json, context: ToolCallContext):
/** close_thread's reply: what closing did, or that the thread was already closed and by whom, and whether the person's sidebar still shows it. */
export function closedThreadText(r: Json): string {
+ if (r.room === true) {
+ return r.alreadyClosed === true
+ ? `#${String(r.title)} is already closed, so nothing changed.`
+ : `#${String(r.title)} closes when this reply ends. Any new message there opens it again.`;
+ }
const thread = `#${String(r.title)}${r.botName ? ` on @${String(r.botName)}` : ""}`;
if (r.alreadyClosed === true) {
const by = typeof r.closedBy === "string" && r.closedBy ? ` by @${r.closedBy}` : "";
diff --git a/server/group-task-state.ts b/server/group-task-state.ts
index 7434768259..82a3de61d5 100644
--- a/server/group-task-state.ts
+++ b/server/group-task-state.ts
@@ -1,4 +1,5 @@
import type { GroupTask } from "../shared/wire.ts";
+import { settleRoomThreadClose } from "./room-thread-close.ts";
import type { GroupRecord, Store } from "./store.ts";
export function groupTasks(group: GroupRecord | undefined): GroupTask[] {
@@ -54,8 +55,10 @@ export function refreshGroupUnread(group: GroupRecord): void {
group.unread = Boolean(group.tasks?.some((task) => task.unread));
}
-export function markGroupThreadUnreadAfterTurn(store: Pick<Store, "patchGroup" | "markGroupThreadUnread">,
+/** A turn's end, however it ended: a close its bot asked for takes effect now, and the thread stays unread until read. */
+export function markGroupThreadUnreadAfterTurn(store: Pick<Store, "patchGroup" | "markGroupThreadUnread" | "groupTaskByThread" | "patchGroupTask">,
groupId: string, threadId: string, busyBotId: string | null): void {
store.patchGroup(groupId, { busyBotId });
store.markGroupThreadUnread(groupId, threadId, true);
+ settleRoomThreadClose(store, groupId, threadId);
}
diff --git a/server/host/idle-reclaim.ts b/server/host/idle-reclaim.ts
index fb6f0a0b45..8fc51d4a87 100644
--- a/server/host/idle-reclaim.ts
+++ b/server/host/idle-reclaim.ts
@@ -78,7 +78,7 @@ export function idleReclaimMode(env: NodeJS.ProcessEnv = process.env): IdleRecla
return "off";
}
-type Stamped = { threadId: string; createdAt?: number; updatedAt?: number; archivedAt?: number; closedBy?: { at?: number } };
+type Stamped = { threadId: string; createdAt?: number; updatedAt?: number; archivedAt?: number; closedAt?: number; closedBy?: { at?: number } | { kind: string } };
/** The records with each conversation's stamps (the store's bots and rooms). */
export interface StampedRecords extends LiveRecords {
readonly bots: ReadonlyArray<LiveRecords["bots"][number] & { tasks?: ReadonlyArray<Stamped & { cwd?: string | null; pinnedCwd?: string | null }> }>;
@@ -90,7 +90,8 @@ export function lastActivity(records: StampedRecords): Map<string, number> {
const at = new Map<string, number>();
for (const owner of [...records.bots, ...records.groups]) {
for (const task of owner.tasks ?? []) {
- const newest = Math.max(task.updatedAt ?? 0, task.createdAt ?? 0, task.closedBy?.at ?? 0, task.archivedAt ?? 0);
+ const closed = task.closedAt ?? (task.closedBy && "at" in task.closedBy ? task.closedBy.at : undefined);
+ const newest = Math.max(task.updatedAt ?? 0, task.createdAt ?? 0, closed ?? 0, task.archivedAt ?? 0);
at.set(task.threadId, Math.max(at.get(task.threadId) ?? 0, newest));
}
}
diff --git a/server/index.ts b/server/index.ts
index fc63928897..0491148f53 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -411,7 +411,7 @@ import {
LEARN_PROMPT, LEARN_RULES_PROMPT,
PROFILE_PROMPT,
TEAM_MEMORY_PROMPT,
- TRIGGER_PROMPT,
+ TRIGGER_PROMPT, ROOM_CLOSE_PROMPT,
ROUTINE_EXECUTION_PROMPT, READ_ONLY_ROUTINE_EXECUTION_PROMPT,
WEBHOOK_PROMPT, BOT_API_PROMPT, BOT_API_OWNER_PROMPT, AUTOMATION_REPLY_PROMPT,
resolveComputerPromptKind,
@@ -9949,7 +9949,7 @@ async function runClaimedGroupMemberTurn(
outsideRoom.length > 0 && roomPeerRosterSystemPrompt(outsideRoom), sharedNamesNote(roomMembers.filter((member) => member.id !== bot.id), Boolean(integrations.agents)),
integrations.agents && (CREDENTIAL_PROMPT + botLogins.secretsPrompt(bot.id, vaultReaders.turn(threadId)) + (orchestration && !orchestration.roomHandoffId ? THREADS_PROMPT : "")).trim(),
integrations.agents && (!orchestration || orchestration.roomHandoffId) && "For actual OpenMausBot teamwork, discover IDs with list_room_targets and use coordinate_bots for advice or work in this or another room. Do not substitute native coding helpers for these named bots. Consult only when needed to make a decision; no discussion step is mandatory. Give concrete responsibilities, exact accessible paths and acceptance checks. End your turn after assigning; busy teammates queue and results automatically resume you. When they return, finish the requested verification and give the user one final answer. Native helper names are not evidence that an OpenMausBot teammate participated. Plain @mentions are only for conversational replies in this room." + requesterRule,
- integrations.agents && TRIGGER_PROMPT.trim(),
+ integrations.agents && TRIGGER_PROMPT.trim(), integrations.agents && !readyGroup.dm && ROOM_CLOSE_PROMPT,
integrations.agents && PROFILE_PROMPT.trim(),
integrations.agents && skillAuthoringEnabled(cfg) && LEARN_RULES_PROMPT.trim(),
orchestration?.systemInstructions,
diff --git a/server/room-bot-close.e2e.test.ts b/server/room-bot-close.e2e.test.ts
new file mode 100644
index 0000000000..12e78b16b7
--- /dev/null
+++ b/server/room-bot-close.e2e.test.ts
@@ -0,0 +1,64 @@
+// A bot closes the room thread it answers in with its final reply, on an isolated fixture with the scripted engine: the
+// room turn's instructions ask it to, close_thread with no thread_id closes that thread once the turn ends (its own reply
+// and digest do not open it again), the thread stays unread until read, and the person's next line opens it.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import type { GroupTask } from "../shared/wire.ts";
+
+it("closes its room thread with its final reply, and a person's next line opens it again", async () => {
+ const session = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });
+ const env = { OPENMAUSBOT_URL: session.info.url };
+ const cli = (...args: string[]) => runControlOmb(args, { env }) as Promise<any>;
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${session.info.url}${path}`, {
+ method, headers: { "content-type": "application/json" },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ const result = await response.json() as any;
+ expect(response.ok, JSON.stringify(result)).toBe(true);
+ return result;
+ };
+ try {
+ const writer = (await cli("new-bot", "--name", "Writer", "--section", "A")).bot;
+ const { group: room } = await api("POST", "/api/groups", {
+ name: "Docs", memberIds: [writer.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: writer.id } },
+ });
+ const planPath = join(session.info.dataDir, "room-plan.json");
+ writeFileSync(planPath, JSON.stringify({ [writer.id]: { script: [
+ { key: "W1", match: ["Fix the typo"], steps: [{ tool: "close_thread", arguments: {} }], reply: "Fixed the typo." },
+ { key: "W2", match: ["one more"], reply: "Done as well." },
+ ] } }));
+ const evidence = () => existsSync(`${planPath}.evidence.jsonl`)
+ ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
+ const task = async (): Promise<GroupTask> => ((await api("GET", "/api/bots")).groups as Array<{ id: string; tasks: GroupTask[] }>)
+ .find((group) => group.id === room.id)!.tasks.find((candidate) => candidate.threadId === room.threadId)!;
+
+ await api("POST", `/api/groups/${room.id}/messages`, { text: "Fix the typo in the README", threadId: room.threadId });
+ await expect.poll(() => evidence().some((turn) => turn.planKey === "W1"), { timeout: 60_000 }).toBe(true);
+ expect((await cli("wait", "--channel", room.id, "--timeout", "45")).status).toBe("settled");
+ const turn = evidence().find((record) => record.planKey === "W1");
+ expect(turn.system).toContain("When the work in this thread is finished, close it with your final reply");
+ expect((turn.evidence[0].result.tools as Array<{ name: string; inputSchema: { required?: string[] } }>).find((tool) => tool.name === "close_thread")?.inputSchema.required ?? []).not.toContain("thread_id");
+ const closeAnswer = turn.evidence.at(-1).response.result;
+ expect(closeAnswer.isError ?? false, JSON.stringify(closeAnswer)).toBe(false);
+ expect(closeAnswer.content[0].text).toContain("closes when this reply ends");
+
+ await expect.poll(async () => (await task()).closedBy, { timeout: 15_000 }).toEqual({ kind: "bot", id: writer.id, name: "Writer" });
+ const closed = await task();
+ expect(closed).toMatchObject({ closedAt: expect.any(Number), unread: true });
+ const transcript = (await api("GET", `/api/threads/${room.threadId}/messages`)).messages as Array<{ role: string; text?: string }>;
+ expect(transcript.some((message) => message.role === "bot" && message.text === "Fixed the typo.")).toBe(true);
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ expect((await task()).closedAt).toBe(closed.closedAt);
+
+ await api("POST", `/api/groups/${room.id}/messages`, { text: "And one more fix, please", threadId: room.threadId });
+ await expect.poll(async () => (await task()).closedAt, { timeout: 15_000 }).toBeUndefined();
+ await expect.poll(() => evidence().some((record) => record.planKey === "W2"), { timeout: 60_000 }).toBe(true);
+ expect((await cli("wait", "--channel", room.id, "--timeout", "45")).status).toBe("settled");
+ expect(await task()).not.toHaveProperty("closedBy");
+ } finally {
+ await session.close();
+ }
+}, 180_000);
diff --git a/server/room-thread-close.e2e.test.ts b/server/room-thread-close.e2e.test.ts
new file mode 100644
index 0000000000..ad5bd126bf
--- /dev/null
+++ b/server/room-thread-close.e2e.test.ts
@@ -0,0 +1,115 @@
+// Closing a room's thread on a real Team Cloud: Ada (an Admin) makes a room of one bot that Bob may chat with, Vic may
+// only view and Eve cannot see. Anyone who may post there closes or reopens any thread, the record says who and when,
+// a new line opens a closed thread again, and closing leaves each person's unread mark alone. The engine is the
+// synthetic Claude CLI.
+import { randomBytes } from "node:crypto";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";
+import type { GroupTask } from "../shared/wire.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+const ADA = { email: "[email protected]", role: "admin" as const };
+const BOB = { email: "[email protected]", role: "member" as const };
+const VIC = { email: "[email protected]", role: "member" as const };
+const EVE = { email: "[email protected]", role: "member" as const };
+
+let fx: CloudSendFixture, team: CloudTeamFixture;
+const token: Record<string, string> = {};
+let room = "";
+
+const as = (who: string, method: string, path: string, body?: unknown) => team.as(token[who]!, method, path, body);
+const taskFor = async (who: string, threadId: string): Promise<GroupTask | undefined> =>
+ ((await as(who, "GET", "/api/bots")).body.groups as Array<{ id: string; tasks?: GroupTask[] }>).find((group) => group.id === room)?.tasks?.find((task) => task.threadId === threadId);
+
+async function until(done: () => Promise<boolean> | boolean, timeoutMs = 60_000): Promise<void> {
+ const end = Date.now() + timeoutMs;
+ while (!(await done())) {
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+}
+
+async function answeredThread(who: string, text: string): Promise<string> {
+ const created = await as(who, "POST", `/api/groups/${room}/tasks`, { activate: false });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ const thread = created.body.task.threadId as string;
+ expect((await as(who, "POST", `/api/groups/${room}/messages`, { text, threadId: thread })).status).toBeLessThan(300);
+ await until(async () => {
+ const task = await taskFor("ada", thread);
+ return Boolean(task && !task.working && !task.busyBotId && (task.updatedAt ?? 0) > task.createdAt);
+ });
+ await until(async () => ((await as(who, "GET", `/api/threads/${thread}/messages`)).body.messages as Array<{ role: string; kind?: string }>)
+ .some((message) => message.role === "bot" && (message.kind ?? "text") === "text"));
+ return thread;
+}
+
+beforeAll(async () => {
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-close", name: "Acme" } });
+ team = fx.team!;
+ for (const [who, member] of Object.entries({ ada: ADA, bob: BOB, vic: VIC, eve: EVE })) {
+ const paired = await team.pair(member);
+ expect(paired.token, JSON.stringify(paired.body)).toBeTruthy();
+ token[who] = paired.token!;
+ }
+ const created = await as("ada", "POST", "/api/bots", { name: "Writer" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ const bot = created.body.bot.id as string;
+ expect((await as("ada", "PUT", `/api/bots/${bot}/access`, { everyone: "none", people: { [BOB.email]: "chat", [VIC.email]: "view" } })).status).toBe(200);
+ const made = await as("ada", "POST", "/api/groups", { memberIds: [bot], name: "Launch", setup: { bulletin: "", defaultResponder: { kind: "everyone" } } });
+ expect(made.status, JSON.stringify(made.body)).toBe(201);
+ room = made.body.group.id;
+}, hostTimeout(180_000));
+
+afterAll(async () => {
+ await fx?.close();
+});
+
+describe("closing a room thread", () => {
+ it("lets anyone who may post close and reopen any thread, and keeps who closed it and when", async () => {
+ const thread = await answeredThread("ada", "Write the launch post");
+ const before = Date.now();
+ const closed = await as("bob", "PATCH", `/api/groups/${room}/tasks/${thread}`, { closed: true });
+ expect(closed.status, JSON.stringify(closed.body)).toBe(200);
+ expect(closed.body.task).toMatchObject({ closedAt: expect.any(Number), closedBy: { kind: "person", id: expect.any(String), name: expect.any(String) } });
+ expect(closed.body.task.closedAt).toBeGreaterThanOrEqual(before);
+ expect(closed.body.task.closedBy.name).toMatch(/bob/i);
+ expect((await taskFor("ada", thread))?.closedBy).toEqual(closed.body.task.closedBy);
+ const summary = await as("ada", "GET", `/api/groups/${room}/threads/summary`);
+ expect((summary.body.threads as Array<{ threadId: string }>).map((row) => row.threadId)).toContain(thread);
+
+ const again = await as("ada", "PATCH", `/api/groups/${room}/tasks/${thread}`, { closed: true });
+ expect(again.body.task.closedBy).toEqual(closed.body.task.closedBy);
+ const reopened = await as("ada", "PATCH", `/api/groups/${room}/tasks/${thread}`, { closed: false });
+ expect(reopened.status).toBe(200);
+ expect(reopened.body.task).not.toHaveProperty("closedAt");
+ expect(await taskFor("bob", thread)).not.toHaveProperty("closedBy");
+ });
+
+ it("refuses someone who may only view the room, and answers someone who cannot see it as if it did not exist", async () => {
+ const thread = await answeredThread("ada", "Check the press list");
+ expect((await as("vic", "PATCH", `/api/groups/${room}/tasks/${thread}`, { closed: true })).status).toBe(403);
+ expect((await as("eve", "PATCH", `/api/groups/${room}/tasks/${thread}`, { closed: true })).status).toBe(404);
+ expect((await as("bob", "PATCH", `/api/groups/${room}/tasks/${thread}`, { closed: "yes" })).status).toBe(400);
+ expect((await as("bob", "PATCH", `/api/groups/${room}/tasks/${thread}`, { closedBy: { kind: "bot", id: "x", name: "x" } })).status).toBe(400);
+ expect(await taskFor("ada", thread)).not.toHaveProperty("closedAt");
+ });
+
+ it("opens a closed thread again when a new line arrives in it", async () => {
+ const thread = await answeredThread("bob", "Draft the FAQ");
+ expect((await as("ada", "PATCH", `/api/groups/${room}/tasks/${thread}`, { closed: true })).status).toBe(200);
+ expect((await as("bob", "POST", `/api/groups/${room}/messages`, { text: "One more question for the FAQ", threadId: thread })).status).toBeLessThan(300);
+ await until(async () => (await taskFor("ada", thread))?.closedAt === undefined);
+ expect(await taskFor("bob", thread)).not.toHaveProperty("closedBy");
+ });
+
+ it("leaves a person's unread mark until they read the thread", async () => {
+ const thread = await answeredThread("ada", "Summarise the launch feedback");
+ await until(async () => (await taskFor("bob", thread))?.unread === true);
+ expect((await as("ada", "PATCH", `/api/groups/${room}/tasks/${thread}`, { closed: true })).status).toBe(200);
+ const bobs = await taskFor("bob", thread);
+ expect(bobs).toMatchObject({ unread: true, closedAt: expect.any(Number) });
+ expect((await as("bob", "POST", `/api/groups/${room}/read`, { threadId: thread })).status).toBe(200);
+ await until(async () => (await taskFor("bob", thread))?.unread !== true);
+ expect((await taskFor("bob", thread))?.closedAt).toEqual(bobs?.closedAt);
+ });
+});
diff --git a/server/room-thread-close.test.ts b/server/room-thread-close.test.ts
new file mode 100644
index 0000000000..14627a765d
--- /dev/null
+++ b/server/room-thread-close.test.ts
@@ -0,0 +1,77 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+let home: string;
+
+async function freshRoom() {
+ home = mkdtempSync(join(tmpdir(), "omb-room-close-"));
+ vi.resetModules();
+ vi.stubEnv("HOME", home);
+ vi.stubEnv("USERPROFILE", home);
+ const { Store } = await import("./store.ts");
+ const close = await import("./room-thread-close.ts");
+ const { markGroupThreadUnreadAfterTurn } = await import("./group-task-state.ts");
+ const store = new Store(() => ({ instanceId: "claude", model: "m" }));
+ const bot = store.createBot();
+ const room = store.createGroup("Launch", [bot.id]);
+ return { store, bot, room, thread: room.threadId, close, turnEnds: () => markGroupThreadUnreadAfterTurn(store, room.id, room.threadId, null) };
+}
+
+afterEach(async () => {
+ const { closeMessageDb } = await import("./message-db.ts");
+ closeMessageDb();
+ vi.unstubAllEnvs();
+ rmSync(home, { recursive: true, force: true });
+});
+
+const writer = { kind: "person" as const, id: "ada", name: "Ada" };
+
+describe("closing a room thread", () => {
+ it("keeps who closed it and when, and a person's line or a bot's reply opens it again", async () => {
+ const { store, bot, room, thread, close } = await freshRoom();
+ store.appendMessage(thread, { role: "user", kind: "text", text: "Ship it" });
+ const closed = close.setRoomThreadClosed(store, room.id, thread, writer)!;
+ expect(closed).toMatchObject({ closedBy: writer, closedAt: expect.any(Number) });
+
+ store.appendMessage(thread, { role: "bot", kind: "activity", from: { botId: bot.id, name: bot.name, color: bot.color }, tool: { name: "Read", ok: true } });
+ store.appendMessage(thread, { role: "bot", kind: "digest", text: "[digest] done" });
+ expect(store.groupTaskByThread(room.id, thread)?.closedAt).toBe(closed.closedAt);
+
+ store.appendMessage(thread, { role: "bot", kind: "text", text: "One more thing", from: { botId: bot.id, name: bot.name, color: bot.color } });
+ expect(store.groupTaskByThread(room.id, thread)).not.toHaveProperty("closedAt");
+ expect(store.groupTaskByThread(room.id, thread)).not.toHaveProperty("closedBy");
+
+ close.setRoomThreadClosed(store, room.id, thread, writer);
+ store.appendMessage(thread, { role: "user", kind: "text", text: "Wait, also this" });
+ expect(store.groupTaskByThread(room.id, thread)?.closedAt).toBeUndefined();
+ });
+
+ it("leaves the thread unread when closing", async () => {
+ const { store, room, thread, close } = await freshRoom();
+ store.markGroupThreadUnread(room.id, thread, true);
+ close.setRoomThreadClosed(store, room.id, thread, writer);
+ expect(store.groupTaskByThread(room.id, thread)).toMatchObject({ unread: true, closedAt: expect.any(Number) });
+ });
+
+ it("closes for a bot when its turn ends, after its own reply", async () => {
+ const { store, bot, room, thread, close, turnEnds } = await freshRoom();
+ store.appendMessage(thread, { role: "user", kind: "text", text: "Fix the typo" });
+ close.closeRoomThreadAtTurnEnd(thread, bot);
+ store.appendMessage(thread, { role: "bot", kind: "text", text: "Fixed.", from: { botId: bot.id, name: bot.name, color: bot.color } });
+ expect(store.groupTaskByThread(room.id, thread)?.closedAt).toBeUndefined();
+ turnEnds();
+ expect(store.groupTaskByThread(room.id, thread)).toMatchObject({ closedBy: { kind: "bot", id: bot.id, name: bot.name }, unread: true });
+ turnEnds();
+ expect(store.groupTaskByThread(room.id, thread)?.closedBy?.kind).toBe("bot");
+ });
+
+ it("drops a bot's close when a person writes before its turn ends", async () => {
+ const { store, bot, room, thread, close, turnEnds } = await freshRoom();
+ close.closeRoomThreadAtTurnEnd(thread, bot);
+ store.appendMessage(thread, { role: "user", kind: "text", text: "Hold on, one more" });
+ turnEnds();
+ expect(store.groupTaskByThread(room.id, thread)?.closedAt).toBeUndefined();
+ });
+});
diff --git a/server/room-thread-close.ts b/server/room-thread-close.ts
new file mode 100644
index 0000000000..7420ced251
--- /dev/null
+++ b/server/room-thread-close.ts
@@ -0,0 +1,42 @@
+import type { RoomThreadCloser } from "../shared/room-threads.ts";
+import { endHeldUnread, isReply } from "./held-unread.ts";
+import type { Store } from "./store.ts";
+
+type Line = { role: string; kind?: string };
+type CloseStore = Pick<Store, "groupByThread" | "groupTaskByThread" | "patchGroupTask">;
+
+/** A bot's close of the room thread its turn speaks in waits for that turn to end, so its own reply does not open the
+ * thread again. Keyed by thread: a room thread has one speaker at a time. */
+const closesAtTurnEnd = new Map<string, RoomThreadCloser>();
+
+export function setRoomThreadClosed(store: Pick<Store, "patchGroupTask">, groupId: string, threadId: string, by: RoomThreadCloser | null) {
+ return store.patchGroupTask(groupId, threadId, { closed: by ? { at: Date.now(), by } : null });
+}
+
+export function closeRoomThreadAtTurnEnd(threadId: string, bot: { id: string; name: string }): void {
+ closesAtTurnEnd.set(threadId, { kind: "bot", id: bot.id, name: bot.name });
+}
+
+export function settleRoomThreadClose(store: Pick<Store, "groupTaskByThread" | "patchGroupTask">, groupId: string, threadId: string): void {
+ const by = closesAtTurnEnd.get(threadId);
+ if (!by) return;
+ closesAtTurnEnd.delete(threadId);
+ const task = store.groupTaskByThread(groupId, threadId);
+ if (task && task.closedAt === undefined) setRoomThreadClosed(store, groupId, threadId, by);
+}
+
+/** A person's line or a bot's reply in a closed room thread opens it again, so nothing new hides under a fold. A
+ * person's line also cancels a close the answering bot asked for, since that bot has not read it. */
+function reopenOnLine(store: CloseStore, threadId: string, line: Line): void {
+ const person = line.role === "user";
+ if (!person && !isReply(line)) return;
+ if (person) closesAtTurnEnd.delete(threadId);
+ const group = store.groupByThread(threadId);
+ if (!group || group.dm) return;
+ if (store.groupTaskByThread(group.id, threadId)?.closedAt !== undefined) setRoomThreadClosed(store, group.id, threadId, null);
+}
+
+export function afterNewLine(store: CloseStore & Parameters<typeof endHeldUnread>[0], threadId: string, line: Line): void {
+ endHeldUnread(store, threadId, line);
+ reopenOnLine(store, threadId, line);
+}
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index 794deececf..de86be80b3 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -17,12 +17,12 @@ import { DATA_DIR, type AppConfig } from "../config.ts";
import type { ProviderInstance, SteerOutcome } from "../contracts.ts";
import { cancelledChatFollowup } from "../message-db.ts";
import { roomThreadSummaries } from "../message-db-thread-summaries.ts";
-import type { RoomThreadSummariesResponse } from "../../shared/room-threads.ts";
+import type { RoomThreadCloser, RoomThreadSummariesResponse } from "../../shared/room-threads.ts";
import { messageTextRefusal } from "../message-text.ts";
import { prepareRoomPointed, roomPickBots, type RoomPick } from "../room-pointed.ts";
import { refusalBody } from "../user-errors.ts";
import type { PhoneSecretSubmissionRegistry } from "../phone-secret.ts";
-import { promptWithReply, type PersonName } from "../replies.ts";
+import { personOf, promptWithReply, type PersonName } from "../replies.ts";
import { clientGroupPatchViolation, requestSource, type RequestAuth } from "../request-auth.ts";
import type { RoomContextTracker } from "../room-context.ts";
import { parseConversationTurnTimeout } from "../room-turn-timeout.ts";
@@ -157,6 +157,10 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
}
return result;
};
+ const personCloser = (auth: RequestAuth, threadId: string): RoomThreadCloser => {
+ const sender = messageSender(auth);
+ return { kind: "person", id: sender?.id ?? "owner", name: sender?.name ?? personOf(deps.userName(threadId), {}) };
+ };
return async ({ req, res, url, path, method, auth, json, readBody }) => {
const own = (group: WireGroup) => deps.groupFor?.(auth, group) ?? group;
let m: RegExpMatchArray | null = null;
@@ -262,7 +266,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
if (!body || typeof body !== "object" || Array.isArray(body)) {
return json(res, 400, { error: "body must be a JSON object" });
}
- const allowed = new Set(["title", "pinned", "turnTimeoutMinutes", "archivedAt"]);
+ const allowed = new Set(["title", "pinned", "turnTimeoutMinutes", "archivedAt", "closed"]);
if (Object.keys(body).some((key) => !allowed.has(key))) return json(res, 400, { error: "unsupported channel thread setting" });
const existing = store.groupTaskByThread(group.id, m[2]);
if (!existing) return json(res, 404, { error: "no such channel task" });
@@ -270,7 +274,9 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
const renaming = body.title !== undefined;
const limiting = Object.prototype.hasOwnProperty.call(body, "turnTimeoutMinutes");
const archiving = body.archivedAt !== undefined;
- if (!pinning && !renaming && !limiting && !archiving) return json(res, 400, { error: "unsupported channel thread setting" });
+ const closing = body.closed !== undefined;
+ if (!pinning && !renaming && !limiting && !archiving && !closing) return json(res, 400, { error: "unsupported channel thread setting" });
+ if (closing && typeof body.closed !== "boolean") return json(res, 400, { error: "closed must be true or false" });
if (pinning && typeof body.pinned !== "boolean") return json(res, 400, { error: "pinned must be a boolean" });
if (renaming && typeof body.title !== "string") return json(res, 400, { error: "title must be a string" });
if (archiving && body.archivedAt !== null && !(typeof body.archivedAt === "number" && Number.isFinite(body.archivedAt) && body.archivedAt >= 0)) {
@@ -290,6 +296,8 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
...(pinning ? { pinned: body.pinned === true } : {}),
...(archiving ? { archivedAt: body.archivedAt as number | null } : {}),
...(titleChange ? { title: body.title } : {}),
+ // Anyone who may post in the room may close or reopen any of its threads; who did comes from the session, never the body.
+ ...(closing && body.closed !== (existing.closedAt !== undefined) ? { closed: body.closed ? { at: Date.now(), by: personCloser(auth, m[2]) } : null } : {}),
};
const task = Object.keys(patch).length ? store.patchGroupTask(group.id, m[2], patch) : existing;
if (!task) return json(res, 404, { error: "no such channel task" });
diff --git a/server/routes/internal-threads.ts b/server/routes/internal-threads.ts
index 75e96d2d05..b7731a94dd 100644
--- a/server/routes/internal-threads.ts
+++ b/server/routes/internal-threads.ts
@@ -4,6 +4,7 @@ import { mainThreadChoicePatch } from "../main-thread.ts";
import { reachablePeers } from "../peer-roster.ts";
import { threadTitleFrom, type BotRecord, type Store, type TaskRecord } from "../store.ts";
import { PASS, type RouteHandler } from "./table.ts";
+import { closeRoomThreadAtTurnEnd } from "../room-thread-close.ts";
import { conversationLanguage, serverLine } from "../server-lines.ts";
const THREADS_PAGE = 100;
@@ -23,7 +24,7 @@ interface ThreadRow {
/** Only dispatch inside the internal capability gate: `from` and `fromThreadId` come from the caller's capability. */
export function createInternalThreadRoutes(deps: {
- store: Pick<Store, "bot" | "bots" | "tasks" | "taskByThread" | "appendMessage" | "patchTask" | "setTaskClosedBy" | "renameTask" | "patchBot">;
+ store: Pick<Store, "bot" | "bots" | "tasks" | "taskByThread" | "appendMessage" | "patchTask" | "setTaskClosedBy" | "renameTask" | "patchBot" | "groupByThread" | "groupTaskByThread">;
coordinator: Pick<Coordinator, "awaitingAnswer" | "parkedDirect" | "activeDirect" | "active">;
from: BotRecord;
fromThreadId: string;
@@ -142,6 +143,13 @@ export function createInternalThreadRoutes(deps: {
return json(res, 403, { error: "source conversation does not belong to sender" });
}
const threadId = closeMatch[1]!;
+ const room = threadId === fromThreadId ? store.groupByThread(threadId) : undefined;
+ if (room && !room.dm) {
+ const task = store.groupTaskByThread(room.id, threadId);
+ if (!task || !room.memberIds.includes(from.id)) return json(res, 404, { error: "this room thread is gone, or you are no longer in its room" });
+ if (task.closedAt === undefined) closeRoomThreadAtTurnEnd(threadId, from);
+ return json(res, 200, { closed: true, room: true, threadId, title: task.title, ...(task.closedAt !== undefined ? { alreadyClosed: true } : {}) });
+ }
const owner = [from, ...reachablePeers(store.bots, from)].find((bot) => store.taskByThread(bot.id, threadId));
const task = owner ? store.taskByThread(owner.id, threadId) : undefined;
if (!owner || !task || !deps.shown(threadId)) return json(res, 404, { error: "no such thread — call list_threads for the ones you can see" });
diff --git a/server/store.ts b/server/store.ts
index 8bd2ccc0b8..258f71336e 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -47,7 +47,7 @@ import { repairLegacyWorkThreads } from "./legacy-work-threads.ts";
import { createBotFork, createGroupFork } from "./store-forks.ts";
import { branchLeafFrom } from "../shared/conversation-branch.ts";
import { createThreadBotIndex } from "./thread-bot-index.ts";
-import { endHeldUnread } from "./held-unread.ts";
+import { afterNewLine } from "./room-thread-close.ts";
import { activeGroupTask, groupTaskByThread, groupTasks, migrateGroupTaskRead, mirrorActiveGroupTask, refreshGroupUnread, setGroupTaskRead, syncGroupReadPatch } from "./group-task-state.ts";
export { titleFromMessage, UNTITLED_TASK } from "./thread-title.ts";
export { threadTitleFrom, UNTITLED_THREAD } from "./task-record.ts";
@@ -118,7 +118,7 @@ const TASK_PATCH_FIELDS = [
] as const satisfies readonly (keyof TaskRecord)[];
export type TaskPatch = Partial<Pick<TaskRecord, typeof TASK_PATCH_FIELDS[number]>>;
-export type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "pinned">> & { turnTimeoutMinutes?: number | null; archivedAt?: number | null; activity?: "waiting-on-you" | null };
+export type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "pinned">> & { turnTimeoutMinutes?: number | null; archivedAt?: number | null; activity?: "waiting-on-you" | null; closed?: { at: number; by: NonNullable<GroupTaskRecord["closedBy"]> } | null };
export const ACTIVITY_BUSY: ReadonlySet<BotActivity> = new Set(["working", "waiting-on-you", "no-signal"]);
@@ -994,9 +994,9 @@ export class Store {
if (!group || !task) return null;
this.commitGroupChange(group, "the thread change", () => {
if (patch.title !== undefined) task.title = patch.title.trim().slice(0, 80) || UNTITLED_TASK;
- if (patch.pinned) task.pinned = true; else if (patch.pinned === false) delete task.pinned;
- if (patch.activity) task.activity = patch.activity; else if (patch.activity === null) delete task.activity;
+ if (patch.pinned) task.pinned = true; else if (patch.pinned === false) delete task.pinned; if (patch.activity) task.activity = patch.activity; else if (patch.activity === null) delete task.activity;
for (const key of ["turnTimeoutMinutes", "archivedAt"] as const) if (patch[key] === null) delete task[key]; else if (patch[key] !== undefined) task[key] = patch[key];
+ if (patch.closed) Object.assign(task, { closedAt: patch.closed.at, closedBy: structuredClone(patch.closed.by) }); else if (patch.closed === null) { delete task.closedAt; delete task.closedBy; }
});
this.emit({ type: "group", groupId });
return task;
@@ -1146,7 +1146,7 @@ export class Store {
}
}
this.noteThreadActivity(threadId, full.at, movesThreadToTop(full), full.turnCompletedAt ?? full.at);
- this.emit({ type: "message", threadId, message: full }); endHeldUnread(this, threadId, full);
+ this.emit({ type: "message", threadId, message: full }); afterNewLine(this, threadId, full);
if (full.role === "user" && full.kind === "text") this.dismissOnboardingCard(threadId);
return full;
}
@@ -1166,7 +1166,7 @@ export class Store {
}
}
this.noteThreadActivity(threadId, full.at, movesThreadToTop(full), full.turnCompletedAt ?? full.at);
- this.emit({ type: "message", threadId, message: full }); endHeldUnread(this, threadId, full);
+ this.emit({ type: "message", threadId, message: full }); afterNewLine(this, threadId, full);
// After the insert, so no client ever sees two siblings claiming the same parent.
for (const child of children) this.patchMessage(threadId, child.id, { parentId: full.id });
return full;
@@ -1214,10 +1214,9 @@ export class Store {
...(dataContext ? { dataContext } : {}), ...from,
};
t.messages.push(full); this.threads.grew(threadId, full);
- t.activeLeafId = full.id;
- mdb.appendMessage(threadId, full);
+ t.activeLeafId = full.id; mdb.appendMessage(threadId, full);
this.noteThreadActivity(threadId, full.at, true);
- this.emit({ type: "message", threadId, message: full });
+ this.emit({ type: "message", threadId, message: full }); afterNewLine(this, threadId, full);
// A client adopts a new message as its leaf only when it chains onto its leaf; a sibling needs this pointer.
this.emit({ type: "thread", threadId, activeLeafId: full.id });
return full;
diff --git a/server/system-prompt.ts b/server/system-prompt.ts
index 834a6bccfe..edc4551adf 100644
--- a/server/system-prompt.ts
+++ b/server/system-prompt.ts
@@ -305,6 +305,8 @@ export function longCommandsPrompt(computer: ComputerPromptKind | null): string
}
export const THREADS_PROMPT =
" A thread is one conversation with its own history and run, a row under its bot; several can run at once. start_thread opens one on yourself for separate work; coordinate_bots with thread \"new\" gives a teammate a job in a fresh one; list_threads shows how yours are going. Write a thread's title as #Title so it links. Never use a ticket comment, note or room post as a stand-in for a thread. When the person says to burst something, or a request is clearly many independent items in parallel, use burst: it shows a card, nothing runs until they press Run, and results come back here as one merged reply.";
+export const ROOM_CLOSE_PROMPT =
+ "When the work in this thread is finished, close it with your final reply (close_thread with no thread_id). Leave it open only when you are waiting on a named person or thing, and say what.";
export const WIDGET_PROMPT =
" Unless the person asked (here or in your instructions) to check with them first, ask only what you cannot find or sensibly default, one thing at a time. For a pick among a few options (a time, a day, a choice), use show_widget: a Card with a Row of Buttons, one per option, whose onClickAction sends that option in one tap, at most six; the caption may say they can also type. To change something that exists (routine, reminder, booking, setting), show a form prefilled with its current values (each field's defaultValue), captioned as the current setting, with a confirm button that saves the change. Use a multi-field form only for that or when several required details truly cannot be defaulted. A plain yes or no needs no widget: ask in one short sentence; a word or 👍 on your message comes back as their reply, and a 👎 reaches you as a note with their next message. Data and comparisons go in a markdown table, not a widget.";
const APPLIED_RESULT_PROMPT =
diff --git a/server/team-backup.ts b/server/team-backup.ts
index f0b4bcebac..a68f45e479 100644
--- a/server/team-backup.ts
+++ b/server/team-backup.ts
@@ -65,7 +65,7 @@ export function createTeamBackup(store: Store, routines: Routine[], name: string
? { botId: task.openedBy.botId, name: task.openedBy.name, at: task.openedBy.at,
...(task.openedBy.kind ? { kind: task.openedBy.kind } : {}) }
: undefined,
- closedBy: "closedBy" in task && task.closedBy
+ closedBy: "closedBy" in task && task.closedBy && "botId" in task.closedBy
? { botId: task.closedBy.botId, name: task.closedBy.name, at: task.closedBy.at }
: undefined,
pinned: task.pinned === true ? true : undefined,
diff --git a/src/components/SidebarBotActivity.tsx b/src/components/SidebarBotActivity.tsx
index 2df1a1eb63..6753870b45 100644
--- a/src/components/SidebarBotActivity.tsx
+++ b/src/components/SidebarBotActivity.tsx
@@ -12,6 +12,7 @@ import { endedOnFailure } from "@/lib/mascot";
import { MainThreadMark, rowSelectedSurface } from "./SidebarRowMarkers";
import { handoffStatusText } from "./HandoffStatusChip";
import { BotAvatar, type BotAvatarProps } from "./Avatar";
+import { threadRowCloser } from "@/lib/room-thread-close";
export function sidebarBotActivityTasks(bot: Bot, queued: Record<string, unknown[]>, archivedApprovals = false): Array<Task & { queued: boolean }> {
const tasks = bot.tasks ?? [{
@@ -69,7 +70,7 @@ export function sidebarGroupActivityTasks(group: Group, bots: Bot[], queued: Rec
const waiting = Boolean(speakerId) && bots.find((bot) => bot.id === speakerId)?.activity === "waiting-on-you";
return {
...task, busy: roomThreadWorking(group, task.threadId), unread: task.unread ?? (task.threadId === group.threadId && Boolean(group.unread)),
- activity: waiting || task.activity === "waiting-on-you" ? "waiting-on-you" as const : undefined,
+ activity: waiting || task.activity === "waiting-on-you" ? "waiting-on-you" as const : undefined, closedBy: threadRowCloser(task),
};
});
return tasks.map((task) => ({ ...task, queued: Boolean(queued[task.threadId]?.length) }))
@@ -189,7 +190,7 @@ export function crossBotPinnedThreads(bots: Bot[], groups: Group[], queued: Reco
const activity = new Map(sidebarGroupActivityTasks(group, bots, queued).map((task) => [task.threadId, task]));
return (group.tasks ?? [])
.filter((task) => task.pinned === true)
- .map((task) => ({ ...task, ...activity.get(task.threadId), queued: Boolean(queued[task.threadId]?.length), groupId: group.id, groupName: group.name, groupThreadId: group.threadId }));
+ .map((task) => ({ ...task, ...activity.get(task.threadId), closedBy: threadRowCloser(task), queued: Boolean(queued[task.threadId]?.length), groupId: group.id, groupName: group.name, groupThreadId: group.threadId }));
}),
];
return orderedThreadList(flat).map(({ botId, botName, groupId, groupName, groupThreadId, ...task }): AttentionThread =>
diff --git a/src/components/SidebarGroupThreadList.tsx b/src/components/SidebarGroupThreadList.tsx
index ec50009855..7286ddba0e 100644
--- a/src/components/SidebarGroupThreadList.tsx
+++ b/src/components/SidebarGroupThreadList.tsx
@@ -2,6 +2,7 @@ import { useMemo, useRef, useState, type Dispatch } from "react";
import { useStore, type Action, type Group } from "@/state/store";
import { activeLocale, t } from "@/lib/i18n";
import { roomThreadAttention, roomThreadWorking } from "@/lib/room-threads";
+import { setRoomThreadClosed, threadRowCloser } from "@/lib/room-thread-close";
import { BulkSelectFilters, ThreadListFooter, deleteThreadsInBulk, useBulkSelect } from "./BulkSelectBar";
import { orderedThreadList, SidebarThreadRow, stampClock, threadRecency, useRelativeNow, useRevealedThreadRow, visibleSidebarThreads } from "./SidebarThreadRow";
@@ -12,6 +13,7 @@ export function roomThreadRowActions(groupId: string, dispatch: Dispatch<Action>
onDelete: (task: { threadId: string }) => dispatch({ type: "deleteGroupTask", groupId, threadId: task.threadId }),
onPin: (task: { threadId: string; title: string }, pinned: boolean) => dispatch({ type: "pinGroupTask", groupId, threadId: task.threadId, pinned, title: task.title }),
onArchive: (task: { threadId: string }, archivedAt: number | null) => dispatch({ type: "archiveGroupTask", groupId, threadId: task.threadId, archivedAt }),
+ onSetClosed: (task: { threadId: string }, closed: boolean) => setRoomThreadClosed(groupId, task.threadId, closed, dispatch),
};
}
@@ -21,10 +23,12 @@ export function GroupThreadList({ group, selected, query = "" }: { group: Group;
const [showAll, setShowAll] = useState(false);
const tasks = (group.tasks ?? [{ threadId: group.threadId, title: group.name, createdAt: group.createdAt }]).map((task) => {
const { waiting, unread } = roomThreadAttention(group, task, state.bots);
- return { ...task, busy: roomThreadWorking(group, task.threadId), unread, activity: waiting ? "waiting-on-you" as const : undefined };
+ return { ...task, busy: roomThreadWorking(group, task.threadId), unread, activity: waiting ? "waiting-on-you" as const : undefined, closedBy: undefined, closer: threadRowCloser(task) };
});
const bulk = useBulkSelect();
- const visible = orderedThreadList(visibleSidebarThreads(tasks, group.threadId, query, [], showAll || bulk.active));
+ // A closed room thread stays in the list, marked; only the feed folds them.
+ const visible = orderedThreadList(visibleSidebarThreads(tasks, group.threadId, query, [], showAll || bulk.active))
+ .map(({ closer, ...task }) => ({ ...task, closedBy: closer }));
const selection = bulk.forRows(visible);
useRevealedThreadRow(state.revealThread, selected ? group.threadId : null);
const latest = useRef(group);
diff --git a/src/components/SidebarThreadRow.tsx b/src/components/SidebarThreadRow.tsx
index 5cf7fab929..7ef167472c 100644
--- a/src/components/SidebarThreadRow.tsx
+++ b/src/components/SidebarThreadRow.tsx
@@ -1,6 +1,6 @@
import { memo, useEffect, useRef, useState, type Dispatch, type ReactNode, type RefObject, type SetStateAction } from "react";
import { createPortal } from "react-dom";
-import { Archive, ArchiveRestore, BellOff, Brain, Check, ChevronRight, Clock, Clock3, FolderInput, Link2, Link2Off, Loader2, MoreHorizontal, Pencil, Pin, PinOff, RefreshCw, Star, Trash2 } from "lucide-react";
+import { Archive, ArchiveRestore, BellOff, Brain, Check, ChevronRight, CircleCheck, CircleDashed, Clock, Clock3, FolderInput, Link2, Link2Off, Loader2, MoreHorizontal, Pencil, Pin, PinOff, RefreshCw, Star, Trash2 } from "lucide-react";
import type { Action, AppState, BotProject, Task } from "@/state/store";
import { api } from "@/state/store";
import type { RoutineRun } from "@/lib/routines";
@@ -282,6 +282,8 @@ type ThreadRowProps = {
onSnooze?: (task: ThreadRowTask, snoozedUntil: number | null) => void;
onLink?: (task: ThreadRowTask, link: string | null) => void;
onRefreshPermissions?: (task: ThreadRowTask) => void;
+ /** A room's thread: Close marks its work finished (`closedBy` says it is), Reopen takes that back. */
+ onSetClosed?: (task: ThreadRowTask, closed: boolean) => void;
/** Opens the bot's memory for this conversation, once the row has opened it. */
onMemory?: (task: ThreadRowTask) => void;
selectMode?: boolean;
@@ -308,7 +310,7 @@ function SetMainThreadItem({ main, onPick }: { main: boolean; onPick: () => void
return <button type="button" disabled={main} title={main ? t("sidebar.bot.simple.isMainThread") : undefined} onClick={onPick} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover disabled:opacity-40"><Star size={16} />{t("sidebar.bot.simple.setMainThread")}</button>;
}
-export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId, current, folders, onSelect, onRename, onRegenerateTitle, onDelete, onMove, onArchive, onPin, onSetMain, onSnooze, onLink, onRefreshPermissions, onMemory, activityLabel: liveActivity, now, selectMode = false, checked = false, onToggleSelect, panel = false, preview, main = false }: ThreadRowProps) {
+export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId, current, folders, onSelect, onRename, onRegenerateTitle, onDelete, onMove, onArchive, onPin, onSetMain, onSnooze, onLink, onRefreshPermissions, onSetClosed, onMemory, activityLabel: liveActivity, now, selectMode = false, checked = false, onToggleSelect, panel = false, preview, main = false }: ThreadRowProps) {
const activityLabel = useHeldText(liveActivity);
// Simple mode's menu keeps what a person needs for a conversation; Advanced adds the rest.
const advanced = useAdvancedMode();
@@ -332,7 +334,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
const openMenu = (x: number, y: number) => setMenu(threadMenuAt(x, y));
const startRename = () => { if (task.sharedChat) return; finishing.current = false; setDraft(task.title); setRenaming(true); setMenu(null); };
const menuSheet = useThreadRowMenu({ task, displayTitle, ownerId, folders, main, menu, setMenu, actionRef, onStartRename: startRename, onSelect, onRegenerateTitle, onDelete, onMove,
- onArchive, onPin, onSetMain, onSnooze, onLink, onRefreshPermissions, onMemory });
+ onArchive, onPin, onSetMain, onSnooze, onLink, onRefreshPermissions, onSetClosed, onMemory });
const finishRename = (save: boolean) => {
if (finishing.current) return;
finishing.current = true;
@@ -399,7 +401,7 @@ export const threadMenuAt = (x: number, y: number): ThreadMenuAt =>
({ left: Math.max(8, Math.min(x, window.innerWidth - 228)), top: Math.max(8, Math.min(y, window.innerHeight - 230)) });
type ThreadMenuProps = Pick<ThreadRowProps, "task" | "ownerId" | "folders" | "main" | "onRegenerateTitle" | "onDelete" | "onMove" | "onArchive" | "onPin" | "onSetMain"
- | "onSnooze" | "onLink" | "onRefreshPermissions" | "onMemory"> & {
+ | "onSnooze" | "onLink" | "onRefreshPermissions" | "onSetClosed" | "onMemory"> & {
menu: ThreadMenuAt | null;
setMenu: Dispatch<SetStateAction<ThreadMenuAt | null>>;
/** The control that opened the menu: a click on it is not a click outside, and focus returns to it. */
@@ -414,7 +416,7 @@ type ThreadMenuProps = Pick<ThreadRowProps, "task" | "ownerId" | "folders" | "ma
};
/** A thread row's menu and its delete confirmation, for every list that draws a thread with its actions. */
-export function useThreadRowMenu({ task, displayTitle, ownerId, folders, main = false, menu, setMenu, actionRef, onStartRename, onSelect, onRegenerateTitle, onDelete, onMove, onArchive, onPin, onSetMain, onSnooze, onLink, onRefreshPermissions, onMemory, extra, deletable = true }: ThreadMenuProps): ReactNode {
+export function useThreadRowMenu({ task, displayTitle, ownerId, folders, main = false, menu, setMenu, actionRef, onStartRename, onSelect, onRegenerateTitle, onDelete, onMove, onArchive, onPin, onSetMain, onSnooze, onLink, onRefreshPermissions, onSetClosed, onMemory, extra, deletable = true }: ThreadMenuProps): ReactNode {
const advanced = useAdvancedMode();
const [webLink, setWebLink] = useState<string | null>(null);
useEffect(() => {
@@ -483,6 +485,7 @@ export function useThreadRowMenu({ task, displayTitle, ownerId, folders, main =
{onPin && <button type="button" onClick={() => { setMenu(null); onPin(task, task.pinned !== true); }} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover">{task.pinned === true ? <PinOff size={16} /> : <Pin size={16} />}{task.pinned === true ? t("sidebar.bot.unpin") : t("sidebar.bot.pin")}</button>}
{onSetMain && !task.routineRunId && !task.private && !archived && <SetMainThreadItem main={main} onPick={() => { setMenu(null); onSetMain(task); }} />}
{advanced && onLink && task.link && <button type="button" onClick={() => { setMenu(null); onLink(task, null); }} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover"><Link2Off size={16} />{t("task.removeLink")}</button>}
+ {onSetClosed && <button type="button" data-thread-close={task.closedBy ? "reopen" : "close"} onClick={() => { setMenu(null); onSetClosed(task, !task.closedBy); }} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover">{task.closedBy ? <CircleDashed size={16} /> : <CircleCheck size={16} />}{task.closedBy ? t("task.reopenThread") : t("task.closeThread")}</button>}
{onArchive && <button type="button" disabled={isWorking(task)} onClick={() => { setMenu(null); onArchive(task, isArchived(task) ? null : Date.now()); }} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover disabled:opacity-40">{archived ? <ArchiveRestore size={16} /> : <Archive size={16} />}{archived ? t("task.unarchive") : t("task.archive")}</button>}
{advanced && onSnooze && <div className="px-2 pt-1">
<span className="flex items-center gap-2 text-[12px] font-medium text-ink-secondary"><Clock size={16} />{t("task.snooze")}</span>
diff --git a/src/components/TaskPicker.tsx b/src/components/TaskPicker.tsx
index caa49bbf3a..0dafaf01a8 100644
--- a/src/components/TaskPicker.tsx
+++ b/src/components/TaskPicker.tsx
@@ -16,6 +16,7 @@ import { useShowThreads } from "@/lib/thread-preferences";
import { attentionJump, attentionOwnerName, AttentionThreadRows, crossBotAttentionThreads, threadsWhenTreeHidden, type AttentionThread } from "./SidebarBotActivity";
import { formatUpdatedAt, orderedThreadList, threadByline, threadRecency, threadUpdatedLabel, useRelativeNow } from "./SidebarThreadRow";
import { Select } from "./Select";
+import { threadRowCloser } from "@/lib/room-thread-close";
export const TASK_PICKER_DISMISS_MS = 500;
@@ -473,6 +474,7 @@ export function GroupTaskPicker({ group }: { group: Group }) {
return (group.tasks ?? []).map((task) => ({
...task,
busy: Boolean(task.working || task.busyBotId),
+ closedBy: threadRowCloser(task),
}));
}, [group.tasks]);
return (
diff --git a/src/components/room-feed/RoomFeedRow.dom.test.ts b/src/components/room-feed/RoomFeedRow.dom.test.ts
index 712b9dfcec..212e5e2be8 100644
--- a/src/components/room-feed/RoomFeedRow.dom.test.ts
+++ b/src/components/room-feed/RoomFeedRow.dom.test.ts
@@ -22,7 +22,7 @@ const render = (data: FeedRowData, onOpen = vi.fn(), open = false, actions?: Fee
act(() => root!.render(createElement(RoomFeedRow, { row: data, groupId: "room", bots: BOTS, you: "Sam", now: NOW, open, onOpen, actions })));
return onOpen;
};
-const roomActions = (deletable = true): FeedRowActions => ({ onRename: vi.fn(), onDelete: vi.fn(), onPin: vi.fn(), onArchive: vi.fn(), deletable });
+const roomActions = (deletable = true): FeedRowActions => ({ onRename: vi.fn(), onDelete: vi.fn(), onPin: vi.fn(), onArchive: vi.fn(), onSetClosed: vi.fn(), deletable });
const menuItem = (label: string) => [...document.querySelectorAll<HTMLButtonElement>("[data-thread-overlay] button")].find((button) => button.textContent?.includes(label));
const item = () => document.querySelector<HTMLElement>("[data-feed-thread]")!;
afterEach(() => { act(() => root?.unmount()); root = null; document.body.innerHTML = ""; });
diff --git a/src/components/room-feed/RoomFeedRow.tsx b/src/components/room-feed/RoomFeedRow.tsx
index a37eff5943..0f7ea72d25 100644
--- a/src/components/room-feed/RoomFeedRow.tsx
+++ b/src/components/room-feed/RoomFeedRow.tsx
@@ -7,7 +7,7 @@ import { splitTranscriptAttachments } from "@/lib/composer-attachments";
import { opensRowMenuFromKey } from "@/lib/bulk-select";
import { intlLocale, t } from "@/lib/i18n";
import { MAUS_COLOR_NAMES } from "@/lib/mascot";
-import type { Bot } from "@/state/store";
+import type { Bot, ThreadCloser } from "@/state/store";
import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";
import { BotAvatar } from "../Avatar";
import { ChatMarkdown } from "../ChatMarkdown";
@@ -35,6 +35,8 @@ export interface FeedRowData {
title?: string;
pinned?: boolean;
archived?: boolean;
+ /** Its work was marked finished; a new line opens it again. */
+ closedBy?: ThreadCloser;
}
/** What a thread row's menu does, the same as the sidebar's room thread rows. */
@@ -43,6 +45,7 @@ export interface FeedRowActions {
onDelete: (task: { threadId: string }) => void;
onPin: (task: { threadId: string; title: string }, pinned: boolean) => void;
onArchive: (task: { threadId: string }, archivedAt: number | null) => void;
+ onSetClosed: (task: { threadId: string }, closed: boolean) => void;
/** False while the room has only this thread, which it keeps. */
deletable: boolean;
}
@@ -103,10 +106,10 @@ export const RoomFeedRow = memo(function RoomFeedRow({ row, groupId, bots, you,
const [renaming, setRenaming] = useState(false);
const moreRef = useRef<HTMLButtonElement>(null);
const titled = row.title !== undefined && row.threadId !== "" && actions ? row.title : undefined;
- const task = useMemo(() => ({ threadId: row.threadId, title: titled ?? "", pinned: row.pinned, archivedAt: row.archived ? 0 : undefined, busy: row.working }),
- [row.threadId, titled, row.pinned, row.archived, row.working]);
+ const task = useMemo(() => ({ threadId: row.threadId, title: titled ?? "", pinned: row.pinned, archivedAt: row.archived ? 0 : undefined, busy: row.working, closedBy: row.closedBy }),
+ [row.threadId, titled, row.pinned, row.archived, row.working, row.closedBy]);
const menuSheet = useThreadRowMenu({ task, displayTitle: localizedTaskTitle(task.title), ownerId: groupId, menu, setMenu, actionRef: moreRef,
- onStartRename: () => { setMenu(null); setRenaming(true); }, onDelete: actions?.onDelete ?? (() => {}), onPin: actions?.onPin, onArchive: actions?.onArchive,
+ onStartRename: () => { setMenu(null); setRenaming(true); }, onDelete: actions?.onDelete ?? (() => {}), onPin: actions?.onPin, onArchive: actions?.onArchive, onSetClosed: actions?.onSetClosed,
deletable: actions?.deletable !== false });
const fromBot = "botId" in row.speaker;
const text = useMemo(() => previewText(row, fromBot), [row, fromBot]);
@@ -118,7 +121,8 @@ export const RoomFeedRow = memo(function RoomFeedRow({ row, groupId, bots, you,
const workingBot = row.workingBotId ? bots.find((bot) => bot.id === row.workingBotId) : undefined;
const replies = row.replies === 1 ? t("room.feed.replyOne") : t("room.feed.replyMany", { count: row.replies });
const markLabel = row.mark === "waiting" ? t("sidebar.preview.waiting") : row.mark === "unread" ? t("task.unread") : null;
- const label = [speaker.name, text || t("room.feed.attachment"), row.replies > 0 ? replies : t("room.feed.noReplies"), markLabel].filter(Boolean).join(", ");
+ const label = [speaker.name, text || t("room.feed.attachment"), row.replies > 0 ? replies : t("room.feed.noReplies"), row.closedBy ? t("task.closed") : null, markLabel].filter(Boolean).join(", ");
+ const quiet = row.archived || Boolean(row.closedBy);
const openMenuAt = (x: number, y: number) => setMenu(threadMenuAt(x, y));
const rename = (title: string | null) => {
setRenaming(false);
@@ -143,13 +147,14 @@ export const RoomFeedRow = memo(function RoomFeedRow({ row, groupId, bots, you,
<time dateTime={new Date(row.at).toISOString()} title={new Date(row.at).toLocaleString(intlLocale())}
className="shrink-0 text-[12px] font-medium leading-4 text-ink-tertiary tabular-nums">{threadUpdatedLabel(row.at, now)}</time>
{row.pinned && <Pin size={11} data-feed-pinned="" className="shrink-0 self-center text-ink-secondary" aria-label={t("sidebar.bot.pin")} />}
- {row.archived && <span className="min-w-0 truncate text-[12px] leading-4 text-ink-tertiary">{t("task.archived")}</span>}
+ {row.archived ? <span className="min-w-0 truncate text-[12px] leading-4 text-ink-tertiary">{t("task.archived")}</span>
+ : row.closedBy && <span data-feed-closed="" className="min-w-0 truncate text-[12px] leading-4 text-ink-tertiary">{t("task.closed")}</span>}
{markLabel && <span aria-hidden="true" data-feed-mark={row.mark} title={markLabel}
className={cn("size-2 shrink-0 self-center rounded-full", row.mark === "waiting" ? "bg-warning" : "bg-accent")} />}
</div>
{renaming && titled !== undefined ? <ThreadRenameField title={titled} onDone={rename} className="mt-1 w-full" /> : (
<div dir="auto" className={cn("chat-text mt-0.5 max-h-[110px] overflow-hidden text-[15px] leading-[22px] text-ink [overflow-wrap:anywhere]",
- long && "[mask-image:linear-gradient(to_bottom,black_60%,transparent)]", !text && "text-ink-secondary", row.archived && "text-ink-secondary")}>
+ long && "[mask-image:linear-gradient(to_bottom,black_60%,transparent)]", !text && "text-ink-secondary", quiet && "text-ink-secondary")}>
{!text ? t("room.feed.attachment")
: fromBot ? <ChatMarkdown text={text} mentionPeers={bots} everyone />
: <div className="whitespace-pre-wrap"><ThreadRefText text={text} peers={bots} everyone /></div>}
diff --git a/src/components/room-feed/RoomFeedView.tsx b/src/components/room-feed/RoomFeedView.tsx
index 9a65026173..f91c674b5f 100644
--- a/src/components/room-feed/RoomFeedView.tsx
+++ b/src/components/room-feed/RoomFeedView.tsx
@@ -4,6 +4,7 @@ import { t } from "@/lib/i18n";
import { catchUpOldMarks, openFeedThread } from "@/lib/room-feed";
import { simpleRoomHeader } from "@/lib/room-panel";
import { roomThreadAttention, roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";
+import { foldClosedRuns, threadRowCloser, unfoldStep } from "@/lib/room-thread-close";
import { useComposerDockPad } from "@/lib/composer-dock";
import { sameDrawnBots } from "@/lib/drawn-bots";
import type { Bot, Group } from "@/state/store";
@@ -47,9 +48,15 @@ function toRow(group: Group, { task, summary }: FeedThread, bots: readonly Bot[]
title: task.title,
pinned: task.pinned === true,
archived: isArchived(task),
+ closedBy: threadRowCloser(task),
};
}
+/** A closed thread folds away once nothing in it waits to be seen: not unread, not waiting, not running, not pinned and
+ * not the one open beside the feed. */
+const folds = (row: FeedRowData, openThread: string | null) =>
+ Boolean(row.closedBy) && row.mark === null && !row.working && !row.pinned && row.threadId !== openThread;
+
/** A room as one feed of its threads, oldest at the top and the newest just above the composer, where a line starts a
* new thread. A row opens its thread beside the feed; the room's current thread, which is everyone's, never moves. */
export function RoomFeedView({ group }: { group: Group }) {
@@ -94,6 +101,7 @@ export function RoomFeedView({ group }: { group: Group }) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [group.id, since]);
const [pending, setPending] = useState<{ text: string; at: number; threadId: string | null } | null>(null);
+ const [unfolded, setUnfolded] = useState<ReadonlySet<string>>(() => new Set());
const rows = useMemo(() => {
if (!threads) return null;
@@ -102,6 +110,12 @@ export function RoomFeedView({ group }: { group: Group }) {
return [...listed, { threadId: pending.threadId ?? "", speaker: { person: {} }, text: pending.text, at: pending.at, replies: 0, lastReplyAt: null,
repliers: [], mark: null, working: false, workingBotId: null } satisfies FeedRowData];
}, [threads, pending, group, bots]);
+ const items = useMemo(() => rows && foldClosedRuns(rows, (row) => folds(row, openThread), unfolded), [rows, openThread, unfolded]);
+ const unfold = useCallback((threadIds: readonly string[]) => {
+ // The fold stays where the person pressed it, and what it shows opens under it.
+ atFoot.current = false;
+ setUnfolded((shown) => new Set([...shown, ...unfoldStep({ threadIds })]));
+ }, []);
const waiting = useCallback((text: string | null) => {
setPending(text === null ? null : { text, at: Date.now(), threadId: null });
@@ -155,7 +169,7 @@ export function RoomFeedView({ group }: { group: Group }) {
className="mt-2 inline-flex h-7 items-center self-center rounded-md px-2 text-[13px] font-medium leading-4 text-ink-secondary hover:text-ink">
{showArchived ? t("room.feed.hideArchived") : t("room.feed.showArchived")}
</button>}
- {rows === null ? (
+ {rows === null || items === null ? (
failed && (
<p role="alert" className="flex items-center justify-center gap-2 py-6 text-[13px] text-ink-secondary">
{t("room.feed.loadFailed")}
@@ -166,8 +180,15 @@ export function RoomFeedView({ group }: { group: Group }) {
<p className="py-6 text-center text-[13px] text-ink-secondary">{t("room.feed.empty")}</p>
) : (
<ol aria-label={t("room.feed.aria", { name: group.name })} className="flex flex-col gap-0.5 py-2">
- {rows.map((row) => (
- <RoomFeedRow key={row.threadId || "pending"} row={row} groupId={group.id} bots={bots} you={you} now={now} open={row.threadId !== "" && row.threadId === openThread}
+ {items.map((item) => item.kind === "fold" ? (
+ <li key={`fold:${item.key}`} className="flex">
+ <button type="button" data-feed-fold={item.key} onClick={() => unfold(item.threadIds)}
+ className="ms-12 flex h-8 touch:h-10 items-center rounded-md px-2 text-[13px] font-medium leading-[18px] text-ink-secondary transition-colors duration-[120ms] hover:bg-ink/[0.06] hover:text-ink active:bg-ink/[0.08] motion-reduce:transition-none">
+ {item.threadIds.length === 1 ? t("room.feed.closedOne") : t("room.feed.closedMany", { count: item.threadIds.length })}
+ </button>
+ </li>
+ ) : (
+ <RoomFeedRow key={item.row.threadId || "pending"} row={item.row} groupId={group.id} bots={bots} you={you} now={now} open={item.row.threadId !== "" && item.row.threadId === openThread}
onOpen={open} actions={actions} />
))}
</ol>
diff --git a/src/components/room-feed/ThreadPanelHeading.tsx b/src/components/room-feed/ThreadPanelHeading.tsx
index 4c08105a8a..de87a50242 100644
--- a/src/components/room-feed/ThreadPanelHeading.tsx
+++ b/src/components/room-feed/ThreadPanelHeading.tsx
@@ -4,11 +4,12 @@ import { requestChatFind } from "@/lib/chat-find";
import { copyTranscriptToClipboard, downloadMarkdownTranscript, formatTranscriptMarkdown, slugifyTranscriptFilename } from "@/lib/export-transcript";
import { t } from "@/lib/i18n";
import { localizedTaskTitle } from "@/lib/task-title";
+import { threadRowCloser } from "@/lib/room-thread-close";
import type { Group, GroupTask, Message } from "@/state/store";
import { useStoreRef } from "@/state/store-ref";
import { PRESET_TURN_LIMITS, useConversationTurnLimit } from "../ConversationTurnLimit";
import { roomThreadRowActions } from "../SidebarGroupThreadList";
-import { THREAD_MENU_WIDTH, threadMenuAt, useThreadRowMenu, type ThreadMenuAt } from "../SidebarThreadRow";
+import { THREAD_MENU_WIDTH, threadMenuAt, threadUpdatedLabel, useRelativeNow, useThreadRowMenu, type ThreadMenuAt } from "../SidebarThreadRow";
import { ThreadRenameField } from "./ThreadRenameField";
const ITEM = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover disabled:opacity-40";
@@ -23,8 +24,10 @@ export function ThreadPanelHeading({ group, task, messages, working }: { group:
const [renaming, setRenaming] = useState(false);
const moreRef = useRef<HTMLButtonElement>(null);
const title = localizedTaskTitle(task.title);
- const row = useMemo(() => ({ threadId: task.threadId, title: task.title, pinned: task.pinned, archivedAt: task.archivedAt, busy: working }),
- [task.threadId, task.title, task.pinned, task.archivedAt, working]);
+ const closer = useMemo(() => threadRowCloser(task), [task]);
+ const row = useMemo(() => ({ threadId: task.threadId, title: task.title, pinned: task.pinned, archivedAt: task.archivedAt, busy: working, closedBy: closer }),
+ [task.threadId, task.title, task.pinned, task.archivedAt, working, closer]);
+ const now = useRelativeNow();
const actions = useMemo(() => roomThreadRowActions(group.id, dispatch), [group.id, dispatch]);
const close = () => dispatch({ type: "closeForkPanel" });
const markdown = () => formatTranscriptMarkdown({ title: task.title, messages, isGroup: true });
@@ -39,6 +42,7 @@ export function ThreadPanelHeading({ group, task, messages, working }: { group:
onStartRename: () => { setMenu(null); setRenaming(true); },
onDelete: (thread) => { close(); actions.onDelete(thread); },
onPin: actions.onPin,
+ onSetClosed: actions.onSetClosed,
onArchive: (thread, archivedAt) => { if (archivedAt !== null) close(); actions.onArchive(thread, archivedAt); },
deletable: (group.tasks?.length ?? 1) > 1,
extra: (done) => <>
@@ -69,8 +73,13 @@ export function ThreadPanelHeading({ group, task, messages, working }: { group:
{renaming
? <ThreadRenameField title={task.title} className="block h-5 w-full px-1 py-0 text-[15px] font-semibold leading-5" onDone={(next) => { setRenaming(false); if (next) actions.onRename(task, next); }} />
: <h2 dir="auto" title={title} className="truncate text-[15px] font-semibold leading-5 text-ink">{title}</h2>}
- <p dir="auto" className="truncate text-[12px] leading-4 text-ink-secondary">{group.name}</p>
+ {closer
+ ? <p data-thread-closed="" className="truncate text-[12px] leading-4 text-ink-tertiary">
+ {t("room.thread.closedBy", { name: closer.name, when: threadUpdatedLabel(closer.at, now) })}
+ </p>
+ : <p dir="auto" className="truncate text-[12px] leading-4 text-ink-secondary">{group.name}</p>}
</div>
+ {closer && <button type="button" data-thread-reopen="" className="ui-button ui-button-sm shrink-0" onClick={() => actions.onSetClosed(task, false)}>{t("task.reopenThread")}</button>}
<button ref={moreRef} type="button" aria-label={t("task.actions", { title })} title={t("task.actions", { title })} aria-expanded={Boolean(menu)}
className="ui-icon-button shrink-0"
onClick={(event) => { if (menu) { setMenu(null); return; } const rect = event.currentTarget.getBoundingClientRect(); setMenu(threadMenuAt(rect.right - THREAD_MENU_WIDTH, rect.bottom)); }}>
diff --git a/src/lib/room-thread-close.test.ts b/src/lib/room-thread-close.test.ts
new file mode 100644
index 0000000000..0b1aa15b06
--- /dev/null
+++ b/src/lib/room-thread-close.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+import { FOLD_STEP, foldClosedRuns, threadRowCloser, unfoldStep } from "./room-thread-close";
+
+const rows = (spec: string) => [...spec].map((mark, index) => ({ threadId: `t${index}`, closed: mark === "c" }));
+const shape = (items: ReturnType<typeof foldClosedRuns<{ threadId: string; closed: boolean }>>) =>
+ items.map((item) => item.kind === "fold" ? `fold(${item.key}:${item.threadIds.length})` : item.row.threadId);
+const none = new Set<string>();
+
+describe("folding a room feed's closed threads", () => {
+ it("folds each run of consecutive closed threads into one row, and leaves open ones alone", () => {
+ expect(shape(foldClosedRuns(rows("occcoc"), (row) => row.closed, none))).toEqual(["t0", "fold(t1:3)", "t4", "fold(t5:1)"]);
+ expect(shape(foldClosedRuns(rows("ooo"), (row) => row.closed, none))).toEqual(["t0", "t1", "t2"]);
+ expect(foldClosedRuns([], () => true, none)).toEqual([]);
+ });
+
+ it("unfolds a run in place, the newest of it first, ten at a time, and keeps what it showed when the run splits", () => {
+ const many = rows(`o${"c".repeat(25)}o`);
+ const closed = (row: { closed: boolean }) => row.closed;
+ const [, fold] = foldClosedRuns(many, closed, none);
+ const once = new Set(unfoldStep(fold as { threadIds: string[] }));
+ expect(once.size).toBe(FOLD_STEP);
+ const shown = shape(foldClosedRuns(many, closed, once));
+ expect(shown.slice(0, 2)).toEqual(["t0", "fold(t1:15)"]);
+ expect(shown.slice(2)).toEqual([...Array.from({ length: 10 }, (_, i) => `t${16 + i}`), "t26"]);
+ const split = shape(foldClosedRuns(many, (row) => closed(row) && row.threadId !== "t20", once));
+ expect(split).toEqual(shown);
+ });
+
+ it("keeps a closed thread with news out of the fold, splitting the run around it", () => {
+ const feed = rows("cccc").map((row) => ({ ...row, unread: row.threadId === "t2" }));
+ expect(shape(foldClosedRuns(feed, (row) => row.closed && !row.unread, none))).toEqual(["fold(t0:2)", "t2", "fold(t3:1)"]);
+ });
+
+ it("reads a room thread's close as a thread row's close", () => {
+ expect(threadRowCloser({})).toBeUndefined();
+ expect(threadRowCloser({ closedAt: 5, closedBy: { kind: "bot", id: "b1", name: "Writer" } })).toEqual({ botId: "b1", name: "Writer", at: 5 });
+ });
+});
diff --git a/src/lib/room-thread-close.ts b/src/lib/room-thread-close.ts
new file mode 100644
index 0000000000..252b0f5b4d
--- /dev/null
+++ b/src/lib/room-thread-close.ts
@@ -0,0 +1,37 @@
+import type { Dispatch } from "react";
+import { api, type Action, type GroupTask, type ThreadCloser } from "@/state/store";
+
+/** How many more of a fold's closed threads one press shows. */
+export const FOLD_STEP = 10;
+
+export const isClosed = (task: Pick<GroupTask, "closedAt">): boolean => task.closedAt !== undefined;
+
+/** A room thread's close as a thread row's menu and byline read a close. */
+export function threadRowCloser(task: Pick<GroupTask, "closedAt" | "closedBy">): ThreadCloser | undefined {
+ return task.closedAt === undefined ? undefined : { botId: task.closedBy?.id ?? "", name: task.closedBy?.name ?? "", at: task.closedAt };
+}
+
+/** Everyone's feed follows from the room's frame, which the server sends once the change is saved. */
+export function setRoomThreadClosed(groupId: string, threadId: string, closed: boolean, dispatch: Dispatch<Action>): void {
+ void api(`/api/groups/${groupId}/tasks/${threadId}`, { method: "PATCH", body: JSON.stringify({ closed }) })
+ .catch((cause) => dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }));
+}
+
+export type FeedItem<Row> = { kind: "row"; row: Row } | { kind: "fold"; key: string; threadIds: string[] };
+
+/** A feed's rows with each run of consecutive rows that `folds` (closed, with nothing new) and the person has not opened
+ * as one fold. A thread once shown stays shown, wherever its run later splits. */
+export function foldClosedRuns<Row extends { threadId: string }>(rows: readonly Row[], folds: (row: Row) => boolean,
+ shown: ReadonlySet<string>): FeedItem<Row>[] {
+ const items: FeedItem<Row>[] = [];
+ for (const row of rows) {
+ if (!folds(row) || shown.has(row.threadId)) { items.push({ kind: "row", row }); continue; }
+ const last = items.at(-1);
+ if (last?.kind === "fold") last.threadIds.push(row.threadId);
+ else items.push({ kind: "fold", key: row.threadId, threadIds: [row.threadId] });
+ }
+ return items;
+}
+
+/** What one press on a fold shows: its newest FOLD_STEP threads, the ones nearest the rows under it. */
+export const unfoldStep = (fold: { threadIds: readonly string[] }): string[] => fold.threadIds.slice(-FOLD_STEP);
diff --git a/src/locales/de.json b/src/locales/de.json
index 6f0d17e852..45d879af22 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -1349,6 +1349,8 @@
"task.updated.hours": "vor {count} Std.",
"task.updated.yesterday": "gestern",
"task.updated.days": "vor {count} T.",
+ "task.closeThread": "Abschließen",
+ "task.reopenThread": "Wieder öffnen",
"task.helperGroup": "Von Bots geöffnet",
"model.backTo": "Zurück zu den {name}-Modellen",
"model.afterSetupOne": "Nach der Einrichtung erscheint 1 Modell.",
@@ -4463,10 +4465,13 @@
"room.feed.hideArchived": "Archivierte Threads ausblenden",
"room.feed.unreadAbove": "Ungelesener Thread weiter oben",
"room.feed.unreadBelow": "Ungelesener Thread weiter unten",
+ "room.feed.closedOne": "1 abgeschlossener Thread",
+ "room.feed.closedMany": "{count} abgeschlossene Threads",
"room.thread.panel": "Thread",
"room.thread.close": "Thread schließen",
"room.thread.backToFeed": "Zurück zu {name}",
"room.thread.resize": "Thread-Breite ändern",
+ "room.thread.closedBy": "Abgeschlossen von {name} · {when}",
"settings.features.teamBoard": "Board",
"settings.features.teamBoardLine": "Verfolge Arbeit in Gruppenchats als Einträge mit Status, Labels und dem, worauf jeder wartet",
"settings.features.error": "Das konnte nicht gespeichert werden. Prüfe deine Verbindung und versuche es erneut.",
diff --git a/src/locales/en.json b/src/locales/en.json
index af0ee37da0..bcb44e53c5 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -3528,6 +3528,8 @@
"task.updated.hours": "{count} h ago",
"task.updated.yesterday": "yesterday",
"task.updated.days": "{count} d ago",
+ "task.closeThread": "Close",
+ "task.reopenThread": "Reopen",
"task.unreadMany": "Unread threads",
"task.deleteConfirm": "Delete thread?",
"task.deleteBody": "“{title}” and its conversation will be deleted. This cannot be undone.",
@@ -12103,10 +12105,13 @@
"room.feed.hideArchived": "Hide archived threads",
"room.feed.unreadAbove": "Unread thread above",
"room.feed.unreadBelow": "Unread thread below",
+ "room.feed.closedOne": "1 closed thread",
+ "room.feed.closedMany": "{count} closed threads",
"room.thread.panel": "Thread",
"room.thread.close": "Close thread",
"room.thread.backToFeed": "Back to {name}",
"room.thread.resize": "Resize thread",
+ "room.thread.closedBy": "Closed by {name} · {when}",
"settings.features.teamBoard": "Board",
"settings.features.teamBoardLine": "Track work in group chats as items with a state, labels and what each one waits for",
"settings.features.error": "Couldn't save that. Check your connection and try again.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index ae0f50087e..7bd9f57117 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -3309,6 +3309,8 @@
"task.updated.hours": "há {count} h",
"task.updated.yesterday": "ontem",
"task.updated.days": "há {count} d",
+ "task.closeThread": "Encerrar",
+ "task.reopenThread": "Reabrir",
"task.unreadMany": "Conversas não lidas",
"task.deleteConfirm": "Excluir conversa?",
"task.deleteBody": "A conversa “{title}” e suas mensagens serão excluídas. Não dá para desfazer.",
@@ -12103,10 +12105,13 @@
"room.feed.hideArchived": "Ocultar conversas arquivadas",
"room.feed.unreadAbove": "Conversa não lida acima",
"room.feed.unreadBelow": "Conversa não lida abaixo",
+ "room.feed.closedOne": "1 conversa encerrada",
+ "room.feed.closedMany": "{count} conversas encerradas",
"room.thread.panel": "Conversa",
"room.thread.close": "Fechar conversa",
"room.thread.backToFeed": "Voltar para {name}",
"room.thread.resize": "Redimensionar conversa",
+ "room.thread.closedBy": "Encerrada por {name} · {when}",
"settings.features.teamBoard": "Quadro",
"settings.features.teamBoardLine": "Acompanhe o trabalho nos chats em grupo como itens com status, rótulos e o que cada um espera",
"settings.features.error": "Não foi possível salvar. Verifique sua conexão e tente de novo.",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 9c102bf3a3..29feddb6ce 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -204,7 +204,7 @@ export interface GroupTask {
pinned?: boolean;
updatedAt?: number;
turnTimeoutMinutes?: number;
- archivedAt?: number; activity?: "waiting-on-you";
+ archivedAt?: number; activity?: "waiting-on-you"; closedAt?: number; closedBy?: import("../../shared/room-threads").RoomThreadCloser;
lastThreadOrderAt?: number;
working?: boolean;
busyBotId?: string | null;