Skip to content

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

Refuse someone else's retry on the server; remove a deleted conversation's and bot's leftover files (#5336)

Milind Soni1ca2f3c5876b
diff --git a/docs/team-cloud.md b/docs/team-cloud.md
index 743ded5701..d7c899b2fc 100644
--- a/docs/team-cloud.md
+++ b/docs/team-cloud.md
@@ -444,6 +444,17 @@ engine writes its copy, and the next spawn in any audience takes the newest sett
or out from the app still happens in the server's HOME and reaches every audience's next turn. Session resume works
within an audience: its home is the same at each turn. A member who leaves takes their engine home with them.
+**Deleting.** A deleted conversation takes its Claude Code and Codex session files with it, from every audience's home
+(`server/host/delete-leftovers.ts`): the session it resumes and every session its event log says it started, unless a
+conversation that stays still resumes the same one. The files uploaded to it go too when no other conversation, picture
+or routine names them, and so does its box uploads folder. A deleted bot also takes its checkpoints
+(`checkpoints/<bot>`), its memory journal and the room and member memory layers kept beside its own folder. Nothing is reached through a link, and a cleanup that fails is logged
+(`delete leftovers: … stayed behind`) and never fails the delete. Still left: sessions kept by the other engines
+(OpenCode, Gemini and the rest of the ACP family, Muse), which only the engine itself can remove; the bot's
+per-folder checkpoints, which its conversations share, until the bot is deleted; and anything on a computer other than
+this server. Kept on purpose: a conversation's own folder (`task-workspaces/<bot>/<thread>`) holds the files the bot
+made for the person, and stays when the conversation or the bot is deleted.
+
**The move.** The first turn after a Team Cloud starts with engine homes moves what the engines kept in the server's
HOME. A Claude Code project's session (`projects/<folder>/<session>.jsonl` and its session folder, `file-history`,
`session-env`, `todos`, `debug`) or a Codex rollout (`sessions/…/rollout-…-<id>.jsonl`, `archived_sessions`) goes to
@@ -694,7 +705,11 @@ run belongs to the person whose own request it answers (`server/host/run-owner.t
`/api/groups/<id>/interrupt`, a typed "stop", a guarded request's `/interrupt`) from anyone else answers 403 with
`code: "stop_not_yours"` and *"Only Priya or an admin can stop this."*; their "@Scout stop" in a group chat is an
ordinary line there. Stop stays the only interrupt. The app shows Stop, and Retry on a stopped request, only to the
- asker and to Owners and Admins (and to everyone for a run no person asked for). The stopped row records who pressed
+ asker and to Owners and Admins (and to everyone for a run no person asked for). The server holds Retry to the same
+ rule: running someone else's request again (`POST /api/bots/<bot>/messages/<id>/edit`, with the same words or new
+ ones) answers 403 with `code: "retry_not_yours"` and *"Only Priya or an admin can run this request again."* In a
+ shared conversation this rule alone decides it, whoever opened the conversation; renaming, deleting or otherwise
+ changing the conversation itself stays with whoever opened it and the Owner's side. The stopped row records who pressed
Stop (`WireMessage.stoppedBy`): it reads "Maya stopped this." to everyone else and "You stopped this." to Maya.
- **Who asked, for what is not a person's line** (read from the records the provenance labels come from, never from
model text). A routine, a webhook and an app's event never run in a person's conversation: each runs in its own and
diff --git a/server/cloud-team-asker-owns.e2e.test.ts b/server/cloud-team-asker-owns.e2e.test.ts
index 145c5a4398..74ce106d2c 100644
--- a/server/cloud-team-asker-owns.e2e.test.ts
+++ b/server/cloud-team-asker-owns.e2e.test.ts
@@ -149,6 +149,41 @@ it("Priya can stop her own run", async () => {
{ timeout: hostTimeout(10_000), interval: 100 }).toBe("Priya");
}, hostTimeout(120_000));
+it("in the shared chat Ada started, Priya retries and rewords her own stopped request; Tom cannot, and nobody but Ada's side renames or deletes the chat", async () => {
+ await priyaRuns();
+ expect((await team.as(priya, "POST", `/api/bots/${botId}/interrupt`, { threadId: shared })).status).toBe(200);
+ await expect.poll(() => busy(), { timeout: hostTimeout(30_000), interval: 100 }).toBe(false);
+ const request = (await transcript(priya)).findLast((row) => row.role === "user" && row.kind === "text" && row.text === PRIYA_ASK)!;
+ const edit = (token: string, text: string) => team.as(token, "POST", `/api/bots/${botId}/messages/${request.id}/edit`, { text, threadId: shared });
+ const answeredAfter = (rows: Row[], id: string) => {
+ const at = rows.findIndex((row) => row.id === id);
+ return at >= 0 && rows.slice(at).some((row) => row.role === "bot" && row.kind === "text");
+ };
+
+ for (const text of [PRIYA_ASK, `${PRIYA_ASK} again`]) {
+ const refused = await edit(tom, text);
+ expect(refused.status, JSON.stringify(refused.body)).toBe(403);
+ expect(refused.body).toMatchObject({ error: "Only Priya or an admin can run this request again.", code: "retry_not_yours" });
+ }
+ for (const token of [priya, tom]) {
+ const renamed = await team.as(token, "PATCH", `/api/bots/${botId}/tasks/${shared}`, { title: "Mine now" });
+ expect(renamed.status, JSON.stringify(renamed.body)).toBe(403);
+ expect(renamed.body.error).toBe("On this Cloud you can only change conversations you started.");
+ const deleted = await team.as(token, "DELETE", `/api/bots/${botId}/tasks/${shared}`);
+ expect(deleted.status, JSON.stringify(deleted.body)).toBe(403);
+ expect(deleted.body.error).toBe("On this Cloud you can only change conversations you started.");
+ }
+ expect(await busy(), "nothing ran for a refusal").toBe(false);
+
+ for (const text of [PRIYA_ASK, `${PRIYA_ASK} again`]) {
+ const retried = await edit(priya, text);
+ expect(retried.status, JSON.stringify(retried.body)).toBe(202);
+ expect(retried.body.message.sender?.name).toBe("Priya");
+ await expect.poll(async () => answeredAfter(await transcript(ada), retried.body.message.id), { timeout: hostTimeout(60_000), interval: 100 }).toBe(true);
+ await release();
+ }
+}, hostTimeout(180_000));
+
it("Priya adding to her own run in the shared chat is steered into it, and person-first still answers her first", async () => {
await priyaRuns();
const stopsBefore = await personFirstStops();
diff --git a/server/host/delete-leftovers.store.test.ts b/server/host/delete-leftovers.store.test.ts
new file mode 100644
index 0000000000..d3b079a5b0
--- /dev/null
+++ b/server/host/delete-leftovers.store.test.ts
@@ -0,0 +1,125 @@
+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { DATA_DIR } from "../config.ts";
+import type { ModelSelection } from "../contracts.ts";
+import { journalFile } from "../memory-journal.ts";
+import * as mdb from "../message-db.ts";
+import { Store } from "../store.ts";
+import { createDeleteLeftovers, engineSessionFolders, type DeleteLeftoversDeps } from "./delete-leftovers.ts";
+import { memoryLayerRecords } from "./team-member-left.ts";
+
+const selection = (): ModelSelection => ({ instanceId: "claude", model: "claude-sonnet-5" });
+const SESSION = "11111111-1111-4111-8111-111111111111";
+const UPLOAD = "00000001-0000-4000-8000-000000000000.png";
+const HOME = join(DATA_DIR, "fixture-engine-home");
+
+function put(path: string): string {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "x");
+ return path;
+}
+
+function fixture(over: Partial<DeleteLeftoversDeps> = {}) {
+ const store = new Store(selection);
+ const warnings: string[] = [];
+ const leftovers = createDeleteLeftovers({
+ dataDir: DATA_DIR,
+ store,
+ threadsReferencing: mdb.threadsReferencing,
+ keptAttachments: () => new Set(),
+ deleteAttachment: (name) => rmSync(join(DATA_DIR, "attachments", name)),
+ engineFolders: () => engineSessionFolders(DATA_DIR, [{ HOME }]),
+ layers: memoryLayerRecords,
+ defer: () => {},
+ warn: (line) => { warnings.push(line); },
+ ...over,
+ });
+ const bot = store.createBot({ name: "Scout" });
+ const task = store.createTask(bot.id, "Launch post", false)!;
+ store.appendMessage(task.threadId, { role: "user", kind: "text", text: `![image](/api/attachments/${UPLOAD})` });
+ store.setResumeCursor(bot.id, "claude", SESSION, task.threadId);
+ const files = {
+ upload: put(join(DATA_DIR, "attachments", UPLOAD)),
+ session: put(join(HOME, ".claude", "projects", "-work", `${SESSION}.jsonl`)),
+ boxUploads: put(join(DATA_DIR, "box-uploads", bot.id, task.threadId, UPLOAD)),
+ };
+ return { store, bot, task, files, warnings, leftovers };
+}
+
+describe("deleting through the store", () => {
+ beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+
+ it("removes a deleted conversation's upload, engine session and box uploads, and keeps the files it made", () => {
+ const { store, bot, task, files, leftovers } = fixture();
+ const made = put(join(DATA_DIR, "task-workspaces", bot.id, task.threadId, "result.txt"));
+ expect(store.deleteTask(bot.id, task.threadId)).not.toBeNull();
+ leftovers.flush();
+ expect(Object.values(files).filter(existsSync)).toEqual([]);
+ expect(existsSync(made)).toBe(true);
+ });
+
+ it("keeps an upload a conversation that stays also shows", () => {
+ const { store, bot, task, files, leftovers } = fixture();
+ store.appendMessage(bot.threadId, { role: "user", kind: "text", text: `![image](/api/attachments/${UPLOAD})` });
+ store.deleteTask(bot.id, task.threadId);
+ leftovers.flush();
+ expect([existsSync(files.upload), existsSync(files.session)]).toEqual([true, false]);
+ });
+
+ it("removes nothing when the delete itself fails", () => {
+ const { store, bot, task, files, leftovers } = fixture();
+ vi.spyOn(store as unknown as { commitBotChange: () => void }, "commitBotChange").mockImplementationOnce(() => { throw new Error("fixture write failure"); });
+ expect(() => store.deleteTask(bot.id, task.threadId)).toThrow("fixture write failure");
+ leftovers.flush();
+ expect(store.messagesFor(task.threadId)).toHaveLength(1);
+ expect(Object.values(files).filter((path) => !existsSync(path))).toEqual([]);
+ });
+
+ it("deletes the conversation even when the cleanup fails", () => {
+ const { store, bot, task, files, warnings, leftovers } = fixture({
+ deleteAttachment: () => { throw new Error("disk is read-only"); },
+ engineFolders: () => { throw new Error("no engine folders"); },
+ });
+ expect(store.deleteTask(bot.id, task.threadId)).not.toBeNull();
+ expect(() => leftovers.flush()).not.toThrow();
+ expect(store.taskByThread(bot.id, task.threadId)).toBeFalsy();
+ expect(mdb.threadsReferencing(UPLOAD)).toEqual([]);
+ expect(existsSync(files.upload)).toBe(true);
+ expect(warnings).toEqual([
+ `delete leftovers: the upload ${UPLOAD} stayed behind: disk is read-only`,
+ "delete leftovers: engine sessions stayed behind: no engine folders",
+ ]);
+ });
+
+ it("removes a deleted bot's uploads, sessions, checkpoints, memory layers and memory journal, and keeps the files it made", () => {
+ const { store, bot, files, leftovers } = fixture();
+ const layer = `${bot.id}--member-p_bobbobbobbobbobbobbobb`;
+ const mine = [
+ ...Object.values(files),
+ put(join(DATA_DIR, "checkpoints", bot.id, "0123456789abcdef", ".git", "HEAD")),
+ put(join(DATA_DIR, "workspaces", layer, "memory", "notes.md")),
+ put(journalFile(layer)),
+ put(journalFile(bot.id)),
+ ];
+ const other = store.createBot({ name: "Ledger" });
+ const others = [put(join(DATA_DIR, "checkpoints", other.id, "0123456789abcdef", ".git", "HEAD")), put(journalFile(other.id)), put(join(DATA_DIR, "task-workspaces", bot.id, bot.threadId, "result.txt"))];
+ expect(store.deleteBot(bot.id)).toBe(true);
+ leftovers.flush();
+ expect(mine.filter(existsSync)).toEqual([]);
+ expect(others.filter((path) => !existsSync(path))).toEqual([]);
+ });
+
+ it("removes a deleted group chat's uploads", () => {
+ const { store, bot, leftovers } = fixture();
+ const other = store.createBot({ name: "Ledger" });
+ const room = store.createGroup("Launch team", [bot.id, other.id], false);
+ const name = "00000002-0000-4000-8000-000000000000.png";
+ const upload = put(join(DATA_DIR, "attachments", name));
+ store.appendMessage(room.threadId, { role: "user", kind: "text", text: `![image](/api/attachments/${name})` });
+ expect(store.deleteGroup(room.id)).toBe(true);
+ leftovers.flush();
+ expect(existsSync(upload)).toBe(false);
+ });
+});
diff --git a/server/host/delete-leftovers.test.ts b/server/host/delete-leftovers.test.ts
new file mode 100644
index 0000000000..182f132251
--- /dev/null
+++ b/server/host/delete-leftovers.test.ts
@@ -0,0 +1,340 @@
+import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createDeleteLeftovers, engineSessionFolders, instanceEnvironment, plainlyUnder, removeMemoryLayer, removeUnder, type DeleteLeftoversDeps } from "./delete-leftovers.ts";
+
+const SESSION = "11111111-1111-4111-8111-111111111111";
+const LOGGED = "22222222-2222-4222-8222-222222222222";
+const SHARED = "33333333-3333-4333-8333-333333333333";
+const upload = (n: number) => `0000000${n}-0000-4000-8000-000000000000.png`;
+const MEMBER = "p_bobbobbobbobbobbobbobb";
+
+const made: string[] = [];
+afterEach(() => {
+ for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+function put(path: string, text = "x"): string {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, text);
+ return path;
+}
+
+type Task = { threadId: string; resumeCursors?: Record<string, unknown> };
+type Bot = { id: string; threadId?: string; resumeCursors?: Record<string, unknown>; tasks?: Task[] };
+
+function fixture(over: Partial<DeleteLeftoversDeps> = {}) {
+ const sandbox = mkdtempSync(join(tmpdir(), "omb-delete-leftovers-"));
+ made.push(sandbox);
+ const dataDir = join(sandbox, "data");
+ const home = join(sandbox, "home");
+ const outside = join(sandbox, "outside");
+ for (const dir of [join(dataDir, "attachments"), home, outside]) mkdirSync(dir, { recursive: true });
+ const messages = new Map<string, unknown[]>();
+ const bots: Bot[] = [];
+ const kept = new Set<string>();
+ const warnings: string[] = [];
+ const forgotten: string[] = [];
+ let listener: (change: { type: string; threadId?: string; botId?: string }) => void = () => {};
+ const store: DeleteLeftoversDeps["store"] = { get bots() { return bots; }, messagesFor: (threadId) => messages.get(threadId) ?? [], onChange: (added) => { listener = added; }, threadsGoing: () => {} };
+ const leftovers = createDeleteLeftovers({
+ dataDir,
+ store,
+ threadsReferencing: (fragment) => [...messages].filter(([, list]) => JSON.stringify(list).includes(fragment)).map(([threadId]) => threadId),
+ keptAttachments: () => kept,
+ deleteAttachment: (name) => rmSync(join(dataDir, "attachments", name)),
+ engineFolders: () => engineSessionFolders(dataDir, [{ HOME: home }]),
+ layers: { journalFile: (layer) => join(dataDir, "memory-journal", `${layer}.ndjson`), forget: (layer) => { forgotten.push(layer); } },
+ defer: () => {},
+ warn: (line) => { warnings.push(line); },
+ ...over,
+ });
+ const say = (threadId: string, ...names: string[]) => {
+ messages.set(threadId, names.map((name) => ({ role: "user", kind: "text", text: `![image](/api/attachments/${name})` })));
+ for (const name of names) put(join(dataDir, "attachments", name));
+ };
+ /** The store's own order: told before, the transcript and the record go, told after. */
+ const deleteThreads = (...threadIds: string[]) => {
+ store.threadsGoing(threadIds);
+ for (const threadId of threadIds) {
+ messages.delete(threadId);
+ for (const bot of bots) bot.tasks = bot.tasks?.filter((task) => task.threadId !== threadId);
+ listener({ type: "thread.deleted", threadId });
+ }
+ leftovers.flush();
+ };
+ const deleteBot = (botId: string) => {
+ const bot = bots.find((one) => one.id === botId)!;
+ const threadIds = (bot.tasks ?? []).map((task) => task.threadId);
+ store.threadsGoing(threadIds);
+ bots.splice(bots.indexOf(bot), 1);
+ for (const threadId of threadIds) {
+ messages.delete(threadId);
+ listener({ type: "thread.deleted", threadId });
+ }
+ listener({ type: "bot.deleted", botId });
+ leftovers.flush();
+ };
+ const stored = (name: string) => existsSync(join(dataDir, "attachments", name));
+ const logSession = (threadId: string, sessionId: string) =>
+ put(join(dataDir, "events", `${threadId}.ndjson`), `${JSON.stringify({ type: "session.started", threadId, sessionId })}\n`);
+ return { sandbox, dataDir, home, outside, messages, bots, kept, warnings, forgotten, say, deleteThreads, deleteBot, stored, logSession, store, leftovers };
+}
+
+describe("a deleted conversation's uploads", () => {
+ it("go with it", () => {
+ const { bots, say, deleteThreads, stored } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }, { threadId: "t2" }] });
+ say("t1", upload(1));
+ deleteThreads("t1");
+ expect(stored(upload(1))).toBe(false);
+ });
+
+ it("stay while another conversation, a picture, a member's picture or a routine still names them", () => {
+ const { dataDir, bots, kept, say, deleteThreads, stored } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }, { threadId: "t2" }] });
+ say("t2", upload(1));
+ say("t1", upload(1), upload(2), upload(3), upload(4));
+ kept.add(upload(2));
+ put(join(dataDir, "people", MEMBER, "profile.json"), JSON.stringify({ name: "Bob", avatarUrl: `/api/attachments/${upload(4)}` }));
+ deleteThreads("t1");
+ expect([stored(upload(1)), stored(upload(2)), stored(upload(3)), stored(upload(4))]).toEqual([true, true, false, true]);
+ });
+
+ it("go once every conversation that named them is deleted together", () => {
+ const { bots, say, deleteThreads, stored } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }, { threadId: "t2" }, { threadId: "t3" }] });
+ say("t1", upload(1));
+ say("t2", upload(1));
+ deleteThreads("t1", "t2");
+ expect(stored(upload(1))).toBe(false);
+ });
+
+ it("stay when the delete did not happen", () => {
+ const { bots, say, store, leftovers, stored } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });
+ say("t1", upload(1));
+ store.threadsGoing(["t1"]);
+ leftovers.flush();
+ expect(stored(upload(1))).toBe(true);
+ });
+
+ it("stay, with a warning, while what still uses uploads cannot be read", () => {
+ const { bots, say, deleteThreads, stored, warnings } = fixture({ keptAttachments: () => null });
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });
+ say("t1", upload(1));
+ deleteThreads("t1");
+ expect(stored(upload(1))).toBe(true);
+ expect(warnings.join("\n")).toContain("uploads stayed behind");
+ });
+
+ it("never reach a file outside attachments/ a message names", () => {
+ const { dataDir, bots, messages, deleteThreads } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });
+ const config = put(join(dataDir, "config.json"));
+ messages.set("t1", [{ text: "attachments/../config.json and attachments/..\\config.json" }]);
+ deleteThreads("t1");
+ expect(existsSync(config)).toBe(true);
+ });
+
+ it("take the conversation's box uploads folder too", () => {
+ const { dataDir, bots, deleteThreads } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }, { threadId: "t2" }] });
+ const mine = put(join(dataDir, "box-uploads", "scout", "t1", upload(1)));
+ const others = put(join(dataDir, "box-uploads", "scout", "t2", upload(2)));
+ deleteThreads("t1");
+ expect([existsSync(dirname(mine)), existsSync(others)]).toEqual([false, true]);
+ });
+});
+
+describe("a deleted conversation's engine sessions", () => {
+ it("go from Claude's and Codex's folders, by the session it resumes and the ones its log says it started", () => {
+ const { home, bots, deleteThreads, logSession } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SESSION } }, { threadId: "t2", resumeCursors: { claude: SHARED } }] });
+ logSession("t1", LOGGED);
+ const claude = join(home, ".claude");
+ const mine = [
+ put(join(claude, "projects", "-work-site", `${SESSION}.jsonl`)),
+ put(join(claude, "projects", "-work-site", SESSION, "subagents", "agent-1.jsonl")),
+ put(join(claude, "projects", "-work-other", `${LOGGED}.jsonl`)),
+ put(join(claude, "file-history", SESSION, "a@v1")),
+ put(join(claude, "session-env", SESSION, "env")),
+ put(join(claude, "todos", `${SESSION}-agent-${SESSION}.json`)),
+ put(join(claude, "debug", `${SESSION}.txt`)),
+ put(join(home, ".codex", "sessions", "2026", "11", "10", `rollout-2026-11-10T10-00-00-${SESSION}.jsonl`)),
+ put(join(home, ".codex", "archived_sessions", `rollout-2026-11-09T10-00-00-${LOGGED}.jsonl`)),
+ ];
+ const others = [
+ put(join(claude, "projects", "-work-site", `${SHARED}.jsonl`)),
+ put(join(claude, ".credentials.json")),
+ put(join(claude, "history.jsonl")),
+ put(join(home, ".codex", "sessions", "2026", "11", "10", `rollout-2026-11-10T11-00-00-${SHARED}.jsonl`)),
+ put(join(home, ".codex", "auth.json")),
+ ];
+ deleteThreads("t1");
+ expect(mine.filter(existsSync)).toEqual([]);
+ expect(others.filter((path) => !existsSync(path))).toEqual([]);
+ });
+
+ it("stay while a remaining conversation resumes the same session", () => {
+ const { home, bots, deleteThreads, logSession } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SHARED } }, { threadId: "fork", resumeCursors: { claude: SHARED } }] });
+ logSession("t1", SHARED);
+ const session = put(join(home, ".claude", "projects", "-work", `${SHARED}.jsonl`));
+ deleteThreads("t1");
+ expect(existsSync(session)).toBe(true);
+ deleteThreads("fork");
+ expect(existsSync(session)).toBe(false);
+ });
+
+ it("go from every audience's engine home on a Team Cloud", () => {
+ const sessions = (dataDir: string) => engineSessionFolders(dataDir, ["team", "member-0123456789abcdef"].map((key) => ({ HOME: join(dataDir, "engine-homes", key) })));
+ let dataDirOf = "";
+ const { dataDir, bots, deleteThreads } = fixture({ engineFolders: () => sessions(dataDirOf) });
+ dataDirOf = dataDir;
+ bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SESSION, codex: LOGGED } }, { threadId: "t2" }] });
+ const team = put(join(dataDir, "engine-homes", "team", ".claude", "projects", "-work", `${SESSION}.jsonl`));
+ const member = put(join(dataDir, "engine-homes", "member-0123456789abcdef", ".codex", "sessions", "2026", "11", "10", `rollout-x-${LOGGED}.jsonl`));
+ deleteThreads("t1");
+ expect([existsSync(team), existsSync(member)]).toEqual([false, false]);
+ });
+
+ it("removes a Pi session, which is named by its file, only inside Pi's own folder", () => {
+ const { home, outside, bots, deleteThreads } = fixture();
+ const mine = put(join(home, ".pi", "agent", "sessions", "--work--", "2026-11-10_a.jsonl"));
+ const elsewhere = put(join(outside, "notes.jsonl"));
+ bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { pi: mine } }, { threadId: "t2", resumeCursors: { pi: elsewhere } }, { threadId: "t3" }] });
+ deleteThreads("t1", "t2");
+ expect([existsSync(mine), existsSync(elsewhere)]).toEqual([false, true]);
+ });
+
+ it("never follows a link out of an engine's folder", () => {
+ const { home, outside, bots, deleteThreads } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SESSION } }, { threadId: "t2" }] });
+ const elsewhere = put(join(outside, "projects", "-work", `${SESSION}.jsonl`));
+ const history = put(join(outside, "history", SESSION, "a@v1"));
+ mkdirSync(join(home, ".claude"), { recursive: true });
+ symlinkSync(join(outside, "projects"), join(home, ".claude", "projects"));
+ mkdirSync(join(home, ".claude", "file-history"));
+ symlinkSync(join(outside, "history", SESSION), join(home, ".claude", "file-history", SESSION));
+ mkdirSync(join(home, ".codex"), { recursive: true });
+ symlinkSync(join(outside, "projects"), join(home, ".codex", "sessions"));
+ deleteThreads("t1");
+ expect([existsSync(elsewhere), existsSync(history)]).toEqual([true, true]);
+ expect(existsSync(join(home, ".claude", "file-history", SESSION))).toBe(false);
+ });
+
+ it("never follows a link out of the data folder to an engine home", () => {
+ const sessions = (dataDir: string) => engineSessionFolders(dataDir, [{ HOME: join(dataDir, "engine-homes", "team") }]);
+ let dataDirOf = "";
+ const { dataDir, outside, bots, deleteThreads } = fixture({ engineFolders: () => sessions(dataDirOf) });
+ dataDirOf = dataDir;
+ bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SESSION } }, { threadId: "t2" }] });
+ const elsewhere = put(join(outside, "claude", "projects", "-work", `${SESSION}.jsonl`));
+ mkdirSync(join(dataDir, "engine-homes", "team"), { recursive: true });
+ symlinkSync(join(outside, "claude"), join(dataDir, "engine-homes", "team", ".claude"));
+ deleteThreads("t1");
+ expect(existsSync(elsewhere)).toBe(true);
+ });
+});
+
+describe("a deleted bot", () => {
+ it("takes its checkpoints, its box uploads and the memory layers kept beside its own folder, and keeps the files its conversations made", () => {
+ const { dataDir, bots, deleteBot, forgotten } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }] }, { id: "scout-two", tasks: [{ threadId: "t9" }] });
+ const layers = [`scout--member-${MEMBER}`, "scout--room-r1"];
+ const mine = [
+ put(join(dataDir, "checkpoints", "scout", "0123456789abcdef", ".git", "HEAD")),
+ put(join(dataDir, "box-uploads", "scout", "t1", upload(1))),
+ ...layers.flatMap((layer) => [put(join(dataDir, "workspaces", layer, "memory", "notes.md")), put(join(dataDir, "memory-journal", `${layer}.ndjson`))]),
+ ];
+ const others = [
+ put(join(dataDir, "checkpoints", "scout-two", "0123456789abcdef", ".git", "HEAD")),
+ put(join(dataDir, "task-workspaces", "scout", "t1", "report.md")),
+ put(join(dataDir, "workspaces", `scout-two--member-${MEMBER}`, "memory", "notes.md")),
+ put(join(dataDir, "workspaces", "scout-two", "memory", "notes.md")),
+ put(join(dataDir, "memory-journal", "scout-two.ndjson")),
+ ];
+ deleteBot("scout");
+ expect(mine.filter(existsSync)).toEqual([]);
+ expect(others.filter((path) => !existsSync(path))).toEqual([]);
+ expect(forgotten.sort()).toEqual([...layers].sort());
+ });
+
+ it("never follows a link out of the data folder", () => {
+ const { dataDir, outside, bots, deleteBot } = fixture();
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });
+ const checkpoint = put(join(outside, "checkpoints", "scout", "repo", "HEAD"));
+ const layer = put(join(outside, "layer", "memory", "notes.md"));
+ symlinkSync(join(outside, "checkpoints"), join(dataDir, "checkpoints"));
+ mkdirSync(join(dataDir, "workspaces"), { recursive: true });
+ symlinkSync(join(outside, "layer"), join(dataDir, "workspaces", `scout--member-${MEMBER}`));
+ deleteBot("scout");
+ expect([existsSync(checkpoint), existsSync(layer)]).toEqual([true, true]);
+ expect(existsSync(join(dataDir, "workspaces", `scout--member-${MEMBER}`))).toBe(false);
+ });
+});
+
+describe("a cleanup that fails", () => {
+ it("is logged, never thrown into the delete, and the rest still goes", () => {
+ const { dataDir, home, bots, say, deleteThreads, warnings } = fixture({ deleteAttachment: () => { throw new Error("disk is read-only"); } });
+ bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SESSION } }, { threadId: "t2" }] });
+ say("t1", upload(1));
+ const session = put(join(home, ".claude", "projects", "-work", `${SESSION}.jsonl`));
+ const box = put(join(dataDir, "box-uploads", "scout", "t1", upload(1)));
+ expect(() => deleteThreads("t1")).not.toThrow();
+ expect(warnings).toEqual([`delete leftovers: the upload ${upload(1)} stayed behind: disk is read-only`]);
+ expect([existsSync(session), existsSync(box)]).toEqual([false, false]);
+ });
+
+ it("is logged when the conversation cannot be read before it goes", () => {
+ const { messages, store, warnings } = fixture();
+ messages.set("t1", [{ toJSON() { throw new Error("unreadable"); } }]);
+ expect(() => store.threadsGoing(["t1"])).not.toThrow();
+ expect(warnings).toEqual(["delete leftovers: leftovers of t1 stayed behind: unreadable"]);
+ });
+});
+
+describe("the helpers", () => {
+ it("removes only what is plainly under its root", () => {
+ const { dataDir, outside } = fixture();
+ const inside = put(join(dataDir, "a", "b", "file"));
+ const out = put(join(outside, "file"));
+ symlinkSync(outside, join(dataDir, "link"));
+ expect(plainlyUnder(dataDir, inside)).toBe(true);
+ expect(plainlyUnder(dataDir, dataDir)).toBe(false);
+ expect(plainlyUnder(dataDir, out)).toBe(false);
+ expect(plainlyUnder(dataDir, join(dataDir, "a", "..", "..", "outside", "file"))).toBe(false);
+ expect(removeUnder(dataDir, join(dataDir, "link", "file"))).toBe(false);
+ expect(existsSync(out)).toBe(true);
+ expect(removeUnder(dataDir, join(dataDir, "link"))).toBe(true);
+ expect(existsSync(out)).toBe(true);
+ expect(removeUnder(dataDir, inside)).toBe(true);
+ expect(removeUnder(dataDir, inside)).toBe(false);
+ });
+
+ it("removes a memory layer and nothing that is not one", () => {
+ const { dataDir } = fixture();
+ const records = { journalFile: (layer: string) => join(dataDir, "memory-journal", `${layer}.ndjson`), forget: () => {} };
+ const own = put(join(dataDir, "workspaces", "scout", "memory", "notes.md"));
+ const layer = put(join(dataDir, "workspaces", "scout--room-r1", "memory", "notes.md"));
+ removeMemoryLayer(dataDir, "scout", records);
+ removeMemoryLayer(dataDir, "scout--room-r1", records);
+ expect([existsSync(own), existsSync(layer)]).toEqual([true, false]);
+ });
+
+ it("finds each engine's folder from the environment its instance runs with", () => {
+ const { dataDir, home } = fixture();
+ mkdirSync(join(dataDir, "providers", "chatgpt-plan", "abc", "codex"), { recursive: true });
+ const work = instanceEnvironment({ HOME: home }, { config: { configDir: "~/.claude-work" } });
+ const endpoint = instanceEnvironment({ HOME: home }, { environment: { CODEX_HOME: join(dataDir, "providers", "relay") } });
+ expect(instanceEnvironment({ HOME: home }, { config: { configDir: "relative" } }).CLAUDE_CONFIG_DIR).toBeUndefined();
+ expect(engineSessionFolders(dataDir, [{ HOME: home }, work, endpoint, {}])).toEqual({
+ claude: [join(home, ".claude"), join(home, ".claude-work")],
+ codex: [join(home, ".codex"), join(dataDir, "providers", "relay"), join(dataDir, "providers", "chatgpt-plan", "abc", "codex")],
+ pi: [join(home, ".pi", "agent")],
+ });
+ });
+});
diff --git a/server/host/delete-leftovers.ts b/server/host/delete-leftovers.ts
new file mode 100644
index 0000000000..7c8b82ecce
--- /dev/null
+++ b/server/host/delete-leftovers.ts
@@ -0,0 +1,323 @@
+// Deleting a conversation or a bot removes what it kept on disk outside its transcript: the files uploaded to the
+// conversation, its box uploads folder, the session files the engines wrote for it, and for a bot its checkpoints and
+// the memory layers kept beside its own folder. A conversation's own folder (task-workspaces/<bot>/<thread>) holds
+// files the bot made for the person, and stays when the conversation or the bot is deleted.
+//
+// Security: a file goes only when it is provably the deleted conversation's or bot's. An upload another conversation,
+// a picture or a routine still names stays; an engine session a remaining conversation still resumes stays. Nothing is
+// reached through a link: every folder between a root and what is removed must be a real folder, and a link found
+// there is removed as a link, never what it points at. Nothing here throws into the delete, which has already happened.
+import { lstatSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+
+import { baseBotId, isLayerId } from "../audience.ts";
+
+/** A file in attachments/, by its URL or by its path (as JSON escapes it) a sent document's tag carries. */
+const ATTACHMENT = /attachments(?:\/|\\)+([A-Za-z0-9][\w.-]{0,200})/g;
+const ID = /^[\w-]{1,128}$/;
+const SESSION_ID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
+const WHOLE_SESSION_ID = new RegExp(`^${SESSION_ID.source}$`, "i");
+const MAX_LOG_BYTES = 64 * 1024 * 1024;
+const MAX_NOTED = 5_000;
+const MAX_DEPTH = 6;
+
+/** Folder names as Claude Code 2.1 keeps a session's files: `projects/<folder>/<session>.jsonl` and its session
+ * folder, and one entry named after the session in each of the others. */
+const CLAUDE_SESSION_FOLDERS = ["file-history", "session-env", "todos", "debug"] as const;
+/** Codex 0.16 keeps a session as `sessions/<year>/<month>/<day>/rollout-<time>-<session>.jsonl`. */
+const CODEX_SESSION_FOLDERS = ["sessions", "archived_sessions"] as const;
+
+export interface EngineSessionFolders {
+ claude: readonly string[];
+ codex: readonly string[];
+ /** Pi names a session by its file's path, so its folders only say where such a file may be. */
+ pi: readonly string[];
+}
+
+type Cursors = Record<string, unknown> | undefined;
+type Change = { type: string; threadId?: string; botId?: string };
+
+export interface DeleteLeftoversDeps {
+ dataDir: string;
+ store: {
+ readonly bots: ReadonlyArray<{ id: string; threadId?: string; resumeCursors?: Cursors; tasks?: ReadonlyArray<{ threadId: string; resumeCursors?: Cursors }> }>;
+ messagesFor(threadId: string): readonly unknown[];
+ onChange(listener: (change: Change) => void): unknown;
+ /** Set here: the store calls it before it tries to delete these conversations. */
+ threadsGoing: (threadIds: readonly string[]) => void;
+ };
+ /** Conversations whose messages still name this text (message-db.ts threadsReferencing). */
+ threadsReferencing(fragment: string): readonly string[];
+ /** Stored names something other than a transcript uses (pictures, routines' files, files on their way into a turn);
+ * null while that cannot be read, and then no upload is removed. */
+ keptAttachments(): ReadonlySet<string> | null;
+ deleteAttachment(name: string): void;
+ engineFolders(): EngineSessionFolders;
+ layers: MemoryLayerRecords;
+ /** Runs `flush` once the delete under way has finished, so one pass covers every conversation it removed. */
+ defer?(flush: () => void): void;
+ warn?(line: string): void;
+}
+
+export interface MemoryLayerRecords {
+ journalFile(layer: string): string;
+ /** The layer's indexed notes and its journal's state in memory. */
+ forget(layer: string): void;
+}
+
+function entries(dir: string): string[] {
+ try { return readdirSync(dir); } catch { return []; }
+}
+
+function realFolder(path: string): boolean {
+ try { return lstatSync(path).isDirectory(); } catch { return false; }
+}
+
+function exists(path: string): boolean {
+ try { lstatSync(path); return true; } catch { return false; }
+}
+
+/** Whether `path` is inside `root` with every folder between them a real folder. */
+export function plainlyUnder(root: string, path: string): boolean {
+ const rel = relative(resolve(root), resolve(path));
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return false;
+ const parts = rel.split(sep);
+ let at = resolve(root);
+ for (const part of parts.slice(0, -1)) {
+ at = join(at, part);
+ if (!realFolder(at)) return false;
+ }
+ return true;
+}
+
+/** Removes `path` when it is plainly under `root`; true when something was there and went. */
+export function removeUnder(root: string, path: string): boolean {
+ if (!exists(path) || !plainlyUnder(root, path)) return false;
+ rmSync(path, { recursive: true, force: true });
+ return true;
+}
+
+const sessionIdIn = (name: string) => SESSION_ID.exec(name)?.[0]?.toLowerCase();
+
+function removeClaudeSessions(root: string, sessions: ReadonlySet<string>): number {
+ let removed = 0;
+ const sweep = (dir: string) => {
+ if (!realFolder(dir)) return;
+ for (const name of entries(dir)) {
+ const id = sessionIdIn(name);
+ if (id && sessions.has(id) && removeUnder(root, join(dir, name))) removed++;
+ }
+ };
+ const projects = join(root, "projects");
+ if (realFolder(projects)) for (const folder of entries(projects)) sweep(join(projects, folder));
+ for (const folder of CLAUDE_SESSION_FOLDERS) sweep(join(root, folder));
+ return removed;
+}
+
+function removeCodexSessions(root: string, sessions: ReadonlySet<string>): number {
+ let removed = 0;
+ const walk = (dir: string, depth: number) => {
+ if (depth > MAX_DEPTH || !realFolder(dir)) return;
+ for (const name of entries(dir)) {
+ const path = join(dir, name);
+ if (realFolder(path)) { walk(path, depth + 1); continue; }
+ const id = sessionIdIn(name);
+ if (id && sessions.has(id) && removeUnder(root, path)) removed++;
+ }
+ };
+ for (const folder of CODEX_SESSION_FOLDERS) walk(join(root, folder), 0);
+ return removed;
+}
+
+function removePiSession(roots: readonly string[], file: string): number {
+ if (!file.endsWith(".jsonl")) return 0;
+ try { if (!lstatSync(file).isFile()) return 0; } catch { return 0; }
+ return roots.some((root) => removeUnder(root, file)) ? 1 : 0;
+}
+
+/** The session ids a conversation's event log says its engines started. */
+function loggedSessions(dataDir: string, threadId: string): string[] {
+ const file = join(dataDir, "events", `${threadId}.ndjson`);
+ try {
+ const stats = lstatSync(file);
+ if (!stats.isFile() || stats.size > MAX_LOG_BYTES) return [];
+ } catch {
+ return [];
+ }
+ const found: string[] = [];
+ for (const line of readFileSync(file, "utf8").split("\n")) {
+ if (!line.includes('"session.started"')) continue;
+ try {
+ const event = JSON.parse(line) as { type?: unknown; threadId?: unknown; sessionId?: unknown };
+ if (event.type === "session.started" && event.threadId === threadId && typeof event.sessionId === "string" && event.sessionId) found.push(event.sessionId);
+ } catch { /* a line cut short by a crash names nothing */ }
+ }
+ return found;
+}
+
+const cursorsOf = (cursors: Cursors): string[] => Object.values(cursors ?? {}).filter((cursor): cursor is string => typeof cursor === "string" && cursor !== "");
+
+/** Removes one memory layer of a bot: its folder beside the bot's own, its journal and its indexed notes. */
+export function removeMemoryLayer(dataDir: string, layer: string, records: MemoryLayerRecords): void {
+ if (!isLayerId(layer)) return;
+ removeUnder(dataDir, join(dataDir, "workspaces", layer));
+ const journal = records.journalFile(layer);
+ removeUnder(dirname(dirname(journal)), journal);
+ records.forget(layer);
+}
+
+/** Where each engine keeps its sessions, for every environment an engine of this server runs with. */
+export function engineSessionFolders(dataDir: string, environments: Iterable<Record<string, string | undefined>>): EngineSessionFolders {
+ const claude = new Set<string>(), codex = new Set<string>(), pi = new Set<string>();
+ const absolute = (value: string | undefined) => (value && isAbsolute(value) ? resolve(value) : null);
+ for (const env of environments) {
+ const home = absolute(env.HOME) ?? absolute(env.USERPROFILE);
+ const claudeFolder = absolute(env.CLAUDE_CONFIG_DIR) ?? (home && join(home, ".claude"));
+ const codexFolder = absolute(env.CODEX_HOME) ?? (home && join(home, ".codex"));
+ if (claudeFolder) claude.add(claudeFolder);
+ if (codexFolder) codex.add(codexFolder);
+ if (home) pi.add(join(home, ".pi", "agent"));
+ }
+ const plans = join(resolve(dataDir), "providers", "chatgpt-plan");
+ for (const plan of entries(plans)) codex.add(join(plans, plan, "codex"));
+ return { claude: [...claude], codex: [...codex], pi: [...pi] };
+}
+
+/** An instance's environment as its engine is started with it: the server's, the instance's own over it, and a Claude
+ * account's folder (`config.configDir`, absolute or under `~/`) as CLAUDE_CONFIG_DIR. */
+export function instanceEnvironment(base: Record<string, string | undefined>, instance: { environment?: Record<string, string>; config?: unknown }): Record<string, string | undefined> {
+ const env = { ...base, ...instance.environment };
+ const configDir = (instance.config as { configDir?: unknown } | null | undefined)?.configDir;
+ const home = env.HOME ?? env.USERPROFILE;
+ if (typeof configDir !== "string" || !configDir.trim()) return env;
+ const named = configDir.trim();
+ const folder = named === "~" ? home : named.startsWith("~/") && home ? join(home, named.slice(2)) : named;
+ return folder && isAbsolute(folder) ? { ...env, CLAUDE_CONFIG_DIR: folder } : env;
+}
+
+interface Noted {
+ attachments: Set<string>;
+ sessions: Set<string>;
+}
+
+export function createDeleteLeftovers(deps: DeleteLeftoversDeps) {
+ const dataDir = resolve(deps.dataDir);
+ const attachments = join(dataDir, "attachments");
+ const warn = deps.warn ?? ((line: string) => console.warn(line));
+ const defer = deps.defer ?? ((flush: () => void) => queueMicrotask(flush));
+ const noted = new Map<string, Noted>();
+ const gone = new Map<string, Noted>();
+ const goneBots = new Set<string>();
+ let scheduled = false;
+
+ const attempt = (what: string, run: () => void) => {
+ try {
+ run();
+ } catch (error) {
+ warn(`delete leftovers: ${what} stayed behind: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ };
+
+ function note(threadId: string): void {
+ if (!ID.test(threadId)) return;
+ const found: Noted = { attachments: new Set(), sessions: new Set() };
+ for (const match of JSON.stringify(deps.store.messagesFor(threadId)).matchAll(ATTACHMENT)) found.attachments.add(match[1]!);
+ for (const bot of deps.store.bots) {
+ if (bot.threadId === threadId) for (const cursor of cursorsOf(bot.resumeCursors)) found.sessions.add(cursor);
+ for (const task of bot.tasks ?? []) if (task.threadId === threadId) for (const cursor of cursorsOf(task.resumeCursors)) found.sessions.add(cursor);
+ }
+ for (const session of loggedSessions(dataDir, threadId)) found.sessions.add(session);
+ noted.delete(threadId);
+ noted.set(threadId, found);
+ if (noted.size > MAX_NOTED) noted.delete(noted.keys().next().value!);
+ }
+
+ /** On a Team Cloud each member's picture is named in their own people/<person>/profile.json. */
+ function memberPictures(): string {
+ const people = join(dataDir, "people");
+ return entries(people).map((person) => {
+ try { return readFileSync(join(people, person, "profile.json"), "utf8"); } catch { return ""; }
+ }).join("\n");
+ }
+
+ function removeAttachments(names: ReadonlySet<string>): void {
+ if (!names.size) return;
+ const kept = deps.keptAttachments();
+ if (!kept) return warn("delete leftovers: uploads stayed behind: what still uses them cannot be read right now");
+ const pictures = memberPictures();
+ for (const name of names) {
+ const path = join(attachments, name);
+ if (name.includes("..") || basename(name) !== name || kept.has(name) || pictures.includes(name) || !plainlyUnder(dataDir, path)) continue;
+ attempt(`the upload ${name}`, () => {
+ if (!lstatSync(path, { throwIfNoEntry: false })?.isFile() || deps.threadsReferencing(name).length) return;
+ deps.deleteAttachment(name);
+ });
+ }
+ }
+
+ function removeSessions(sessions: ReadonlySet<string>): void {
+ if (!sessions.size) return;
+ const resumed = new Set(deps.store.bots.flatMap((bot) => [...cursorsOf(bot.resumeCursors), ...(bot.tasks ?? []).flatMap((task) => cursorsOf(task.resumeCursors))]));
+ const ended = [...sessions].filter((session) => !resumed.has(session));
+ const ids = new Set(ended.filter((session) => WHOLE_SESSION_ID.test(session)).map((session) => session.toLowerCase()));
+ const files = ended.filter((session) => isAbsolute(session));
+ if (!ids.size && !files.length) return;
+ const folders = deps.engineFolders();
+ const reached = (roots: readonly string[]) => roots.filter((root) => !relative(dataDir, resolve(root)).startsWith("..") ? plainlyUnder(dataDir, root) && realFolder(root) : true);
+ if (ids.size) {
+ for (const root of reached(folders.claude)) attempt(`engine sessions in ${root}`, () => void removeClaudeSessions(root, ids));
+ for (const root of reached(folders.codex)) attempt(`engine sessions in ${root}`, () => void removeCodexSessions(root, ids));
+ }
+ for (const file of files) attempt(`the engine session ${file}`, () => void removePiSession(reached(folders.pi), file));
+ }
+
+ function removeBoxUploads(threadId: string): void {
+ const root = join(dataDir, "box-uploads");
+ for (const bot of entries(root)) removeUnder(dataDir, join(root, bot, threadId));
+ }
+
+ function removeBot(botId: string): void {
+ if (!ID.test(botId) || isLayerId(botId)) return;
+ attempt(`checkpoints of ${botId}`, () => void removeUnder(dataDir, join(dataDir, "checkpoints", botId)));
+ attempt(`box uploads of ${botId}`, () => void removeUnder(dataDir, join(dataDir, "box-uploads", botId)));
+ const live = new Set(deps.store.bots.map((bot) => bot.id));
+ for (const layer of entries(join(dataDir, "workspaces"))) {
+ if (!isLayerId(layer) || baseBotId(layer) !== botId || live.has(layer)) continue;
+ attempt(`the memory layer ${layer}`, () => removeMemoryLayer(dataDir, layer, deps.layers));
+ }
+ }
+
+ function flush(): void {
+ scheduled = false;
+ const threads = new Map(gone);
+ const bots = [...goneBots];
+ gone.clear();
+ goneBots.clear();
+ attempt("uploads", () => removeAttachments(new Set([...threads.values()].flatMap((found) => [...found.attachments]))));
+ attempt("engine sessions", () => removeSessions(new Set([...threads.values()].flatMap((found) => [...found.sessions]))));
+ for (const threadId of threads.keys()) attempt(`box uploads of ${threadId}`, () => removeBoxUploads(threadId));
+ for (const botId of bots) removeBot(botId);
+ }
+
+ function schedule(): void {
+ if (scheduled) return;
+ scheduled = true;
+ defer(() => attempt("leftovers", flush));
+ }
+
+ deps.store.threadsGoing = (threadIds) => {
+ for (const threadId of new Set(threadIds)) attempt(`leftovers of ${threadId}`, () => note(threadId));
+ };
+ deps.store.onChange((change) => {
+ if (change.type === "thread.deleted" && change.threadId && ID.test(change.threadId)) {
+ gone.set(change.threadId, noted.get(change.threadId) ?? { attachments: new Set(), sessions: new Set() });
+ noted.delete(change.threadId);
+ schedule();
+ } else if (change.type === "bot.deleted" && change.botId) {
+ goneBots.add(change.botId);
+ schedule();
+ }
+ });
+
+ return { flush };
+}
diff --git a/server/host/run-owner.test.ts b/server/host/run-owner.test.ts
index e0cf553aa8..bc617ff62e 100644
--- a/server/host/run-owner.test.ts
+++ b/server/host/run-owner.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { RequestAuth } from "../request-auth.ts";
-import { arrivalDecision, createRunOwners, mayJoinRun, mayRemoveQueued, mayStop, routeRunOwners, type RunOwnersDeps } from "./run-owner.ts";
+import { arrivalDecision, createRunOwners, mayJoinRun, mayRemoveQueued, mayRetry, mayStop, routeRunOwners, type RunOwnersDeps } from "./run-owner.ts";
const PRIYA = "p_priyapriyapriyapriyapr";
const TOM = "p_tomtomtomtomtomtomtomt";
@@ -38,6 +38,17 @@ describe("the rule", () => {
expect(mayRemoveQueued({ shared: true, by: { person: TOM, admin: true } })).toBe(true);
});
+ it("lets a request's writer or an admin run it again, and anyone one no person wrote", () => {
+ const sender = { name: "Priya", id: PRIYA };
+ expect(mayRetry({ shared: true, sender, by: { person: PRIYA, admin: false } })).toBe(true);
+ expect(mayRetry({ shared: true, sender, by: { person: TOM, admin: false } })).toBe(false);
+ expect(mayRetry({ shared: true, sender, by: { admin: false } })).toBe(false);
+ expect(mayRetry({ shared: true, sender, by: { person: TOM, admin: true } })).toBe(true);
+ expect(mayRetry({ shared: true, sender: { name: "Slack" }, by: { person: TOM, admin: false } })).toBe(true);
+ expect(mayRetry({ shared: true, by: { person: TOM, admin: false } })).toBe(true);
+ expect(mayRetry({ shared: false, sender, by: { person: TOM, admin: false } })).toBe(true);
+ });
+
it("joins waiting lines to the run only when the asker adds their own", () => {
expect(mayJoinRun({ shared: true, asker: priya, senders: [{ name: "Priya", id: PRIYA }], by: { person: PRIYA, admin: false } })).toBe(true);
expect(mayJoinRun({ shared: true, asker: priya, senders: [{ name: "Priya", id: PRIYA }, { name: "Tom", id: TOM }], by: { person: PRIYA, admin: false } })).toBe(false);
@@ -82,6 +93,13 @@ describe("who asked", () => {
expect(dev.shownSender("t", { name: "[email protected]", id: TOM })).toEqual({ name: "Dev", id: TOM });
});
+ it("names the request's writer when someone else may not run it again", () => {
+ const sender = { name: "[email protected]", id: PRIYA };
+ expect(owners(undefined).retryRefusal("t", sender, { person: TOM, admin: false })).toBe("Only Priya or an admin can run this request again.");
+ expect(owners(undefined).retryRefusal("t", sender, { person: PRIYA, admin: false })).toBeNull();
+ expect(owners(undefined).retryRefusal("t", sender, { person: TOM, admin: true })).toBeNull();
+ });
+
it("names the asker in the refusal", () => {
expect(owners({ messageId: "m1" }).stopRefusal("t", { person: TOM, admin: false })).toBe("Only Priya or an admin can stop this.");
expect(owners({ messageId: "m1" }).stopRefusal("t", { person: PRIYA, admin: false })).toBeNull();
@@ -96,5 +114,7 @@ describe("a route built without the rule", () => {
expect(owners.stopRefusal(auth, "t")).toBeNull();
expect(owners.removeRefusal(auth, "t", { name: "Tom", id: TOM })).toBeNull();
expect(owners.joinRefusal(auth, "t", [{ name: "Tom", id: TOM }])).toBeNull();
+ expect(owners.retryRefusal(auth, "t", { name: "Tom", id: TOM })).toBeNull();
+ expect(owners.decidesRetry("t")).toBe(false);
});
});
diff --git a/server/host/run-owner.ts b/server/host/run-owner.ts
index 4fdc87b040..cb3873514d 100644
--- a/server/host/run-owner.ts
+++ b/server/host/run-owner.ts
@@ -46,6 +46,12 @@ export function mayRemoveQueued(input: { shared: boolean; sender?: ResolvedSende
return writer ? writer === by.person : by.admin;
}
+/** A request is its writer's to run again; an Owner or Admin runs anyone's again, and anyone one no person wrote. */
+export function mayRetry(input: { shared: boolean; sender?: ResolvedSender; by: Actor }): boolean {
+ const { shared, sender, by } = input;
+ return !shared || !sender?.id || by.admin || sender.id === by.person;
+}
+
/** Waiting lines join the running turn only when every one is the asker's own and the asker adds them. */
export function mayJoinRun(input: { shared: boolean; asker: RunAsker; senders: ReadonlyArray<ResolvedSender | undefined>; by: Actor }): boolean {
const { shared, asker, senders, by } = input;
@@ -128,19 +134,29 @@ export function createRunOwners(deps: RunOwnersDeps) {
const shared = deps.shared(threadId);
return mayJoinRun({ shared, asker: shared ? asker(threadId) : null, senders, by }) ? null : serverLine(deps.language(threadId), "server.runOwner.waitsItsTurn");
},
+ /** The sentence someone who may not run this request again reads, or null when they may. */
+ retryRefusal(threadId: string, sender: ResolvedSender | undefined, by: Actor): string | null {
+ if (mayRetry({ shared: deps.shared(threadId), sender, by })) return null;
+ return serverLine(deps.language(threadId), "server.runOwner.onlyAskerRetries", { name: shownPersonName(deps.personName(sender!.id!) ?? sender!.name) });
+ },
};
}
export type RunOwners = ReturnType<typeof createRunOwners>;
+export type RouteRunOwners = Pick<RunOwners, "shared" | "stopRefusal" | "removeRefusal" | "joinRefusal" | "retryRefusal">;
+
/** The rule as a route asks it, by the request's sign-in. A route built without it (a server one person uses, or a
* route's own test) refuses nothing and sees no admin, so nothing changes there. */
-export function routeRunOwners(owners: Pick<RunOwners, "stopRefusal" | "removeRefusal" | "joinRefusal"> | undefined, actorOf: ((auth: RequestAuth) => Actor) | undefined) {
+export function routeRunOwners(owners: RouteRunOwners | undefined, actorOf: ((auth: RequestAuth) => Actor) | undefined) {
const by = (auth: RequestAuth): Actor => actorOf?.(auth) ?? { admin: false };
return {
admin: (auth: RequestAuth) => by(auth).admin,
+ /** Where several people write, who wrote a request decides who runs it again or rewords it, not who opened the conversation. */
+ decidesRetry: (threadId: string) => owners?.shared(threadId) ?? false,
stopRefusal: (auth: RequestAuth, threadId: string) => owners?.stopRefusal(threadId, by(auth)) ?? null,
removeRefusal: (auth: RequestAuth, threadId: string, sender: ResolvedSender | undefined) => owners?.removeRefusal(threadId, sender, by(auth)) ?? null,
joinRefusal: (auth: RequestAuth, threadId: string, senders: ReadonlyArray<ResolvedSender | undefined>) => owners?.joinRefusal(threadId, senders, by(auth)) ?? null,
+ retryRefusal: (auth: RequestAuth, threadId: string, sender: ResolvedSender | undefined) => owners?.retryRefusal(threadId, sender, by(auth)) ?? null,
};
}
diff --git a/server/host/team-member-left.ts b/server/host/team-member-left.ts
index d9cb111dfe..7c09084de4 100644
--- a/server/host/team-member-left.ts
+++ b/server/host/team-member-left.ts
@@ -22,12 +22,21 @@ import { audienceHome } from "../engine-homes/layout.ts";
import { forgetBotMemoryJournal, journalFile } from "../memory-journal.ts";
import { deleteBotMemoryFiles } from "../message-db.ts";
import { personKey } from "../person-key.ts";
+import { removeMemoryLayer, type MemoryLayerRecords } from "./delete-leftovers.ts";
import { memberUploads } from "./member-uploads.ts";
/** A file in attachments/, by its URL or by its path (as JSON escapes it) a sent document's tag carries. */
const ATTACHMENT = /attachments(?:\/|\\)+([A-Za-z0-9][\w.-]{0,200})/g;
const PERSON = /^p_[\w-]{22}$/;
+export const memoryLayerRecords: MemoryLayerRecords = {
+ journalFile,
+ forget(layer) {
+ deleteBotMemoryFiles(layer);
+ forgetBotMemoryJournal(layer);
+ },
+};
+
export interface TeamMemberLeftDeps {
dataDir: string;
store: {
@@ -135,10 +144,7 @@ export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string)
let entries: string[] = [];
try { entries = readdirSync(workspaces); } catch {}
for (const layer of entries.filter((entry) => entry.endsWith(`--member-${person}`))) {
- rmSync(join(workspaces, layer), { recursive: true, force: true });
- rmSync(journalFile(layer), { force: true });
- deleteBotMemoryFiles(layer);
- forgetBotMemoryJournal(layer);
+ removeMemoryLayer(deps.dataDir, layer, memoryLayerRecords);
layers++;
}
rmSync(join(deps.dataDir, "people", person), { recursive: true, force: true });
diff --git a/server/index.ts b/server/index.ts
index 813ba4fc33..3bac65772c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -276,7 +276,7 @@ import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } from
import { hostedModelPolicy, HOSTED_MODEL_POLICY_HEADER } from "./hosted-models.ts";
import { CLOUD_HOME_SECRET_KEYS, CLOUD_IGNORED_KEYS, cloudHomeConfiguration, cloudHomeOffersPlace, cloudHomePlaceRefusal, firstCloudTurnPatch } from "./cloud-home.ts";
import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { attachmentsForBox } from "./box-attachments.ts"; import { brokerPath } from "./bot-box/broker-probe.ts";
-import { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, refusalFor, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";
+import { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { createDeleteLeftovers, engineSessionFolders, instanceEnvironment } from "./host/delete-leftovers.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft, memoryLayerRecords } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, refusalFor, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";
import { cloudPowerNow, createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createWokeNotifier } from "./cloud-woke.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";
import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { mcpReconnectLine, retryBrokeredMcp } from "./bot-box/broker-mcp.ts";
import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";
@@ -12120,6 +12120,7 @@ const { react } = createReactions({
});
const publishedPages = createPublishedPages({ dataDir: DATA_DIR, cloudHome: CLOUD_HOME, selfHosted: !CLOUD_HOME && !HOSTED_WORKSPACE && utilityParentPort === undefined, patch: (threadId, messageId, text, publishedPage) => void store.patchMessage(threadId, messageId, { text, publishedPage }), liveRoots: (botId, threadId) => liveRoots(threadId, botId), paused: () => workspaceMaintenance.active || moveFreeze.frozen(), apps: { chat: chatApps, store } }); ROUTES.push(createReactionRoutes({ react, reactorFor, cloudGuestSendRefusal }), publishedPages.routes, savedSteps.routes, createPlacesElsewhereRoutes({ elsewhere: placesElsewhere, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (auth.kind === "loopback" || ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }));
// `let` slots are read per request.
+const keptAttachments = () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles, ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; }; createDeleteLeftovers({ dataDir: DATA_DIR, store, threadsReferencing, keptAttachments, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), engineFolders: () => engineSessionFolders(DATA_DIR, [process.env, ...Object.values(providerConfigs()).map((instance) => instanceEnvironment(process.env, instance))].flatMap((env) => engineHomes.everyHome(env))), layers: memoryLayerRecords });
ROUTES.push(createThreadRoutes({
groupFor: personRooms.groupForAuth, ...(botOrders ? { botOrderFor: (auth: RequestAuth, bots: readonly BotRecord[]) => { const person = botOrders.personOf(auth); return person ? botOrders.ordered(person, bots) : bots; } } : {}),
store, userName: userNameFor, sessions, groupUsageReader, lendingEnabled,
@@ -12132,8 +12133,7 @@ ROUTES.push(createThreadRoutes({
botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => { const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name, opened: (made) => void mausbotOwnChat.claim(made) }); if (own) void mausbotOwnChat.claim(own); return own; } : undefined,
uploads: uploadsFor(createUploadOwners(DATA_DIR), Boolean(CLOUD_TEAM)),
attachmentInUse: (name) => threadsReferencing(name).length > 0 || store.bots.some((bot) => bot.avatarUrl === `/api/attachments/${name}`),
- keptAttachments: CLOUD_TEAM ? undefined : () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles,
- ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; },
+ keptAttachments: CLOUD_TEAM ? undefined : keptAttachments,
})); offerAttachmentClear(!CLOUD_TEAM);
ROUTES.push(createBotCreateRoutes({
store, cfg, presetStore, orgInstallStatuses,
diff --git a/server/routes/bot-messages.test.ts b/server/routes/bot-messages.test.ts
index d464434791..36e4c373e5 100644
--- a/server/routes/bot-messages.test.ts
+++ b/server/routes/bot-messages.test.ts
@@ -10,6 +10,7 @@ import { createAgentCard } from "../chat-widgets.ts";
import { DATA_DIR } from "../config.ts";
import type { ModelSelection } from "../contracts.ts";
import { json, readBody } from "../harness/http.ts";
+import { createRunOwners } from "../host/run-owner.ts";
import { promptWithReply } from "../replies.ts";
import type { RequestAuth } from "../request-auth.ts";
import { acceptedSendMatch, sendFingerprint, SendSequencer } from "../send-idempotency.ts";
@@ -179,6 +180,68 @@ describe("editing a message with no AI", () => {
});
});
+describe("running a request again where several people write", () => {
+ const PRIYA = "p_priyapriyapriyapriyapr", TOM = "p_tomtomtomtomtomtomtomt";
+ const team = (by: { person?: string; admin: boolean }, shared = true) => ({
+ runOwners: createRunOwners({ shared: () => shared, directRequest: () => undefined, roomRequestMessageId: () => undefined, isRoom: () => false,
+ messages: () => [], personName: () => undefined, language: () => undefined }),
+ runActor: () => by,
+ });
+ const asked = (store: Store, threadId: string) => store.appendMessage(threadId, { role: "user", kind: "text", text: "Draft the launch post", sender: { name: "Priya", id: PRIYA } });
+
+ it("lets the person who asked, and an admin, retry it", async () => {
+ for (const by of [{ person: PRIYA, admin: false }, { person: TOM, admin: true }]) {
+ const { store, threadId, state, edit } = await fixture(team(by));
+ const request = asked(store, threadId);
+ expect((await edit(request.id, { threadId, text: request.text })).status).toBe(202);
+ expect(state.started).toMatchObject([{ text: "Draft the launch post", opts: { editedMessageId: request.id } }]);
+ }
+ });
+
+ it("refuses another member who calls the route directly, with the same words or new ones", async () => {
+ const { store, threadId, state, edit } = await fixture(team({ person: TOM, admin: false }));
+ const request = asked(store, threadId);
+ const refusal = { status: 403, body: { error: "Only Priya or an admin can run this request again.", code: "retry_not_yours" } };
+ expect(await edit(request.id, { threadId, text: request.text })).toEqual(refusal);
+ expect(await edit(request.id, { threadId, text: "Draft something else" })).toEqual(refusal);
+ expect(state.started).toEqual([]);
+ });
+
+ it("lets anyone there retry a request no person wrote", async () => {
+ const { store, threadId, edit } = await fixture(team({ person: TOM, admin: false }));
+ const request = store.appendMessage(threadId, { role: "user", kind: "text", text: "From the API" });
+ expect((await edit(request.id, { threadId, text: request.text })).status).toBe(202);
+ });
+
+ it("decides by who wrote the request, not by who started the conversation, and after a restart cut the run off", async () => {
+ const startedByOther = { cloudThreadRefusal: () => "On this Cloud you can only change conversations you started." };
+ for (const [by, text] of [[PRIYA, "Draft the launch post"], [PRIYA, "Draft the launch note"]] as const) {
+ const { store, threadId, state, edit } = await fixture({ ...team({ person: by, admin: false }), ...startedByOther });
+ const request = asked(store, threadId);
+ store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: "turn interrupted — OpenMausBot restarted", ok: false } });
+ expect((await edit(request.id, { threadId, text })).status).toBe(202);
+ expect(state.started).toMatchObject([{ text, opts: { editedMessageId: request.id } }]);
+ }
+ const { store, threadId, edit } = await fixture({ ...team({ person: TOM, admin: false }), ...startedByOther });
+ expect((await edit(asked(store, threadId).id, { threadId, text: "Draft the launch post" })).body).toEqual({ error: "Only Priya or an admin can run this request again.", code: "retry_not_yours" });
+ });
+
+ it("leaves a private chat to whoever started it", async () => {
+ const { store, threadId, state, edit } = await fixture({ ...team({ person: PRIYA, admin: false }, false), cloudThreadRefusal: () => "On this Cloud you can only change conversations you started." });
+ const request = asked(store, threadId);
+ expect(await edit(request.id, { threadId, text: request.text })).toEqual({ status: 403, body: { error: "On this Cloud you can only change conversations you started." } });
+ expect(state.started).toEqual([]);
+ });
+
+ it("changes nothing in a private chat or on a personal install", async () => {
+ for (const over of [team({ person: TOM, admin: false }, false), {}]) {
+ const { store, threadId, edit } = await fixture(over);
+ const request = asked(store, threadId);
+ expect((await edit(request.id, { threadId, text: request.text })).status).toBe(202);
+ }
+ });
+});
+
describe("POST /api/bots/:id/messages and who typed it", () => {
const words = "Look at this and /standup it";
diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.ts
index 77e3df7f8e..579a5959c3 100644
--- a/server/routes/bot-messages.ts
+++ b/server/routes/bot-messages.ts
@@ -30,7 +30,7 @@ import type { RoutineManager } from "../routines.ts";
import { acceptedSendMatch, parseSendId } from "../send-idempotency.ts";
import type { DirectSendInput, DirectSendReceipt } from "../direct-send.ts";
import { cancelSteeredMessage, holdSteeredQueue, queuedSteerSender, queuedSteeredMessage, restoreHeldSteeredQueue, settleHeldSteeredQueue } from "../steer-queue.ts";
-import { routeRunOwners, type Actor, type RunOwners } from "../host/run-owner.ts";
+import { routeRunOwners, type Actor, type RouteRunOwners } from "../host/run-owner.ts";
import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";
import { extractSteerImages } from "../turn-images.ts";
import { followupFacts, helperFollowup, helperFollowupBody, mayFollowUp } from "../helper-followup.ts";
@@ -112,7 +112,7 @@ export interface BotMessageRouteDeps {
deliverLateQuestionAnswer(auth: RequestAuth, threadId: string, requestId: string, answer: string, cardMessage: Message, owner: BotRecord): Promise<{ queued: boolean }>;
stopThreadForPerson(botId: string, threadId: string, by?: ResolvedSender): Promise<void>;
/** Whoever asked owns the run, where several people write. */
- runOwners?: Pick<RunOwners, "stopRefusal" | "removeRefusal" | "joinRefusal">;
+ runOwners?: RouteRunOwners;
runActor?(auth: RequestAuth): Actor;
cancelDirectTurnDispatch(botId: string, expectedThreadId?: string): unknown;
revokeInternalCapabilitiesForThread(threadId: string): void;
@@ -500,7 +500,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
const body = await readBody(req);
requirePinnedClientThread(m[1], body?.threadId);
const bot = requestedTaskBot(m[1], body.threadId);
- const notYours = cloudThreadRefusal(auth, bot.threadId);
+ const notYours = owners.decidesRetry(bot.threadId) ? null : cloudThreadRefusal(auth, bot.threadId);
if (notYours) return json(res, 403, { error: notYours });
const textRefused = messageTextRefusal(body.text);
if (textRefused) return json(res, 400, { error: textRefused });
@@ -511,6 +511,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
if (!source || source.role !== "user" || source.kind !== "text") {
return json(res, 404, { error: "only user messages can be edited" });
}
+ const notYoursToRetry = owners.retryRefusal(auth, bot.threadId, source.sender);
+ if (notYoursToRetry) return json(res, 403, { error: notYoursToRetry, code: "retry_not_yours" });
// Before the busy guard: a retried edit's own fork is what is busy.
const sendId = parseSendId(body.sendId);
if (sendId) {
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index d23c60369f..abb2511692 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { routeRunOwners, type Actor, type RunOwners } from "../host/run-owner.ts";
+import { routeRunOwners, type Actor, type RouteRunOwners } from "../host/run-owner.ts";
import type { ResolvedSender, WireGroup } from "../../shared/wire.ts";
import { admit } from "../admission.ts";
import {
@@ -42,7 +42,7 @@ export type MessagePage = { messages: Array<Message | Record<string, unknown>>;
export interface ChannelRouteDeps {
/** Whoever asked owns the run, where several people write. */
- runOwners?: Pick<RunOwners, "stopRefusal" | "removeRefusal" | "joinRefusal">;
+ runOwners?: RouteRunOwners;
runActor?(auth: RequestAuth): Actor;
store: Pick<Store,
| "group" | "groupTaskByThread" | "bot" | "switchGroupTask" | "patchGroupTask" | "patchGroup" | "messagesFor" | "groupTasks" | "deleteGroupTasks" | "deleteGroup"
diff --git a/server/store.ts b/server/store.ts
index a9539ec037..9dbfa4a5f0 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -281,7 +281,7 @@ function taskCountsAsBotUnread(task: { unread?: boolean; routineRunId?: string }
export class Store {
bots: BotRecord[] = [];
- groups: GroupRecord[] = [];
+ groups: GroupRecord[] = []; /** Told before a delete of these conversations is tried; "thread.deleted" follows only for those that went. Must not throw. */ threadsGoing: (threadIds: readonly string[]) => void = () => {};
private threads = new ThreadCache(() => this.busyThreadIds());
private defaultSelection: () => ModelSelection;
private completeNewBotSelection: (selection: ModelSelection) => ModelSelection;
@@ -915,7 +915,7 @@ export class Store {
deleteGroup(id: string): boolean {
const group = this.group(id);
if (!group) return false;
- const remaining = this.groups.filter((g) => g.id !== id);
+ const remaining = this.groups.filter((g) => g.id !== id); this.threadsGoing([group.threadId, ...(group.tasks ?? []).map((task) => task.threadId)]);
saveRegistryFor("groups.json", group.dm ? "the chat deletion" : "the room deletion", () => this.saveGroups(remaining));
this.groups = remaining;
for (const threadId of new Set([group.threadId, ...(group.tasks ?? []).map((task) => task.threadId)])) {
@@ -1059,7 +1059,7 @@ export class Store {
const missing = unique.filter((id) => !present.has(id));
if (deleted.length >= group.tasks.length) return null;
if (!deleted.length) return { group, deleted, missing };
- const doomed = new Set(deleted);
+ const doomed = new Set(deleted); this.threadsGoing(deleted);
mdb.deleteThreads(deleted, () => this.commitGroupChange(group, "the thread deletion", () => {
group.tasks = group.tasks!.filter((task) => !doomed.has(task.threadId));
if (doomed.has(group.threadId)) mirrorActiveGroupTask(group, group.tasks[0]!);
@@ -1450,7 +1450,7 @@ export class Store {
const bot = this.bot(id);
if (!bot) return false;
if (bot.defaultBot) throw Object.assign(new Error(defaultBotRefusal(bot.name)), { status: 409 });
- let nextBots = this.bots.filter((b) => b.id !== id);
+ let nextBots = this.bots.filter((b) => b.id !== id); this.threadsGoing([bot.threadId, ...(bot.tasks ?? []).map((t) => t.threadId)]);
if (setupRequest) {
const chief = this.bot(setupRequest.botId);
if (!chief || chief.id === id || setupRequest.deletion?.botId !== id) throw new Error("The reviewed deletion no longer has a valid owner");
@@ -2267,7 +2267,7 @@ export class Store {
const deleted = unique.filter((id) => present.has(id));
const missing = unique.filter((id) => !present.has(id));
if (!deleted.length) return { bot, deleted, missing };
- const doomed = new Set(deleted);
+ const doomed = new Set(deleted); this.threadsGoing(deleted);
mdb.deleteThreads(deleted, () => this.commitBotChange(bot, "the thread deletion", () => {
const kept = bot.tasks!.filter((t) => !doomed.has(t.threadId));
const visible = nextOpenThread(kept) ?? this.buildTask(bot);
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 5d627b8769..d595e1bbf7 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -786,7 +786,7 @@ const MessagesList = memo(function MessagesList({
onStartEdit={onStartEdit}
onCancelEdit={onCancelEdit}
onSubmitEdit={onSubmitEdit}
- onRegenerate={m.id === lastBotTextId && !m.automation ? onRegenerate : undefined}
+ onRegenerate={m.id === lastBotTextId && !m.automation && canRetryLast ? onRegenerate : undefined}
replyTarget={lookups.replyTarget(m)}
onReply={onReply}
/>
diff --git a/src/locales/de.json b/src/locales/de.json
index cc9ff519d3..20fb066b24 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -3017,6 +3017,7 @@
"server.runOwner.onlyAskerStops": "Nur {name} oder ein Admin kann das stoppen.",
"server.runOwner.notYourQueued": "Nur die Person, die diese Nachricht geschickt hat, kann sie entfernen.",
"server.runOwner.waitsItsTurn": "Diese Nachricht wartet, bis sie dran ist, und läuft nach der Anfrage, die gerade läuft.",
+ "server.runOwner.onlyAskerRetries": "Nur {name} oder ein Admin kann diese Anfrage noch einmal ausführen.",
"server.routines.held.planCancelled": "Deine Routinen sind pausiert, weil der Tarif gekündigt wurde. Damit eine bis zum Ende des Tarifs weiterläuft, schalte sie unter Routines wieder ein.",
"server.routines.held.noEngine": "Deine Routinen sind pausiert: Keines deiner KI-Konten ist hier noch angemeldet. Sie schalten sich von selbst wieder ein, wenn du dich erneut anmeldest.",
"server.routines.held.noConnections": "Deine Routinen sind pausiert: Alle verbundenen Apps und MCP-Server wurden entfernt. Sie schalten sich wieder ein, wenn du eine App oder einen MCP-Server verbindest oder eine Routine unter Routines wieder einschaltest.",
diff --git a/src/locales/en.json b/src/locales/en.json
index 7be61ea591..ff28ebf257 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -9803,6 +9803,7 @@
"server.runOwner.onlyAskerStops": "Only {name} or an admin can stop this.",
"server.runOwner.notYourQueued": "Only the person who sent this message can remove it.",
"server.runOwner.waitsItsTurn": "This message waits its turn and runs after the request that is running now.",
+ "server.runOwner.onlyAskerRetries": "Only {name} or an admin can run this request again.",
"server.routines.held.planCancelled": "Your routines are paused because the plan was cancelled. To keep one running until the plan ends, turn it back on in Routines.",
"server.routines.held.noEngine": "Your routines are paused: none of your AI accounts is signed in here any more. They turn back on by themselves when you sign in again.",
"server.routines.held.noConnections": "Your routines are paused: every connected app and MCP server was removed. They turn back on when you connect one, or turn one back on in Routines.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index b0f7bc247d..ee4b098727 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -9755,6 +9755,7 @@
"server.runOwner.onlyAskerStops": "Só {name} ou um administrador pode interromper isto.",
"server.runOwner.notYourQueued": "Só quem enviou esta mensagem pode removê-la.",
"server.runOwner.waitsItsTurn": "Esta mensagem espera a vez dela e roda depois do pedido em andamento.",
+ "server.runOwner.onlyAskerRetries": "Só {name} ou um administrador pode rodar este pedido de novo.",
"server.personFirst.stoppedMinutes": "Interrompi um passo que já durava {minutes} min para responder a você primeiro",
"server.routines.held.planCancelled": "Suas rotinas estão pausadas porque o plano foi cancelado. Para manter uma delas rodando até o fim do plano, ligue-a novamente em “Rotinas”.",
"server.routines.held.noEngine": "Suas rotinas estão pausadas: nenhuma das suas contas de IA continua conectada aqui. O app liga as rotinas automaticamente quando você entrar novamente.",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 714227142e..5a55f9b1df 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -3459,6 +3459,7 @@
"server.runOwner.onlyAskerStops": "832c893848422bf9040e17b415756f5466d3988354b4e661cb73511be36ff56e",
"server.runOwner.notYourQueued": "18216333edfdf5e36266b29f5fb8f41152345ab4700f69fe64a0f609743fe25d",
"server.runOwner.waitsItsTurn": "e8cd9fac4417e654d67bd9b2bb8a0ebf3ffc70b328de47fd1039da6995b84462",
+ "server.runOwner.onlyAskerRetries": "d484d96fcb6a67c571cccb47ec50b631f17253f7ab1261c929bb7e91571f6c82",
"server.mcp.alsoOn": "a7717d98c90c14e338a9e5d265c8f4c8f8c3d5ea4eb197a93705b868bc5f0dc7",
"server.rooms.chiefRetargeted": "2f8fbfd73503b5871395ef76bc69b867583dae6b03003099d551a7f019a070fb"
},
@@ -33811,6 +33812,7 @@
"server.runOwner.onlyAskerStops": "832c893848422bf9040e17b415756f5466d3988354b4e661cb73511be36ff56e",
"server.runOwner.notYourQueued": "18216333edfdf5e36266b29f5fb8f41152345ab4700f69fe64a0f609743fe25d",
"server.runOwner.waitsItsTurn": "e8cd9fac4417e654d67bd9b2bb8a0ebf3ffc70b328de47fd1039da6995b84462",
+ "server.runOwner.onlyAskerRetries": "d484d96fcb6a67c571cccb47ec50b631f17253f7ab1261c929bb7e91571f6c82",
"secretCard.modelgo.description": "b09e97c010524be77e50e4429d199218a3a3199a187f3edbacd81c9c661b1439",
"native.teamLink.otherTitle": "d160e3032fd4f4fedabfad5fc84852563d0cf85dcdbf92e82f9a06359a8d8522",
"native.teamLink.otherDetail": "11b8a9828b4afd5d0e6aef778751b00fe688893eee2e81e9865e834f21f8391d",