Skip to content

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

Write less on the server while a bot works (#4151)

Milind Sonieae8332d1291
diff --git a/scripts/verify-codex-sandbox.mjs b/scripts/verify-codex-sandbox.mjs
index c5a270b945..0e5320dab0 100644
--- a/scripts/verify-codex-sandbox.mjs
+++ b/scripts/verify-codex-sandbox.mjs
@@ -11,6 +11,7 @@ mkdirSync(join(root, "omb", "native"), { recursive: true });
console.log(`Evidence: ${root}`);
const { CodexDriver } = await import("../server/drivers/codex.ts");
const { recordEvents } = await import("../server/testing/events.ts");
+const { flushNativeLogs } = await import("../server/drivers/native.ts");
const captures = [];
const server = createServer(async (req, res) => {
if (req.method !== "POST") {
@@ -70,6 +71,7 @@ requires_openai_auth=false
const done = await recorder.until(event => event.type === "turn.completed" && event.turnId === turnId, 30000);
assert.equal(done.ok, true, JSON.stringify(recorder.events.filter(event => event.turnId === turnId)));
cursor = recorder.events.find(event => event.turnId === turnId && event.type === "session.started").sessionId;
+ flushNativeLogs();
const log = readFileSync(join(root, "omb", "native", `${threadId}.ndjson`), "utf8").trim().split("\n").map(JSON.parse);
const start = log.find(row => row.dir === "out" && ["thread/start", "thread/resume"].includes(row.msg.method));
const resolved = log.find(row => row.dir === "in" && row.msg.id === start.msg.id).msg.result.sandbox;
diff --git a/server/atomic.ts b/server/atomic.ts
index aa8ab3f989..909b6e3f4f 100644
--- a/server/atomic.ts
+++ b/server/atomic.ts
@@ -110,3 +110,27 @@ export function writeFileAtomicIfChanged(path: string, data: string, options: At
writeFileAtomic(path, data, options);
return true;
}
+
+/** A file only this process writes while it runs: a save whose text equals the last one written (or read at load) is
+ * skipped without reading the disk back. */
+export class OwnedFile {
+ private last: string | undefined;
+ readonly path: string;
+ private readonly options: AtomicWriteOptions;
+
+ constructor(path: string, options: AtomicWriteOptions = {}) {
+ this.path = path;
+ this.options = options;
+ }
+
+ loaded(text: string): void {
+ this.last = text;
+ }
+
+ write(text: string): boolean {
+ if (text === this.last) return false;
+ writeFileAtomic(this.path, text, this.options);
+ this.last = text;
+ return true;
+ }
+}
diff --git a/server/data/deps.ts b/server/data/deps.ts
index 47d6fe1af0..e59bc79a45 100644
--- a/server/data/deps.ts
+++ b/server/data/deps.ts
@@ -1,10 +1,12 @@
import type { ChartCompiler, ChartRenderer, DataEngine, VegaLiteValidator } from "./types.ts";
import { dataEngine as engine } from "./engine.ts";
import { compileChart as compile } from "./chart-compiler.ts";
-import { validateVegaLite as validate } from "./vega-lite-validator.ts";
-import { chartRenderer as renderer } from "./render.ts";
export const dataEngine: DataEngine = engine;
export const compileChart: ChartCompiler = compile;
-export const validateVegaLite: VegaLiteValidator = validate;
-export const chartRenderer: ChartRenderer = renderer;
+// Vega, Vega-Lite and its JSON schema load at the first chart, not with the server.
+export const validateVegaLite: VegaLiteValidator = async (spec) => (await import("./vega-lite-validator.ts")).validateVegaLite(spec);
+export const chartRenderer: ChartRenderer = {
+ svg: async (...args) => (await import("./render.ts")).chartRenderer.svg(...args),
+ png: async (...args) => (await import("./render.ts")).chartRenderer.png(...args),
+};
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index a831a8d7d7..9fe548db79 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ProviderInstance, RuntimeEvent } from "../contracts.ts";
import { DATA_DIR, NATIVE_DIR } from "../config.ts";
+import { flushNativeLog } from "./native.ts";
import { ChatGptPlanAuthController } from "./chatgpt-plan-auth.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { CodexDriver, codexNativeIncomingLogMessage, codexUpdateCommand } from "./codex.ts";
@@ -1002,6 +1003,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
]);
expect(JSON.stringify(seen)).not.toContain(attachments);
+ flushNativeLog("t-native-input-image");
const nativeLog = readFileSync(join(NATIVE_DIR, "t-native-input-image.ndjson"), "utf8");
expect(nativeLog).toContain('"type":"image"');
expect(nativeLog).toContain("[inline image omitted");
diff --git a/server/drivers/native.test.ts b/server/drivers/native.test.ts
index 476ea7d3be..3234f82218 100644
--- a/server/drivers/native.test.ts
+++ b/server/drivers/native.test.ts
@@ -1,10 +1,14 @@
// The native tee goes into bug reports, so this checks that the writer actually redacts.
-import { readFileSync, statSync } from "node:fs";
-import { join } from "node:path";
-import { beforeAll, describe, expect, it } from "vitest";
+import { spawnSync } from "node:child_process";
+import { existsSync, readFileSync, rmSync, statSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { ensureDirs, NATIVE_DIR } from "../config.ts";
-import { appendNative } from "./native.ts";
+import type { RuntimeEvent } from "../contracts.ts";
+import { EventBus } from "../harness/bus.ts";
+import { appendNative, discardNativeLog, flushNativeLog, flushNativeLogs, streamedFragment } from "./native.ts";
beforeAll(() => ensureDirs());
@@ -55,6 +59,7 @@ describe("appendNative", () => {
small: { type: "image", source: { type: "base64", media_type: "image/png", data: "[image data: 12 base64 chars]" } },
},
});
+ flushNativeLog("t-inline");
const line = JSON.parse(readFileSync(join(NATIVE_DIR, "t-inline.ndjson"), "utf8").trim());
const blocks = line.msg.message.content[0].content;
expect(blocks[0].source).toEqual({ type: "base64", media_type: "image/png", data: "[image data: 150000 base64 chars]" });
@@ -72,6 +77,7 @@ describe("appendNative", () => {
source: "acp",
msg: { data: `${"log line ".repeat(500)}ANTHROPIC_API_KEY=${key}`, result: { type: "text", data: `${"x".repeat(2_000)} ${key}` } },
});
+ flushNativeLog("t-long");
const log = readFileSync(join(NATIVE_DIR, "t-long.ndjson"), "utf8");
expect(log).not.toContain(key);
expect(log).toContain("«redacted");
@@ -80,6 +86,7 @@ describe("appendNative", () => {
it("writes the log private to the user", () => {
appendNative("t-mode", { dir: "in", source: "acp", msg: { hello: "world" } });
+ flushNativeLog("t-mode");
const mode = statSync(join(NATIVE_DIR, "t-mode.ndjson")).mode & 0o777;
// Windows does not implement POSIX modes; everywhere else, owner-only
if (process.platform !== "win32") expect(mode).toBe(0o600);
@@ -92,3 +99,71 @@ describe("appendNative", () => {
expect(() => appendNative("t-cyclic", { dir: "in", source: "acp", msg: cyclic })).not.toThrow();
});
});
+
+const file = (threadId: string) => join(NATIVE_DIR, `${threadId}.ndjson`);
+const rows = (threadId: string) => existsSync(file(threadId))
+ ? readFileSync(file(threadId), "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line) as { dir: string; msg: Record<string, unknown> })
+ : [];
+
+describe("the native tee", () => {
+ beforeEach(() => {
+ flushNativeLogs();
+ rmSync(NATIVE_DIR, { recursive: true, force: true });
+ ensureDirs();
+ });
+
+ it("keeps whole messages and drops the fragments a later record carries whole", () => {
+ expect(streamedFragment("claude.sdk.message", { type: "stream_event", event: { type: "content_block_delta", delta: { text: "Hi" } } })).toBe(true);
+ expect(streamedFragment("claude.sdk.message", { type: "stream_event", event: { type: "content_block_start" } })).toBe(false);
+ expect(streamedFragment("claude.sdk.message", { type: "assistant", message: { content: [] } })).toBe(false);
+ expect(streamedFragment("codex.app-server", { method: "item/agentMessage/delta", params: {} })).toBe(true);
+ expect(streamedFragment("codex.app-server", { method: "item/commandExecution/outputDelta", params: {} })).toBe(true);
+ expect(streamedFragment("codex.app-server", { method: "item/completed", params: {} })).toBe(false);
+ expect(streamedFragment("pi.rpc", { type: "message_update" })).toBe(true);
+ expect(streamedFragment("pi.rpc", { type: "message_end" })).toBe(false);
+ expect(streamedFragment("acp", { method: "session/update" })).toBe(false);
+ });
+
+ it("holds incoming lines, in order, until a flush or the timer, and writes what it sent at once", () => {
+ vi.useFakeTimers();
+ try {
+ appendNative("t-held", { dir: "in", source: "claude.sdk.message", msg: { type: "system", n: 1 } });
+ appendNative("t-held", { dir: "in", source: "claude.sdk.message", msg: { type: "stream_event", event: { type: "content_block_delta" } } });
+ appendNative("t-held", { dir: "in", source: "claude.sdk.message", msg: { type: "assistant", n: 2 } });
+ expect(rows("t-held")).toEqual([]);
+ appendNative("t-held", { dir: "out", source: "claude.sdk.message", msg: { type: "user", n: 3 } });
+ expect(rows("t-held").map((row) => row.msg.n)).toEqual([1, 2, 3]);
+ appendNative("t-held", { dir: "in", source: "claude.sdk.message", msg: { type: "result", n: 4 } });
+ vi.advanceTimersByTime(300);
+ expect(rows("t-held").map((row) => row.msg.n)).toEqual([1, 2, 3, 4]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("writes a thread's held lines when its turn ends on the bus", () => {
+ const bus = new EventBus(() => {});
+ appendNative("t-turn-end", { dir: "in", source: "claude.sdk.message", msg: { type: "assistant", n: 1 } });
+ bus.publish({ eventId: "e1", provider: "claudeAgent", threadId: "t-turn-end", createdAt: new Date().toISOString(), type: "turn.completed", ok: true } as unknown as RuntimeEvent);
+ expect(rows("t-turn-end").map((row) => row.msg.n)).toEqual([1]);
+ });
+
+ it("drops a deleted thread's held lines, so no flush recreates its log", () => {
+ appendNative("t-deleted", { dir: "in", source: "claude.sdk.message", msg: { type: "assistant" } });
+ discardNativeLog("t-deleted");
+ flushNativeLog("t-deleted");
+ flushNativeLogs();
+ expect(existsSync(file("t-deleted"))).toBe(false);
+ });
+
+ it("writes every held line when the process exits", () => {
+ const script = `const { appendNative } = await import(${JSON.stringify(pathToFileURL(join(import.meta.dirname, "native.ts")).href)});
+ for (let n = 0; n < 5; n++) appendNative("t-exit", { dir: "in", source: "claude.sdk.message", msg: { type: "assistant", n } });
+ process.exit(0);`;
+ const child = spawnSync(process.execPath, ["--experimental-strip-types", "--input-type=module", "-e", script], {
+ env: { ...process.env, OMB_DATA_DIR: dirname(NATIVE_DIR) }, encoding: "utf8",
+ });
+ expect(child.status, child.stderr).toBe(0);
+ expect(rows("t-exit").map((row) => row.msg.n)).toEqual([0, 1, 2, 3, 4]);
+ });
+});
diff --git a/server/drivers/native.ts b/server/drivers/native.ts
index c1bf48ad0c..8887af0071 100644
--- a/server/drivers/native.ts
+++ b/server/drivers/native.ts
@@ -1,4 +1,5 @@
-// Tees every provider-native message beside the canonical stream, so protocol drift shows up in a diff.
+// Tees every provider-native message beside the canonical stream, so protocol drift shows up in a diff. Lines are held
+// per thread and appended together every FLUSH_MS, when a caller flushes, and at exit.
import { appendFileSync } from "node:fs";
import { join } from "node:path";
@@ -8,6 +9,12 @@ import { capThreadLog, currentThreadLogCap } from "../thread-log-rotation.ts";
const INLINE_DATA_CHARS = 1024;
const DATA_URL = /^data:[^,;]{0,100};base64,/;
+const FLUSH_MS = 250;
+const MAX_HELD_CHARS = 256 * 1024;
+
+const held = new Map<string, string[]>();
+let heldChars = 0;
+let timer: ReturnType<typeof setTimeout> | null = null;
function carriesBase64(record: Record<string, unknown>): boolean {
return record.type === "base64" || record.type === "image" || imageMedia(record);
@@ -44,16 +51,68 @@ function withoutInlineData(value: unknown, depth = 0): unknown {
return copy ?? value;
}
+/** A fragment a later record of the same protocol carries whole: Claude Code's content_block_delta stream events (then
+ * the assistant message), Codex app-server item deltas (then item/completed), Pi's message and tool updates (then
+ * message_end and tool_execution_end). */
+export function streamedFragment(source: string, msg: unknown): boolean {
+ if (msg === null || typeof msg !== "object") return false;
+ const record = msg as Record<string, unknown>;
+ if (source === "claude.sdk.message") return record.type === "stream_event" && (record.event as { type?: unknown } | undefined)?.type === "content_block_delta";
+ if (source === "codex.app-server") return typeof record.method === "string" && record.method.startsWith("item/") && /delta$/i.test(record.method);
+ if (source === "pi.rpc") return record.type === "message_update" || record.type === "tool_execution_update";
+ return false;
+}
+
export function appendNative(threadId: string, entry: { dir: "in" | "out"; source: string; msg: unknown }) {
- const file = join(NATIVE_DIR, `${threadId}.ndjson`);
+ if (streamedFragment(entry.source, entry.msg)) return;
+ let line: string;
try {
// Session setup carries agent credentials (boat/comms tokens, MCP headers) and
// people paste these logs into bug reports, so values are masked.
- appendFileSync(
- file,
- JSON.stringify({ at: new Date().toISOString(), ...entry, msg: redactSecrets(withoutInlineData(entry.msg)) }) + "\n",
- { mode: 0o600 },
- );
+ line = JSON.stringify({ at: new Date().toISOString(), ...entry, msg: redactSecrets(withoutInlineData(entry.msg)) }) + "\n";
+ } catch {
+ return;
+ }
+ const lines = held.get(threadId);
+ if (lines) lines.push(line);
+ else held.set(threadId, [line]);
+ heldChars += line.length;
+ // What OpenMausBot sent is a few lines a turn, and the line a bug report most needs: it lands at once.
+ if (entry.dir === "out") flushNativeLog(threadId);
+ else if (heldChars >= MAX_HELD_CHARS) flushNativeLogs();
+ else if (!timer) {
+ timer = setTimeout(flushNativeLogs, FLUSH_MS);
+ timer.unref?.();
+ }
+}
+
+export function flushNativeLog(threadId: string): void {
+ const lines = take(threadId);
+ if (!lines) return;
+ const file = join(NATIVE_DIR, `${threadId}.ndjson`);
+ try {
+ appendFileSync(file, lines.join(""), { mode: 0o600 });
capThreadLog(file, currentThreadLogCap());
} catch {}
}
+
+export function flushNativeLogs(): void {
+ if (timer) clearTimeout(timer);
+ timer = null;
+ for (const threadId of Array.from(held.keys())) flushNativeLog(threadId);
+}
+
+/** A deleted thread's held lines are dropped, so a later flush cannot recreate its log. */
+export function discardNativeLog(threadId: string): void {
+ take(threadId);
+}
+
+function take(threadId: string): string[] | undefined {
+ const lines = held.get(threadId);
+ if (!lines) return undefined;
+ held.delete(threadId);
+ for (const line of lines) heldChars -= line.length;
+ return lines;
+}
+
+process.once("exit", flushNativeLogs);
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index 784e36bc52..e7877b76c3 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -6,6 +6,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ensureDirs, NATIVE_DIR } from "../config.ts";
+import { discardNativeLog, flushNativeLog } from "./native.ts";
import type { RuntimeEvent, SendTurnInput } from "../contracts.ts";
import { GrokDriver } from "./grok.ts";
import { MinimaxDriver } from "./minimax.ts";
@@ -807,6 +808,7 @@ describe("createOpenAIChatRuntime refused tool calls", () => {
it("stops after three refusals, says what happened and what to do, and logs each refusal whole", async () => {
ensureDirs();
const log = join(NATIVE_DIR, "thread.ndjson");
+ discardNativeLog("thread");
rmSync(log, { force: true });
let requests = 0;
const events = await runTurn(() => (requests++, refusedStream()));
@@ -816,6 +818,7 @@ describe("createOpenAIChatRuntime refused tool calls", () => {
message: `The model tried to use a tool it was not given ("JSON"). Nothing ran. Retry; if it keeps happening, rephrase the request or choose another model. Provider: ${refusal.message}`,
});
expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "error" });
+ flushNativeLog("thread");
const refusals = readFileSync(log, "utf8").trim().split("\n").map((line) => JSON.parse(line)).filter((entry) => entry.msg?.refused);
expect(refusals.map((entry) => entry.msg)).toEqual([1, 2, 3].map((attempt) => ({ refused: "tool_use_failed", attempt, error: refusal })));
});
diff --git a/server/harness/bus.ts b/server/harness/bus.ts
index 3dfac158fa..ed155afc92 100644
--- a/server/harness/bus.ts
+++ b/server/harness/bus.ts
@@ -3,7 +3,9 @@ import { appendFile } from "node:fs/promises";
import { join } from "node:path";
import { EVENTS_DIR } from "../config.ts";
+import { flushNativeLog } from "../drivers/native.ts";
import { redactSecrets } from "../redact.ts";
+import { batchSaves } from "../save-batch.ts";
import { capThreadLog, currentThreadLogCap } from "../thread-log-rotation.ts";
import { newId, type ProviderAdapter, type ProviderInstance, type RuntimeEvent, type RuntimeEventListener } from "../contracts.ts";
import { LiveSteps } from "./live-steps.ts";
@@ -153,7 +155,9 @@ export class EventBus {
// Queue first, then deliver: a listener publishing during delivery queues after this, so the log keeps publication order.
this.enqueue(event);
this.deliver(event);
- if (isTerminalEvent(event)) void this.flushDisk();
+ if (!isTerminalEvent(event)) return;
+ flushNativeLog(event.threadId);
+ void this.flushDisk();
}
private enqueue(event: RuntimeEvent) {
@@ -274,13 +278,15 @@ export class EventBus {
}
private deliver(event: RuntimeEvent) {
- for (const listener of Array.from(this.listeners)) {
- try {
- listener(event);
- } catch (e) {
- console.error("bus: listener threw", e);
+ batchSaves(() => {
+ for (const listener of Array.from(this.listeners)) {
+ try {
+ listener(event);
+ } catch (e) {
+ console.error("bus: listener threw", e);
+ }
}
- }
+ });
}
subscribe(listener: RuntimeEventListener): () => void {
diff --git a/server/index.ts b/server/index.ts
index 129f31d834..a9bc97d1bf 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -430,7 +430,7 @@ import { claudeUserSkillsEnabled, settingsTurnFields } 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 RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts";
+import { ROUTINE_RESTARTED, RoutineManager, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts"; import { routineRunsFor } from "./routine-run-window.ts"; import { batchSaves } 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";
@@ -7648,7 +7648,9 @@ function threadTitleGate(bot: Pick<BotRecord, "modelSelection">): { ok: true; in
const titleRegenerations = new Set<string>();
-async function startTurn(
+/** The turn's start saves its thread's bookkeeping (title, last asked, read) once, when its synchronous part returns. */
+function startTurn(...args: Parameters<typeof beginTurn>): ReturnType<typeof beginTurn> { return batchSaves(() => beginTurn(...args)); }
+async function beginTurn(
botId: string,
text: string,
opts?: {
@@ -14834,14 +14836,9 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}
if (path === "/api/routines" && method === "GET") {
- const fromParam = url.searchParams.get("from");
- const toParam = url.searchParams.get("to");
- const from = fromParam == null ? undefined : Number(fromParam);
- const to = toParam == null ? undefined : Number(toParam);
return json(res, 200, {
routines: routines!.listRoutines().filter((routine) => routineVisible(routine, visible)),
- runs: routines!.listRuns(from != null && Number.isFinite(from) ? from : undefined, to != null && Number.isFinite(to) ? to : undefined)
- .filter((run) => routineRunVisible(run, visible)),
+ runs: routineRunsFor((from, to) => routines!.listRuns(from, to), url.searchParams).filter((run) => routineRunVisible(run, visible)),
});
}
const routineResultsRefusal = (body: unknown): string | null =>
diff --git a/server/registry-save.ts b/server/registry-save.ts
index 4ac0dd23d0..5b65579303 100644
--- a/server/registry-save.ts
+++ b/server/registry-save.ts
@@ -45,6 +45,8 @@ function restore(target: object, saved: object): void {
const PERMISSION_FIELDS = ["approvalMode", "autoApprove", "alwaysAllow"] as const;
+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. */
export function keptRevocation(before: ApprovalFields, after: ApprovalFields, patch: TaskPatch): TaskPatch | undefined {
const fields = PERMISSION_FIELDS.filter((key) => Object.hasOwn(patch, key));
diff --git a/server/routes/bot-settings.ts b/server/routes/bot-settings.ts
index 7207ce7456..df72f1017c 100644
--- a/server/routes/bot-settings.ts
+++ b/server/routes/bot-settings.ts
@@ -165,11 +165,12 @@ export function createBotSettingsRoutes(deps: BotSettingsRouteDeps): RouteHandle
const current = requestedTaskBot(m[1], body?.threadId);
sawThread(current.threadId);
deps.threadRead?.(auth, current.threadId);
- store.patchTask(current.id, current.threadId, { unread: false, ...readCursor(current.threadId) });
+ const task = store.taskByThread(current.id, current.threadId), cursor = readCursor(current.threadId);
+ const changed = Boolean(task?.unread) || (cursor.lastReadMessageId !== undefined && task?.lastReadMessageId !== cursor.lastReadMessageId);
+ if (changed) store.patchTask(current.id, current.threadId, { unread: false, ...cursor });
readThreadNotifications(current.threadId, broadcast, auth);
- const bot = store.bot(current.id)!;
- const visible = wireBot(bot);
- broadcast({ kind: "bot", bot: visible });
+ const visible = wireBot(store.bot(current.id)!);
+ if (changed) broadcast({ kind: "bot", bot: visible });
return json(res, 200, { bot: visible });
}
m = path.match(/^\/api\/bots\/([\w-]+)\/command-allowlist(?:\/([\w-]+))?$/);
diff --git a/server/routes/status.ts b/server/routes/status.ts
index 121a0a3984..32827b27c5 100644
--- a/server/routes/status.ts
+++ b/server/routes/status.ts
@@ -5,6 +5,7 @@ import { loadBrand } from "../brand.ts";
import { browserEngineStatus, ensureChrome, installAgentBrowserBinary, resolveAgentBrowserBinary } from "../browser-engine.ts";
import { DATA_DIR, EVENTS_DIR, NATIVE_DIR, instanceConfigs, type AppConfig } from "../config.ts";
import { boundRetentionDays, decisionsCsv, readDecisionRange, readDecisions, type DecisionRow } from "../decision-log.ts";
+import { flushNativeLog } from "../drivers/native.ts";
import { editionForMembers, editionStatus, entitled } from "../enterprise.ts";
import { fleetAvailable, fleetRequest, fleetSocketPath } from "../fleet-client.ts";
import { noteKeyAccepted, noteKeyRejected } from "../key-rejections.ts";
@@ -125,6 +126,7 @@ export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {
return json(res, 400, { error: "limit must be a positive whole number" });
}
const limit = parsedLimit;
+ flushNativeLog(threadId);
return json(res, 200, readThreadEvents({ eventsDir: EVENTS_DIR, nativeDir: NATIVE_DIR, threadId, limit }));
}
diff --git a/server/routine-run-window.test.ts b/server/routine-run-window.test.ts
new file mode 100644
index 0000000000..ba1373a72a
--- /dev/null
+++ b/server/routine-run-window.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+
+import { appRunWindow, NEWEST_RUNS_PER_AUTOMATION, routineRunsFor } from "./routine-run-window.ts";
+import type { RoutineRun } from "./routines.ts";
+
+const DAY = 86_400_000;
+const NOW = Date.UTC(2026, 10, 1);
+const run = (id: string, routineId: string, daysAgo: number, status: RoutineRun["status"], extra: Partial<RoutineRun> = {}) =>
+ ({ id, routineId, routineName: routineId, botId: "b", target: "bot", scheduledFor: NOW - daysAgo * DAY, status, manual: false, ...extra }) as RoutineRun;
+const ids = (runs: readonly RoutineRun[]) => runs.map((candidate) => candidate.id);
+
+describe("the app's run window", () => {
+ it("keeps recent runs and, whatever their age, the ones a status, a badge or a panel reads", () => {
+ const old = Array.from({ length: 20 }, (_, i) => run(`daily-${i}`, "daily", 30 + i, "completed"));
+ const runs = [
+ run("recent", "daily", 1, "completed"),
+ ...old,
+ run("waiting", "weekly", 60, "waiting"),
+ run("unseen", "weekly", 61, "failed"),
+ run("seen", "weekly", 62, "failed", { seenAt: NOW }),
+ run("weekly-ok", "weekly", 63, "completed"),
+ run("weekly-older", "weekly", 64, "completed"),
+ ...Array.from({ length: 10 }, (_, i) => run(`weekly-${i}`, "weekly", 70 + i, "completed")),
+ ];
+ const kept = ids(appRunWindow(runs, NOW - 14 * DAY));
+ expect(kept.filter((id) => id.startsWith("daily-"))).toHaveLength(NEWEST_RUNS_PER_AUTOMATION - 1);
+ expect(kept).toEqual(expect.arrayContaining(["recent", "waiting", "unseen", "seen", "weekly-ok", "weekly-older"]));
+ expect(kept).not.toContain("weekly-9");
+ });
+
+ it("reaches back past a run of failures to the last success, so the streak counts the same", () => {
+ const runs = [
+ ...Array.from({ length: 9 }, (_, i) => run(`fail-${i}`, "r", 20 + i, "failed", { seenAt: NOW })),
+ run("cancelled", "r", 40, "cancelled"),
+ run("ok", "r", 41, "completed"),
+ run("older", "r", 42, "completed"),
+ ];
+ expect(ids(appRunWindow(runs, NOW - 14 * DAY))).toEqual(runs.slice(0, 11).map((candidate) => candidate.id));
+ });
+
+ it("answers a range, a thread, the window, or everything", () => {
+ const runs = [run("a", "r", 1, "completed", { threadId: "t1" }), run("b", "r", 30, "completed")];
+ const listRuns = (from?: number, to?: number) => runs.filter((candidate) => (from === undefined || candidate.scheduledFor >= from) && (to === undefined || candidate.scheduledFor <= to));
+ expect(ids(routineRunsFor(listRuns, new URLSearchParams()))).toEqual(["a", "b"]);
+ expect(ids(routineRunsFor(listRuns, new URLSearchParams({ from: String(NOW - 40 * DAY), to: String(NOW - 20 * DAY) })))).toEqual(["b"]);
+ expect(ids(routineRunsFor(listRuns, new URLSearchParams({ thread: "t1" })))).toEqual(["a"]);
+ expect(ids(routineRunsFor(listRuns, new URLSearchParams({ since: String(NOW - 7 * DAY) })))).toEqual(["a", "b"]);
+ });
+});
diff --git a/server/routine-run-window.ts b/server/routine-run-window.ts
new file mode 100644
index 0000000000..34afaaaa97
--- /dev/null
+++ b/server/routine-run-window.ts
@@ -0,0 +1,36 @@
+import { isRoutineProblemRun } from "../shared/routines.ts";
+import type { RoutineRun } from "./routines.ts";
+
+/** However old they are, each automation keeps at least this many of its newest runs in the app's window. */
+export const NEWEST_RUNS_PER_AUTOMATION = 5;
+
+const ACTIVE = new Set<RoutineRun["status"]>(["queued", "running", "waiting"]);
+
+/** The runs the app loads at start (`GET /api/routines?since=`): those scheduled since `since`, and, whatever their age,
+ * every unfinished run, every failed or missed run not yet seen, and each automation's newest runs back to its newest
+ * settled run that was no problem, so its status, its run of failures and its latest runs read as with every run loaded.
+ * `newestFirst` is ordered by scheduledFor, newest first. */
+export function appRunWindow(newestFirst: readonly RoutineRun[], since: number): RoutineRun[] {
+ const reach = new Map<string, { count: number; settled: boolean }>();
+ return newestFirst.filter((run) => {
+ const own = reach.get(run.routineId) ?? { count: 0, settled: false };
+ reach.set(run.routineId, own);
+ const reached = own.count < NEWEST_RUNS_PER_AUTOMATION || !own.settled;
+ own.count += 1;
+ if (run.status !== "cancelled" && run.status !== "queued" && !isRoutineProblemRun(run)) own.settled = true;
+ return reached || run.scheduledFor >= since || ACTIVE.has(run.status) || (isRoutineProblemRun(run) && !run.seenAt);
+ });
+}
+
+/** `since` asks for the app's window; `from` and `to` for exactly the runs scheduled in that range; `thread` for the
+ * runs that worked in one conversation; nothing, for every run. */
+export function routineRunsFor(listRuns: (from?: number, to?: number) => RoutineRun[], query: URLSearchParams): RoutineRun[] {
+ const time = (name: string) => {
+ const raw = query.get(name);
+ const value = raw === null ? Number.NaN : Number(raw);
+ return Number.isFinite(value) ? value : undefined;
+ };
+ const since = time("since"), thread = query.get("thread");
+ if (thread) return listRuns().filter((run) => run.threadId === thread);
+ return since === undefined ? listRuns(time("from"), time("to")) : appRunWindow(listRuns(), since);
+}
diff --git a/server/routines.test.ts b/server/routines.test.ts
index 6d06696988..7c9364debf 100644
--- a/server/routines.test.ts
+++ b/server/routines.test.ts
@@ -1424,7 +1424,7 @@ describe("RoutineManager", () => {
let failureWasPersistedBeforeCallback = false;
h.options.onRunFailed = (run) => {
h.failed.push(run);
- failureWasPersistedBeforeCallback = readFileSync(routineFile, "utf8").includes('"status": "failed"');
+ failureWasPersistedBeforeCallback = JSON.parse(readFileSync(routineFile, "utf8")).runs.some((saved: RoutineRun) => saved.status === "failed");
};
const cut: RoutineRun[] = [];
h.options.onRunCut = (run) => cut.push(run);
@@ -1683,7 +1683,7 @@ describe("RoutineManager", () => {
const file = h.options.file;
if (!file) throw new Error("test harness did not configure routine persistence");
const stored = readFileSync(file, "utf8");
- const malformed = stored.replace(`"sourceThreadId": "${request.threadId}"`, '"sourceThreadId": 42');
+ const malformed = stored.replace(`"sourceThreadId":"${request.threadId}"`, '"sourceThreadId":42');
expect(malformed).not.toBe(stored);
writeFileSync(file, malformed);
diff --git a/server/routines.ts b/server/routines.ts
index 80507dc1e1..fcaa15850c 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -4,7 +4,7 @@ import { dirname, join } from "node:path";
import { DATA_DIR } from "./config.ts";
import type { RuntimeEvent } from "./contracts.ts";
-import { writeFileAtomic } from "./atomic.ts";
+import { OwnedFile } from "./atomic.ts"; import { saveSoon } from "./save-batch.ts";
import { redactSecretsInText } from "./redact.ts";
import { activeRunsOf, nextDueOf, schedulerDueOf, wakeHoldOf } from "./routine-due.ts";
import { startDueTimer, type DueTimer } from "./due-timer.ts";
@@ -294,7 +294,7 @@ function cloneRun(run: RoutineRun): RoutineRun {
}
export class RoutineManager {
- private readonly file: string;
+ private readonly file: string; private readonly disk: OwnedFile;
private readonly now: () => number;
private readonly options: RoutineManagerOptions;
private routines: Routine[] = [];
@@ -320,11 +320,11 @@ export class RoutineManager {
constructor(options: RoutineManagerOptions) {
this.options = options;
- this.file = options.file ?? join(DATA_DIR, "routines.json");
+ this.file = options.file ?? join(DATA_DIR, "routines.json"); this.disk = new OwnedFile(this.file, { mode: 0o600 });
this.now = options.now ?? Date.now;
this.bootedAt = this.now();
try {
- const disk = JSON.parse(readFileSync(this.file, "utf8")) as Partial<RoutineFile>;
+ const text = readFileSync(this.file, "utf8"), disk = JSON.parse(text) as Partial<RoutineFile>; this.disk.loaded(text);
if (disk === null || typeof disk !== "object" || Array.isArray(disk)) throw new Error("Invalid routines file");
for (const key of ["routines", "runs", "routineRequestReceipts", "webhookRunReceipts"] as const) {
if (key in disk && !Array.isArray(disk[key])) throw new Error(`Invalid routines file: ${key} is not a list`);
@@ -371,7 +371,7 @@ export class RoutineManager {
}
cut.push(cloneRun(run));
}
- if (cut.length > 0) this.save();
+ if (cut.length > 0) this.saveLater();
for (const run of cut) {
if (run.threadId) this.options.onRunCut?.(run);
this.notifyRunChanged(run);
@@ -390,7 +390,7 @@ export class RoutineManager {
this.options.frozenResultsThread?.(routine.botId, routine.resultsThreadId)) delete routine.resultsThreadId;
}
this.frozenPending = false;
- this.save();
+ this.saveLater();
}
private routineWithHealth(routine: Routine): Routine {
@@ -510,7 +510,7 @@ export class RoutineManager {
if (!run) return null;
if (report) run.report = report;
else delete run.report;
- this.save();
+ this.saveLater();
this.emitRun(run);
return cloneRun(run);
}
@@ -711,7 +711,7 @@ export class RoutineManager {
}
changed = true;
}
- if (changed) this.save();
+ if (changed) this.saveLater();
}
runNow(id: string, request?: RoutineRequestCommitFor<"run_now">): RoutineRun | null {
@@ -823,7 +823,7 @@ export class RoutineManager {
this.emitRun(run);
changed = true;
}
- if (changed) this.save();
+ if (changed) this.saveLater();
}
async cancelRun(id: string, reason?: string): Promise<RoutineRun | null> {
@@ -834,7 +834,7 @@ export class RoutineManager {
run.attention = undefined;
run.finishedAt = this.now();
if (reason) run.error = reason;
- this.save();
+ this.saveLater();
this.emitRun(run);
if (run.threadId) {
if (run.target === "room-goal") {
@@ -852,7 +852,7 @@ export class RoutineManager {
if (!run) return null;
if (!run.seenAt) {
run.seenAt = this.now();
- this.save();
+ this.saveLater();
this.emitRun(run);
}
return cloneRun(run);
@@ -886,7 +886,7 @@ export class RoutineManager {
routine.nextRunAt = next;
return true;
});
- if (moved.length) this.save();
+ if (moved.length) this.saveLater();
for (const routine of moved) this.emitRoutine(routine);
return moved.length;
}
@@ -901,7 +901,7 @@ export class RoutineManager {
routine.nextRunAt = schedule.at;
return true;
});
- if (moved.length) this.save();
+ if (moved.length) this.saveLater();
for (const routine of moved) this.emitRoutine(routine);
return moved.length;
}
@@ -1071,10 +1071,12 @@ export class RoutineManager {
}
for (const { id, hold } of checks) this.runChecks(id, hold).catch((error) => console.error(`routines: the checks of ${id} failed`, error));
- // Oldest first, by id: a rollback across awaits can replace the run objects.
+ // Oldest first, by id: a rollback across awaits can replace the run objects, and the array with them.
+ let indexed: RoutineRun[] | null = null, byId = new Map<string, RoutineRun>();
for (const id of this.runs.map((run) => run.id)) {
if (this.closing) return;
- const run = this.runs.find((candidate) => candidate.id === id);
+ if (indexed !== this.runs) [indexed, byId] = [this.runs, new Map(this.runs.map((run) => [run.id, run]))];
+ const run = byId.get(id);
if (!run || run.status !== "queued" || (run.retryAt ?? 0) > now) continue;
const triggerSource = run.triggerSource ?? (run.manual ? "manual" : "schedule");
const definition = triggerSource === "schedule"
@@ -1084,7 +1086,7 @@ export class RoutineManager {
const latest = latestIntervalOccurrence(definition.schedule, now);
if (latest !== null && latest > run.scheduledFor) {
run.scheduledFor = latest;
- this.save();
+ this.saveLater();
this.emitRun(run);
}
const requiresCurrentDayOccurrence =
@@ -1109,12 +1111,12 @@ export class RoutineManager {
if (state === "busy") {
if (run.deferredAt == null) {
run.deferredAt = now;
- this.save();
+ this.saveLater();
this.emitRun(run);
}
if (run.deferredNoticeAt == null && !run.checkKey && now - run.deferredAt >= ROUTINE_DEFERRAL_NOTICE_MS) {
run.deferredNoticeAt = now;
- this.save();
+ this.saveLater();
this.emitRun(run);
this.options.onRunDeferred?.(cloneRun(run));
}
@@ -1287,7 +1289,7 @@ export class RoutineManager {
} else {
return null;
}
- this.save();
+ this.saveLater();
this.emitRun(run);
if (event.type === "turn.completed") queueMicrotask(() => this.tickInBackground());
return cloneRun(run);
@@ -1311,7 +1313,7 @@ export class RoutineManager {
const recovery = recoverRun(run, failure, { ...facts, ...(backupReady ? { backupReady } : {}) }, this.now(), this.ownerNotices);
if (!recovery.queued) this.failRun(run, recovery.error, "failed", recovery.alert);
else {
- this.save();
+ this.saveLater();
this.emitRun(run);
if (recovery.alert) this.options.onRunDeferred?.(cloneRun(run), recovery.alert);
}
@@ -1336,7 +1338,7 @@ export class RoutineManager {
} else if (status === "needs-input" || status === "paused") {
this.wait(run, safeDetail.slice(0, 500) || (status === "paused" ? "The room goal is paused" : "The team needs your input"));
run.error = undefined;
- this.save();
+ this.saveLater();
this.emitRun(run);
} else {
run.status = status === "stopped" ? "cancelled" : "completed";
@@ -1344,7 +1346,7 @@ export class RoutineManager {
run.finishedAt = this.now();
run.error = undefined;
if (status !== "stopped") run.output = safeDetail.slice(0, 2_000) || undefined;
- this.save();
+ this.saveLater();
this.emitRun(run);
}
queueMicrotask(() => this.tickInBackground());
@@ -1354,8 +1356,7 @@ export class RoutineManager {
/** Timed from when it began, so a later occurrence can tell a wait that went unanswered. */
private wait(run: RoutineRun, attention: string | undefined) {
if (run.status !== "waiting" || run.waitingSince === undefined) run.waitingSince = this.now();
- run.status = "waiting";
- run.attention = attention;
+ Object.assign(run, { status: "waiting", attention } satisfies Partial<RoutineRun>);
}
private async stopRun(run: RoutineRun, detail: string, status: "stopped" | "limit-reached") {
@@ -1367,11 +1368,8 @@ export class RoutineManager {
}
private failRun(run: RoutineRun, message: string, status: "failed" | "missed" = "failed", alert?: RoutineAlert | null) {
- run.status = status;
- run.attention = undefined;
- run.error = redactSecretsInText(message).slice(0, 500);
- run.finishedAt = this.now();
- this.save();
+ Object.assign(run, { status, attention: undefined, error: redactSecretsInText(message).slice(0, 500), finishedAt: this.now() } satisfies Partial<RoutineRun>);
+ this.saveLater();
this.emitRun(run);
const repeat = failsLikeLastOutcome(this.runs, run) || (run.checkKey !== undefined && outcomesNewestFirst(this.runs, run.routineId, run.id)[0]?.status === "failed");
this.options.onRunFailed?.(cloneRun(run), alert === undefined && repeat ? null : alert);
@@ -1542,6 +1540,8 @@ export class RoutineManager {
}
}
+ /** Lands at the end of the running save batch (server/save-batch.ts); what a caller rolls back on failure uses save. */
+ private saveLater() { saveSoon(this, () => this.save()); }
private save() {
if (this.unreadable) return;
// Evict only terminal receipts: an active one owns cancellation, timeout and event routing.
@@ -1555,7 +1555,7 @@ export class RoutineManager {
excess -= 1;
}
mkdirSync(dirname(this.file), { recursive: true });
- writeFileAtomic(this.file, JSON.stringify({
+ this.disk.write(JSON.stringify({
version: 1,
...(this.frozenPending ? {} : { frozenResultsCleared: true }),
routines: [...this.routines, ...this.unloadedRoutines],
@@ -1565,6 +1565,6 @@ export class RoutineManager {
...(this.startupLaunchId === undefined ? {} : { startupLaunchId: this.startupLaunchId }),
...(this.ownerNotices.length ? { ownerNotices: this.ownerNotices } : {}),
...(this.holds.length ? { holds: this.holds } : {}),
- } satisfies RoutineFile, null, 2), { mode: 0o600 });
+ } satisfies RoutineFile));
}
}
diff --git a/server/save-batch.test.ts b/server/save-batch.test.ts
new file mode 100644
index 0000000000..b3fce2a33c
--- /dev/null
+++ b/server/save-batch.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { batchSaves, saveSoon } from "./save-batch.ts";
+
+describe("batchSaves", () => {
+ it("writes at once outside a batch, and once per file when the outermost batch returns", () => {
+ const writes: string[] = [];
+ const a = {}, b = {};
+ saveSoon(a, () => writes.push("a0"));
+ expect(writes).toEqual(["a0"]);
+ batchSaves(() => {
+ saveSoon(a, () => writes.push("a1"));
+ batchSaves(() => saveSoon(b, () => writes.push("b1")));
+ saveSoon(a, () => writes.push("a2"));
+ expect(writes).toEqual(["a0"]);
+ });
+ expect(writes).toEqual(["a0", "a2", "b1"]);
+ });
+
+ it("writes what was asked for when the batch throws, and a failed write never stops the others", () => {
+ const writes: string[] = [];
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ expect(() => batchSaves(() => {
+ saveSoon({}, () => { throw new Error("disk full"); });
+ saveSoon({}, () => writes.push("b"));
+ throw new Error("listener");
+ })).toThrow("listener");
+ expect(writes).toEqual(["b"]);
+ expect(error).toHaveBeenCalledOnce();
+ error.mockRestore();
+ });
+
+ it("hands back what the batch returned", () => {
+ expect(batchSaves(() => 42)).toBe(42);
+ });
+});
diff --git a/server/save-batch.ts b/server/save-batch.ts
new file mode 100644
index 0000000000..0cf14cd28a
--- /dev/null
+++ b/server/save-batch.ts
@@ -0,0 +1,35 @@
+// 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.
+
+let depth = 0;
+const pending = new Map<object, () => void>();
+
+export function batchSaves<T>(run: () => T): T {
+ depth += 1;
+ try {
+ return run();
+ } finally {
+ depth -= 1;
+ if (depth === 0) writePending();
+ }
+}
+
+/** Writes now, or once at the end of the running batch; `owner` keeps one pending write per file. */
+export function saveSoon(owner: object, write: () => void): void {
+ if (depth === 0) write();
+ else pending.set(owner, write);
+}
+
+function writePending(): void {
+ while (pending.size) {
+ const [owner, write] = pending.entries().next().value!;
+ pending.delete(owner);
+ try {
+ write();
+ } catch (error) {
+ // The changes stay in memory and the next save of the file writes them; a failed save never ends the pass early.
+ console.error("a batched save failed; the next save of the file retries it", error);
+ }
+ }
+}
diff --git a/server/server-writes.e2e.test.ts b/server/server-writes.e2e.test.ts
new file mode 100644
index 0000000000..d5a9fb852d
--- /dev/null
+++ b/server/server-writes.e2e.test.ts
@@ -0,0 +1,57 @@
+// The real server killed in the middle of a turn: what the files hold is what a later start reads.
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { afterEach, expect, it } from "vitest";
+
+import { launchVerificationServer, runControlOmb, type VerificationServer } from "../scripts/control-omb.ts";
+import { waitForExit } from "./testing/cleanup.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+let fixture: VerificationServer | undefined;
+afterEach(async () => {
+ await fixture?.close();
+ fixture = undefined;
+});
+
+const read = (path: string) => {
+ try { return readFileSync(path, "utf8"); } catch { return ""; }
+};
+const json = (path: string) => {
+ try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
+};
+
+it.each(["SIGKILL", "SIGTERM"] as const)("a turn and a routine run cut by %s keep everything saved so far", async (signal) => {
+ fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_MODE: "hang" });
+ const { url, dataDir } = fixture.info;
+ const cli = (...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: { "content-type": "application/json", origin: url }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ expect(response.status, path).toBeLessThan(300);
+ return await response.json() as any;
+ };
+ const { bot } = await cli("new-bot", "--name", "Talks");
+ const { bot: worker } = await cli("new-bot", "--name", "Works");
+ const task = (id: string, threadId: string) => (json(join(dataDir, "bots.json")) as any[] | null)?.find((row) => row.id === id)?.tasks?.find((row: any) => row.threadId === threadId);
+
+ const { routine } = await api("POST", "/api/routines", { name: "Morning", prompt: "Summarise.", botId: worker.id, enabled: false, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } });
+ const { run } = await api("POST", `/api/routines/${routine.id}/run`);
+ const savedRun = () => (json(join(dataDir, "routines.json")) as { runs?: any[] } | null)?.runs?.find((row) => row.id === run.id);
+ await expect.poll(() => savedRun()?.status, { timeout: hostTimeout(30_000) }).toBe("running");
+
+ await cli("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", "Plan the offsite");
+ await expect.poll(() => Object.keys(task(bot.id, bot.activeTaskId)?.resumeCursors ?? {}).length, { timeout: hostTimeout(30_000) }).toBe(1);
+
+ await waitForExit(fixture.child, { signal });
+
+ const saved = task(bot.id, bot.activeTaskId);
+ expect(saved.title).toBe("Plan the offsite");
+ expect(saved.askedAt).toEqual(expect.any(Number));
+ expect(saved.cwd).toEqual(expect.any(String));
+ expect(saved.resumeCursors.claude).toEqual(expect.any(String));
+ expect(savedRun()).toMatchObject({ status: "running", threadId: expect.any(String) });
+
+ const native = read(join(dataDir, "native", `${bot.activeTaskId}.ndjson`)).split("\n").filter(Boolean).map((line) => JSON.parse(line));
+ expect(JSON.stringify(native.filter((row) => row.dir === "out"))).toContain("Plan the offsite");
+ // An orderly exit writes the lines still held; a kill can lose only those, the last FLUSH_MS of what the engine said.
+ if (signal === "SIGTERM") expect(native.some((row) => row.dir === "in" && row.msg?.subtype === "init")).toBe(true);
+}, hostTimeout(90_000));
diff --git a/server/server-writes.test.ts b/server/server-writes.test.ts
new file mode 100644
index 0000000000..3cc0e74125
--- /dev/null
+++ b/server/server-writes.test.ts
@@ -0,0 +1,126 @@
+// Whole-file saves of bots.json and routines.json: fewer writes, and at every point the server yields to the event loop
+// (where a crash or an exit can land) the files hold what one write per change would have left.
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// Spied, not replaced: every call reaches the real filesystem, and a test counts the renames a save costs.
+vi.mock("node:fs", { spy: true });
+vi.resetModules();
+const fs = await import("node:fs");
+const { DATA_DIR } = await import("./config.ts");
+const { batchSaves } = await import("./save-batch.ts");
+const { Store } = await import("./store.ts");
+const { RoutineManager } = await import("./routines.ts");
+type RuntimeEvent = import("./contracts.ts").RuntimeEvent;
+
+const selection = () => ({ instanceId: "claude", model: "claude-sonnet-5" });
+const writesOf = (name: string) => vi.mocked(fs.renameSync).mock.calls.filter(([, to]) => String(to).endsWith(`/${name}`)).length;
+const reads = (name: string) => vi.mocked(fs.readFileSync).mock.calls.filter(([path]) => String(path).endsWith(`/${name}`)).length;
+const bots = () => readFileSync(join(DATA_DIR, "bots.json"), "utf8");
+
+describe("bots.json saves", () => {
+ beforeEach(() => {
+ rmSync(DATA_DIR, { recursive: true, force: true });
+ vi.mocked(fs.renameSync).mockClear();
+ });
+
+ it("are compact, and skip an unchanged save without reading the file back", () => {
+ const store = new Store(selection);
+ const bot = store.createBot({ name: "Pepper" });
+ expect(bots()).not.toContain("\n");
+ store.patchTask(bot.id, bot.threadId, { lastContextModel: "claude:claude-sonnet-5" });
+ const writes = writesOf("bots.json");
+ const before = reads("bots.json");
+ store.patchTask(bot.id, bot.threadId, { lastContextModel: "claude:claude-sonnet-5" });
+ store.setResumeCursor(bot.id, "claude", "session-1", bot.threadId);
+ store.setResumeCursor(bot.id, "claude", "session-1", bot.threadId);
+ expect(writesOf("bots.json")).toBe(writes + 1);
+ expect(reads("bots.json")).toBe(before);
+ });
+
+ it("land once per batch, and the file holds every change when the batch returns", () => {
+ const store = new Store(selection);
+ const bot = store.createBot({ name: "Pepper" });
+ const writes = writesOf("bots.json");
+ batchSaves(() => {
+ store.titleTaskFromFirstMessage(bot.id, "Plan the offsite", bot.threadId);
+ store.setTaskAskedAt(bot.id, bot.threadId, 1_000);
+ store.patchTask(bot.id, bot.threadId, { unread: false });
+ store.setResumeCursor(bot.id, "claude", "session-1", bot.threadId);
+ store.markTaskDispatched(bot.id, bot.threadId, "claude");
+ store.addTaskUsage(bot.id, bot.threadId, { input: 10, output: 5, costUsd: 0.01 });
+ store.patchTask(bot.id, bot.threadId, { unread: true });
+ expect(writesOf("bots.json")).toBe(writes);
+ });
+ expect(writesOf("bots.json")).toBe(writes + 1);
+ // A crash here, with no exit handler run, starts from exactly this.
+ const task = new Store(selection).taskByThread(bot.id, bot.threadId)!;
+ expect(task).toMatchObject({ title: "Plan the offsite", askedAt: 1_000, unread: true, lastInstanceId: "claude", resumeCursors: { claude: "session-1" } });
+ expect(task.usage).toMatchObject({ input: 10, output: 5, turns: 1 });
+ });
+
+ it("write a permission change at once, even inside a batch", () => {
+ const store = new Store(selection);
+ const bot = store.createBot({ name: "Pepper" });
+ batchSaves(() => {
+ store.patchTask(bot.id, bot.threadId, { approvalMode: "ask" });
+ expect(new Store(selection).taskByThread(bot.id, bot.threadId)?.approvalMode).toBe("ask");
+ });
+ });
+
+ it("keep a change whose batched save failed, and the next save writes it", () => {
+ const store = new Store(selection);
+ const bot = store.createBot({ name: "Pepper" });
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ vi.mocked(fs.renameSync).mockImplementationOnce(() => { throw Object.assign(new Error("disk full"), { code: "ENOSPC" }); });
+ batchSaves(() => store.setTaskAskedAt(bot.id, bot.threadId, 2_000));
+ expect(error).toHaveBeenCalled();
+ error.mockRestore();
+ expect(new Store(selection).taskByThread(bot.id, bot.threadId)?.askedAt).toBeUndefined();
+ store.setTaskAskedAt(bot.id, bot.threadId, 3_000);
+ expect(new Store(selection).taskByThread(bot.id, bot.threadId)?.askedAt).toBe(3_000);
+ });
+});
+
+describe("routines.json saves", () => {
+ let dir: string;
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "omb-routine-writes-")); });
+ afterEach(() => rmSync(dir, { recursive: true, force: true }));
+
+ const event = (threadId: string, rest: Record<string, unknown>) =>
+ ({ eventId: `e-${Math.random()}`, provider: "claudeAgent", threadId, turnId: "turn-1", createdAt: new Date().toISOString(), ...rest }) as unknown as RuntimeEvent;
+
+ it("write a manual run four times, and a restart after any step reads what that step saved", async () => {
+ const file = join(dir, "routines.json");
+ const options = {
+ file,
+ botState: () => "ready" as const,
+ createTask: () => ({ threadId: "thread-1" }),
+ startTurn: async () => {},
+ };
+ const manager = new RoutineManager(options);
+ const routine = manager.create({ name: "Morning", prompt: "Summarise.", botId: "bot-1", enabled: false, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } });
+ vi.mocked(fs.renameSync).mockClear();
+ const restart = () => new RoutineManager({ ...options, startTurn: async () => {} }).listRuns()[0];
+
+ const run = manager.runNow(routine.id)!;
+ expect(restart()).toMatchObject({ id: run.id, status: "queued" });
+ await manager.tick();
+ expect(JSON.parse(readFileSync(file, "utf8")).runs[0]).toMatchObject({ status: "running", threadId: "thread-1" });
+
+ const deliver = (rest: Record<string, unknown>) => batchSaves(() => manager.handleRuntimeEvent(event("thread-1", rest)));
+ deliver({ type: "turn.started" });
+ deliver({ type: "item.completed", itemType: "assistant_text", text: "Calendar clear." });
+ expect(JSON.parse(readFileSync(file, "utf8")).runs[0]).toMatchObject({ status: "running", output: "Calendar clear." });
+ batchSaves(() => {
+ manager.handleRuntimeEvent(event("thread-1", { type: "turn.completed", ok: true }));
+ manager.noteReport(run.id, { state: "pending" });
+ manager.noteReport(run.id, { state: "quiet" });
+ });
+ expect(JSON.parse(readFileSync(file, "utf8")).runs[0]).toMatchObject({ status: "completed", output: "Calendar clear.", report: { state: "quiet" } });
+ expect(writesOf("routines.json")).toBe(4);
+ expect(readFileSync(file, "utf8")).not.toContain("\n");
+ });
+});
diff --git a/server/store.test.ts b/server/store.test.ts
index 7abe961be7..bb65e31262 100644
--- a/server/store.test.ts
+++ b/server/store.test.ts
@@ -422,14 +422,14 @@ describe("Store", () => {
store.setResumeCursor(bot.id, "claude", { sessionId: "s-1" }, bot.threadId);
store.patchTask(bot.id, bot.threadId, { lastContextModel: "claude-sonnet-5" });
expect(statSync(file).ino).toBe(saved);
- expect(events).toEqual([{ type: "bot", botId: bot.id }, { type: "bot", botId: bot.id }]);
+ expect(events).toEqual([{ type: "bot", botId: bot.id }]);
store.setResumeCursor(bot.id, "claude", { sessionId: "s-2" }, bot.threadId);
expect(statSync(file).ino).not.toBe(saved);
expect(new Store(selection).taskByThread(bot.id, bot.threadId)?.resumeCursors).toEqual({ claude: { sessionId: "s-2" } });
});
- it("still overwrites a bots.json changed on disk when the next save differs from it", () => {
+ it("overwrites a bots.json changed on disk with the next change it saves", () => {
const file = join(DATA_DIR, "bots.json");
const store = new Store(selection);
const bot = store.createBot({ name: "Original" }, { seedMessages: false });
@@ -438,7 +438,7 @@ describe("Store", () => {
edited[0].name = "Edited on disk";
writeFileSync(file, JSON.stringify(edited, null, 2));
- store.setResumeCursor(bot.id, "claude", { sessionId: "s-1" }, bot.threadId);
+ store.setResumeCursor(bot.id, "claude", { sessionId: "s-2" }, bot.threadId);
expect(JSON.parse(readFileSync(file, "utf8"))[0].name).toBe("Original");
});
diff --git a/server/store.ts b/server/store.ts
index 2bdaec41f9..1f839ce68b 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 { join } from "node:path"; import { isDeepStrictEqual } from "node:util";
-import { writeFileAtomic, writeFileAtomicIfChanged } from "./atomic.ts";
-import { commitRegistryChange, keptRevocation, saveRegistryFor } from "./registry-save.ts";
+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 { parseToolScope, toolScopeWidens } from "../shared/tool-scope.ts"; import { grantScopedApps } from "../shared/connector-scopes.ts";
import { reorderStable } from "../shared/bot-order.ts";
import { botOwner, chiefConflict, chiefScope, ownerEmail } from "../shared/bot-owner.ts";
@@ -310,6 +310,7 @@ export class Store {
private personName: () => string | undefined;
private listeners = new Set<(change: StoreChange) => void>();
private registeringInitialSections = true;
+ private readonly botsFile = new OwnedFile(BOTS_FILE, { mode: 0o600 }); private readonly groupsFile = new OwnedFile(GROUPS_FILE, { mode: 0o600 });
/** Clearing this slot must not clear a concurrently running task's activity. */
private legacyActivities = new Map<string, BotActivity>();
@@ -333,13 +334,12 @@ export class Store {
// An unreadable bots.json must never read as "every member was deleted".
let botsLoaded = false;
try {
- this.bots = JSON.parse(readFileSync(BOTS_FILE, "utf8"));
- botsLoaded = Array.isArray(this.bots);
+ const text = readFileSync(BOTS_FILE, "utf8"); this.bots = JSON.parse(text); this.botsFile.loaded(text); botsLoaded = Array.isArray(this.bots);
} catch {
this.bots = [];
}
try {
- this.groups = JSON.parse(readFileSync(GROUPS_FILE, "utf8"));
+ const text = readFileSync(GROUPS_FILE, "utf8"); this.groups = JSON.parse(text); this.groupsFile.loaded(text);
} catch {
this.groups = [];
}
@@ -698,28 +698,28 @@ export class Store {
if (botsDirty) this.saveBots();
}
- private commitBotChange(bot: BotRecord, action: string, change: () => void, onRollback?: () => void) {
- commitRegistryChange(bot, "bots.json", action, () => this.saveBots(), change, onRollback);
+ 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 commitGroupChange(group: GroupRecord, action: string, change: () => void) {
commitRegistryChange(group, "groups.json", action, () => this.saveGroups(), change);
}
+ private saveBotsSoon() { saveSoon(this.botsFile, () => this.saveBots()); }
private saveBots(bots: BotRecord[] = this.bots, registerSections = true) {
if (registerSections) this.rememberSections([...this.bots, ...bots].map((bot) => bot.section));
- writeFileAtomicIfChanged(BOTS_FILE, JSON.stringify(bots.map(({ busy: _busy, activity: _activity, ...bot }) => ({
- ...bot,
+ 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)),
- })), null, 2), { mode: 0o600 });
+ }))));
}
private saveGroups(groups: GroupRecord[] = this.groups, registerSections = true) {
if (registerSections) this.rememberSections(groups.map((group) => group.section));
- writeFileAtomicIfChanged(GROUPS_FILE, JSON.stringify(groups.map(({ busyBotId: _busyBotId, turnStartedAt: _turnStartedAt, ...g }) => ({
+ this.groupsFile.write(JSON.stringify(groups.map(({ busyBotId: _busyBotId, turnStartedAt: _turnStartedAt, ...g }) => ({
...g,
...(g.tasks ? { tasks: g.tasks.map((task) => persistedPin(task)) } : {}),
- })), null, 2), { mode: 0o600 });
+ }))));
}
get sections(): string[] { return readSections(); }
@@ -928,7 +928,7 @@ export class Store {
}
private deleteThreadRecord(threadId: string, dbAlreadyDeleted = false) {
- this.threads.delete(threadId);
+ this.threads.delete(threadId); discardNativeLog(threadId);
if (!dbAlreadyDeleted) mdb.deleteThread(threadId);
for (const file of [
messagesFile(threadId),
@@ -1843,10 +1843,10 @@ export class Store {
setResumeCursor(botId: string, instanceId: string, cursor: unknown, threadId?: string) {
const bot = this.bot(botId);
if (!bot) return;
- const task = threadId ? this.taskByThread(botId, threadId) : this.activeTask(botId);
- if (task) task.resumeCursors[instanceId] = cursor;
- if (!threadId || bot.threadId === threadId) bot.resumeCursors[instanceId] = cursor;
- saveRegistryFor("bots.json", "the conversation's engine session", () => this.saveBots());
+ const task = threadId ? this.taskByThread(botId, threadId) : this.activeTask(botId), mirrored = !threadId || bot.threadId === threadId;
+ 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 });
}
@@ -1854,7 +1854,7 @@ export class Store {
const task = this.taskByThread(botId, threadId);
if (!task || task.lastInstanceId === instanceId) return;
task.lastInstanceId = instanceId;
- saveRegistryFor("bots.json", "which engine has this conversation", () => this.saveBots());
+ saveRegistryFor("bots.json", "which engine has this conversation", () => this.saveBotsSoon());
}
setHandedMessages(botId: string, threadId: string, instanceId: string, state: HandedState) {
@@ -1863,7 +1863,7 @@ export class Store {
const live = Object.entries(task.handedMessages ?? {})
.filter(([id, record]) => id !== instanceId && record.session !== undefined && record.session === task.resumeCursors[id]);
task.handedMessages = { ...Object.fromEntries(live), [instanceId]: state };
- saveRegistryFor("bots.json", "what this conversation handed its engine", () => this.saveBots());
+ saveRegistryFor("bots.json", "what this conversation handed its engine", () => this.saveBotsSoon());
}
addTaskUsage(
@@ -1900,7 +1900,7 @@ export class Store {
? { context: { tokens: contextTokens, ...(contextWindow > 0 ? { window: contextWindow } : {}) } }
: prev.context ? { context: prev.context } : {}),
};
- saveRegistryFor("bots.json", "the thread's usage", () => this.saveBots());
+ saveRegistryFor("bots.json", "the thread's usage", () => this.saveBotsSoon());
this.emit({ type: "bot", botId });
return task.usage;
}
@@ -2087,7 +2087,7 @@ 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)));
+ }, revocation && (() => Object.assign(task, revocation)), !touchesPermissions(patch));
this.emit({ type: "bot", botId });
return task;
}
@@ -2236,7 +2236,7 @@ export class Store {
const task = this.taskByThread(botId, threadId);
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.saveBots());
+ saveRegistryFor("bots.json", "when you last wrote in this thread", () => this.saveBotsSoon());
this.emit({ type: "bot", botId });
return task;
}
@@ -2274,7 +2274,7 @@ export class Store {
this.commitBotChange(bot, "the thread's title", () => {
task.title = titleFromMessage(text);
task.titleFromFirstMessage = true;
- });
+ }, undefined, true);
this.emit({ type: "bot", botId });
return task;
}
diff --git a/server/thread-log-rotation.test.ts b/server/thread-log-rotation.test.ts
index b039791c8d..f37fa9def8 100644
--- a/server/thread-log-rotation.test.ts
+++ b/server/thread-log-rotation.test.ts
@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ensureDirs, EVENTS_DIR, NATIVE_DIR } from "./config.ts";
import type { RuntimeEvent } from "./contracts.ts";
-import { appendNative } from "./drivers/native.ts";
+import { appendNative, flushNativeLog } from "./drivers/native.ts";
import { EventBus } from "./harness/bus.ts";
import { bindThreadLogCapProvider, capThreadLog, currentThreadLogCap } from "./thread-log-rotation.ts";
import { readThreadEvents } from "./thread-events.ts";
@@ -107,7 +107,10 @@ describe("thread log rotation", () => {
it("the native tee caps its log after appending", () => {
bindThreadLogCapProvider(() => 400);
- for (let i = 0; i < 12; i++) appendNative(THREAD, { dir: "in", source: "test", msg: { i } });
+ for (let i = 0; i < 12; i++) {
+ appendNative(THREAD, { dir: "in", source: "test", msg: { i } });
+ flushNativeLog(THREAD);
+ }
const file = join(NATIVE_DIR, `${THREAD}.ndjson`);
const lines = linesOf(NATIVE_DIR);
expect(statSync(file).size).toBeLessThanOrEqual(400);
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 8a240e72c3..744335d365 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -57,7 +57,7 @@ import { normalizeState, stateForBot } from "@/lib/mascot";
import { peerLine, peerRequest, type PeerLine } from "@/lib/peer-message";
import { showWorkingDots } from "@/lib/turn-tail";
import { lastNonReceipt } from "@/lib/receipts";
-import { useTurnLive } from "@/state/turn-status"; import { useTurnNow } from "./NowCard";
+import { useTurnLive } from "@/state/turn-status"; import { useTurnNow } from "./NowCard"; import { useThreadRoutineRun } from "@/state/older-routine-runs";
import { ChatMarkdown } from "./ChatMarkdown";
import { liveToolIds } from "@/lib/tool-liveness";
import { VoiceNoteBubble, type VoiceNoteAttachment } from "./VoiceNoteBubble";
@@ -1001,7 +1001,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {
? { link: currentLink, assign: (link: string | null) => dispatch({ type: "updateTask", botId: bot.id, threadId: bot.threadId, patch: { link } }) }
: null, [canWrite, currentLink, bot.id, bot.threadId, dispatch]);
- const routineExecution = state.routineRuns.find((run) => run.target === "bot" && run.botId === bot.id && run.threadId === bot.threadId);
+ const routineExecution = useThreadRoutineRun(bot.id, bot.threadId);
const resultsThreadId = routineExecution?.resultsThreadId ?? routineExecution?.sourceThreadId;
const canOpenResults = resultsThreadId && [...state.bots, ...state.groups].some((owner) => owner.threadId === resultsThreadId || owner.tasks?.some((task) => task.threadId === resultsThreadId));
diff --git a/src/components/automations/AutomationsCalendar.tsx b/src/components/automations/AutomationsCalendar.tsx
index aa6ce78828..b0ab069042 100644
--- a/src/components/automations/AutomationsCalendar.tsx
+++ b/src/components/automations/AutomationsCalendar.tsx
@@ -10,6 +10,7 @@ import { resetMarkers, useEngineLimits, type ResetMarker } from "@/lib/limit-res
import { automationsFrom, automationStatus } from "@/lib/automations";
import type { RoutineRun } from "@/lib/routines";
import { api, useStore } from "@/state/store";
+import { useRoutineRunsFrom } from "@/state/older-routine-runs";
import { CalendarGrid, EventDetails, EventEditor, QuickComposer, type CalendarEventItem, type EventKind, type EventSeed } from "../RoutineCalendarPage";
import type { ResetDrop } from "../routines/LimitResetMarkers";
@@ -33,6 +34,7 @@ export function AutomationsCalendar({ botFilter, selectedAutomationId, onOpenAut
const visibleBots = state.bots.filter((bot) => !bot.hidden);
const rangeStart = days === 7 ? startOfWeek(anchor) : startOfDay(anchor);
const rangeEnd = addDays(rangeStart, days);
+ useRoutineRunsFrom(rangeStart);
const markers = resetMarkers(useEngineLimits(), rangeStart, rangeEnd);
const loadCalls = useCallback(async () => {
diff --git a/src/onboarding-preview.tsx b/src/onboarding-preview.tsx
index d2f4584df0..8492cf305a 100644
--- a/src/onboarding-preview.tsx
+++ b/src/onboarding-preview.tsx
@@ -54,7 +54,7 @@ function fixture(url: string, ai: boolean, bots: number): unknown {
}
if (path === "/api/config") return { onboarding: EMPTY_ONBOARDING, profile: { name: "", email: "", aboutMe: "" } };
if (path === "/api/auth/session") return { kind: "local" };
- if (path === "/api/routines") return { routines: [], runs: [] };
+ if (path.startsWith("/api/routines?since=")) return { routines: [], runs: [] };
if (path === "/api/notifications") return { notifications: [] };
if (path === "/api/webhooks") return { webhooks: [], attempts: [], ingress: null };
if (path === "/api/phones") return { phones: [] };
diff --git a/src/state/card-answer-recovery.test.ts b/src/state/card-answer-recovery.test.ts
index 94631d86e9..4eae7281cf 100644
--- a/src/state/card-answer-recovery.test.ts
+++ b/src/state/card-answer-recovery.test.ts
@@ -63,7 +63,7 @@ beforeAll(async () => {
vi.stubGlobal("fetch", (path: string) => {
if (path.startsWith("/api/bots?")) return json({ bots: [bot], groups: [room] });
if (path.endsWith("/respond")) return respond();
- return json(answers[path] ?? {});
+ return json(answers[path.replace(/\?since=[^&]*$/, "")] ?? {});
});
const container = document.createElement("div");
document.body.append(container);
diff --git a/src/state/data-sheets.test.ts b/src/state/data-sheets.test.ts
index accbcea013..6ffd131234 100644
--- a/src/state/data-sheets.test.ts
+++ b/src/state/data-sheets.test.ts
@@ -61,7 +61,7 @@ beforeAll(async () => {
vi.stubGlobal("EventSource", FixtureEventSource);
vi.stubGlobal("fetch", (path: string, init?: RequestInit) => {
requests.push({ path, method: init?.method ?? "GET", body: init?.body ? JSON.parse(String(init.body)) : undefined });
- return path.startsWith("/api/bots?") ? json({ bots: [bot], groups: [] }) : json(answers[path] ?? {});
+ return path.startsWith("/api/bots?") ? json({ bots: [bot], groups: [] }) : json(answers[path.replace(/\?since=[^&]*$/, "")] ?? {});
});
const container = document.createElement("div");
document.body.append(container);
@@ -125,7 +125,7 @@ describe("data sheets in the store", () => {
it("tell the panel, not the app, when the route refuses", async () => {
vi.stubGlobal("fetch", (path: string) => path === DATA_ROUTES.sheet("other")
? Promise.resolve(new Response(JSON.stringify({ error: "Not Found" }), { status: 404 }))
- : json(answers[path] ?? {}));
+ : json(answers[path.replace(/\?since=[^&]*$/, "")] ?? {}));
const onError = vi.fn();
dispatch({ type: "loadDataSheet", botId: "other", onError });
await settle();
diff --git a/src/state/follow-bot-model.test.ts b/src/state/follow-bot-model.test.ts
index 180bdff11f..32772d8edf 100644
--- a/src/state/follow-bot-model.test.ts
+++ b/src/state/follow-bot-model.test.ts
@@ -50,7 +50,7 @@ beforeAll(async () => {
return json({ switched: 0, busy: 1, bot: before });
}
if (path === "/api/instances") return json({ instances: [] });
- if (path === "/api/routines") return json({ routines: [], runs: [] });
+ if (path.startsWith("/api/routines?since=")) return json({ routines: [], runs: [] });
if (path === "/api/webhooks") return json({ webhooks: [], attempts: [] });
return json({});
});
diff --git a/src/state/live-frames.test.ts b/src/state/live-frames.test.ts
index cf068cde11..4fb8b3ed83 100644
--- a/src/state/live-frames.test.ts
+++ b/src/state/live-frames.test.ts
@@ -52,7 +52,7 @@ const send = async (frame: ServerFrame) => {
beforeAll(async () => {
vi.stubGlobal("EventSource", FixtureEventSource);
- vi.stubGlobal("fetch", (path: string) => path.startsWith("/api/bots?") ? json({ bots: [bot], groups: [] }) : json(answers[path] ?? {}));
+ vi.stubGlobal("fetch", (path: string) => path.startsWith("/api/bots?") ? json({ bots: [bot], groups: [] }) : json(answers[path.replace(/\?since=[^&]*$/, "")] ?? {}));
const container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
diff --git a/src/state/notification-open.test.ts b/src/state/notification-open.test.ts
index 5b701753c6..059e12b2ae 100644
--- a/src/state/notification-open.test.ts
+++ b/src/state/notification-open.test.ts
@@ -93,7 +93,7 @@ beforeAll(() => {
server = { ...server, tasks, unread: tasks.some((task) => task.unread) };
return announcedThen({ bot: structuredClone(server) });
}
- if (path === "/api/routines") return Promise.resolve(json({ routines: [], runs: [] }));
+ if (path.startsWith("/api/routines?since=")) return Promise.resolve(json({ routines: [], runs: [] }));
if (path === "/api/webhooks") return Promise.resolve(json({ webhooks: [], attempts: [] }));
if (path === "/api/instances") return Promise.resolve(json({ instances: [] }));
return Promise.resolve(json({}));
diff --git a/src/state/older-routine-runs.test.ts b/src/state/older-routine-runs.test.ts
new file mode 100644
index 0000000000..26973ebd72
--- /dev/null
+++ b/src/state/older-routine-runs.test.ts
@@ -0,0 +1,56 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { RoutineRun } from "@/lib/routines";
+import { useRoutineRunsFrom, useThreadRoutineRun } from "./older-routine-runs";
+
+const fixture = vi.hoisted(() => ({
+ api: vi.fn(),
+ dispatch: vi.fn(),
+ state: { routineRunsSince: 1_000 as number | null, routineRuns: [] as unknown[], bots: [] as unknown[] },
+}));
+vi.mock("./store", () => ({ api: fixture.api, useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }) }));
+
+const settle = () => new Promise((resolve) => setTimeout(resolve));
+const mount = (hook: () => void) => {
+ const root = createRoot(document.createElement("div"));
+ flushSync(() => root.render(createElement(() => { hook(); return null; })));
+ return root;
+};
+const run = { id: "old", target: "bot", botId: "b", threadId: "t", scheduledFor: 10 } as RoutineRun;
+
+describe("older routine runs on demand", () => {
+ beforeEach(() => {
+ fixture.api.mockReset().mockResolvedValue({ runs: [run] });
+ fixture.dispatch.mockReset();
+ fixture.state = { routineRunsSince: 1_000, routineRuns: [], bots: [] };
+ });
+
+ it("a view loads the dates before the app's window, once", async () => {
+ mount(() => useRoutineRunsFrom(400));
+ await settle();
+ expect(fixture.api.mock.calls).toEqual([["/api/routines?from=400&to=1000"]]);
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "routineRunsLoaded", runs: [run], from: 400, to: 1_000 });
+ });
+
+ it.each([["inside the window", 1_000, 2_000], ["when every run is loaded", null, 400]])("a view asks for nothing %s", async (_name, since, start) => {
+ fixture.state.routineRunsSince = since;
+ mount(() => useRoutineRunsFrom(start));
+ await settle();
+ expect(fixture.api).not.toHaveBeenCalled();
+ });
+
+ it("a chat of an old run loads that run; any other chat asks for nothing", async () => {
+ fixture.state.bots = [{ id: "b", tasks: [{ threadId: "t", routineRunId: "old" }, { threadId: "plain" }] }];
+ mount(() => useThreadRoutineRun("b", "plain"));
+ await settle();
+ expect(fixture.api).not.toHaveBeenCalled();
+ mount(() => useThreadRoutineRun("b", "t"));
+ await settle();
+ expect(fixture.api.mock.calls).toEqual([["/api/routines?thread=t"]]);
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "routineRunsLoaded", runs: [run] });
+ });
+});
diff --git a/src/state/older-routine-runs.ts b/src/state/older-routine-runs.ts
new file mode 100644
index 0000000000..6f77051664
--- /dev/null
+++ b/src/state/older-routine-runs.ts
@@ -0,0 +1,35 @@
+import { useEffect } from "react";
+
+import type { RoutineRun } from "@/lib/routines";
+import { api, useStore } from "./store";
+
+/** Loads the runs scheduled from `start` up to where the app's window begins, once a view shows dates before it. */
+export function useRoutineRunsFrom(start: number): void {
+ const { state, dispatch } = useStore();
+ const since = state.routineRunsSince;
+ useEffect(() => {
+ if (since === null || start >= since) return;
+ let live = true;
+ api(`/api/routines?from=${start}&to=${since}`)
+ .then(({ runs }) => { if (live && Array.isArray(runs)) dispatch({ type: "routineRunsLoaded", runs, from: start, to: since }); })
+ .catch(() => {});
+ return () => { live = false; };
+ }, [start, since, dispatch]);
+}
+
+/** The run that worked in this conversation; one older than the app's window is loaded when the thread is a run's. */
+export function useThreadRoutineRun(botId: string, threadId: string): RoutineRun | undefined {
+ const { state, dispatch } = useStore();
+ const run = state.routineRuns.find((candidate) => candidate.target === "bot" && candidate.botId === botId && candidate.threadId === threadId);
+ const marked = state.bots.find((bot) => bot.id === botId)?.tasks?.some((task) => task.threadId === threadId && task.routineRunId);
+ const missing = !run && Boolean(marked) && state.routineRunsSince !== null;
+ useEffect(() => {
+ if (!missing) return;
+ let live = true;
+ api(`/api/routines?thread=${encodeURIComponent(threadId)}`)
+ .then(({ runs }) => { if (live && Array.isArray(runs) && runs.length) dispatch({ type: "routineRunsLoaded", runs }); })
+ .catch(() => {});
+ return () => { live = false; };
+ }, [missing, threadId, dispatch]);
+ return run;
+}
diff --git a/src/state/room-navigation.test.ts b/src/state/room-navigation.test.ts
index beb671724b..ddb2970715 100644
--- a/src/state/room-navigation.test.ts
+++ b/src/state/room-navigation.test.ts
@@ -64,7 +64,7 @@ beforeAll(async () => {
if (path.startsWith("/api/groups/")) {
return new Promise<Response>((resolve) => { held.set(path, (body) => resolve(new Response(JSON.stringify(body)))); });
}
- return json(answers[path] ?? {});
+ return json(answers[path.replace(/\?since=[^&]*$/, "")] ?? {});
});
const container = document.createElement("div");
document.body.append(container);
diff --git a/src/state/routine-runs.test.ts b/src/state/routine-runs.test.ts
new file mode 100644
index 0000000000..c7eb15d2f3
--- /dev/null
+++ b/src/state/routine-runs.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import type { RoutineRun } from "@/lib/routines";
+import { olderRunsSince, withOlderRoutineRuns } from "./routine-runs";
+
+const run = (id: string, scheduledFor: number, status: RoutineRun["status"] = "completed") => ({ id, routineId: "r", scheduledFor, status }) as RoutineRun;
+
+describe("older routine runs", () => {
+ it("adds the runs a view loaded and keeps the app's newer copy of one it already holds", () => {
+ const held = [run("a", 30, "running"), run("b", 20)];
+ const merged = withOlderRoutineRuns(held, [run("a", 30, "queued"), run("c", 10)]);
+ expect(merged.map((candidate) => [candidate.id, candidate.status])).toEqual([["a", "running"], ["b", "completed"], ["c", "completed"]]);
+ });
+
+ it("moves the window's start back only when the loaded range reaches it", () => {
+ expect(olderRunsSince(100, { from: 40, to: 100 })).toBe(40);
+ expect(olderRunsSince(100, { from: 40, to: 90 })).toBe(100);
+ expect(olderRunsSince(100, {})).toBe(100);
+ expect(olderRunsSince(null, { from: 40, to: 100 })).toBeNull();
+ });
+});
diff --git a/src/state/routine-runs.ts b/src/state/routine-runs.ts
index d1df7f2c8b..31d92eaee2 100644
--- a/src/state/routine-runs.ts
+++ b/src/state/routine-runs.ts
@@ -18,3 +18,19 @@ export function trimRoutineRuns(runs: readonly RoutineRun[]): RoutineRun[] {
return true;
});
}
+
+/** The app starts with the runs of the last two weeks (the server adds older ones each automation's status needs); a
+ * view that shows older dates loads them. */
+export const ROUTINE_RUNS_WINDOW_MS = 14 * 24 * 60 * 60_000;
+
+/** Runs a view loaded on top of those the app holds; what it holds is newer, so it wins. */
+export function withOlderRoutineRuns(current: readonly RoutineRun[], loaded: readonly RoutineRun[]): RoutineRun[] {
+ const held = new Set(current.map((run) => run.id));
+ return trimRoutineRuns([...current, ...loaded.filter((run) => !held.has(run.id))]);
+}
+
+/** Where the loaded runs now begin: lower only when the loaded range reaches the window the app holds. */
+export function olderRunsSince(since: number | null, loaded: { from?: number; to?: number }): number | null {
+ if (since === null || loaded.from === undefined || loaded.to === undefined || loaded.to < since) return since;
+ return Math.min(since, loaded.from);
+}
diff --git a/src/state/snapshot-navigation.test.ts b/src/state/snapshot-navigation.test.ts
index 188d157c81..55d954ffc4 100644
--- a/src/state/snapshot-navigation.test.ts
+++ b/src/state/snapshot-navigation.test.ts
@@ -87,7 +87,7 @@ beforeEach(async () => {
if (path.startsWith("/api/groups/room/tasks/room-b")) return json({ group: room("b", "fresh-room-b") });
if (path === "/api/bots/bot/messages" || path === "/api/groups/room/messages") sends.push(JSON.parse(String(init?.body)));
if (path === "/api/instances") return json({ instances: [] });
- if (path === "/api/routines") return json({ routines: [], runs: [] });
+ if (path.startsWith("/api/routines?since=")) return json({ routines: [], runs: [] });
if (path === "/api/webhooks") return json({ webhooks: [], attempts: [] });
return json({});
});
diff --git a/src/state/stop-turn-store.test.ts b/src/state/stop-turn-store.test.ts
index 0d9e832961..f98f5ae8b2 100644
--- a/src/state/stop-turn-store.test.ts
+++ b/src/state/stop-turn-store.test.ts
@@ -54,7 +54,7 @@ beforeAll(async () => {
vi.stubGlobal("EventSource", FixtureEventSource);
vi.stubGlobal("fetch", (path: string, init?: RequestInit) => {
requests.push({ path, body: init?.body ? JSON.parse(String(init.body)) : undefined });
- return path.startsWith("/api/bots?") ? json({ bots: [bot], groups: [] }) : json(answers[path] ?? { ok: true });
+ return path.startsWith("/api/bots?") ? json({ bots: [bot], groups: [] }) : json(answers[path.replace(/\?since=[^&]*$/, "")] ?? { ok: true });
});
const container = document.createElement("div");
document.body.append(container);
diff --git a/src/state/store.test.ts b/src/state/store.test.ts
index aff61e4b11..6189cbe53d 100644
--- a/src/state/store.test.ts
+++ b/src/state/store.test.ts
@@ -2881,7 +2881,7 @@ describe("restoring the open conversation", () => {
});
vi.stubGlobal("EventSource", FixtureEventSource);
vi.stubGlobal("fetch", (path: string) =>
- path.startsWith("/api/bots?") ? json({ bots: [first, second], groups: [room] }) : json(answers[path] ?? {}),
+ path.startsWith("/api/bots?") ? json({ bots: [first, second], groups: [room] }) : json(answers[path.replace(/\?since=[^&]*$/, "")] ?? {}),
);
container = document.createElement("div");
@@ -2921,7 +2921,7 @@ describe("restoring the open conversation", () => {
"/api/groups/room-1/queue/q-room/steer": { ok: true, queued: true, threadId: "room-thread", blockedBy: "images" },
"/api/bots/bot-1/queue/q-plain/steer": { ok: true, queued: true, threadId: "bot-1-thread" },
};
- vi.stubGlobal("fetch", (path: string) => Promise.resolve(new Response(JSON.stringify(answers[path] ?? {}))));
+ vi.stubGlobal("fetch", (path: string) => Promise.resolve(new Response(JSON.stringify(answers[path.replace(/\?since=[^&]*$/, "")] ?? {}))));
const settled = vi.fn();
flushSync(() => dispatch({ type: "steerQueued", botId: "bot-1", queueId: "q-plain", onSettled: settled }));
diff --git a/src/state/store.tsx b/src/state/store.tsx
index fc41d73106..bab86b3e97 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -69,7 +69,7 @@ import { liveCallFromFrame, nextLiveCallLookup } from "./live-call";
import { useChatErrorClear } from "./chat-error";
import { openLiveEvents, publishLiveFrame, publishMissedFrames, withoutScreenPixels } from "@/lib/live-events";
import { unlessRefused } from "@/lib/admin-scope";
-import { trimRoutineRuns } from "./routine-runs";
+import { olderRunsSince, ROUTINE_RUNS_WINDOW_MS, trimRoutineRuns, withOlderRoutineRuns } from "./routine-runs";
import { reconcileSnapshotQueues, rememberConsumedQueueId, replaceBotQueues } from "./queue-receipts";
export type { MausColor } from "@/lib/mascot";
@@ -567,7 +567,7 @@ export interface AppState {
filesSuggest: string[] | null; webPanelId?: string;
routines: Routine[];
routineRuns: RoutineRun[];
- routinesLoadState: "loading" | "ready" | "error";
+ routinesLoadState: "loading" | "ready" | "error"; routineRunsSince: number | null;
routinesFocus: { section?: "schedule" | "logs"; view?: "calendar" | "list"; botId?: string; routineId?: string; runStatus?: RoutineRunStatusFilter; nonce: number };
webhooks: WebhookTrigger[];
webhookAttempts: WebhookAttempt[];
@@ -647,8 +647,8 @@ export type Action =
| { type: "showTeamMap" } | { type: "showWebPanel"; id: string }
| { type: "showFiles"; suggest?: string[] }
| { type: "showChat" }
- | { type: "routinesHydrated"; routines: Routine[]; runs: RoutineRun[] }
- | { type: "routinesLoadFailed" }
+ | { type: "routinesHydrated"; routines: Routine[]; runs: RoutineRun[]; since?: number }
+ | { type: "routinesLoadFailed" } | { type: "routineRunsLoaded"; runs: RoutineRun[]; from?: number; to?: number }
| { type: "routinePatched"; routine: Routine }
| { type: "routineDeleted"; routineId: string }
| { type: "routineRunPatched"; run: RoutineRun }
@@ -996,7 +996,7 @@ export function reducer(state: AppState, action: Action): AppState {
settingsOpen: false, computerOpen: false, inspectorOpen: false, activityOpen: false, appSettingsOpen: false, pluginsOpen: false,
};
case "routinesHydrated":
- return { ...state, routines: action.routines, routineRuns: trimRoutineRuns(action.runs), routinesLoadState: "ready" };
+ return { ...state, routines: action.routines, routineRuns: trimRoutineRuns(action.runs), routineRunsSince: action.since ?? null, routinesLoadState: "ready" };
case "routinesLoadFailed":
return { ...state, routinesLoadState: "error" };
case "routinePatched": {
@@ -1017,11 +1017,10 @@ export function reducer(state: AppState, action: Action): AppState {
const runs = exists
? state.routineRuns.map((run) => (run.id === action.run.id ? action.run : run))
: [action.run, ...state.routineRuns];
- return {
- ...state,
- routineRuns: trimRoutineRuns(runs),
- };
+ return { ...state, routineRuns: trimRoutineRuns(runs) };
}
+ case "routineRunsLoaded":
+ return { ...state, routineRuns: withOlderRoutineRuns(state.routineRuns, action.runs), routineRunsSince: olderRunsSince(state.routineRunsSince, action) };
case "webhooksHydrated":
return { ...state, webhooks: action.webhooks, webhookAttempts: action.attempts, webhookIngress: action.ingress };
case "webhookPatched": {
@@ -1864,7 +1863,7 @@ export const initialState: AppState = {
selectedId: "",
activeView: "chat",
routines: [],
- routineRuns: [],
+ routineRuns: [], routineRunsSince: null,
routinesLoadState: "loading",
routinesFocus: { nonce: 0 },
filesSuggest: null,
@@ -2979,8 +2978,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {
{
key: "routines",
request: async () => {
- const { routines, runs } = await api("/api/routines");
- return () => rawDispatch({ type: "routinesHydrated", routines, runs });
+ const since = Date.now() - ROUTINE_RUNS_WINDOW_MS, { routines, runs } = await api(`/api/routines?since=${since}`);
+ return () => rawDispatch({ type: "routinesHydrated", routines, runs, since });
},
},
{