Skip to content

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

perf: bot frames carry only the changed thread; a turn's bookkeeping reaches bots.json in one coalesced save (#6169)

Milind Sonif8a2b5034f54
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index 83154fe65a..da61ca1001 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -961,7 +961,7 @@ export type ServerFrame =
| { kind: "message"; threadId: string; message: WireMessage }
| { kind: "message.patch"; threadId: string; message: WireMessage }
| { kind: "thread"; threadId: string; activeLeafId: string }
- | { kind: "bot"; bot: WireBot }
+ | { kind: "bot"; bot: WireBot; /** Only on a stream opened with `?frames=thread`: `bot.tasks` holds just the changed threads; keep the rest. */ tasksPartial?: true }
| { kind: "group"; group: WireGroup }
| { kind: "notify"; notification: NotificationLogEntry }
| { kind: "notifications.read"; threadId: string; ids: string[] }
diff --git a/scripts/bench-bots-save.ts b/scripts/bench-bots-save.ts
new file mode 100644
index 0000000000..9f7fe55a8c
--- /dev/null
+++ b/scripts/bench-bots-save.ts
@@ -0,0 +1,89 @@
+// Synthetic bots and threads only, in a temporary directory. Measures what one whole-file save of bots.json costs and
+// how many of them a round of turns causes. Never import config before isolating data.
+import { mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { randomUUID } from "node:crypto";
+import { arch, platform, tmpdir } from "node:os";
+import { join } from "node:path"; import { fileURLToPath } from "node:url";
+import { monitorEventLoopDelay, performance } from "node:perf_hooks";
+import { setTimeout as delay } from "node:timers/promises";
+
+const shapes = process.argv.slice(2).filter((arg) => !arg.startsWith("--")).map((shape) => shape.split("x").map(Number)).filter((shape) => shape.length === 2 && shape.every((n) => n > 0));
+const TURNS_TOGETHER = 34;
+console.log(JSON.stringify({ benchmark: "bots-save", node: process.version, platform: platform(), arch: arch(),
+ scope: "Real Store and bots.json with fsync, synthetic bots and threads. A round is what 34 later turns (engine and session already named) write to bots.json, one turn per pass of the event loop, batched as the server batches it." }));
+for (const [bots, threads] of shapes.length ? shapes : [[34, 200], [100, 200], [200, 200]]) {
+ const directory = mkdtempSync(join(tmpdir(), "omb-bots-save-"));
+ // Each shape runs in its own process: the store binds its data directory when first imported.
+ if (process.env.OMB_BENCH_SHAPE !== `${bots}x${threads}`) {
+ const { spawnSync } = await import("node:child_process");
+ const child = spawnSync(process.execPath, ["--experimental-strip-types", fileURLToPath(import.meta.url), `${bots}x${threads}`],
+ { env: { ...process.env, OMB_DATA_DIR: directory, OMB_BENCH_SHAPE: `${bots}x${threads}` }, encoding: "utf8" });
+ process.stdout.write(child.stdout.split("\n").filter((line) => line.includes('"bots":')).join("\n") + "\n");
+ if (child.status !== 0) process.stderr.write(child.stderr);
+ rmSync(directory, { recursive: true, force: true });
+ continue;
+ }
+ const { Store } = await import("../server/store.ts");
+ const batch = await import("../server/save-batch.ts") as { batchSaves<T>(run: () => T): T; flushLaterSaves?: () => void };
+ const selection = () => ({ instanceId: "claude", model: "synthetic" });
+ const seed = new Store(selection);
+ const first = seed.createBot({ name: "Bench 0" }, { seedMessages: false });
+ const file = join(process.env.OMB_DATA_DIR!, "bots.json");
+ const template = JSON.parse(JSON.stringify(seed.bot(first.id)));
+ const rows = Array.from({ length: bots }, (_, b) => ({ ...template, id: randomUUID(), threadId: `thread-${b}-0`, name: `Bench ${b}`,
+ tasks: Array.from({ length: threads }, (_, t) => ({ ...template.tasks[0], id: randomUUID(), threadId: `thread-${b}-${t}`,
+ title: `Synthetic thread ${t} with a title of ordinary length`, resumeCursors: { claude: { sessionId: randomUUID() } },
+ usage: { input: 120_000 + t, output: 4_000 + t, cachedInput: 90_000, costUsd: null, turns: 12, lastTurn: { input: 900, output: 80, costUsd: null } } })) }));
+ writeFileSync(file, JSON.stringify(rows));
+ const store = new Store(selection);
+ const bytes = statSync(file).size;
+
+ const saves: number[] = [];
+ for (let i = 0; i < 9; i++) {
+ const at = performance.now();
+ store.patchBot(rows[0]!.id, { title: `Durable change ${i}` });
+ saves.push(performance.now() - at);
+ }
+ const oneSaveMs = Number(saves.sort((a, b) => a - b)[4]!.toFixed(1));
+
+ let writes = 0, inode = statSync(file).ino;
+ const counted = () => { const now = statSync(file).ino; if (now !== inode) { writes += 1; inode = now; } };
+ // As the server does: the turn's start is one batch, its dispatch records which engine has the thread and what it was
+ // handed, the session event names the engine session, and the event that settles the turn is one batch.
+ const oneTurn = (turn: number) => {
+ const botId = rows[turn % bots]!.id, threadId = `thread-${turn % bots}-1`;
+ batch.batchSaves(() => { store.setTaskAskedAt(botId, threadId, Date.now()); store.patchTask(botId, threadId, { unread: false }); }); counted();
+ store.markTaskDispatched(botId, threadId, "claude"); counted();
+ store.setHandedMessages(botId, threadId, "claude", { session: { sessionId: `session-${turn % bots}` }, lastMessageId: `m-${turn}-${Date.now()}` } as never); counted();
+ batch.batchSaves(() => store.setResumeCursor(botId, "claude", { sessionId: `session-${turn % bots}` }, threadId)); counted();
+ batch.batchSaves(() => {
+ store.addTaskUsage(botId, threadId, { input: 900, output: 80, costUsd: null });
+ store.patchTask(botId, threadId, { lastContextModel: "claude:synthetic" });
+ (store.patchTask as (...args: unknown[]) => unknown)(botId, threadId, { unread: true }, { turnEnd: true });
+ }); counted();
+ };
+ // A first round names each thread's engine and session; the measured round is a later one, as most turns are.
+ for (let turn = 0; turn < TURNS_TOGETHER; turn++) oneTurn(turn);
+ batch.flushLaterSaves?.();
+ writes = 0; inode = statSync(file).ino;
+ const lag = monitorEventLoopDelay({ resolution: 1 });
+ lag.enable();
+ await delay(20);
+ lag.reset();
+ const start = performance.now();
+ let busyMs = 0;
+ for (let turn = 0; turn < TURNS_TOGETHER; turn++) {
+ const at = performance.now();
+ oneTurn(turn);
+ busyMs += performance.now() - at;
+ await new Promise((resolve) => setImmediate(resolve));
+ counted();
+ }
+ const roundMs = performance.now() - start;
+ await delay(1_200);
+ counted();
+ lag.disable();
+ batch.flushLaterSaves?.();
+ console.log(JSON.stringify({ bots, threads, botsJsonMb: Number((bytes / 1e6).toFixed(1)), oneSaveMs, turns: TURNS_TOGETHER, wholeFileWrites: writes,
+ roundBlockedMs: Math.round(busyMs), roundMs: Math.round(roundMs), eventLoopMaxMs: Number((lag.max / 1e6).toFixed(1)) }));
+}
diff --git a/scripts/bench-many-bots.ts b/scripts/bench-many-bots.ts
new file mode 100644
index 0000000000..f0b4a0e368
--- /dev/null
+++ b/scripts/bench-many-bots.ts
@@ -0,0 +1,161 @@
+// A real server from source in a temporary home, driven by the repository's fake Claude engine: many bots, each with
+// many threads, are sent work at once. Reports send-to-start latency, stream volume, health stalls and what the
+// server's own diagnostics say. No AI account is used and no user data is touched.
+import { readFileSync, writeFileSync } from "node:fs";
+import { randomUUID } from "node:crypto";
+import { arch, availableParallelism, platform } from "node:os";
+import { join } from "node:path";
+import { performance } from "node:perf_hooks";
+import { setTimeout as delay } from "node:timers/promises";
+
+import { launchRestartableServer } from "../server/testing/restartable-server.ts";
+
+const arg = (name: string, fallback: string): string => {
+ const at = process.argv.indexOf(`--${name}`);
+ return at > 0 && process.argv[at + 1] ? process.argv[at + 1]! : fallback;
+};
+const BOTS = Number(arg("bots", "34")), THREADS = Number(arg("threads", "200")), ROUNDS = Number(arg("rounds", "3"));
+/** What the measuring client tells the server it understands: "whole" is a client from before thread frames. */
+const FRAMES = arg("frames", "whole");
+const quantile = (values: number[], q: number): number | null => values.length
+ ? Math.round([...values].sort((a, b) => a - b)[Math.min(values.length - 1, Math.floor(values.length * q))]!) : null;
+
+const WAIT_MS = Number(arg("wait", "90")) * 1_000;
+
+const server = await launchRestartableServer();
+for (const signal of ["SIGINT", "SIGTERM", "SIGALRM"] as const) process.once(signal, () => { void server.close().finally(() => process.exit(1)); });
+const api = async (method: string, path: string, body?: unknown): Promise<any> => {
+ const response = await fetch(`${server.url}${path}`, { method, headers: { "content-type": "application/json", origin: server.url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ const text = await response.text();
+ if (!response.ok) throw new Error(`${method} ${path}: ${response.status} ${text.slice(0, 300)}`);
+ return text ? JSON.parse(text) : {};
+};
+
+try {
+ const botIds: string[] = [];
+ for (let i = 0; i < BOTS; i++) botIds.push((await api("POST", "/api/bots", { name: `Bench ${i + 1}` })).bot.id);
+ for (const botId of botIds) await api("POST", `/api/bots/${botId}/tasks`, { title: "Bench thread" });
+ await server.stop();
+ const botsFile = join(server.dataDir, "bots.json");
+ const bots = JSON.parse(readFileSync(botsFile, "utf8")) as Array<{ id: string; tasks: Array<Record<string, unknown>> }>;
+ const targets = new Map<string, string>();
+ for (const bot of bots) {
+ const template = bot.tasks[0]!;
+ targets.set(bot.id, String(template.threadId));
+ for (let i = bot.tasks.length; i < THREADS; i++) {
+ bot.tasks.push({ ...template, id: randomUUID(), threadId: randomUUID(), title: `Synthetic thread ${i} with a title of ordinary length`,
+ usage: { inputTokens: 120_000 + i, outputTokens: 4_000 + i, cachedInputTokens: 90_000, contextTokens: 60_000 } });
+ }
+ }
+ const bytesOnDisk = Buffer.byteLength(JSON.stringify(bots));
+ writeFileSync(botsFile, JSON.stringify(bots));
+ await server.start();
+
+ const started = new Map<string, number>(), completed = new Set<string>();
+ const stream = { bytes: 0, reconnects: 0, snapshots: 0, snapshotBytes: 0, byKind: new Map<string, { frames: number; bytes: number }>() };
+ const abort = new AbortController();
+ /** Reads the stream as EventSource does: when the server ends it, connect again from the last id, and load everything
+ * again when the server says it could not resume. */
+ void (async () => {
+ const decoder = new TextDecoder();
+ let cursor = "";
+ while (!abort.signal.aborted) {
+ try {
+ const query = `window=1${FRAMES === "whole" ? "" : `&frames=${FRAMES}`}${cursor ? `&since=${encodeURIComponent(cursor)}` : ""}`;
+ const events = await fetch(`${server.url}/api/events?${query}`, { headers: { origin: server.url }, signal: abort.signal });
+ let buffered = "";
+ for await (const chunk of events.body as unknown as AsyncIterable<Uint8Array>) {
+ stream.bytes += chunk.byteLength;
+ buffered += decoder.decode(chunk, { stream: true });
+ for (let end = buffered.indexOf("\n\n"); end >= 0; end = buffered.indexOf("\n\n")) {
+ const block = buffered.slice(0, end);
+ buffered = buffered.slice(end + 2);
+ const lines = block.split("\n");
+ const id = lines.find(line => line.startsWith("id: "));
+ if (id) cursor = id.slice(4);
+ const data = lines.find(line => line.startsWith("data: "));
+ if (!data) continue;
+ const frame = JSON.parse(data.slice(6)) as { kind?: string; resumed?: boolean; cursor?: string; event?: { type?: string; threadId?: string } };
+ const kind = String(frame.kind);
+ const tally = stream.byKind.get(kind) ?? { frames: 0, bytes: 0 };
+ tally.frames += 1; tally.bytes += Buffer.byteLength(block) + 2;
+ stream.byKind.set(kind, tally);
+ if (kind === "hello" && frame.cursor) {
+ if (cursor && frame.resumed === false) {
+ const snapshot = await fetch(`${server.url}/api/bots?messages=0`, { headers: { origin: server.url }, signal: abort.signal });
+ const body = await snapshot.arrayBuffer();
+ stream.snapshots += 1; stream.snapshotBytes += body.byteLength;
+ for (const bot of (JSON.parse(decoder.decode(body)) as { bots: Array<{ tasks?: Array<{ threadId: string; busy?: boolean }> }> }).bots) {
+ for (const task of bot.tasks ?? []) if (started.has(task.threadId) && !task.busy) completed.add(task.threadId);
+ }
+ }
+ if (!cursor || frame.resumed === false) cursor = frame.cursor;
+ }
+ const threadId = frame.event?.threadId;
+ if (kind === "runtime" && threadId && frame.event?.type === "turn.started" && !started.has(threadId)) started.set(threadId, performance.now());
+ if (kind === "runtime" && threadId && frame.event?.type === "turn.completed") completed.add(threadId);
+ }
+ }
+ } catch { /* closed: by abort, or by the server */ }
+ if (abort.signal.aborted) break;
+ stream.reconnects += 1;
+ await delay(250);
+ }
+ })();
+
+ const health: number[] = [];
+ let probing = true;
+ const probe = (async () => {
+ while (probing) {
+ const at = performance.now();
+ try { await fetch(`${server.url}/api/health`, { signal: AbortSignal.timeout(20_000) }); } catch { /* counted as its duration */ }
+ health.push(performance.now() - at);
+ await delay(20);
+ }
+ })();
+
+ await delay(1_000);
+ console.log(JSON.stringify({ benchmark: "many-bots", node: process.version, platform: platform(), arch: arch(), cpus: availableParallelism(),
+ bots: BOTS, threadsPerBot: THREADS, clientFrames: FRAMES, botsJsonBytes: bytesOnDisk,
+ scope: "Real server from source with the fake Claude engine; each round sends one message to every bot at once. Not model throughput." }));
+ for (let round = 1; round <= ROUNDS; round++) {
+ started.clear(); completed.clear(); health.length = 0;
+ const bytesBefore = stream.bytes + stream.snapshotBytes, reconnectsBefore = stream.reconnects, kindsBefore = new Map([...stream.byKind].map(([kind, tally]) => [kind, { ...tally }]));
+ const sent = new Map<string, number>();
+ const roundStart = performance.now();
+ await Promise.all(botIds.map(async (botId) => {
+ const threadId = targets.get(botId)!;
+ sent.set(threadId, performance.now());
+ await api("POST", `/api/bots/${botId}/messages`, { text: `Round ${round}: reply with one line.`, threadId });
+ }));
+ const deadline = Date.now() + WAIT_MS;
+ while (completed.size < BOTS && Date.now() < deadline) await delay(25);
+ const roundMs = Math.round(performance.now() - roundStart);
+ // A stream the server cut and could not resume misses turn events: ask the server what finished.
+ const seenOnStream = completed.size;
+ if (seenOnStream < BOTS) {
+ const wanted = new Set(targets.values());
+ for (const bot of (await api("GET", "/api/bots?messages=0")).bots as Array<{ tasks?: Array<{ threadId: string; busy?: boolean }> }>) {
+ for (const task of bot.tasks ?? []) if (wanted.has(task.threadId) && !task.busy) completed.add(task.threadId);
+ }
+ }
+ await delay(1_500);
+ const toStart = [...sent].flatMap(([threadId, at]) => started.has(threadId) ? [started.get(threadId)! - at] : []);
+ const bot = stream.byKind.get("bot"), botBefore = kindsBefore.get("bot");
+ console.log(JSON.stringify({ round, turnsCompleted: completed.size, turnEndsSeenOnStream: seenOnStream, roundMs,
+ sendToStartP50Ms: quantile(toStart, .5), sendToStartP95Ms: quantile(toStart, .95), sendToStartMaxMs: quantile(toStart, 1),
+ streamKbPerTurn: Math.round((stream.bytes + stream.snapshotBytes - bytesBefore) / 1024 / BOTS), streamCutByServer: stream.reconnects - reconnectsBefore, botFramesPerTurn: Number((((bot?.frames ?? 0) - (botBefore?.frames ?? 0)) / BOTS).toFixed(1)),
+ botFrameKbPerTurn: Math.round(((bot?.bytes ?? 0) - (botBefore?.bytes ?? 0)) / 1024 / BOTS),
+ healthP95Ms: quantile(health, .95), healthMaxMs: quantile(health, 1) }));
+ }
+ probing = false;
+ await probe;
+ const perf = await api("GET", "/api/diagnostics/performance").catch((error) => ({ error: String(error) }));
+ console.log(JSON.stringify({ diagnostics: perf }).slice(0, 6_000));
+ const botsBody = await fetch(`${server.url}/api/bots`, { headers: { origin: server.url } });
+ console.log(JSON.stringify({ getBotsBytes: (await botsBody.arrayBuffer()).byteLength }));
+ abort.abort();
+} finally {
+ await server.close();
+}
diff --git a/scripts/bench-persistence.ts b/scripts/bench-persistence.ts
index 81e0708d2e..7fdfac9d06 100644
--- a/scripts/bench-persistence.ts
+++ b/scripts/bench-persistence.ts
@@ -1,4 +1,5 @@
// Synthetic local persistence only. Never import config before isolating data.
+// `--bots [BOTSxTHREADS ...]` measures whole-file saves of bots.json instead (scripts/bench-bots-save.ts).
import { appendFileSync, mkdtempSync, mkdirSync, rmSync } from "node:fs";
import { DatabaseSync } from "node:sqlite";
import { tmpdir, platform, arch } from "node:os";
@@ -6,6 +7,11 @@ import { join } from "node:path";
import { monitorEventLoopDelay, performance } from "node:perf_hooks";
import { setImmediate as yieldLoop, setTimeout as delay } from "node:timers/promises";
+if (process.argv.includes("--bots")) {
+ await import("./bench-bots-save.ts");
+ process.exit(0);
+}
+
const directory = mkdtempSync(join(tmpdir(), "omb-persistence-bench-"));
const previousDataDir = process.env.OMB_DATA_DIR;
process.env.OMB_DATA_DIR = directory;
diff --git a/server/bot-thread-frames.e2e.test.ts b/server/bot-thread-frames.e2e.test.ts
new file mode 100644
index 0000000000..e63e2e653b
--- /dev/null
+++ b/server/bot-thread-frames.e2e.test.ts
@@ -0,0 +1,80 @@
+// Real server and the repository's fake Claude: what a stream gets when one thread of a bot changes.
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it, vi } from "vitest";
+
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { openSse } from "./testing/sse.ts";
+
+it("sends a thread's change alone to a stream that asked for it, the whole bot to one that did not, and saves the turn's bookkeeping together", async () => {
+ const fixture = await launchVerificationServer({ ...process.env });
+ const { url, dataDir } = fixture.info;
+ const control = (args: string[]) => runControlOmb([...args, "--url", url]) as Promise<any>;
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${url}${path}`, { method, headers: { origin: url, "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;
+ };
+ const snapshot = async (botId: string) => ((await api("GET", "/api/bots?messages=0")).bots as any[]).find((bot) => bot.id === botId);
+ const { bot } = await control(["new-bot", "--name", "Maus"]);
+ for (const title of ["Second", "Third"]) await api("POST", `/api/bots/${bot.id}/tasks`, { title });
+ const known = await snapshot(bot.id);
+ expect(known.tasks).toHaveLength(3);
+ const threadId = known.tasks.find((task: any) => task.title === "Second").threadId as string;
+
+ const threads = await openSse(`${url}/api/events?frames=thread`, { origin: url });
+ let whole = await openSse(`${url}/api/events`, { origin: url });
+ const botFrames = (stream: { frames: any[] }) => stream.frames.filter((frame) => frame.kind === "bot" && frame.bot.id === bot.id);
+ const turn = async (text: string) => {
+ expect((await control(["send", "--bot", bot.id, "--task", threadId, "--text", text])).success).toBe(true);
+ expect((await control(["wait", "--bot", bot.id, "--task", threadId, "--timeout", "30"])).status).toBe("settled");
+ };
+ try {
+ await turn("Reply with one line.");
+ await vi.waitFor(() => expect(botFrames(threads).at(-1)?.bot.tasks[0]).toMatchObject({ busy: false, unread: true }), { timeout: 10_000 });
+ const partial = botFrames(threads);
+ expect(partial.length).toBeGreaterThanOrEqual(5);
+ for (const frame of partial) {
+ expect(frame.tasksPartial).toBe(true);
+ expect(frame.bot.tasks.map((task: any) => task.threadId)).toEqual([threadId]);
+ expect(frame.bot).toMatchObject({ id: bot.id, name: "Maus" });
+ }
+
+ await vi.waitFor(() => expect(botFrames(whole).length).toBe(partial.length), { timeout: 10_000 });
+ for (const frame of botFrames(whole)) {
+ expect(frame.tasksPartial).toBeUndefined();
+ expect(frame.bot.tasks).toHaveLength(3);
+ }
+
+ // The thread frames, applied to what the client knew, are the bot as the server now gives it whole.
+ const applied = partial.reduce((seen: any, frame: any) => ({ ...frame.bot, tasks: seen.tasks.map((task: any) => frame.bot.tasks.find((next: any) => next.threadId === task.threadId) ?? task) }), known);
+ const now = await snapshot(bot.id);
+ expect(applied.tasks).toEqual(now.tasks);
+ expect(botFrames(whole).at(-1).bot.tasks).toEqual(now.tasks);
+
+ // The turn's bookkeeping reaches bots.json a moment later, in one piece.
+ const saved = () => (JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8")) as any[])[0].tasks.find((task: any) => task.threadId === threadId);
+ await vi.waitFor(() => expect(saved()).toMatchObject({ usage: { turns: 1 }, unread: true }), { timeout: 5_000, interval: 50 });
+ expect(Object.keys(saved().resumeCursors)).toHaveLength(1);
+
+ // With no whole-frame stream open the whole bot is not built, so such a stream cannot resume across the gap: it is told to load again.
+ const cursor = (whole.frames.find((frame) => frame.kind === "hello").cursor as string).split(":")[0];
+ const lastSeq = Math.max(...whole.frames.map((frame) => frame.seq ?? 0));
+ whole.close();
+ await vi.waitFor(async () => expect((await api("GET", "/api/health")).app).toBe("openmausbot"));
+ await turn("And another line.");
+ whole = await openSse(`${url}/api/events?since=${cursor}:${lastSeq}`, { origin: url });
+ expect((await whole.until((frame) => frame.kind === "hello")).resumed).toBe(false);
+ const again = await openSse(`${url}/api/events?frames=thread&since=${cursor}:${lastSeq}`, { origin: url });
+ try {
+ expect((await again.until((frame) => frame.kind === "hello")).resumed).toBe(true);
+ const replayed = await again.until((frame) => frame.kind === "bot" && frame.bot.id === bot.id);
+ expect(replayed.tasksPartial).toBe(true);
+ } finally { again.close(); }
+ } finally {
+ threads.close();
+ whole.close();
+ await fixture.close();
+ }
+}, 120_000);
diff --git a/server/host/bot-frames.test.ts b/server/host/bot-frames.test.ts
new file mode 100644
index 0000000000..db0081907c
--- /dev/null
+++ b/server/host/bot-frames.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vitest";
+
+import { createBotFrames, takesFrame, type BotFrameForm } from "./bot-frames.ts";
+
+interface Bot { id: string; tasks?: Array<{ threadId: string; title: string }> }
+
+function rig(wholeListeners: boolean) {
+ const sent: Array<{ payload: Record<string, unknown>; frames?: BotFrameForm }> = [];
+ const wired: Array<string | undefined> = [];
+ const state = { wholeListeners, seq: 0 };
+ const frames = createBotFrames<Bot>({
+ broadcast: (payload, options) => { state.seq += 1; sent.push({ payload, ...(options ? { frames: options.frames } : {}) }); },
+ wire: (bot, onlyThreadId) => {
+ wired.push(onlyThreadId);
+ return { id: bot.id, name: "Maus", tasks: (bot.tasks ?? []).filter((task) => onlyThreadId === undefined || task.threadId === onlyThreadId) };
+ },
+ wholeListeners: () => state.wholeListeners,
+ lastSeq: () => state.seq,
+ });
+ return { frames, sent, wired, state };
+}
+
+const bot: Bot = { id: "b1", tasks: [{ threadId: "t1", title: "One" }, { threadId: "t2", title: "Two" }, { threadId: "t3", title: "Three" }] };
+
+describe("bot frames", () => {
+ it("sends one thread's change as the bot with that thread alone, and builds no whole bot when nobody takes one", () => {
+ const { frames, sent, wired } = rig(false);
+ frames.send(bot, "t2");
+ expect(sent).toEqual([{ frames: "thread", payload: { kind: "bot", tasksPartial: true, bot: { id: "b1", name: "Maus", tasks: [{ threadId: "t2", title: "Two" }] } } }]);
+ expect(wired).toEqual(["t2"]);
+ });
+
+ it("also sends the whole bot, unmarked, while a stream that takes only whole frames is open", () => {
+ const { frames, sent } = rig(true);
+ frames.send(bot, "t2", { messages: [] });
+ expect(sent.map((frame) => frame.frames)).toEqual(["thread", "whole"]);
+ expect(sent[0]!.payload).toMatchObject({ tasksPartial: true, bot: { messages: [] } });
+ expect(sent[1]!.payload).toEqual({ kind: "bot", bot: { id: "b1", name: "Maus", tasks: bot.tasks, messages: [] } });
+ });
+
+ it("sends the whole bot to every stream when the change names no thread, or one the bot does not have", () => {
+ const { frames, sent } = rig(false);
+ frames.send(bot);
+ frames.send(bot, "gone");
+ frames.send({ id: "b2" }, "t1");
+ expect(sent.map((frame) => frame.frames)).toEqual([undefined, undefined, undefined]);
+ expect(sent.every((frame) => !("tasksPartial" in frame.payload))).toBe(true);
+ expect((sent[0]!.payload.bot as Bot).tasks).toHaveLength(3);
+ });
+
+ it("gives each stream exactly one form of a thread's change", () => {
+ for (const form of ["thread", "whole"] as const) {
+ expect(takesFrame(true, form)).toBe(form === "thread");
+ expect(takesFrame(false, form)).toBe(form === "whole");
+ }
+ expect(takesFrame(true, undefined)).toBe(true);
+ expect(takesFrame(false, undefined)).toBe(true);
+ });
+
+ it("does not let a whole-frame stream resume across a whole frame that was never built", () => {
+ const { frames, state } = rig(true);
+ frames.send(bot, "t1");
+ expect(frames.resumable(0, false)).toBe(true);
+ state.wholeListeners = false;
+ frames.send(bot, "t1");
+ const skippedAt = state.seq;
+ expect(frames.resumable(skippedAt - 1, false)).toBe(false);
+ expect(frames.resumable(skippedAt, false)).toBe(true);
+ expect(frames.resumable(0, true)).toBe(true);
+ });
+});
diff --git a/server/host/bot-frames.ts b/server/host/bot-frames.ts
new file mode 100644
index 0000000000..979d959e40
--- /dev/null
+++ b/server/host/bot-frames.ts
@@ -0,0 +1,33 @@
+/** Which streams a bot frame goes to: those that said they take frames carrying only the changed thread, or the rest. */
+export type BotFrameForm = "thread" | "whole";
+
+export const takesFrame = (threadFrames: boolean, form: BotFrameForm | undefined): boolean =>
+ form === undefined || (form === "thread") === threadFrames;
+
+export interface BotFramesDeps<Bot> {
+ broadcast(payload: Record<string, unknown>, options?: { frames: BotFrameForm }): void;
+ /** The bot as clients see it; with `onlyThreadId`, carrying that thread alone. */
+ wire(bot: Bot, onlyThreadId?: string): object;
+ /** Whether a stream is open that takes only whole frames. */
+ wholeListeners(): boolean;
+ lastSeq(): number;
+}
+
+/** A change to one thread of a bot is sent as the bot with that thread alone (`tasksPartial`) to streams that asked for
+ * it. Any other stream gets the whole bot, as before; with none open, the whole bot is not built at all. */
+export function createBotFrames<Bot extends { tasks?: ReadonlyArray<{ threadId: string }> }>(deps: BotFramesDeps<Bot>) {
+ let wholeSkippedAt = 0;
+ return {
+ send(bot: Bot, threadId?: string, extra: object = {}): void {
+ if (threadId === undefined || !bot.tasks?.some((task) => task.threadId === threadId)) {
+ deps.broadcast({ kind: "bot", bot: { ...deps.wire(bot), ...extra } });
+ return;
+ }
+ deps.broadcast({ kind: "bot", bot: { ...deps.wire(bot, threadId), ...extra }, tasksPartial: true }, { frames: "thread" });
+ if (deps.wholeListeners()) deps.broadcast({ kind: "bot", bot: { ...deps.wire(bot), ...extra } }, { frames: "whole" });
+ else wholeSkippedAt = deps.lastSeq();
+ },
+ /** A stream that takes only whole frames cannot resume across one that was never built: it loads everything again. */
+ resumable: (since: number, threadFrames: boolean): boolean => threadFrames || wholeSkippedAt <= since,
+ };
+}
diff --git a/server/host/sse-replay.ts b/server/host/sse-replay.ts
index 234a0bde15..9fd13be7d0 100644
--- a/server/host/sse-replay.ts
+++ b/server/host/sse-replay.ts
@@ -1,3 +1,5 @@
+import type { BotFrameForm } from "./bot-frames.ts";
+
export interface ReplayFrame {
seq: number;
kind: string;
@@ -6,6 +8,8 @@ export interface ReplayFrame {
payload: Record<string, unknown> | null;
/** Only this person's streams get it (a Team Cloud's room as they read it). */
person?: string;
+ /** Only streams that take this form of bot frame get it. */
+ frames?: BotFrameForm;
}
export const REPLAY_MAX_FRAMES = 500;
diff --git a/server/index.ts b/server/index.ts
index d2a1bb51e6..45130ec9a3 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -437,7 +437,7 @@ import { claudeUserSkillsEnabled } from "./turn-settings.ts";
import { addHeldSecretScrubber, redactSecretsInText, scrubHeldSecrets } from "./redact.ts";
import * as vps from "./vps-computer.ts";
import { vpsConfigForBot, vpsSshAliasForBot } from "./vps-hosts.ts";
-import { ROUTINE_RESTARTED, RoutineManager, type Routine, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts"; import { routineModelRefusal, routineThreadModel, type RoutineModelChecks } from "./routine-input.ts"; import { routineHistoryFor, routineRunsFor } from "./routine-run-window.ts"; import { runTurnLive } from "./routine-turn-live.ts"; import { batchSaves } from "./save-batch.ts";
+import { ROUTINE_RESTARTED, RoutineManager, type Routine, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts"; import { routineModelRefusal, routineThreadModel, type RoutineModelChecks } from "./routine-input.ts"; import { routineHistoryFor, routineRunsFor } from "./routine-run-window.ts"; import { runTurnLive } from "./routine-turn-live.ts"; import { batchSaves, flushLaterSaves } from "./save-batch.ts";
import { CalendarCallManager, type CalendarCall } from "./calendar-calls.ts";
import { BROWSER_UPLOAD_TOOL, browserRuntimeEnv } from "./browser-runtime.ts";
import { BrowserUploadRefusal, uploadableFiles } from "./browser-upload.ts";
@@ -579,7 +579,7 @@ import {
type Viewer,
} from "./bot-visibility.ts";
import { describeBrand, loadBrand } from "./brand.ts";
-import { deliverSseFrame, openSseHeartbeat } from "./sse-fanout.ts";
+import { deliverSseFrame, openSseHeartbeat } from "./sse-fanout.ts"; import { createBotFrames, takesFrame, type BotFrameForm } from "./host/bot-frames.ts";
import { PhoneSecretBridge, PhoneSecretSubmissionRegistry } from "./phone-secret.ts";
// Keep these two last, so loading the route table leaves module start-up order as is.
import { gzipTunnelReplies, json, onJsonBody, parsedBodyOf, readBody } from "./harness/http.ts";
@@ -2921,7 +2921,7 @@ const wireTask = (task: TaskRecord, botModel: ModelSelection, awaiting = threads
};
/** Strips provider session ids (resumeCursors) here, not at call sites, so no broadcast or paired phone ever gets them. */
-const wireBot = (bot: BotRecord): WireBot => {
+const wireBot = (bot: BotRecord, onlyThreadId?: string): WireBot => {
const { resumeCursors: _resumeCursors, tasks, approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, ...rest } = bot;
// Clients see Ask while an elevated grant awaits the desktop's confirmation, never a grant that may still roll back.
const visible = approvalGrant && !approvalGrant.threadOnly
@@ -2930,7 +2930,7 @@ const wireBot = (bot: BotRecord): WireBot => {
const awaiting = threadsAwaitingTeammates();
return { ...visible, waitingForTeammates: awaiting.has(bot.threadId) && !threadBusy(bot.id, bot.threadId),
mainThreadId: botMainThread(bot.id),
- avatarUrl: visible.avatarUrl ?? null, ...(tasks ? { tasks: tasks.map((task) => wireTask(task, bot.modelSelection, awaiting)) } : {}) };
+ avatarUrl: visible.avatarUrl ?? null, ...(tasks ? { tasks: (onlyThreadId === undefined ? tasks : tasks.filter((task) => task.threadId === onlyThreadId)).map((task) => wireTask(task, bot.modelSelection, awaiting)) } : {}) };
};
function toolScopeForTurn(botId: string) {
@@ -3935,7 +3935,7 @@ const botLink = createBotLinkHost({ dataDir: DATA_DIR, environmentId: ENVIRONMEN
for (const threadId of directThreadIds) {
settleTrackedRequest(threadId);
const bot = store.botByThread(threadId);
- if (bot) broadcast({ kind: "bot", bot: wireBot(bot) });
+ if (bot) botFrames.send(bot, threadId);
}
// Node changes are the release signal for messages parked behind a settled coordination: no later turn.completed arrives.
if (directThreadIds.size > 0) drainQueuedSends();
@@ -4548,7 +4548,7 @@ store.onChange((change) => {
break;
case "bot": {
const bot = store.bot(change.botId);
- if (bot) broadcast({ kind: "bot", bot: { ...wireBot(bot), ...pageIfThreadChanged(bot.id, bot.threadId) } });
+ if (bot) botFrames.send(bot, change.threadId, pageIfThreadChanged(bot.id, bot.threadId));
if (bot) for (const group of store.groups.filter((candidate) => candidate.memberIds.includes(bot.id))) settleRoomFloor(group);
break;
}
@@ -4629,7 +4629,7 @@ interface SseClient {
admin: boolean;
/** On a Team Cloud, who the stream is for: its config frames carry that person's own profile. */
person?: SessionRecord;
- screens: boolean;
+ screens: boolean; /** Takes bot frames that carry only the changed thread (`?frames=thread`). */ threadFrames: boolean;
appWindow: boolean; /** The phone behind this stream, as routes/phones.ts keys it: while it is open, that phone gets no push. */ pushKey?: string;
/** Revoking or expiring this session must end the stream, not just future requests. */
sessionId?: string;
@@ -4724,7 +4724,7 @@ const SSE_HEARTBEAT_MS =
let lastSeq = 0;
const replayBuffer = new ReplayBuffer();
-const wants = (client: SseClient, kind: string) => kind !== "screen" || client.screens;
+const wants = (client: SseClient, kind: string, form?: BotFrameForm) => (kind !== "screen" || client.screens) && takesFrame(threadFramesFor(client), form); /** A stream narrowed to what one person may see derives fields from the bot's whole thread list, so it keeps whole frames. */ const threadFramesFor = (client: SseClient) => client.threadFrames && client.viewer.kind === "all" && !visibleTo(client.viewer).filtersThreads; const botFrames = createBotFrames<BotRecord>({ broadcast, wire: (bot, onlyThreadId) => wireBot(bot, onlyThreadId), wholeListeners: () => Array.from(sseClients).some((client) => !threadFramesFor(client)), lastSeq: () => lastSeq });
function cursorSeq(raw: string | string[] | undefined): number | null {
const value = Array.isArray(raw) ? raw[0] : raw;
@@ -4736,7 +4736,7 @@ function cursorSeq(raw: string | string[] | undefined): number | null {
}
/** `adminOnly` frames are withheld from client sessions, live and on replay; a `person`'s frames reach only their streams. */
-function broadcast(payload: Record<string, unknown>, options: { adminOnly?: boolean; person?: string } = {}) {
+function broadcast(payload: Record<string, unknown>, options: { adminOnly?: boolean; person?: string; frames?: BotFrameForm } = {}) {
// Close stale email streams before any further workspace data is delivered.
sessions.recheckMembership();
const seq = ++lastSeq;
@@ -4745,10 +4745,10 @@ function broadcast(payload: Record<string, unknown>, options: { adminOnly?: bool
// Members get config as configured-or-not and every bot without its server alias.
const clientPayload = options.adminOnly ? null : kind === "config" ? configForAccess(payload as ReturnType<typeof configStatus>, false) : memberFramePayload(payload);
const clientFrame = clientPayload === null ? null : clientPayload === payload ? frame : `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...clientPayload, seq })}\n\n`;
- replayBuffer.push({ seq, kind, frame, clientFrame, payload, ...(options.person ? { person: options.person } : {}) }); if (kind === "notify") phonePush.offer({ notification: payload.notification, seq }, (key) => pushReaches(key, payload, seq, options)); if (kind === "notify" || kind === "bot" || kind === "runtime") phoneActivity.offer(payload, (key) => pushReaches(key, payload, seq, options));
+ replayBuffer.push({ seq, kind, frame, clientFrame, payload, ...(options.person ? { person: options.person } : {}), ...(options.frames ? { frames: options.frames } : {}) }); if (kind === "notify") phonePush.offer({ notification: payload.notification, seq }, (key) => pushReaches(key, payload, seq, options)); if (kind === "notify" || kind === "bot" || kind === "runtime") phoneActivity.offer(payload, (key) => pushReaches(key, payload, seq, options));
const ownGroups: OwnGroupFrames = new Map();
for (const client of Array.from(sseClients)) {
- if (!wants(client, kind) || !teamOwners.reaches(client.ask, payload) || !streamFor(client, options.person)) continue;
+ if (!wants(client, kind, options.frames) || !teamOwners.reaches(client.ask, payload) || !streamFor(client, options.person)) continue;
// Admin-only frames (clientFrame null) never reach members, and a member never falls back to the admin frame.
const out = CLOUD_TEAM && kind === "config" && clientFrame !== null ? teamConfigFrame(client, seq, payload)
: memberFrame(client, seq, payload, client.admin ? frame : clientFrame, ownGroups);
@@ -5242,7 +5242,7 @@ const cacheKeepWarm = createCacheKeepWarm({
book: bookForkUsage,
changed: ({ threadId }) => {
const bot = store.botByThread(threadId);
- if (bot) broadcast({ kind: "bot", bot: wireBot(bot) });
+ if (bot) botFrames.send(bot, threadId);
},
});
cacheKeepWarmStatus = (threadId) => cacheKeepWarm.status(threadId);
@@ -6819,7 +6819,7 @@ bus.subscribe((event: RuntimeEvent) => {
settlingTurns.add(event.threadId);
liveTurnByThread.delete(event.threadId);
const routineReportThread = routineRun ? routineSourceThread(routineRun) : null;
- if (!routineReportThread && (!internal || reviewAnswer) && (!routineRun || routineRunNeedsReview(routineRun, reply) || personWaits.open(event.threadId))) store.patchTask(bot.id, event.threadId, { unread: true });
+ if (!routineReportThread && (!internal || reviewAnswer) && (!routineRun || routineRunNeedsReview(routineRun, reply) || personWaits.open(event.threadId))) store.patchTask(bot.id, event.threadId, { unread: true }, { turnEnd: true });
if (routineRun && routineReportThread !== event.threadId) automationReports.runSettled(routineRun, completedTurnId);
else if ((!routineRun || routineRun.status === "completed") && (!internal || reviewAnswer) && !computerSelectionTurns.get(event.threadId)?.selected && doneNotice.atTurnEnd({ botId: bot.id, threadId: event.threadId, review: reviewAnswer, ok: event.ok, routine: Boolean(routineRun) }) === "notify" && !personWaits.atTurnEnd(event.threadId, reply) && !unaskedBotThread(settledTask, store.activePath(event.threadId))) {
notify(buildNotification("done", bot, event.threadId, routineRun ? reply || routineRun.output || routineRun.routineName : reply, { avatarUrl: bot.avatarUrl }), routineRun ? { routine: true } : reviewAnswer ? { summary: true } : undefined);
@@ -14628,7 +14628,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const pushKey = phoneKey(auth);
const client: SseClient = {
res, ...streamView(auth, viewer), ...(pushKey ? { pushKey } : {}),
- screens: url.searchParams.get("screens") !== "off", appWindow: url.searchParams.get("window") === "1",
+ screens: url.searchParams.get("screens") !== "off", threadFrames: url.searchParams.get("frames") === "thread", appWindow: url.searchParams.get("window") === "1",
backpressured: false,
// A comment frame keeps intermediaries from idling the connection; a data frame resets EventSource's own liveness watchdog. Heartbeats carry no id.
close: openSseHeartbeat(res, {
@@ -14654,7 +14654,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const resumed =
since !== null &&
since <= lastSeq &&
- replayBuffer.covers(since, lastSeq) &&
+ replayBuffer.covers(since, lastSeq) && botFrames.resumable(since, threadFramesFor(client)) &&
// A replay is judged by today's audience and cannot withdraw what an audience change hid: snapshot instead.
!(viewer.kind === "member" && audienceChangedAt > 0 && since <= audienceChangedAt);
res.write(
@@ -14666,7 +14666,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
);
if (resumed) {
for (const buffered of replayBuffer) {
- if (buffered.seq <= since || !wants(client, buffered.kind) || (buffered.payload && !teamOwners.reaches(client.ask, buffered.payload)) || !streamFor(client, buffered.person)) continue;
+ if (buffered.seq <= since || !wants(client, buffered.kind, buffered.frames) || (buffered.payload && !teamOwners.reaches(client.ask, buffered.payload)) || !streamFor(client, buffered.person)) continue;
const frame = CLOUD_TEAM && buffered.kind === "config" && buffered.clientFrame !== null && buffered.payload
? teamConfigFrame(client, buffered.seq, buffered.payload)
: buffered.payload
@@ -15420,7 +15420,7 @@ const gracefulShutdown = createGracefulShutdown({
console.error("Session persistence failed during shutdown; account sign-in will be required again.");
exitCode = 1;
}
- closeMessageDb();
+ flushLaterSaves(); closeMessageDb();
mcpOAuth.dispose();
releaseDataDirLeaseAtExit();
process.exit(restartRequested && exitCode === 0 ? RESTART_EXIT_CODE : exitCode);
diff --git a/server/registry-save.ts b/server/registry-save.ts
index 5b65579303..ef066594a1 100644
--- a/server/registry-save.ts
+++ b/server/registry-save.ts
@@ -45,6 +45,24 @@ function restore(target: object, saved: object): void {
const PERMISSION_FIELDS = ["approvalMode", "autoApprove", "alwaysAllow"] as const;
+/**
+ * The only task changes whose save may wait (server/save-batch.ts saveLater), because losing the last second of them in
+ * a crash changes nothing a turn or a person relies on:
+ * - `lastContextModel` (which model the last context reading was for): lost, the next compaction check reads the
+ * context size as unmeasured, as after a fresh start.
+ * - `unread: true` set by a turn's own end (`turnEnd`): lost, a thread that just answered shows as read.
+ * - `usage` (addTaskUsage, not a patch): lost, the thread's token counters are short by the last turn. Plan limits and
+ * billing read their own ledgers, not these.
+ * Everything else is saved before the call returns: an engine session set or cleared, which engine has the thread, what
+ * was handed to it, when the person last wrote, read marks, a person's own unread mark, titles, grants.
+ */
+const DEFERRABLE_FIELDS: ReadonlySet<string> = new Set(["lastContextModel"]);
+
+export const deferrablePatch = (patch: TaskPatch, turnEnd = false): boolean => {
+ const keys = Object.keys(patch);
+ return keys.length > 0 && (keys.every((key) => DEFERRABLE_FIELDS.has(key)) || (turnEnd && keys.length === 1 && patch.unread === true));
+};
+
export const touchesPermissions = (patch: TaskPatch): boolean => PERMISSION_FIELDS.some((key) => Object.hasOwn(patch, key));
/** A revocation stays live when its save fails; a widening never does. */
diff --git a/server/save-batch.test.ts b/server/save-batch.test.ts
index b3fce2a33c..e6ea8c90ab 100644
--- a/server/save-batch.test.ts
+++ b/server/save-batch.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { batchSaves, saveSoon } from "./save-batch.ts";
+import { batchSaves, flushLaterSaves, SAVE_LATER_MAX_MS, saveLater, saveLaterDelayMs, saveSoon, supersedeLaterSave, waitingSaves } from "./save-batch.ts";
describe("batchSaves", () => {
it("writes at once outside a batch, and once per file when the outermost batch returns", () => {
@@ -34,3 +34,70 @@ describe("batchSaves", () => {
expect(batchSaves(() => 42)).toBe(42);
});
});
+
+describe("saveLater", () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { flushLaterSaves(); vi.useRealTimers(); });
+
+ it("writes once for every change asked for within the delay, across passes of the event loop", async () => {
+ const writes: string[] = [];
+ saveLater("a", () => writes.push("a1"));
+ await vi.advanceTimersByTimeAsync(10);
+ saveLater("a", () => writes.push("a2"));
+ batchSaves(() => saveLater("a", () => writes.push("a3")));
+ saveLater("b", () => writes.push("b1"));
+ expect(writes).toEqual([]);
+ expect(waitingSaves()).toBe(2);
+ await vi.advanceTimersByTimeAsync(saveLaterDelayMs());
+ expect(writes).toEqual(["a3", "b1"]);
+ expect(waitingSaves()).toBe(0);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(writes).toEqual(["a3", "b1"]);
+ });
+
+ it("counts the delay from the first change still waiting, so a steady stream of changes cannot put the write off", async () => {
+ const writes: number[] = [];
+ const delay = saveLaterDelayMs();
+ for (let i = 0; i < 10; i++) {
+ saveLater("a", () => writes.push(i));
+ await vi.advanceTimersByTimeAsync(delay / 5);
+ }
+ expect(writes.length).toBeGreaterThanOrEqual(1);
+ expect(delay).toBeLessThanOrEqual(SAVE_LATER_MAX_MS);
+ });
+
+ it("writes everything waiting at once when flushed, and nothing twice", async () => {
+ const writes: string[] = [];
+ saveLater("a", () => writes.push("a"));
+ saveLater("b", () => writes.push("b"));
+ flushLaterSaves();
+ expect(writes).toEqual(["a", "b"]);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(writes).toEqual(["a", "b"]);
+ });
+
+ it("drops a waiting write once the file was written whole another way", async () => {
+ const writes: string[] = [];
+ saveLater("a", () => writes.push("a"));
+ supersedeLaterSave("a");
+ await vi.advanceTimersByTimeAsync(5_000);
+ flushLaterSaves();
+ expect(writes).toEqual([]);
+ });
+
+ it("keeps a failed write waiting and tries it again", async () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ let fail = true;
+ const writes: string[] = [];
+ saveLater("a", () => { if (fail) throw new Error("disk full"); writes.push("a"); });
+ saveLater("b", () => writes.push("b"));
+ await vi.advanceTimersByTimeAsync(saveLaterDelayMs());
+ expect(writes).toEqual(["b"]);
+ expect(waitingSaves()).toBe(1);
+ fail = false;
+ await vi.advanceTimersByTimeAsync(SAVE_LATER_MAX_MS);
+ expect(writes).toEqual(["b", "a"]);
+ expect(error).toHaveBeenCalledOnce();
+ error.mockRestore();
+ });
+});
diff --git a/server/save-batch.ts b/server/save-batch.ts
index 0cf14cd28a..0a379f7a39 100644
--- a/server/save-batch.ts
+++ b/server/save-batch.ts
@@ -1,3 +1,5 @@
+import { RESTART_EXIT_CODE } from "./restart.ts";
+
// Whole-file saves asked for while one synchronous pass runs (one runtime event's delivery, a turn's start) are written
// once when the pass returns, before anything else can run: the files hold what they would have held at every point
// the server yields to the event loop, with one write instead of one per change.
@@ -33,3 +35,73 @@ function writePending(): void {
}
}
}
+
+// A few changes a turn makes at its end are harmless to lose (server/registry-save.ts DEFERRABLE_FIELDS says which and
+// why), and each whole-file save blocks the server for as long as the file is big. Those changes are written together,
+// a bounded moment after the first one. A crash inside that moment loses them: the file then holds the state of at most
+// SAVE_LATER_MAX_MS earlier, whole and consistent, since it is still written in one piece. Anything else (what a person
+// or a bot asked for, an engine session set or cleared, what was handed to an engine) never goes through here.
+const SAVE_LATER_MIN_MS = 50;
+export const SAVE_LATER_MAX_MS = 1_000;
+/** Saving waits this many times as long as the last save took, so it stays under a tenth of the server's time however big the file is. */
+const SAVE_LATER_COST_FACTOR = 10;
+const SAVE_LATER_RETRIES = 5;
+
+const later = new Map<unknown, () => void>();
+let laterTimer: ReturnType<typeof setTimeout> | undefined;
+let lastLaterWriteMs = 0;
+let laterFailures = 0;
+let flushesAtExit = false;
+
+export const saveLaterDelayMs = (): number => Math.min(SAVE_LATER_MAX_MS, Math.max(SAVE_LATER_MIN_MS, lastLaterWriteMs * SAVE_LATER_COST_FACTOR));
+
+/** Writes within saveLaterDelayMs() of the first change still waiting; `owner` (the file's path) keeps one waiting write per file. */
+export function saveLater(owner: unknown, write: () => void): void {
+ later.set(owner, write);
+ if (!flushesAtExit) {
+ flushesAtExit = true;
+ process.on("exit", flushAtCleanExit);
+ }
+ laterTimer ??= setTimeout(flushLaterSaves, saveLaterDelayMs());
+}
+
+/** A write still waiting for this file has nothing left to add: the file was just written whole, or is being loaded afresh. */
+export function supersedeLaterSave(owner: unknown): void {
+ later.delete(owner);
+}
+
+export const waitingSaves = (): number => later.size;
+
+/**
+ * What waits is written when the process ends cleanly: a graceful shutdown (server/index.ts flushes before its exit),
+ * a restart it asked for (75), or a plain exit (0). An exit after a fatal error (1 from an uncaught exception, 70 from
+ * the crash guard) writes nothing: memory may hold half a change, and the file on disk is the last whole state, at most
+ * SAVE_LATER_MAX_MS old. A kill (SIGKILL, or Windows' TerminateProcess, which is how the desktop app stops its server
+ * there) runs no handler at all, so the same holds.
+ */
+export function flushAtCleanExit(code: number): void {
+ if (code === 0 || code === RESTART_EXIT_CODE) flushLaterSaves();
+}
+
+/** Writes everything still waiting, now. Called before the process exits and before anything reads the files from disk. */
+export function flushLaterSaves(): void {
+ if (laterTimer) clearTimeout(laterTimer);
+ laterTimer = undefined;
+ if (!later.size) return;
+ const started = performance.now();
+ let failed = false;
+ for (const [owner, write] of Array.from(later)) { // a snapshot: a failed write is put back and must not be met again here
+ later.delete(owner);
+ try {
+ write();
+ } catch (error) {
+ failed = true;
+ if (!later.has(owner)) later.set(owner, write);
+ console.error("a deferred save failed; it is tried again", error);
+ }
+ }
+ lastLaterWriteMs = performance.now() - started;
+ laterFailures = failed ? laterFailures + 1 : 0;
+ // After SAVE_LATER_RETRIES failures in a row the write waits for the file's next save or the exit, instead of a timer.
+ if (later.size && laterFailures <= SAVE_LATER_RETRIES) laterTimer = setTimeout(flushLaterSaves, SAVE_LATER_MAX_MS);
+}
diff --git a/server/store-deferred-saves.test.ts b/server/store-deferred-saves.test.ts
new file mode 100644
index 0000000000..72110cf45e
--- /dev/null
+++ b/server/store-deferred-saves.test.ts
@@ -0,0 +1,128 @@
+import { readFileSync, rmSync, statSync } from "node:fs";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { DATA_DIR } from "./config.ts";
+import type { ModelSelection } from "./contracts.ts";
+import { RESTART_EXIT_CODE } from "./restart.ts";
+import { flushAtCleanExit, flushLaterSaves, SAVE_LATER_MAX_MS, waitingSaves } from "./save-batch.ts";
+import { Store, type BotRecord } from "./store.ts";
+
+const selection = (): ModelSelection => ({ instanceId: "claude", model: "claude-sonnet-5" });
+const file = join(DATA_DIR, "bots.json");
+const onDisk = (botId: string) => (JSON.parse(readFileSync(file, "utf8")) as BotRecord[]).find((bot) => bot.id === botId)!;
+const written = () => statSync(file).ino;
+
+describe("what bots.json holds, and when", () => {
+ beforeEach(() => {
+ rmSync(DATA_DIR, { recursive: true, force: true });
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ flushLaterSaves();
+ vi.useRealTimers();
+ });
+
+ /** What a turn's end writes that may wait: its usage, the context reading's model, and the turn's own unread mark. */
+ function turnEnd(store: Store, botId: string, threadId: string): void {
+ store.addTaskUsage(botId, threadId, { input: 100, output: 10, costUsd: null });
+ store.patchTask(botId, threadId, { lastContextModel: "claude:claude-sonnet-5" });
+ store.patchTask(botId, threadId, { unread: true }, { turnEnd: true });
+ }
+
+ it("writes the harmless end-of-turn changes once, a bounded moment later, however many turns end together", async () => {
+ const store = new Store(selection);
+ const bots = Array.from({ length: 6 }, (_, i) => store.createBot({ name: `Bot ${i}` }, { seedMessages: false }));
+ const before = written();
+ for (let n = 0; n < 3; n++) {
+ for (const bot of bots) turnEnd(store, bot.id, bot.threadId);
+ await vi.advanceTimersByTimeAsync(5);
+ expect(written(), "nothing is written while the changes are still arriving").toBe(before);
+ }
+ expect(waitingSaves()).toBe(1);
+ await vi.advanceTimersByTimeAsync(SAVE_LATER_MAX_MS);
+ expect(waitingSaves()).toBe(0);
+ expect(written()).not.toBe(before);
+ for (const bot of bots) {
+ const task = onDisk(bot.id).tasks!.find((candidate) => candidate.threadId === bot.threadId)!;
+ expect(task).toMatchObject({ usage: { turns: 3 }, unread: true, lastContextModel: "claude:claude-sonnet-5" });
+ }
+ const once = written();
+ await vi.advanceTimersByTimeAsync(10 * SAVE_LATER_MAX_MS);
+ expect(written(), "one write for the lot").toBe(once);
+ });
+
+ it("holds everything else before the call returns, with the end-of-turn changes that were waiting", () => {
+ const store = new Store(selection);
+ const bot = store.createBot({ name: "Maus" }, { seedMessages: false }), threadId = bot.threadId;
+ const task = (saved: BotRecord) => saved.tasks!.find((candidate) => candidate.threadId === threadId)!;
+ const durable: Array<[string, () => void, (saved: BotRecord) => void]> = [
+ ["an engine session", () => store.setResumeCursor(bot.id, "claude", { sessionId: "s-1" }, threadId),
+ (saved) => expect(task(saved).resumeCursors).toEqual({ claude: { sessionId: "s-1" } })],
+ ["which engine has the thread", () => store.markTaskDispatched(bot.id, threadId, "claude"), (saved) => expect(task(saved).lastInstanceId).toBe("claude")],
+ ["what was handed to the engine", () => store.setHandedMessages(bot.id, threadId, "claude", { session: { sessionId: "s-1" }, lastMessageId: "m-1" } as never),
+ (saved) => expect(task(saved).handedMessages).toMatchObject({ claude: { lastMessageId: "m-1" } })],
+ ["a result posted into the chat (context changed elsewhere)", () => store.patchTask(bot.id, threadId, { resumeCursors: {}, lastInstanceId: "external:1" }),
+ (saved) => expect(task(saved)).toMatchObject({ resumeCursors: {}, lastInstanceId: "external:1" })],
+ ["a context reset", () => store.patchTask(bot.id, threadId, { resumeCursors: {} }), (saved) => expect(task(saved).resumeCursors).toEqual({})],
+ ["when the person last wrote", () => store.setTaskAskedAt(bot.id, threadId, 5_000), (saved) => expect(task(saved).askedAt).toBe(5_000)],
+ ["a read mark", () => store.patchTask(bot.id, threadId, { unread: false, lastReadMessageId: "m-9" }),
+ (saved) => expect(task(saved)).toMatchObject({ unread: false, lastReadMessageId: "m-9" })],
+ ["a person's own unread mark", () => store.patchTask(bot.id, threadId, { unread: true }), (saved) => expect(task(saved).unread).toBe(true)],
+ ["a thread's title", () => store.patchTask(bot.id, threadId, { title: "Quarterly numbers" }), (saved) => expect(task(saved).title).toBe("Quarterly numbers")],
+ ["an always-allow grant", () => store.patchTask(bot.id, threadId, { alwaysAllow: ["Bash(git status)"] }),
+ (saved) => expect(task(saved).alwaysAllow).toEqual(["Bash(git status)"])],
+ ["a new thread", () => store.createTask(bot.id, "Second thread", false), (saved) => expect(saved.tasks!.map((candidate) => candidate.title)).toContain("Second thread")],
+ ["the bot's own settings", () => store.patchBot(bot.id, { name: "Renamed" }), (saved) => expect(saved.name).toBe("Renamed")],
+ ];
+ durable.forEach(([what, change, check], n) => {
+ turnEnd(store, bot.id, threadId);
+ expect(waitingSaves(), what).toBe(1);
+ change();
+ const saved = onDisk(bot.id);
+ check(saved);
+ expect(task(saved).usage, `${what}: the waiting changes ride along`).toMatchObject({ turns: n + 1 });
+ expect(waitingSaves(), `${what}: nothing is left waiting`).toBe(0);
+ });
+ });
+
+ it("does not hold back the unread mark that wakes a snoozed thread", () => {
+ const store = new Store(selection);
+ const bot = store.createBot({ name: "Maus" }, { seedMessages: false });
+ store.patchTask(bot.id, bot.threadId, { snoozedUntil: 0 });
+ store.patchTask(bot.id, bot.threadId, { unread: true });
+ expect(waitingSaves()).toBe(0);
+ const task = onDisk(bot.id).tasks!.find((candidate) => candidate.threadId === bot.threadId)!;
+ expect(task.unread).toBe(true);
+ expect(task.snoozedUntil).toBeUndefined();
+ });
+
+ it("writes what is waiting when flushed, as shutdown and a backup do, and at a clean exit but not after a fatal one", () => {
+ const store = new Store(selection);
+ const bot = store.createBot({ name: "Maus" }, { seedMessages: false });
+ turnEnd(store, bot.id, bot.threadId);
+ expect(onDisk(bot.id).tasks![0]!.usage).toBeUndefined();
+ // 1: an uncaught exception; 70: the crash guard's fatal exit (server/crash-guard.ts).
+ for (const fatal of [1, 70]) flushAtCleanExit(fatal);
+ expect(onDisk(bot.id).tasks![0]!.usage, "a fatal exit leaves the last whole file").toBeUndefined();
+ flushAtCleanExit(RESTART_EXIT_CODE);
+ expect(onDisk(bot.id).tasks![0]).toMatchObject({ usage: { turns: 1 } });
+ turnEnd(store, bot.id, bot.threadId);
+ flushLaterSaves();
+ expect(new Store(selection).taskByThread(bot.id, bot.threadId)?.usage?.turns).toBe(2);
+ });
+
+ it("names the changed thread on each bookkeeping event, so its frame can carry that thread alone", () => {
+ const store = new Store(selection);
+ const bot = store.createBot({ name: "Maus" }, { seedMessages: false });
+ const second = store.createTask(bot.id, "Second thread")!;
+ const events: unknown[] = [];
+ store.onChange((change) => { if (change.type === "bot") events.push(change); });
+ turnEnd(store, bot.id, second.threadId);
+ store.setResumeCursor(bot.id, "claude", { sessionId: "s-1" }, second.threadId);
+ store.setTaskAskedAt(bot.id, second.threadId, 1_000);
+ store.setTaskActivity(bot.id, second.threadId, "working");
+ expect(events.length).toBeGreaterThanOrEqual(6);
+ for (const event of events) expect(event).toEqual({ type: "bot", botId: bot.id, threadId: second.threadId });
+ });
+});
diff --git a/server/store.test.ts b/server/store.test.ts
index 41f7bf422c..4ee8a20a77 100644
--- a/server/store.test.ts
+++ b/server/store.test.ts
@@ -19,6 +19,7 @@ import {
import type { ModelSelection } from "./contracts.ts";
import * as mdb from "./message-db.ts";
import { hasTeamAuthority } from "./peer-roster.ts";
+import { flushLaterSaves } from "./save-batch.ts";
import { Store, toWireTask, type BotRecord } from "./store.ts";
import type { TeamSetupRequest } from "../shared/team-setup.ts";
import { SECTION_CONTEXTS_FILE, readSectionContext, writeSectionContext } from "./section-context.ts";
@@ -434,16 +435,19 @@ describe("Store", () => {
const bot = store.createBot({}, { seedMessages: false });
store.setResumeCursor(bot.id, "claude", { sessionId: "s-1" }, bot.threadId);
store.patchTask(bot.id, bot.threadId, { lastContextModel: "claude-sonnet-5" });
+ flushLaterSaves();
const saved = statSync(file).ino;
const events: unknown[] = [];
store.onChange((change) => events.push(change));
store.setResumeCursor(bot.id, "claude", { sessionId: "s-1" }, bot.threadId);
store.patchTask(bot.id, bot.threadId, { lastContextModel: "claude-sonnet-5" });
+ flushLaterSaves();
expect(statSync(file).ino).toBe(saved);
- expect(events).toEqual([{ type: "bot", botId: bot.id }]);
+ expect(events).toEqual([{ type: "bot", botId: bot.id, threadId: bot.threadId }]);
store.setResumeCursor(bot.id, "claude", { sessionId: "s-2" }, bot.threadId);
+ flushLaterSaves();
expect(statSync(file).ino).not.toBe(saved);
expect(new Store(selection).taskByThread(bot.id, bot.threadId)?.resumeCursors).toEqual({ claude: { sessionId: "s-2" } });
});
@@ -453,11 +457,13 @@ describe("Store", () => {
const store = new Store(selection);
const bot = store.createBot({ name: "Original" }, { seedMessages: false });
store.setResumeCursor(bot.id, "claude", { sessionId: "s-1" }, bot.threadId);
+ flushLaterSaves();
const edited = JSON.parse(readFileSync(file, "utf8"));
edited[0].name = "Edited on disk";
writeFileSync(file, JSON.stringify(edited, null, 2));
store.setResumeCursor(bot.id, "claude", { sessionId: "s-2" }, bot.threadId);
+ flushLaterSaves();
expect(JSON.parse(readFileSync(file, "utf8"))[0].name).toBe("Original");
});
@@ -869,6 +875,7 @@ describe("Store", () => {
// Providers occasionally report a cache count larger than input.
store.addTaskUsage(bot.id, bot.threadId, { input: 10, output: 0, cachedInput: 20, costUsd: null });
expect(store.addTaskUsage(bot.id, "no-such-thread", { input: 5, output: 5, costUsd: null })).toBeNull();
+ flushLaterSaves();
const reloaded = new Store(selection);
expect(reloaded.taskByThread(bot.id, bot.threadId)?.usage).toMatchObject({
@@ -1646,6 +1653,7 @@ describe("Store", () => {
const bot = store.createBot();
store.setResumeCursor(bot.id, "claude", "sess-abc");
store.setResumeCursor(bot.id, "codex", "thread-xyz");
+ flushLaterSaves();
const reloaded = new Store(selection);
expect(reloaded.bot(bot.id)?.resumeCursors).toEqual({ claude: "sess-abc", codex: "thread-xyz" });
diff --git a/server/store.ts b/server/store.ts
index e1d7c137d0..f9d8fa6f89 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -1,8 +1,8 @@
import { chmodSync, existsSync, readFileSync, mkdirSync, rmSync, statSync, unlinkSync } from "node:fs";
import { join } from "node:path"; import { isDeepStrictEqual } from "node:util";
-import { OwnedFile, writeFileAtomic } from "./atomic.ts"; import { saveSoon } from "./save-batch.ts"; import { discardNativeLog } from "./drivers/native.ts";
-import { commitRegistryChange, keptRevocation, saveRegistryFor, touchesPermissions } from "./registry-save.ts";
+import { OwnedFile, writeFileAtomic } from "./atomic.ts"; import { saveLater, saveSoon, supersedeLaterSave } from "./save-batch.ts"; import { discardNativeLog } from "./drivers/native.ts";
+import { commitRegistryChange, deferrablePatch, keptRevocation, saveRegistryFor, touchesPermissions } from "./registry-save.ts";
import { parseToolScope, toolScopeWidens } from "../shared/tool-scope.ts"; import { grantScopedApps } from "../shared/connector-scopes.ts"; import { dropRetiredApps } from "./retired-apps.ts";
import { reorderInPlace } from "../shared/bot-order.ts"; import { trimOutboundPolicy } from "../shared/outbound.ts";
import { botOwner, chiefConflict, chiefScope, ownerEmail } from "../shared/bot-owner.ts"; import { reshowWhenMoved } from "../shared/default-bot.ts";
@@ -131,7 +131,7 @@ export type StoreChange =
| { type: "message.patch"; threadId: string; message: Message }
| { type: "thread"; threadId: string; activeLeafId: string }
| { type: "thread.deleted"; threadId: string }
- | { type: "bot"; botId: string }
+ | { type: "bot"; botId: string; /** Only this thread of the bot changed, besides the bot's own fields. */ threadId?: string }
| { type: "bot.deleted"; botId: string }
/** The fleet or the rooms were reordered as a whole; the broadcast carries every id in its new place. */
| { type: "bots.order" } | { type: "groups.order" }
@@ -309,7 +309,7 @@ export class Store {
// An unreadable bots.json must never read as "every member was deleted".
let botsLoaded = false;
try {
- const text = readFileSync(BOTS_FILE, "utf8"); this.bots = JSON.parse(text); this.botsFile.loaded(text); botsLoaded = Array.isArray(this.bots);
+ supersedeLaterSave(BOTS_FILE); const text = readFileSync(BOTS_FILE, "utf8"); this.bots = JSON.parse(text); this.botsFile.loaded(text); botsLoaded = Array.isArray(this.bots);
} catch {
this.bots = [];
}
@@ -653,20 +653,20 @@ export class Store {
if (botsDirty) this.saveBots();
}
- private commitBotChange(bot: BotRecord, action: string, change: () => void, onRollback?: () => void, bookkeeping = false) {
- commitRegistryChange(bot, "bots.json", action, bookkeeping ? () => this.saveBotsSoon() : () => this.saveBots(), change, onRollback);
+ private commitBotChange(bot: BotRecord, action: string, change: () => void, onRollback?: () => void, bookkeeping: boolean | "later" = false) {
+ commitRegistryChange(bot, "bots.json", action, bookkeeping === "later" ? () => this.saveBotsLater() : bookkeeping ? () => this.saveBotsSoon() : () => this.saveBots(), change, onRollback);
}
private commitGroupChange(group: GroupRecord, action: string, change: () => void) {
commitRegistryChange(group, "groups.json", action, () => this.saveGroups(), change);
}
- private saveBotsSoon() { saveSoon(this.botsFile, () => this.saveBots()); }
+ private saveBotsSoon() { saveSoon(this.botsFile, () => this.saveBots()); } private saveBotsLater() { saveLater(BOTS_FILE, () => this.saveBots()); }
private saveBots(bots: BotRecord[] = this.bots, registerSections = true) {
if (registerSections) this.rememberSections([...this.bots, ...bots].map((bot) => bot.section));
this.botsFile.write(JSON.stringify(bots.map(({ busy: _busy, activity: _activity, ...bot }) => ({ ...bot,
tasks: bot.tasks?.map(({ busy: _taskBusy, activity: _taskActivity, turnStartedAt: _taskTurnStarted, ...task }) => persistedPin(task)),
- }))));
+ })))); if (bots === this.bots) supersedeLaterSave(BOTS_FILE);
}
private saveGroups(groups: GroupRecord[] = this.groups, registerSections = true) {
@@ -1654,7 +1654,7 @@ export class Store {
this.saveBots();
}
this.refreshBotActivity(bot);
- this.emit({ type: "bot", botId });
+ this.emit({ type: "bot", botId, threadId });
return bot;
}
@@ -1813,7 +1813,7 @@ export class Store {
if (isDeepStrictEqual(task?.resumeCursors[instanceId], cursor) && (!mirrored || isDeepStrictEqual(bot.resumeCursors[instanceId], cursor))) return;
if (task) task.resumeCursors[instanceId] = cursor; if (mirrored) bot.resumeCursors[instanceId] = cursor;
saveRegistryFor("bots.json", "the conversation's engine session", () => this.saveBotsSoon());
- this.emit({ type: "bot", botId });
+ this.emit({ type: "bot", botId, ...(task ? { threadId: task.threadId } : {}) });
}
markTaskDispatched(botId: string, threadId: string, instanceId: string) {
@@ -1866,8 +1866,8 @@ export class Store {
? { context: { tokens: contextTokens, ...(contextWindow > 0 ? { window: contextWindow } : {}) } }
: prev.context ? { context: prev.context } : {}),
};
- saveRegistryFor("bots.json", "the thread's usage", () => this.saveBotsSoon());
- this.emit({ type: "bot", botId });
+ saveRegistryFor("bots.json", "the thread's usage", () => this.saveBotsLater());
+ this.emit({ type: "bot", botId, threadId });
return task.usage;
}
@@ -1887,20 +1887,20 @@ export class Store {
if (opts.privateOnly && task.cwd === undefined) {
const cwd = fallbackCwd ?? null;
this.commitBotChange(bot, "the thread's folder", () => { task.cwd = cwd; });
- this.emit({ type: "bot", botId });
+ this.emit({ type: "bot", botId, threadId });
return cwd;
}
if (opts.none) {
if (task.cwd !== null) {
this.commitBotChange(bot, "the thread's folder", () => { task.cwd = null; });
- this.emit({ type: "bot", botId });
+ this.emit({ type: "bot", botId, threadId });
}
return null;
}
if (task.cwd !== undefined) return task.cwd;
const cwd = Object.keys(task.resumeCursors).length === 0 ? (bot.cwd ?? fallbackCwd ?? null) : null;
this.commitBotChange(bot, "the thread's folder", () => { task.cwd = cwd; });
- this.emit({ type: "bot", botId });
+ this.emit({ type: "bot", botId, threadId });
return cwd;
}
@@ -2035,7 +2035,7 @@ export class Store {
};
}
- patchTask(botId: string, threadId: string, patch: TaskPatch): TaskRecord | null {
+ patchTask(botId: string, threadId: string, patch: TaskPatch, options: { turnEnd?: true } = {}): TaskRecord | null {
const bot = this.bot(botId);
const task = this.taskByThread(botId, threadId);
if (!bot || !task) return null;
@@ -2053,8 +2053,8 @@ export class Store {
if (task.routineRunId) task.unread = false;
if (bot.threadId === threadId) this.mirrorActiveTask(bot, task);
bot.unread = bot.tasks!.some(taskCountsAsBotUnread);
- }, revocation && (() => Object.assign(task, revocation)), !touchesPermissions(patch));
- this.emit({ type: "bot", botId });
+ }, revocation && (() => Object.assign(task, revocation)), touchesPermissions(patch) ? false : deferrablePatch(patch, options.turnEnd) && !(task.snoozedUntil === 0 && patch.unread === true) ? "later" : true);
+ this.emit({ type: "bot", botId, threadId });
return task;
}
@@ -2201,7 +2201,7 @@ export class Store {
if (!task || !Number.isFinite(at) || (task.askedAt ?? -1) >= at) return task ?? null;
task.askedAt = at;
saveRegistryFor("bots.json", "when you last wrote in this thread", () => this.saveBotsSoon());
- this.emit({ type: "bot", botId });
+ this.emit({ type: "bot", botId, threadId });
return task;
}
diff --git a/server/workspace-backup.ts b/server/workspace-backup.ts
index 4a0abf4a00..c565a29a5d 100644
--- a/server/workspace-backup.ts
+++ b/server/workspace-backup.ts
@@ -17,6 +17,7 @@ import { INSTRUCTION_FILE, restorePaths, validRelative } from "./workspace-backu
import { cjkSearchText } from "./cjk-search.ts";
import { ephemeralWorkspaceTokenPath, excludedWorkspaceAuthPath, liveDataEnginePath, managedTaskSkillLink, portableWorkspaceConfig, redownloadedOrgLibraryPath, restoredWorkspaceConfig } from "./workspace-backup-policy.ts";
import { omittedAsTeamPrivate, routinesWithoutTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts";
+import { flushLaterSaves } from "./save-batch.ts";
import type { WorkspaceBackupClientState, WorkspaceBackupPrivateMetadata, WorkspaceBackupSummary, WorkspaceLeftBehind } from "../shared/workspace-backup.ts";
export type { WorkspaceBackupSummary, WorkspaceBackupPrivateMetadata } from "../shared/workspace-backup.ts";
@@ -276,6 +277,7 @@ function databaseCounts(path: string): { threads: number; messages: number } {
/** The existing maintenance gate owns exclusivity until this worker has exited.
* Keep synchronous file validation/fsync intact, but off the request thread. */
export async function createWorkspaceBackup(dataDir: string, options: CreateWorkspaceBackupOptions): Promise<CreatedWorkspaceBackup> {
+ flushLaterSaves();
const source = new URL("./workspace-backup.worker.ts", import.meta.url);
// Assign ownership before the worker can create staging, even if it crashes before reporting back.
const jobId = randomUUID();
diff --git a/src/lib/live-events.test.ts b/src/lib/live-events.test.ts
index bee1e2988e..516366c998 100644
--- a/src/lib/live-events.test.ts
+++ b/src/lib/live-events.test.ts
@@ -98,10 +98,10 @@ afterEach(() => { vi.useRealTimers(); resetCloudPowerForTests(); });
describe("live events URL", () => {
it("builds cold and resumable stream URLs", () => {
- expect(liveEventsUrl()).toBe("/api/events?window=1");
- expect(liveEventsUrl({ since: "ab12cd34:9" })).toBe("/api/events?since=ab12cd34%3A9&window=1");
- expect(liveEventsUrl({ since: "ab12cd34:9", screens: false })).toBe("/api/events?since=ab12cd34%3A9&screens=off&window=1");
- expect(liveEventsUrl({ screens: true })).toBe("/api/events?window=1");
+ expect(liveEventsUrl()).toBe("/api/events?window=1&frames=thread");
+ expect(liveEventsUrl({ since: "ab12cd34:9" })).toBe("/api/events?since=ab12cd34%3A9&window=1&frames=thread");
+ expect(liveEventsUrl({ since: "ab12cd34:9", screens: false })).toBe("/api/events?since=ab12cd34%3A9&screens=off&window=1&frames=thread");
+ expect(liveEventsUrl({ screens: true })).toBe("/api/events?window=1&frames=thread");
});
});
@@ -139,7 +139,7 @@ describe("live events supervisor", () => {
test.sources[0].error();
retryLiveEvents();
expect(test.sources).toHaveLength(2);
- expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1");
+ expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1&frames=thread");
test.sources[1].open();
test.sources[1].message({ kind: "ping" });
vi.advanceTimersByTime(500);
@@ -196,7 +196,7 @@ describe("live events supervisor", () => {
test.setNow(1_900);
vi.advanceTimersByTime(500);
expect(test.sources).toHaveLength(2);
- expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1");
+ expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1&frames=thread");
expect(test.sources[0].close).toHaveBeenCalledOnce();
stop();
});
@@ -238,19 +238,19 @@ describe("live events supervisor", () => {
test.sources[0].message({ kind: "message" }, "oldrun00:10");
test.sources[0].error();
vi.advanceTimersByTime(100);
- expect(test.sources[1].url).toBe("/api/events?since=oldrun00%3A10&screens=off&window=1");
+ expect(test.sources[1].url).toBe("/api/events?since=oldrun00%3A10&screens=off&window=1&frames=thread");
test.sources[1].message({ kind: "hello", resumed: true, cursor: "oldrun00:13" });
test.sources[1].error();
vi.advanceTimersByTime(100);
- expect(test.sources[2].url).toBe("/api/events?since=oldrun00%3A10&screens=off&window=1");
+ expect(test.sources[2].url).toBe("/api/events?since=oldrun00%3A10&screens=off&window=1&frames=thread");
test.sources[2].message({ kind: "hello", resumed: false, cursor: "newrun00:7" });
test.sources[2].message({ kind: "message", value: "behind failed snapshot" }, "newrun00:8");
snapshotResolutions.shift()?.(false);
await Promise.resolve();
vi.advanceTimersByTime(100);
- expect(test.sources[3].url).toBe("/api/events?since=oldrun00%3A10&screens=off&window=1");
+ expect(test.sources[3].url).toBe("/api/events?since=oldrun00%3A10&screens=off&window=1&frames=thread");
test.sources[3].message({ kind: "hello", resumed: false, cursor: "newrun00:8" });
test.sources[3].message({ kind: "message", value: "after snapshot" }, "newrun00:9");
@@ -258,7 +258,7 @@ describe("live events supervisor", () => {
await Promise.resolve();
test.sources[3].error();
vi.advanceTimersByTime(100);
- expect(test.sources[4].url).toBe("/api/events?since=newrun00%3A9&screens=off&window=1");
+ expect(test.sources[4].url).toBe("/api/events?since=newrun00%3A9&screens=off&window=1&frames=thread");
expect(frames).toEqual([
{ kind: "message" },
{ kind: "message", value: "behind failed snapshot" },
@@ -423,7 +423,7 @@ describe("a Cloud home that goes to sleep", () => {
expect(test.sources).toHaveLength(1);
markCloudAwake();
expect(test.sources).toHaveLength(2);
- expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1");
+ expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1&frames=thread");
stop();
});
@@ -465,7 +465,7 @@ describe("a Cloud home that goes to sleep", () => {
loading.sources[0].message(sleeping, "run00000:5");
expect(cloudAsleep()).toBe(true);
markCloudAwake();
- expect(loading.sources[1].url).toBe("/api/events?screens=off&window=1");
+ expect(loading.sources[1].url).toBe("/api/events?screens=off&window=1&frames=thread");
stopLoading();
});
@@ -483,7 +483,7 @@ describe("live screens", () => {
it("leave screens out until a view that draws them listens, then reopen from the cursor both ways", async () => {
const test = harness();
const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, test.platform);
- expect(test.sources[0].url).toBe("/api/events?screens=off&window=1");
+ expect(test.sources[0].url).toBe("/api/events?screens=off&window=1&frames=thread");
test.sources[0].open();
test.sources[0].message({ kind: "hello", resumed: true, cursor: "run00000:3" });
test.sources[0].message({ kind: "message" }, "run00000:4");
@@ -494,7 +494,7 @@ describe("live screens", () => {
const viewer = listenLiveFrames({ screens: true, onFrame: () => {} });
const second = listenLiveFrames({ screens: true, onFrame: () => {} });
await Promise.resolve();
- expect(test.sources.map((source) => source.url)).toEqual(["/api/events?screens=off&window=1", "/api/events?since=run00000%3A4&window=1"]);
+ expect(test.sources.map((source) => source.url)).toEqual(["/api/events?screens=off&window=1&frames=thread", "/api/events?since=run00000%3A4&window=1&frames=thread"]);
expect(test.sources[0].close).toHaveBeenCalledOnce();
viewer();
@@ -502,7 +502,7 @@ describe("live screens", () => {
expect(test.sources).toHaveLength(2);
second();
await Promise.resolve();
- expect(test.sources[2].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1");
+ expect(test.sources[2].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1&frames=thread");
quiet();
stop();
});
diff --git a/src/lib/live-events.ts b/src/lib/live-events.ts
index 1c9f04261d..940fdf0b89 100644
--- a/src/lib/live-events.ts
+++ b/src/lib/live-events.ts
@@ -59,12 +59,14 @@ export interface LiveEventsHandlers {
retryMaxMs?: number;
}
-/** `screens: false` asks the server to leave out live screen frames; `window=1` tells it an app window is open. */
+/** `screens: false` asks the server to leave out live screen frames; `window=1` tells it an app window is open;
+ * `frames=thread` that this client keeps a bot's other threads when a bot frame says `tasksPartial`. */
export function liveEventsUrl(options?: { since?: string | null; screens?: boolean }): string {
const params = new URLSearchParams();
if (options?.since) params.set("since", options.since);
if (options?.screens === false) params.set("screens", "off");
params.set("window", "1");
+ params.set("frames", "thread");
return `${LIVE_EVENTS_PATH}?${params}`;
}
diff --git a/src/state/bot-thread-frame.test.ts b/src/state/bot-thread-frame.test.ts
new file mode 100644
index 0000000000..a77cb16244
--- /dev/null
+++ b/src/state/bot-thread-frame.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+
+import { unreadBeyondFrame, wholeBotFrame } from "./bot-thread-frame";
+import { initialState, reducer, type Bot, type BotAnnouncement } from "./store";
+
+const bot: Bot = {
+ id: "bot", threadId: "first", name: "Maus", title: "", description: "", notifications: true, color: "green", unread: false,
+ modelSelection: { instanceId: "claude", model: "m" }, approvalMode: "ask", alwaysAllow: [], messages: [],
+ tasks: [
+ { threadId: "first", title: "First", createdAt: 1, activity: "idle", busy: false, unread: false, modelSelection: { instanceId: "claude", model: "m" } },
+ { threadId: "second", title: "Second", createdAt: 2, activity: "idle", busy: false, unread: false, modelSelection: { instanceId: "claude", model: "m" } },
+ { threadId: "third", title: "Third", createdAt: 3, activity: "idle", busy: false, unread: true, modelSelection: { instanceId: "claude", model: "m" } },
+ ],
+};
+const { messages: _messages, ...settings } = bot;
+const frame = (tasks: BotAnnouncement["tasks"], patch: Partial<BotAnnouncement> = {}): BotAnnouncement => ({ ...settings, ...patch, tasks });
+const start = () => ({ ...initialState, bots: [bot], selectedId: "other" });
+
+describe("a bot frame that carries only the changed thread", () => {
+ it("replaces that thread and keeps every other one, in order", () => {
+ const working = { ...bot.tasks![1]!, busy: true, activity: "working" as const, turnStartedAt: 9 };
+ const next = reducer(start(), { type: "botPatched", bot: frame([working], { busy: false }), tasksPartial: true });
+ expect(next.bots[0]!.tasks!.map((task) => task.threadId)).toEqual(["first", "second", "third"]);
+ expect(next.bots[0]!.tasks![1]).toMatchObject({ busy: true, activity: "working", turnStartedAt: 9 });
+ expect(next.bots[0]!.tasks![0]).toEqual(bot.tasks![0]);
+ expect(next.bots[0]!.tasks![2]).toEqual(bot.tasks![2]);
+ });
+
+ it("applies frames for two threads sent back to back, neither undoing the other", () => {
+ const first = { ...bot.tasks![0]!, busy: true }, second = { ...bot.tasks![1]!, unread: true };
+ let state = reducer(start(), { type: "botPatched", bot: frame([first]), tasksPartial: true });
+ state = reducer(state, { type: "botPatched", bot: frame([second], { unread: true }), tasksPartial: true });
+ expect(state.bots[0]!.tasks![0]!.busy).toBe(true);
+ expect(state.bots[0]!.tasks![1]!.unread).toBe(true);
+ expect(state.bots[0]!.unread).toBe(true);
+ });
+
+ it("takes the bot's own fields from the frame", () => {
+ const next = reducer(start(), { type: "botPatched", bot: frame([], { name: "Renamed", busy: true }), tasksPartial: true });
+ expect(next.bots[0]).toMatchObject({ name: "Renamed", busy: true });
+ expect(next.bots[0]!.tasks).toHaveLength(3);
+ });
+
+ it("is the same as the whole frame it stands for", () => {
+ const changed = { ...bot.tasks![2]!, unread: false, title: "Third, renamed" };
+ const whole = reducer(start(), { type: "botPatched", bot: frame([bot.tasks![0]!, bot.tasks![1]!, changed]) });
+ const partial = reducer(start(), { type: "botPatched", bot: frame([changed]), tasksPartial: true });
+ expect(partial.bots).toEqual(whole.bots);
+ });
+
+ it("waits for the whole bot when the frame is about one this client does not have", () => {
+ const state = { ...initialState, bots: [], selectedId: "" };
+ expect(reducer(state, { type: "botPatched", bot: frame([bot.tasks![0]!]), tasksPartial: true })).toBe(state);
+ });
+
+ it("without the mark, a frame's threads are the bot's whole list, as before", () => {
+ const next = reducer(start(), { type: "botPatched", bot: frame([bot.tasks![0]!]) });
+ expect(next.bots[0]!.tasks!.map((task) => task.threadId)).toEqual(["first"]);
+ });
+
+ it("adds a carried thread it has not seen after the ones it has", () => {
+ const fresh = { ...bot.tasks![0]!, threadId: "fourth", title: "Fourth" };
+ expect(wholeBotFrame(bot, frame([fresh])).tasks!.map((task) => task.threadId)).toEqual(["first", "second", "third", "fourth"]);
+ });
+
+ it("keeps the bot unread while a thread the frame did not carry is unread", () => {
+ const read = { ...bot.tasks![1]!, unread: false };
+ expect(unreadBeyondFrame(bot, frame([read]))).toBe(true);
+ expect(unreadBeyondFrame({ tasks: bot.tasks!.slice(0, 2) }, frame([read]))).toBe(false);
+ expect(unreadBeyondFrame(bot, frame([{ ...bot.tasks![2]!, unread: false }]))).toBe(false);
+ });
+});
diff --git a/src/state/bot-thread-frame.ts b/src/state/bot-thread-frame.ts
new file mode 100644
index 0000000000..2da68dc13f
--- /dev/null
+++ b/src/state/bot-thread-frame.ts
@@ -0,0 +1,22 @@
+import { botShowsUnread } from "@/lib/bot-unread";
+import type { Bot, BotAnnouncement } from "./store";
+
+/** A bot frame that carries only its changed threads (`tasksPartial`), made whole against the bot as it is known here:
+ * each carried thread replaces the known one, and every other thread is kept. */
+export function wholeBotFrame(known: Pick<Bot, "tasks"> | undefined, bot: BotAnnouncement): BotAnnouncement {
+ const changed = new Map((bot.tasks ?? []).map((task) => [task.threadId, task]));
+ if (!known?.tasks) return bot;
+ const tasks = known.tasks.map((task) => {
+ const next = changed.get(task.threadId);
+ changed.delete(task.threadId);
+ return next ?? task;
+ });
+ return { ...bot, tasks: [...tasks, ...changed.values()] };
+}
+
+/** After the visible thread of a partial frame was marked read, the bot still shows unread if a thread the frame did
+ * not carry is unread. */
+export function unreadBeyondFrame(known: Pick<Bot, "tasks"> | undefined, bot: BotAnnouncement): boolean {
+ const carried = new Set((bot.tasks ?? []).map((task) => task.threadId));
+ return botShowsUnread({ unread: false, tasks: (known?.tasks ?? []).filter((task) => !carried.has(task.threadId)) }) || botShowsUnread({ unread: false, tasks: bot.tasks ?? [] });
+}
diff --git a/src/state/live-frames.test.ts b/src/state/live-frames.test.ts
index e5d7ede0c6..e9b62130b9 100644
--- a/src/state/live-frames.test.ts
+++ b/src/state/live-frames.test.ts
@@ -69,7 +69,7 @@ afterAll(() => {
describe("live frames the store does not keep", () => {
it("come from the app's one stream", () => {
expect(seen.bots.map((candidate) => candidate.id)).toEqual(["bot"]);
- expect(FixtureEventSource.opened.map((source) => source.url)).toEqual(["/api/events?screens=off&window=1"]);
+ expect(FixtureEventSource.opened.map((source) => source.url)).toEqual(["/api/events?screens=off&window=1&frames=thread"]);
});
it("hand a screen frame to its listener without touching app state", async () => {
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 01b26afc1a..76fc281a0a 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -15,7 +15,7 @@ import type { NotificationLogEntry } from "../../shared/notification";
import { isNotificationFeedAction, reduceNotificationFeed, type NotificationFeedAction } from "./notification-feed";
import { bumpThreadUpdatedAt, mergeTaskStamps, rewindThreadUpdatedAt } from "./thread-stamps";
import { botOpensTo, closeTrayUnlessShown, closeUnpinnedTray, openBot, openThread, visibleNotificationThread, withRememberedTrayPin } from "./thread-navigation";
-import { patchGroupTask } from "./thread-edits";
+import { patchGroupTask } from "./thread-edits"; import { unreadBeyondFrame, wholeBotFrame } from "./bot-thread-frame";
import type { EngineInstall } from "./engine-install";
import { optimisticMessageId, optimisticUserMessage, sendArrived, sendReconciled } from "./optimistic-send";
import { patchedGroups, roomAnswers, snapshotPatch } from "./room-frames";
@@ -711,7 +711,7 @@ export type Action =
| { type: "botDeletionPending"; botId: string; on: boolean }
| { type: "duplicateBot"; botId: string }
| { type: "markUnread"; botId: string }
- | { type: "botPatched"; bot: BotAnnouncement }
+ | { type: "botPatched"; bot: BotAnnouncement; tasksPartial?: true }
| { type: "messageAdded"; threadId: string; message: Message }
| { type: "messagePatched"; threadId: string; message: Message }
| { type: "optimisticMessageRemoved"; threadId: string; sendId: string; restoreLeafId?: string | null }
@@ -1110,6 +1110,7 @@ export function reducer(state: AppState, action: Action): AppState {
return updateBot(withMascotMotion(state, action.botId, "surprise"), action.botId, (b) => ({ ...b, unread: true }));
case "botPatched": {
const before = state.bots.find((b) => b.id === action.bot.id);
+ if (action.tasksPartial) return before ? reducer(state, { type: "botPatched", bot: wholeBotFrame(before, action.bot) }) : state;
if (!before) {
const added = {
...state,
@@ -3091,16 +3092,14 @@ export function StoreProvider({ children }: { children: ReactNode }) {
rawDispatch({ type: "forkPanelActive", threadId: frame.threadId, activeLeafId: frame.activeLeafId });
break;
case "bot": {
- const bot = frame.bot as BotAnnouncement;
+ const bot = frame.bot as BotAnnouncement, serverUnread = bot.unread;
markVisibleBotThreadsRead(stateRef.current, bot, document.hasFocus(), (_path, threadId, newest) => {
const read = `${bot.id}:${threadId}`, open = readsInFlight.get(read);
if (!open) sendRead(bot.id, threadId, read, newest);
else if (newest > open.covers) readsInFlight.set(read, { covers: newest, again: true });
});
- rawDispatch({
- type: "botPatched",
- bot: withTaskWrites({ ...bot, ...botPatchQueue.overlayFor(bot.id) }),
- });
+ if (frame.tasksPartial && serverUnread && !bot.unread) bot.unread = unreadBeyondFrame(stateRef.current.bots.find((known) => known.id === bot.id), bot);
+ rawDispatch({ type: "botPatched", bot: withTaskWrites({ ...bot, ...botPatchQueue.overlayFor(bot.id) }), ...(frame.tasksPartial ? { tasksPartial: true as const } : {}) });
break;
}
case "group": {