Skip to content

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

Server: settings saves skip the engine re-probe, cached usage ledger, faster thread lookup (#6729)

Milind Soni9f7f7b1f3c8b
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 694a4e88cf..a217b329c3 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -11,7 +11,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_ACP_QUIET_TICK_MS", "OMB_ACP_SESSION_IDLE_", "OMB_ACP_SHARED_RECYCLE_MS", "OMB_ADMIN_", "OMB_ADMIN_MEMBERSHIP",
"OMB_ADMIN_URL", "OMB_ADMIN_WORKSPACE", "OMB_AGENT_BROWSER_PATH", "OMB_AI_CHECKS", "OMB_ANTHROPIC_API_KEY",
"OMB_ANTHROPIC_API_URL", "OMB_APP_VERSION", "OMB_ATTACHMENTS_MAX_BYTES", "OMB_AZURE_OPENAI_LIVE_DEPLOYMENT",
- "OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BOAT_API", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE",
+ "OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BENCH", "OMB_BOAT_API", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE",
"OMB_BROWSER_CONNECTION", "OMB_BROWSER_IDLE_HANDOVER_MS", "OMB_BROWSER_LANG", "OMB_BROWSER_LEGACY_SHELL",
"OMB_BROWSER_MAX_RUNNING", "OMB_BROWSER_SANDBOX", "OMB_BROWSER_SCREEN", "OMB_BROWSER_TIMEZONE", "OMB_BROWSER_TIMING",
"OMB_BUG_REPORT_URL", "OMB_CADDY_PATH", "OMB_CHECKPOINT_GIT_MAX", "OMB_CHROME_PATH", "OMB_CLAUDE_AUTOCOMPACT",
diff --git a/server/config.ts b/server/config.ts
index 3900b9dd79..f3b217fd42 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -1,6 +1,6 @@
// ~/.openmausbot/config.json, with env vars overriding its credentials.
import { readFileSync, mkdirSync, existsSync, renameSync } from "node:fs";
-import { dataHome } from "./data-dir.ts";
+import { dataHome, defaultDataDir } from "./data-dir.ts";
import { signInFromEnv } from "./sign-in-env.ts";
export { signInFromEnv };
import { join } from "node:path";
@@ -693,7 +693,7 @@ export function changedInstanceIds(before: Record<string, unknown>, after: Recor
.filter((id) => !isDeepStrictEqual(before[id], after[id]));
}
-export const DATA_DIR = process.env.OMB_DATA_DIR || join(dataHome(), ".openmausbot");
+export const DATA_DIR = defaultDataDir();
const LEGACY_DATA_DIR = join(dataHome(), ".opengrokbot");
export const EVENTS_DIR = join(DATA_DIR, "events");
export const NATIVE_DIR = join(DATA_DIR, "native");
diff --git a/server/data-dir.test.ts b/server/data-dir.test.ts
new file mode 100644
index 0000000000..9312367cc8
--- /dev/null
+++ b/server/data-dir.test.ts
@@ -0,0 +1,46 @@
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { defaultDataDir, testRunSignal } from "./data-dir.ts";
+
+const REAL = join("/fake-account", "person");
+const ELSEWHERE = join("/fake-temp", "omb-test-home-1");
+const resolved = (env: Record<string, string | undefined>, home: string) => defaultDataDir(env, () => home, () => REAL);
+
+describe("the default data folder", () => {
+ it("is .openmausbot under the home in a normal run, whatever the home is", () => {
+ expect(resolved({}, REAL)).toBe(join(REAL, ".openmausbot"));
+ expect(resolved({ NODE_ENV: "production" }, REAL)).toBe(join(REAL, ".openmausbot"));
+ expect(resolved({ OMB_BENCH: "0" }, REAL)).toBe(join(REAL, ".openmausbot"));
+ });
+
+ it("never asks for the account's home in a normal run", () => {
+ expect(defaultDataDir({}, () => REAL, () => { throw new Error("read the account's home"); })).toBe(join(REAL, ".openmausbot"));
+ });
+
+ it.each([{ VITEST: "true" }, { NODE_ENV: "test" }, { OMB_BENCH: "1" }])("refuses the real home's folder in a test or benchmark run: %o", (env) => {
+ expect(() => resolved(env, REAL)).toThrow(/OMB_DATA_DIR is not set.*before the process starts/);
+ expect(() => resolved(env, join(REAL, "."))).toThrow(/refusing to use the real data folder/);
+ });
+
+ it("names what marked the run", () => {
+ expect(() => resolved({ OMB_BENCH: "1" }, REAL)).toThrow(/^OMB_BENCH=1 marks/);
+ expect(testRunSignal({ NODE_ENV: "test" })).toBe("NODE_ENV=test");
+ expect(testRunSignal({ NODE_ENV: "development", OMB_BENCH: "" })).toBeNull();
+ });
+
+ it("accepts a redirected home in a test run, and one inside the real home", () => {
+ expect(resolved({ VITEST: "true" }, ELSEWHERE)).toBe(join(ELSEWHERE, ".openmausbot"));
+ expect(resolved({ NODE_ENV: "test" }, join(REAL, "AppData", "Local", "Temp", "omb-test-home-1"))).toBe(join(REAL, "AppData", "Local", "Temp", "omb-test-home-1", ".openmausbot"));
+ });
+
+ it("takes OMB_DATA_DIR as given in every kind of run, and treats an empty one as unset", () => {
+ expect(resolved({ OMB_BENCH: "1", OMB_DATA_DIR: join(REAL, "bench-data") }, REAL)).toBe(join(REAL, "bench-data"));
+ expect(resolved({ OMB_DATA_DIR: "" }, ELSEWHERE)).toBe(join(ELSEWHERE, ".openmausbot"));
+ expect(() => resolved({ OMB_BENCH: "1", OMB_DATA_DIR: "" }, REAL)).toThrow(/OMB_DATA_DIR is not set/);
+ });
+
+ it("does not refuse where the account has no home entry", () => {
+ expect(defaultDataDir({ NODE_ENV: "test" }, () => REAL, () => null)).toBe(join(REAL, ".openmausbot"));
+ });
+});
diff --git a/server/data-dir.ts b/server/data-dir.ts
index 0766b3dfac..ead4257ac4 100644
--- a/server/data-dir.ts
+++ b/server/data-dir.ts
@@ -1,6 +1,6 @@
-import { mkdtempSync } from "node:fs";
+import { mkdtempSync, realpathSync } from "node:fs";
import { homedir, tmpdir, userInfo } from "node:os";
-import { join } from "node:path";
+import { join, resolve } from "node:path";
let home: string | undefined;
@@ -12,3 +12,42 @@ export function dataHome(): string {
home = process.env.VITEST !== undefined && real === userInfo().homedir ? mkdtempSync(join(tmpdir(), "omb-test-home-")) : real;
return home;
}
+
+type Env = Record<string, string | undefined>;
+
+/** What marks this process as a test or a benchmark, if anything does. */
+export function testRunSignal(env: Env): string | null {
+ if (env.VITEST !== undefined) return "VITEST";
+ if (env.NODE_ENV === "test") return "NODE_ENV=test";
+ return env.OMB_BENCH === "1" ? "OMB_BENCH=1" : null;
+}
+
+function canonical(path: string): string {
+ let real = resolve(path);
+ try { real = realpathSync(real); } catch {}
+ // macOS and Windows file systems fold case by default.
+ return process.platform === "linux" ? real : real.toLowerCase();
+}
+
+/** The account's own home whatever HOME says; null where the account has no entry (some containers). */
+function accountHome(): string | null {
+ try { return userInfo().homedir; } catch { return null; }
+}
+
+/**
+ * The data folder: OMB_DATA_DIR, else `.openmausbot` under the home.
+ * Security: a test or benchmark run (testRunSignal) with no OMB_DATA_DIR never gets the person's own data folder. It
+ * throws instead, since the folder is fixed when server/config.ts is first imported and a later assignment is ignored.
+ */
+export function defaultDataDir(env: Env = process.env, under: () => string = dataHome, realHome: () => string | null = accountHome): string {
+ if (env.OMB_DATA_DIR) return env.OMB_DATA_DIR;
+ const base = under();
+ const signal = testRunSignal(env);
+ if (signal) {
+ const real = realHome();
+ if (real && canonical(base) === canonical(real)) {
+ throw new Error(`${signal} marks this as a test or benchmark run, and OMB_DATA_DIR is not set: refusing to use the real data folder ${join(base, ".openmausbot")}. Set OMB_DATA_DIR to a temp folder in the environment before the process starts; setting it inside the script is too late.`);
+ }
+ }
+ return join(base, ".openmausbot");
+}
diff --git a/server/doctor/command.ts b/server/doctor/command.ts
index d50fddbf37..ae67e2efd1 100644
--- a/server/doctor/command.ts
+++ b/server/doctor/command.ts
@@ -1,8 +1,8 @@
// `openmausbot doctor --data [--fix] [--data-dir DIR] [--json]`: the doctor on this computer's data folder, without the
// server. It reports; with --fix it applies the safe repairs, only while no server uses the folder.
-import { join, resolve } from "node:path";
+import { resolve } from "node:path";
-import { dataHome } from "../data-dir.ts";
+import { defaultDataDir } from "../data-dir.ts";
import { serverVersion } from "../environment.ts";
import { EXIT, flag } from "../headless/args.ts";
import type { VerbContext, VerbOutcome } from "../headless/context.ts";
@@ -29,6 +29,6 @@ export function dataDoctorOutcome(report: DoctorReport): VerbOutcome {
}
export async function dataDoctor(ctx: VerbContext): Promise<VerbOutcome> {
- const dataDir = resolve(flag(ctx.flags, "data-dir") ?? (ctx.env.OMB_DATA_DIR || join(dataHome(), ".openmausbot")));
+ const dataDir = resolve(flag(ctx.flags, "data-dir") ?? defaultDataDir(ctx.env));
return dataDoctorOutcome(runDoctor({ dataDir, version: serverVersion(), mode: "command", fix: ctx.flags.fix === true }));
}
diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.ts
index 788799f0ac..1611170b5e 100644
--- a/server/perf/perf-host.ts
+++ b/server/perf/perf-host.ts
@@ -107,6 +107,7 @@ export function createPerfHost(deps: PerfHostDeps) {
list: linux ? () => linuxProcessList() : psProcessList, intervalMs: linux ? LINUX_SAMPLE_MS : OTHER_SAMPLE_MS,
scope: deps.wholeMachine && linux ? "all" : "tree", utilization: nodeUtilization(), now, engines: enginePids,
stalled: (ms) => say("loop", `event loop stalled: the ${linux ? 60 : 300}s sampler fired ${duration(ms)} late`), afterSample: watchHolds,
+ resumed: (ms) => say("sleep", `the computer slept or the server was paused: the ${linux ? 60 : 300}s sampler fired ${duration(ms)} late, not counted as a stall`),
seen: (rows, buckets) => { processes.sample(rows, buckets); guarded("bots", () => footprints.sample(rows), null); },
});
if (deps.timer !== false && !windows) sampler.start();
diff --git a/server/perf/process-sampler.test.ts b/server/perf/process-sampler.test.ts
index b4e3b8564e..e6e130ec6a 100644
--- a/server/perf/process-sampler.test.ts
+++ b/server/perf/process-sampler.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { classifyProcesses, parseCgroupCpuMs, parseProcStat, parsePsLine, parsePsTime, parseReapedChildrenMs, type ProcessRow } from "./process-buckets.ts";
-import { createProcessSampler, linuxProcessList, type ProcessList } from "./process-sampler.ts";
+import { createProcessSampler, LATE_TIMER_MS, linuxProcessList, pausedNotStalled, type ProcessList } from "./process-sampler.ts";
const SERVER = 100;
const row = (pid: number, ppid: number, name: string, cpuMs = 0, rssBytes = 1_048_576): ProcessRow => ({ pid, ppid, name, cpuMs, rssBytes, start: `s${pid}` });
@@ -118,6 +118,53 @@ describe("the sampler", () => {
});
});
+describe("a late sampler timer", () => {
+ afterEach(() => { vi.useRealTimers(); });
+
+ const lateBy = async (lateMs: number, waitedMs: number | null) => {
+ vi.useFakeTimers();
+ let mono = 0, waited = 0;
+ const stalled: number[] = [], resumed: number[] = [];
+ const sampler = createProcessSampler({
+ list: () => ({ rows: [row(SERVER, 1, "node")], reapedMs: null, totalMs: null }), intervalMs: 60_000, scope: "tree", serverPid: SERVER,
+ now: () => 1_800_000_000_000 + mono, monotonic: () => mono, idle: () => (waitedMs === null ? null : waited),
+ stalled: (ms) => stalled.push(ms), resumed: (ms) => resumed.push(ms),
+ });
+ sampler.start();
+ await vi.advanceTimersByTimeAsync(0);
+ mono += 60_000 + lateMs; waited += waitedMs ?? 0;
+ await vi.advanceTimersByTimeAsync(60_000);
+ sampler.stop();
+ return { stalled, resumed, loop: sampler.report().loop };
+ };
+
+ it("is a sleep, not a stall, when the loop only waited through the gap, and stays out of the loop's lateness", async () => {
+ const hour = 3_600_000;
+ const slept = await lateBy(hour, 60_000 + hour - 40);
+ expect(slept).toMatchObject({ stalled: [], resumed: [hour], loop: { driftMaxMs: 0, driftP95Ms: 0 } });
+ });
+
+ it("is a stall when the loop worked through the lateness", async () => {
+ const held = await lateBy(5_000, 58_000);
+ expect(held).toMatchObject({ stalled: [5_000], resumed: [], loop: { driftMaxMs: 5_000 } });
+ });
+
+ it("is a stall where the loop's waiting time is not known", async () => {
+ expect(await lateBy(3_600_000, null)).toMatchObject({ stalled: [3_600_000], resumed: [] });
+ });
+
+ it("says nothing for a timer that is on time", async () => {
+ expect(await lateBy(40, 59_900)).toMatchObject({ stalled: [], resumed: [] });
+ });
+
+ it("needs the loop to have worked for at least half the lateness to call it a stall", () => {
+ expect(pausedNotStalled(60_000, 10_000, 65_001)).toBe(true);
+ expect(pausedNotStalled(60_000, 10_000, 65_000)).toBe(false);
+ expect(pausedNotStalled(60_000, LATE_TIMER_MS - 1, 60_000 + LATE_TIMER_MS - 1)).toBe(false);
+ expect(pausedNotStalled(60_000, 10_000, null)).toBe(false);
+ });
+});
+
describe("the sampler's cost", () => {
it("parses, classifies and diffs 500 processes in well under a few milliseconds", async () => {
const stats = Array.from({ length: 500 }, (_, index) => statLine(1000 + index, index % 7 ? "node" : "chrome", index ? 1000 + Math.floor(index / 3) : SERVER, index, index));
diff --git a/server/perf/process-sampler.ts b/server/perf/process-sampler.ts
index d5b1d909fd..3749e2011d 100644
--- a/server/perf/process-sampler.ts
+++ b/server/perf/process-sampler.ts
@@ -2,6 +2,8 @@
// a minute on Linux from /proc (a few hundred small file reads), one every five minutes elsewhere from a single `ps`; no
// other process, no network. The event loop is read from the sampler's own timer (how late it fired) and Node's
// utilization counter, never a fast timer of its own. Memory: the last sample's rows and an hour of per-bucket totals.
+// A timer that fires late while the loop only waited was not held up by the server: the computer slept or the process
+// was paused, and that is told apart from a stall.
import { execFile } from "node:child_process";
import { readdirSync, readFileSync } from "node:fs";
import { performance } from "node:perf_hooks";
@@ -15,6 +17,15 @@ export const LINUX_SAMPLE_MS = 60_000;
export const OTHER_SAMPLE_MS = 5 * 60_000;
const HOUR = 3_600_000, FIVE_MINUTES = 5 * 60_000;
const BUCKETS_SHOWN = 12;
+export const LATE_TIMER_MS = 2_000;
+
+/** A timer `lateMs` overdue was held up by the loop only if the loop worked through that lateness. `waitedMs` is how
+ * long the loop sat waiting since the timer was set `intervalMs` ago; null where that is not known. */
+export function pausedNotStalled(intervalMs: number, lateMs: number, waitedMs: number | null): boolean {
+ if (waitedMs === null || lateMs < LATE_TIMER_MS) return false;
+ const workedMs = Math.max(0, intervalMs + lateMs - waitedMs);
+ return workedMs < lateMs / 2;
+}
export interface ProcessList {
rows: ProcessRow[];
@@ -81,8 +92,12 @@ export interface ProcessSamplerOptions {
monotonic?: () => number;
/** Node's event-loop utilization since the previous call, 0–1; null where not available. */
utilization?: () => number | null;
- /** The sampler's timer fired this much later than it was due. */
+ /** The event loop's time spent waiting so far, ms; null where not available. Node's own counter unless `monotonic` is given. */
+ idle?: () => number | null;
+ /** The sampler's timer fired this much later than it was due, with the loop at work. */
stalled?: (driftMs: number) => void;
+ /** The timer fired this much late with the loop waiting throughout: the computer slept or the process was paused. */
+ resumed?: (gapMs: number) => void;
/** The engine processes the server started, by pid, with their engine kinds. */
engines?: () => ReadonlyMap<number, string>;
/** After each timed sample: other once-a-sample checks ride the same timer. */
@@ -104,10 +119,11 @@ export function nodeUtilization(): () => number | null {
export function createProcessSampler(options: ProcessSamplerOptions) {
const now = options.now ?? Date.now, monotonic = options.monotonic ?? (() => performance.now());
const serverPid = options.serverPid ?? process.pid;
+ const idle = options.idle ?? (options.monotonic ? () => null : () => performance.eventLoopUtilization().idle);
const samples: Sample[] = [];
let previous: { at: number; rows: Map<number, { start: string; cpuMs: number; bucket: ProcessBucket; ppid: number }>; reapedMs: number | null; totalMs: number | null } | null = null;
let latest: { at: number; procs: Partial<Record<ProcessBucket, number>>; rss: Partial<Record<ProcessBucket, number>>; browsers: number } | null = null;
- let timer: ReturnType<typeof setTimeout> | null = null, due = 0, running = false;
+ let timer: ReturnType<typeof setTimeout> | null = null, due = 0, idleAtSchedule: number | null = null, running = false;
const take = (list: ProcessList, driftMs: number) => {
const at = monotonic();
@@ -143,14 +159,18 @@ export function createProcessSampler(options: ProcessSamplerOptions) {
};
const tick = async () => {
- const driftMs = Math.max(0, monotonic() - due);
- if (driftMs >= 2_000) options.stalled?.(Math.round(driftMs));
- await sampleNow(driftMs);
+ const lateMs = Math.max(0, monotonic() - due);
+ const idleNow = idle();
+ const paused = pausedNotStalled(options.intervalMs, lateMs, idleNow === null || idleAtSchedule === null ? null : idleNow - idleAtSchedule);
+ if (paused) options.resumed?.(Math.round(lateMs));
+ else if (lateMs >= LATE_TIMER_MS) options.stalled?.(Math.round(lateMs));
+ await sampleNow(paused ? 0 : lateMs);
try { options.afterSample?.(); } catch {}
schedule();
};
const schedule = () => {
due = monotonic() + options.intervalMs;
+ idleAtSchedule = idle();
timer = setTimeout(() => void tick(), options.intervalMs);
timer.unref?.();
};
diff --git a/server/routes/config-engine-effect.test.ts b/server/routes/config-engine-effect.test.ts
new file mode 100644
index 0000000000..d5d3c4eac1
--- /dev/null
+++ b/server/routes/config-engine-effect.test.ts
@@ -0,0 +1,138 @@
+import { rmSync } from "node:fs";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { CONFIG_PATCH_FIELDS, DATA_DIR } from "../config.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { patchMayChangeEngineStatus } from "./config-engine-effect.ts";
+import { createConfigRoutes, type ConfigRouteDeps } from "./config.ts";
+
+describe("which config patches can change an engine's status", () => {
+ it("is none of what the app shows, or the names and text that go into prompts", () => {
+ for (const patch of [
+ { onboarding: { hintsSeen: ["welcome"], reelSeen: true, completedAt: "2026-11-20", version: 3, firstTurnAt: "2026-11-20" } },
+ { profile: { name: "Ada", email: "[email protected]", aboutMe: "I write compilers", avatarUrl: "" } },
+ { features: { showToolCalls: true } },
+ { language: "de" },
+ { computerName: "Desk" },
+ { everyBotRules: "Be brief." },
+ { language: "de", onboarding: { reelSeen: true }, features: { showToolCalls: false, browser: undefined }, tts: undefined },
+ {},
+ ]) expect(patchMayChangeEngineStatus(patch), JSON.stringify(patch)).toBe(false);
+ });
+
+ it("is every other field a patch can carry, whatever it holds", () => {
+ const quiet = new Set(["language", "computerName", "everyBotRules", "onboarding", "profile", "features"]);
+ const others = Object.keys(CONFIG_PATCH_FIELDS).filter((field) => !quiet.has(field));
+ expect(others).toEqual(expect.arrayContaining(["anthropic", "openai", "openaiCompat", "xai", "opencodeGo", "composio", "box", "vps", "tts", "decider", "imageGen", "live", "signIn",
+ "defaultModelSelection", "automaticRecovery", "localVm", "browserEngine", "browserProfiles", "threads", "context", "mcp"]));
+ for (const field of others) {
+ expect(patchMayChangeEngineStatus({ [field]: {} }), field).toBe(true);
+ expect(patchMayChangeEngineStatus({ onboarding: { reelSeen: true }, [field]: "" }), `${field} beside a quiet field`).toBe(true);
+ }
+ });
+
+ it("is a field or a flag nobody has listed yet", () => {
+ expect(patchMayChangeEngineStatus({ somethingNew: true })).toBe(true);
+ expect(patchMayChangeEngineStatus({ instances: {} })).toBe(true);
+ expect(patchMayChangeEngineStatus({ features: { showToolCalls: true, somethingNew: true } })).toBe(true);
+ expect(patchMayChangeEngineStatus({ onboarding: { somethingNew: 1 } })).toBe(true);
+ expect(patchMayChangeEngineStatus({ profile: { name: "Ada", shell: "/bin/zsh" } })).toBe(true);
+ expect(patchMayChangeEngineStatus({ toString: 1 })).toBe(true);
+ });
+
+ it("is every engine-facing feature flag", () => {
+ for (const flag of ["browser", "claudeUserMcp", "claudeUserSkills", "acpPlanLines", "agentsToolBridge", "skillsLibrary", "sharedComputers"]) {
+ expect(patchMayChangeEngineStatus({ features: { [flag]: true } }), flag).toBe(true);
+ }
+ });
+
+ it("is a quiet field holding something other than its own shape", () => {
+ expect(patchMayChangeEngineStatus({ onboarding: null })).toBe(true);
+ expect(patchMayChangeEngineStatus({ features: ["showToolCalls"] })).toBe(true);
+ expect(patchMayChangeEngineStatus({ profile: "Ada" })).toBe(true);
+ });
+});
+
+describe("saving config and the engines' status", () => {
+ beforeEach(() => { rmSync(DATA_DIR, { recursive: true, force: true }); });
+
+ const auth = { kind: "owner", via: "loopback", scopes: ["admin", "client"] } as unknown as RequestAuth;
+
+ function routes() {
+ let forgotten = 0, broadcasts = 0;
+ const busy = () => ({ get: () => false, set: () => {} });
+ const deps = {
+ store: { bots: [], patchBot: () => null, clearVoiceSelections: () => {} },
+ cfg: {},
+ registry: { get: () => undefined, forgetSnapshots: () => { forgotten += 1; } },
+ sessions: { revalidateEmailSessions: () => {} },
+ browserCleanup: { hasPendingProfile: () => false, prepare: () => { throw new Error("no profile is removed here"); }, abort: () => {}, commit: () => { throw new Error("no profile is removed here"); }, ensure: async () => true },
+ browserLive: { closeAll: () => {}, closeForSession: () => {} },
+ browserRuntime: { heldBy: () => undefined },
+ usedBrowserSessions: new Map(),
+ closeBrowser: async () => true,
+ browserEngineSwitched: () => {},
+ decider: { testKey: async () => ({ ok: true }) },
+ sharedComputers: { close: () => {} },
+ sharedComputerControl: { close: () => {} },
+ hostedModels: false,
+ cloudHome: false,
+ sharedMembership: () => false,
+ lendingEnabled: () => true,
+ providerConfigs: () => ({}),
+ localVmIdleMs: () => 0,
+ localVmIdles: new Map(),
+ localVmActiveThreads: new Set(),
+ localVmLifecycleBusy: new Set(),
+ localVmImageBusy: busy(),
+ localVmModeChangeBusy: busy(),
+ localVmModeChanging: () => () => {},
+ providerConfigBusy: busy(),
+ computerProviderConfigTransitions: new Set(),
+ managedBoatOwners: () => [],
+ providerOperationConflict: () => null,
+ perBotLocalVmCountForModeChange: async () => 0,
+ checkedModelSelection: () => ({ ok: false, status: 400, error: "no engines here" }),
+ policyModelRefusal: () => undefined,
+ browserSessionSpec: () => ({ command: "", env: {} }),
+ configStatus: () => ({}),
+ configForAccess: (status: unknown) => status,
+ resyncOpenCodeProviderKeys: () => {},
+ revokeEngineCapabilities: () => {},
+ reloadProviders: async () => {},
+ broadcast: () => { broadcasts += 1; },
+ drainQueuedSends: () => {},
+ } as unknown as ConfigRouteDeps;
+ const route = createConfigRoutes(deps);
+ const save = async (body: Record<string, unknown>) => {
+ const replies: number[] = [];
+ await route({
+ req: {}, res: {}, url: new URL("http://host/api/config"), path: "/api/config", method: "PUT", auth,
+ json: (_res: unknown, status: number) => { replies.push(status); },
+ readBody: async () => body,
+ } as unknown as Parameters<typeof route>[0]);
+ return replies;
+ };
+ return { save, forgotten: () => forgotten, broadcasts: () => broadcasts, cfg: deps.cfg };
+ }
+
+ it("keeps every engine's status through a save of what the app shows", async () => {
+ const { save, forgotten, broadcasts, cfg } = routes();
+ expect(await save({ onboarding: { hintsSeen: ["welcome"] } })).toEqual([200]);
+ expect(await save({ features: { showToolCalls: true } })).toEqual([200]);
+ expect(await save({ profile: { name: "Ada" }, language: "de" })).toEqual([200]);
+ expect(cfg).toMatchObject({ onboarding: { hintsSeen: ["welcome"] }, features: { showToolCalls: true }, profile: { name: "Ada" }, language: "de" });
+ expect(broadcasts()).toBe(3);
+ expect(forgotten()).toBe(0);
+ });
+
+ it("reads every engine again after a save that can reach one, alone or beside what the app shows", async () => {
+ const { save, forgotten } = routes();
+ expect(await save({ groq: { url: "http://127.0.0.1:9/v1" } })).toEqual([200]);
+ expect(forgotten()).toBe(1);
+ expect(await save({ onboarding: { reelSeen: true }, features: { showToolCalls: false, claudeUserMcp: true } })).toEqual([200]);
+ expect(forgotten()).toBe(2);
+ expect(await save({ context: { autoCompact: false } })).toEqual([200]);
+ expect(forgotten()).toBe(3);
+ });
+});
diff --git a/server/routes/config-engine-effect.ts b/server/routes/config-engine-effect.ts
new file mode 100644
index 0000000000..8c72bfe06e
--- /dev/null
+++ b/server/routes/config-engine-effect.ts
@@ -0,0 +1,30 @@
+// Which saved config fields can change what an engine's status read reports. Saving any other field makes every
+// engine probe its CLI again on the next read, so the fields listed here are the ones known not to: what the app
+// shows, and text and names that go into prompts and labels. A field missing from the list, such as one added later,
+// counts as one that can.
+
+const WHOLE = "whole";
+
+const NO_ENGINE_EFFECT: Readonly<Record<string, typeof WHOLE | ReadonlySet<string>>> = {
+ language: WHOLE,
+ computerName: WHOLE,
+ everyBotRules: WHOLE,
+ onboarding: new Set(["completedAt", "version", "reelSeen", "hintsSeen", "firstTurnAt"]),
+ profile: new Set(["name", "email", "aboutMe", "avatarUrl"]),
+ features: new Set(["showToolCalls"]),
+};
+
+/** False only when every field the patch sets is known to leave every engine's status as it was. */
+export function patchMayChangeEngineStatus(patch: Readonly<Record<string, unknown>>): boolean {
+ for (const [field, value] of Object.entries(patch)) {
+ if (value === undefined) continue;
+ const known = Object.hasOwn(NO_ENGINE_EFFECT, field) ? NO_ENGINE_EFFECT[field] : undefined;
+ if (known === undefined) return true;
+ if (known === WHOLE) continue;
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return true;
+ for (const [inner, innerValue] of Object.entries(value)) {
+ if (innerValue !== undefined && !known.has(inner)) return true;
+ }
+ }
+ return false;
+}
diff --git a/server/routes/config.ts b/server/routes/config.ts
index 625a26f77f..20ecf0bb32 100644
--- a/server/routes/config.ts
+++ b/server/routes/config.ts
@@ -46,6 +46,7 @@ import * as vps from "../vps-computer.ts";
import { refusalBody, userError, userErrorFields } from "../user-errors.ts";
import type { ServerErrorBody } from "../../shared/server-text.ts";
import type { Postiz } from "../postiz/service.ts";
+import { patchMayChangeEngineStatus } from "./config-engine-effect.ts";
import { PASS, type RouteHandler } from "./table.ts";
export interface BusyFlag {
@@ -607,7 +608,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {
localVmModeChanged?.();
postiz?.configSaved(patch);
// A saved key reaches an engine through the environment its status read uses, often with no reload.
- registry.forgetSnapshots();
+ if (patchMayChangeEngineStatus(patch)) registry.forgetSnapshots();
if (patch.localVm?.idleTimeoutMinutes !== undefined) {
for (const idle of localVmIdles.values()) idle.setIdleMs(localVmIdleMs());
}
diff --git a/server/store.ts b/server/store.ts
index e3120d9215..a60d73a635 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -44,6 +44,7 @@ import { lastMessageId, messagesBefore } from "./thread-history.ts";
import { titleFromMessage, UNTITLED_TASK } from "./thread-title.ts";
import { buildTask, threadTitleFrom, UNTITLED_THREAD } from "./task-record.ts";
import { createBotFork, createGroupFork } from "./store-forks.ts";
+import { createThreadBotIndex } from "./thread-bot-index.ts";
import { activeGroupTask, groupTaskByThread, groupTasks, migrateGroupTaskRead, mirrorActiveGroupTask, refreshGroupUnread, setGroupTaskRead, syncGroupReadPatch } from "./group-task-state.ts";
export { titleFromMessage, UNTITLED_TASK } from "./thread-title.ts";
export { threadTitleFrom, UNTITLED_THREAD } from "./task-record.ts";
@@ -1260,9 +1261,8 @@ export class Store {
return this.bots.find((b) => b.id === id) ?? this.standIns.get(id) ?? null; } /** One of this place's own bots. Every method that changes a bot looks here and never among the stand-ins: a record with `home` is read-only on this place. */ private own(id: string) { return this.bots.find((b) => b.id === id) ?? null;
}
- botByThread(threadId: string) {
- return this.bots.find((b) => b.threadId === threadId || b.tasks?.some((t) => t.threadId === threadId)) ?? null;
- }
+ private readonly threadBots = createThreadBotIndex<BotRecord>();
+ botByThread(threadId: string): BotRecord | null { return this.threadBots.find(this.bots, threadId); }
private newBotSelection(requested?: ModelSelection): ModelSelection {
return this.completeNewBotSelection(requested ?? this.defaultSelection());
diff --git a/server/thread-bot-index.test.ts b/server/thread-bot-index.test.ts
new file mode 100644
index 0000000000..7bea53f952
--- /dev/null
+++ b/server/thread-bot-index.test.ts
@@ -0,0 +1,137 @@
+import { rmSync } from "node:fs";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { DATA_DIR } from "./config.ts";
+import type { ModelSelection } from "./contracts.ts";
+import { Store } from "./store.ts";
+import { createThreadBotIndex, scanBotByThread } from "./thread-bot-index.ts";
+
+interface Owner { id: string; threadId: string; tasks?: Array<{ threadId: string }> }
+
+/** A fixed sequence, so a failure repeats. */
+function sequence(seed: number) {
+ let state = seed;
+ return (below: number) => {
+ state = (state * 1_664_525 + 1_013_904_223) >>> 0;
+ return state % below;
+ };
+}
+
+describe("the thread-to-bot index", () => {
+ it("answers as the scan does after every one of 4,000 mixed changes made behind its back", () => {
+ const next = sequence(7);
+ const index = createThreadBotIndex<Owner>();
+ let bots: Owner[] = [];
+ let made = 0;
+ const everSeen: string[] = ["never-a-thread"];
+ const thread = () => { const id = `t${made++}`; everSeen.push(id); return id; };
+ const bot = (): Owner => { const main = thread(); return { id: `b${made++}`, threadId: main, tasks: [{ threadId: main }, { threadId: thread() }] }; };
+ const any = () => bots[next(bots.length)]!;
+ const changes: Array<() => void> = [
+ () => { bots.unshift(bot()); },
+ () => { bots.push(bot()); },
+ () => { if (bots.length > 1) bots.splice(next(bots.length), 1); },
+ () => { if (bots.length > 1) { const gone = any(); bots = bots.filter((each) => each !== gone); } },
+ () => { bots = bots.map((each) => ({ ...each })); },
+ () => { if (bots.length) { const at = next(bots.length); bots[at] = { ...bots[at]!, tasks: [...(bots[at]!.tasks ?? [])] }; } },
+ () => { if (bots.length) { const at = next(bots.length); bots[at] = bot(); } },
+ () => { if (bots.length) { const owner = any(); owner.tasks = [{ threadId: thread() }, ...(owner.tasks ?? [])]; } },
+ () => { if (bots.length) any().tasks?.push({ threadId: thread() }); },
+ () => { if (bots.length) { const owner = any(); owner.tasks = owner.tasks?.filter((task, at) => at % 2 === 0 || task.threadId === owner.threadId); } },
+ () => { if (bots.length) { const owner = any(); if (owner.tasks?.length) owner.threadId = owner.tasks[next(owner.tasks.length)]!.threadId; } },
+ () => { if (bots.length) { const owner = any(); const task = owner.tasks?.[0]; if (task) task.threadId = thread(); } },
+ () => { if (bots.length) { const owner = any(); owner.threadId = thread(); delete owner.tasks; } },
+ () => {
+ if (bots.length < 2) return;
+ const from = any(), to = any();
+ const moved = from.tasks?.pop();
+ if (!moved) return;
+ if (from === to) { from.tasks!.push(moved); return; }
+ to.tasks = [moved, ...(to.tasks ?? [])];
+ if (from.threadId === moved.threadId) from.threadId = from.tasks?.[0]?.threadId ?? thread();
+ },
+ () => { if (bots.length > 1) { const a = next(bots.length), b = next(bots.length); [bots[a], bots[b]] = [bots[b]!, bots[a]!]; } },
+ () => { bots.reverse(); },
+ () => { if (bots.length) Object.assign(any(), bot(), { id: "reused" }); },
+ ];
+ const used = new Set<number>();
+ let hits = 0;
+ for (let step = 0; step < 4_000; step++) {
+ const which = next(changes.length);
+ used.add(which);
+ changes[which]!();
+ for (let asked = 0; asked < 12; asked++) {
+ const live = bots.flatMap((each) => [each.threadId, ...(each.tasks ?? []).map((task) => task.threadId)]);
+ const id = asked % 2 && live.length ? live[next(live.length)]! : everSeen[next(everSeen.length)]!;
+ const scanned = scanBotByThread(bots, id);
+ expect(index.find(bots, id), `step ${step}, change ${which}, thread ${id}`).toBe(scanned);
+ expect(index.find(bots, id), `step ${step}, change ${which}, thread ${id}, asked again`).toBe(scanned);
+ if (scanned) hits += 1;
+ }
+ }
+ expect(used.size).toBe(changes.length);
+ expect(hits).toBeGreaterThan(20_000);
+ });
+
+ it("finds a remembered thread without looking at any other bot's threads", () => {
+ let looked = 0;
+ const watched = (id: string, threads: string[]): Owner => ({
+ id, threadId: threads[0]!,
+ get tasks() { looked += 1; return threads.map((threadId) => ({ threadId })); },
+ });
+ const bots = Array.from({ length: 50 }, (_, at) => watched(`b${at}`, [`t${at}-0`, `t${at}-1`, `t${at}-2`]));
+ const index = createThreadBotIndex<Owner>();
+ expect(index.find(bots, "t49-2")).toBe(bots[49]);
+ expect(looked).toBe(50);
+ looked = 0;
+ expect(index.find(bots, "t49-2")).toBe(bots[49]);
+ expect(looked).toBe(1);
+ });
+});
+
+describe("Store.botByThread", () => {
+ const selection = (): ModelSelection => ({ instanceId: "claude", model: "claude-sonnet-5" });
+ beforeEach(() => { rmSync(DATA_DIR, { recursive: true, force: true }); });
+
+ it("matches a scan of the bots after creating, forking, switching, deleting, reordering and loading from disk", () => {
+ let store = new Store(selection);
+ const seen = new Set<string>(["no-such-thread"]);
+ const agrees = (when: string) => {
+ for (const bot of store.bots) for (const id of [bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)]) seen.add(id);
+ for (const group of store.groups) seen.add(group.threadId);
+ for (const id of seen) expect(store.botByThread(id), `${when}: ${id}`).toBe(scanBotByThread(store.bots, id));
+ };
+ const a = store.createBot({ name: "Ada" }), b = store.createBot({ name: "Bo" }), c = store.createBot({ name: "Cy" });
+ agrees("three bots");
+ const first = store.createTask(a.id, "one")!, second = store.createTask(a.id, "two", false)!;
+ const other = store.createTask(b.id, "three")!;
+ agrees("new threads");
+ expect(store.botByThread(second.threadId)?.id).toBe(a.id);
+ store.switchTask(a.id, second.threadId);
+ agrees("switched thread");
+ const said = store.appendMessage(first.threadId, { role: "user", kind: "text", text: "hello" });
+ const fork = store.forkTask(a.id, first.threadId, said.id);
+ agrees("forked thread");
+ expect(store.botByThread(fork!.threadId)?.id).toBe(a.id);
+ store.deleteTask(a.id, first.threadId);
+ agrees("deleted thread");
+ expect(store.botByThread(first.threadId)).toBeNull();
+ store.reorderBots([c.id, a.id, b.id]);
+ agrees("reordered bots");
+ store.patchBot(b.id, { name: "Bo the second" });
+ agrees("patched bot");
+ store.createGroup("Room", [a.id, b.id]);
+ agrees("a room");
+ store.deleteBot(b.id);
+ agrees("deleted bot");
+ expect(store.botByThread(other.threadId)).toBeNull();
+ const d = store.createBot({ name: "Di" });
+ agrees("a bot after a delete");
+ expect(store.botByThread(d.threadId)?.id).toBe(d.id);
+ store = new Store(selection);
+ agrees("loaded from disk");
+ expect(store.botByThread(second.threadId)?.id).toBe(a.id);
+ store.deleteTasks(a.id, [second.threadId]);
+ agrees("deleted after loading");
+ });
+});
diff --git a/server/thread-bot-index.ts b/server/thread-bot-index.ts
new file mode 100644
index 0000000000..080eae55d9
--- /dev/null
+++ b/server/thread-bot-index.ts
@@ -0,0 +1,46 @@
+// Which bot a thread belongs to, remembered between lookups. Bots and their threads change in place all over the
+// store, so nothing here is told of a change: a remembered answer is given only after it is checked against the bot
+// list as it is now, and anything else is found by the scan.
+
+interface ThreadOwner { threadId: string; tasks?: ReadonlyArray<{ threadId: string }> }
+
+const owns = (bot: ThreadOwner, threadId: string): boolean =>
+ bot.threadId === threadId || Boolean(bot.tasks?.some((task) => task.threadId === threadId));
+
+/** The first bot whose current thread or any of whose threads is `threadId`. */
+export function scanBotByThread<Bot extends ThreadOwner>(bots: readonly Bot[], threadId: string): Bot | null {
+ return bots.find((bot) => owns(bot, threadId)) ?? null;
+}
+
+const REMEMBERED_MAX = 50_000;
+
+/**
+ * `find` answers as scanBotByThread does. A remembered bot is returned only while it sits at the same place in the
+ * same list and still owns the thread; a list replaced or resized forgets everything. A thread no bot owns (a room's)
+ * is scanned for every time.
+ * Known open risk: two bots owning one thread id, the earlier one gaining it after the later one was remembered, would
+ * get the later bot until the list changes. Thread ids are random, so that takes one written into two bots by hand.
+ */
+export function createThreadBotIndex<Bot extends ThreadOwner>() {
+ const remembered = new Map<string, { bot: Bot; at: number }>();
+ let list: readonly Bot[] | null = null, length = 0;
+ return {
+ find(bots: readonly Bot[], threadId: string): Bot | null {
+ if (bots !== list || bots.length !== length) {
+ remembered.clear();
+ list = bots;
+ length = bots.length;
+ }
+ const held = remembered.get(threadId);
+ if (held && bots[held.at] === held.bot && owns(held.bot, threadId)) return held.bot;
+ const at = bots.findIndex((bot) => owns(bot, threadId));
+ if (at < 0) {
+ remembered.delete(threadId);
+ return null;
+ }
+ if (remembered.size >= REMEMBERED_MAX) remembered.clear();
+ remembered.set(threadId, { bot: bots[at]!, at });
+ return bots[at]!;
+ },
+ };
+}
diff --git a/server/usage-ledger.test.ts b/server/usage-ledger.test.ts
index 7f0bd9a1ad..ae43af79c1 100644
--- a/server/usage-ledger.test.ts
+++ b/server/usage-ledger.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { appendFileSync, existsSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
@@ -13,8 +13,11 @@ import {
triggerLabel,
usageCsv,
usageFileFor,
+ usageLedgerParses,
+ USAGE_GROUPINGS,
type UsageRow,
} from "./usage-ledger.ts";
+import { summarizeInsights } from "./usage-insights.ts";
function row(overrides: Partial<UsageRow> = {}): Omit<UsageRow, "at"> & { at?: string } {
return {
@@ -96,6 +99,94 @@ describe("usage ledger files", () => {
});
});
+describe("usage ledger reads", () => {
+ let dataDir: string;
+ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), "omb-usage-")); });
+ afterEach(async () => { await removeTempDir(dataDir); });
+
+ const september = { from: new Date("2026-09-01T00:00:00Z"), to: new Date("2026-09-30T23:59:59Z") };
+ const both = { from: new Date("2026-09-01T00:00:00Z"), to: new Date("2026-10-31T23:59:59Z") };
+ const file = () => usageFileFor(dataDir, new Date("2026-09-15T00:00:00Z"));
+ /** The rows a plain parse of the files gives, with no memory of an earlier read. */
+ const parsedAfresh = (range: { from: Date; to: Date }): UsageRow[] => ["2026-09", "2026-10"].flatMap((month) => {
+ const path = join(dataDir, "usage", `${month}.jsonl`);
+ if (!existsSync(path)) return [];
+ return readFileSync(path, "utf8").split("\n").flatMap((line) => {
+ try {
+ const value = JSON.parse(line) as UsageRow;
+ const at = Date.parse(value.at);
+ return typeof value.botId === "string" && at >= range.from.getTime() && at <= range.to.getTime() ? [value] : [];
+ } catch { return []; }
+ });
+ });
+ const seed = async () => {
+ appendUsage(dataDir, row({ at: "2026-09-03T10:00:00.000Z" }));
+ appendUsage(dataDir, row({ at: "2026-09-20T11:00:00.000Z", botId: "b2", botName: "Clerk", costUsd: null }));
+ appendUsage(dataDir, row({ at: "2026-10-01T00:00:00.000Z", botId: "b3", botName: "Later" }));
+ await flushUsageLedger(dataDir);
+ };
+ const parsesDuring = (run: () => void) => { const before = usageLedgerParses(); run(); return usageLedgerParses() - before; };
+
+ it("parses a month file once, and answers every later read and range from it with the same rows", async () => {
+ await seed();
+ let first: UsageRow[] = [];
+ expect(parsesDuring(() => { first = readUsage(dataDir, both); })).toBe(2);
+ expect(first).toEqual(parsedAfresh(both));
+ expect(parsesDuring(() => {
+ expect(readUsage(dataDir, both)).toEqual(first);
+ expect(readUsage(dataDir, september)).toEqual(parsedAfresh(september));
+ const late = { from: new Date("2026-09-10T00:00:00Z"), to: new Date("2026-09-30T23:59:59Z") };
+ expect(readUsage(dataDir, late).map((r) => r.botId)).toEqual(["b2"]);
+ expect(readUsage(dataDir, late)).toEqual(parsedAfresh(late));
+ })).toBe(0);
+ });
+
+ it("reads again after the server's own append", async () => {
+ await seed();
+ readUsage(dataDir, september);
+ appendUsage(dataDir, row({ at: "2026-09-21T00:00:00.000Z", botId: "b4" }));
+ await flushUsageLedger(dataDir);
+ let rows: UsageRow[] = [];
+ expect(parsesDuring(() => { rows = readUsage(dataDir, september); })).toBe(1);
+ expect(rows.map((r) => r.botId)).toEqual(["b1", "b2", "b4"]);
+ expect(rows).toEqual(parsedAfresh(september));
+ });
+
+ it("reads again when anything else changed the file: more bytes, a new time, another file in its place, or none", async () => {
+ await seed();
+ readUsage(dataDir, september);
+ appendFileSync(file(), JSON.stringify({ ...row({ botId: "b5" }), at: "2026-09-22T00:00:00.000Z" }) + "\n");
+ expect(readUsage(dataDir, september).map((r) => r.botId)).toEqual(["b1", "b2", "b5"]);
+
+ utimesSync(file(), new Date("2026-09-25T00:00:00Z"), new Date("2026-09-25T00:00:00Z"));
+ expect(parsesDuring(() => readUsage(dataDir, september))).toBe(1);
+
+ const replacement = `${file()}.next`;
+ writeFileSync(replacement, readFileSync(file(), "utf8").replaceAll('"botId":"b5"', '"botId":"b6"'));
+ utimesSync(replacement, statSync(file()).atime, statSync(file()).mtime);
+ renameSync(replacement, file());
+ expect(readUsage(dataDir, september).map((r) => r.botId)).toEqual(["b1", "b2", "b6"]);
+
+ rmSync(file());
+ expect(readUsage(dataDir, september)).toEqual([]);
+ expect(readUsage(dataDir, both).map((r) => r.botId)).toEqual(["b3"]);
+ });
+
+ it("hands every reader the same row objects, which no summary changes", async () => {
+ await seed();
+ const frozen = <T>(value: T): T => {
+ if (value && typeof value === "object") { Object.freeze(value); Object.values(value).forEach(frozen); }
+ return value;
+ };
+ const rows = frozen(readUsage(dataDir, both));
+ const before = JSON.stringify(rows);
+ for (const groupBy of USAGE_GROUPINGS) summarizeUsage(rows, groupBy, null, groupBy === "model" ? null : "model");
+ usageCsv(rows);
+ summarizeInsights(rows, { from: "2026-09-01", to: "2026-10-31" }, "UTC");
+ expect(JSON.stringify(readUsage(dataDir, both))).toBe(before);
+ });
+});
+
describe("usage ranges", () => {
const now = new Date("2026-09-15T12:00:00Z");
diff --git a/server/usage-ledger.ts b/server/usage-ledger.ts
index e1bfe89a6b..51a87a1122 100644
--- a/server/usage-ledger.ts
+++ b/server/usage-ledger.ts
@@ -1,6 +1,6 @@
// Append-only usage rows under <data>/usage/ (0600): bookkeeping never fails the turn, and rows never carry message text.
import { personOf } from "./usage-attribution.ts";
-import { readFileSync } from "node:fs";
+import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
import { appendFile, mkdir } from "node:fs/promises";
import { join } from "node:path";
import type { TraceParent, TraceStatus, TraceUsageStatus } from "../shared/usage-trace.ts";
@@ -142,7 +142,12 @@ export function appendUsage(dataDir: string, row: Omit<UsageRow, "at"> & { at?:
async function write(dataDir: string, record: UsageRow): Promise<void> {
await mkdir(join(dataDir, DIR), { recursive: true, mode: 0o700 });
- await appendFile(usageFileFor(dataDir, new Date(record.at)), JSON.stringify(record) + "\n", { mode: 0o600 });
+ const file = usageFileFor(dataDir, new Date(record.at));
+ try {
+ await appendFile(file, JSON.stringify(record) + "\n", { mode: 0o600 });
+ } finally {
+ parsedFiles.delete(file);
+ }
}
export async function flushUsageLedger(dataDir: string): Promise<void> {
@@ -172,26 +177,63 @@ export function monthsBetween(from: Date, to: Date): string[] {
return keys;
}
+interface ParsedFile { stamp: string; rows: Array<{ at: number; row: UsageRow }> }
+/** A month file's rows as last parsed, kept while the file's stamp stays the same. A year of months for two data folders. */
+const parsedFiles = new Map<string, ParsedFile>();
+const PARSED_FILES_KEPT = 26;
+let parses = 0;
+/** How many times a month file has been parsed in this process. */
+export const usageLedgerParses = (): number => parses;
+
+function parseMonth(text: string): ParsedFile["rows"] {
+ const rows: ParsedFile["rows"] = [];
+ for (const line of text.split("\n")) {
+ if (!line) continue;
+ try {
+ const value: unknown = JSON.parse(line);
+ if (isUsageRow(value)) rows.push({ at: Date.parse(value.at), row: value });
+ } catch {
+ }
+ }
+ return rows;
+}
+
+/** The file's valid rows in file order, parsed again only when its size, times or identity changed. Callers share the
+ * row objects and must not change them. */
+function monthRows(file: string): ParsedFile["rows"] {
+ let fd: number;
+ try {
+ fd = openSync(file, "r");
+ } catch {
+ parsedFiles.delete(file);
+ return [];
+ }
+ try {
+ const stat = fstatSync(fd);
+ const stamp = `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.ino}`;
+ const held = parsedFiles.get(file);
+ if (held?.stamp === stamp) return held.rows;
+ const rows = parseMonth(readFileSync(fd, "utf8"));
+ parses += 1;
+ parsedFiles.delete(file);
+ parsedFiles.set(file, { stamp, rows });
+ if (parsedFiles.size > PARSED_FILES_KEPT) parsedFiles.delete(parsedFiles.keys().next().value!);
+ return rows;
+ } catch {
+ parsedFiles.delete(file);
+ return [];
+ } finally {
+ closeSync(fd);
+ }
+}
+
export function readUsage(dataDir: string, range: { from: Date; to: Date }): UsageRow[] {
const rows: UsageRow[] = [];
const from = range.from.getTime();
const to = range.to.getTime();
for (const key of monthsBetween(range.from, range.to)) {
- let text: string;
- try {
- text = readFileSync(join(dataDir, DIR, `${key}.jsonl`), "utf8");
- } catch {
- continue;
- }
- for (const line of text.split("\n")) {
- if (!line) continue;
- try {
- const value: unknown = JSON.parse(line);
- if (!isUsageRow(value)) continue;
- const at = Date.parse(value.at);
- if (at >= from && at <= to) rows.push(value);
- } catch {
- }
+ for (const { at, row } of monthRows(join(dataDir, DIR, `${key}.jsonl`))) {
+ if (at >= from && at <= to) rows.push(row);
}
}
return rows;