Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
No config file read per frame, screens only for viewers (#4155)
Milind Soni0f2ae3a4fd2c
diff --git a/server/config.test.ts b/server/config.test.tsindex ae3436bca9..c73bbfbc00 100644--- a/server/config.test.ts+++ b/server/config.test.ts@@ -706,6 +706,29 @@ describe("a config.json saved with a byte order mark", () => {});});+describe("loadConfig between changes", () => {+ it("hands every caller its own copy, and sees a save or an edit made outside the app", () => {+ const path = join(DATA_DIR, "config.json");+ mkdirSync(DATA_DIR, { recursive: true });+ const settle = () => { const past = new Date(Date.now() - 60_000); utimesSync(path, past, past); };+ writeFileSync(path, JSON.stringify({ budgets: { monthlyUsd: 10, warnAtPercent: 50 } }));+ settle();+ try {+ const first = loadConfig();+ first.budgets!.monthlyUsd = 999;+ expect(loadConfig().budgets).toEqual({ monthlyUsd: 10, warnAtPercent: 50 });+ saveConfig({ budgets: { monthlyUsd: 20, warnAtPercent: 50 } });+ settle();+ expect(loadConfig().budgets).toEqual({ monthlyUsd: 20, warnAtPercent: 50 });+ writeFileSync(path, JSON.stringify({ budgets: { monthlyUsd: 30, warnAtPercent: 50 } }));+ settle();+ expect(loadConfig().budgets).toEqual({ monthlyUsd: 30, warnAtPercent: 50 });+ } finally {+ rmSync(path, { force: true });+ }+ });+});+describe("saving the newer sections", () => {it("persists the Anthropic key, the spend limit and the price list, section by section", () => {const path = join(DATA_DIR, "config.json");diff --git a/server/config.ts b/server/config.tsindex 5a3de103d9..fba9df31df 100644--- a/server/config.ts+++ b/server/config.ts@@ -1,5 +1,5 @@// ~/.openmausbot/config.json, with env vars overriding its credentials.-import { readFileSync, mkdirSync, existsSync, renameSync, statSync } from "node:fs";+import { readFileSync, mkdirSync, existsSync, renameSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";import { isDeepStrictEqual } from "node:util";@@ -20,6 +20,7 @@ import { PROVIDER_ICON_PRESETS, providerIconError } from "../shared/provider-icoimport { helperStoredShape, type HelperConfig } from "./side-jobs.ts";import { loopGuardConfigSchema, type LoopGuardConfig } from "./host/loop-guard.ts";import { migrateLegacyFeatureFlags } from "./legacy-feature-flags.ts";+import { settledFileCache, settledFileStamp } from "./settled-file.ts";import { isRemoteMcpServer, mcpServerServes, parseStoredMcpServer } from "./mcp-registry.ts"; import { postizKeyHeaders } from "./postiz/connection.ts";import { parseJson, schemaIssue, type JsonObject, type JsonValue } from "./schema.ts";import { deciderConfigSchema, type DeciderConfig } from "./decider/config.ts";@@ -749,11 +750,12 @@ export function ensureDirs() {}let lastIgnoredConfigWarning = "";+const storedConfig = settledFileCache(() => join(DATA_DIR, "config.json"), () => parseStoredConfig(parseJson(readFileSync(join(DATA_DIR, "config.json"), "utf8"))));export function loadConfig(): AppConfig {let cfg: AppConfig = {};try {- cfg = parseStoredConfig(parseJson(readFileSync(join(DATA_DIR, "config.json"), "utf8")));+ cfg = structuredClone(storedConfig.read());lastIgnoredConfigWarning = "";} catch (error) {if ((error as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {@@ -818,12 +820,7 @@ export function loadConfig(): AppConfig {export function cacheUntilConfigChanges<T>(derive: (config: AppConfig) => T): () => T {let cached: { stamp: string; value: T } | null = null;return () => {- let stamp: string | null = null;- try {- const file = statSync(join(DATA_DIR, "config.json"), { bigint: true });- if (Date.now() - Number(file.mtimeMs) >= 2_000) stamp = `${file.ino}:${file.size}:${file.mtimeNs}:${file.ctimeNs}`;- } catch {- }+ const stamp = settledFileStamp(join(DATA_DIR, "config.json"));if (stamp !== null && cached?.stamp === stamp) return cached.value;const value = derive(loadConfig());cached = stamp === null || lastIgnoredConfigWarning !== "" ? null : { stamp, value };@@ -1046,6 +1043,7 @@ export function saveConfig(}mkdirSync(DATA_DIR, { recursive: true });writeFileAtomic(p, JSON.stringify(disk, null, 2), { mode: 0o600 });+ storedConfig.forget();for (const listener of configSaveListeners) {try {listener(before, disk);diff --git a/server/index.ts b/server/index.tsindex 4835992fe5..129f31d834 100644--- a/server/index.ts+++ b/server/index.ts@@ -680,8 +680,8 @@ const sessions = new SessionRegistry({const membership = signInAllowList();return (email) => allowedScopes(email, membership);},- portalMembership: hostedWorkspaceConfiguration()?.portalMembership === true,-});+ portalMembership: hostedWorkspaceConfiguration()?.portalMembership === true, recheckMs: 1_000,+}); onConfigSaved(() => sessions.membershipChanged());const deviceLinks = new DeviceLinks(); const sharedComputers = new SharedComputers(id => sessions.isLive(id), new LentComputers(join(DATA_DIR, "lent-computers.json")), deviceLinks, lentCopies);// A Cloud home's secrets come over the launcher's pipe, never this process's environment.const CLOUD_SECRETS = BOOT_CLOUD_SECRETS;@@ -4809,7 +4809,7 @@ function cursorSeq(raw: string | string[] | undefined): number | null {/** `adminOnly` frames are withheld from client sessions, live and on replay; a `person`'s frames reach only their streams. */function broadcast(payload: Record<string, unknown>, options: { adminOnly?: boolean; person?: string } = {}) {// Close stale email streams before any further workspace data is delivered.- sessions.revalidateEmailSessions();+ sessions.recheckMembership();const seq = ++lastSeq;const kind = String(payload.kind ?? "");const frame = `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...payload, seq })}\n\n`;diff --git a/server/message-db-memory-index.ts b/server/message-db-memory-index.tsnew file mode 100644index 0000000000..430f04531d--- /dev/null+++ b/server/message-db-memory-index.ts@@ -0,0 +1,27 @@+import type { DatabaseSync } from "node:sqlite";++export function ensureMemoryIndex(db: DatabaseSync): void {+ db.exec(`+ CREATE TABLE IF NOT EXISTS memory_files (+ bot_id TEXT NOT NULL,+ path TEXT NOT NULL,+ text TEXT NOT NULL,+ mtime_ms INTEGER NOT NULL,+ bytes INTEGER NOT NULL,+ PRIMARY KEY (bot_id, path)+ );+ CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(+ text, content='memory_files', content_rowid='rowid', tokenize='unicode61'+ );+ CREATE TRIGGER IF NOT EXISTS memory_fts_ai AFTER INSERT ON memory_files BEGIN+ INSERT INTO memory_fts(rowid, text) VALUES (new.rowid, new.text);+ END;+ CREATE TRIGGER IF NOT EXISTS memory_fts_ad AFTER DELETE ON memory_files BEGIN+ INSERT INTO memory_fts(memory_fts, rowid, text) VALUES ('delete', old.rowid, old.text);+ END;+ CREATE TRIGGER IF NOT EXISTS memory_fts_au AFTER UPDATE ON memory_files BEGIN+ INSERT INTO memory_fts(memory_fts, rowid, text) VALUES ('delete', old.rowid, old.text);+ INSERT INTO memory_fts(rowid, text) VALUES (new.rowid, new.text);+ END;+ `);+}diff --git a/server/message-db.test.ts b/server/message-db.test.tsindex 1bbf0a2f4a..2ffab07456 100644--- a/server/message-db.test.ts+++ b/server/message-db.test.ts@@ -1,7 +1,7 @@import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";import { join } from "node:path";import { DatabaseSync } from "node:sqlite";-import { beforeEach, describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import { DATA_DIR } from "./config.ts";import { closeMessageDb,@@ -111,6 +111,22 @@ describe("message-db", () => {expect(existsSync(`${legacy(bot.threadId)}.imported`)).toBe(true);});+ // Windows will not delete a file SQLite holds open.+ it.skipIf(process.platform === "win32")("opens the database again when its file was deleted under it, looking at most once a second", () => {+ const now = Date.now();+ const clock = vi.spyOn(Date, "now").mockReturnValue(now);+ try {+ insertMessage("t-gone", msg("m1", "before"));+ for (const suffix of ["", "-wal", "-shm"]) rmSync(join(DATA_DIR, `messages.db${suffix}`), { force: true });+ clock.mockReturnValue(now + 1_000);+ insertMessage("t-gone", msg("m2", "after"));+ expect(existsSync(join(DATA_DIR, "messages.db"))).toBe(true);+ expect(readThread("t-gone", legacy("t-gone")).messages.map((m) => m.id)).toEqual(["m2"]);+ } finally {+ clock.mockRestore();+ }+ });+it("stores transcripts with owner-only permissions", () => {insertMessage("private", msg("m1", "secret"));if (process.platform !== "win32") {diff --git a/server/message-db.ts b/server/message-db.tsindex 4055b958c1..cc4f71d3ce 100644--- a/server/message-db.ts+++ b/server/message-db.ts@@ -1,13 +1,14 @@import { randomUUID } from "node:crypto";import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync } from "node:fs";import { join } from "node:path";-import { DatabaseSync } from "node:sqlite";+import { DatabaseSync, type StatementSync } from "node:sqlite";import { DATA_DIR } from "./config.ts";import { peerProvenanceAuthor, type WorkOrigin } from "./peer-provenance.ts";import type { ResolvedSender, SteerQueueReason } from "../shared/wire.ts";import type { Message } from "./store.ts";import type { UsageTrigger } from "./usage-ledger.ts";+import { ensureMemoryIndex } from "./message-db-memory-index.ts";import { MessageSearchWorker } from "./message-search-worker.ts";import { searchMessagesInDatabase, type SearchHit } from "./message-search-query.ts";import type { Notification, NotificationLogEntry } from "../shared/notification.ts";@@ -21,6 +22,10 @@ const FAILED_CALL = "kind = 'activity' AND instr(json, '\"ok\":false') > 0";let handle: DatabaseSync | null = null;let handlePath: string | null = null;+let handleCheckedAt = 0;+let statements = new Map<string, StatementSync>();+/** SQLite keeps writing to a database file deleted under it without an error, so the file is looked for again this often. */+const FILE_RECHECK_MS = 1_000;let searchWorker: MessageSearchWorker | null = null;let closingSearch: Promise<void> = Promise.resolve();@@ -97,32 +102,6 @@ function open(): DatabaseSync {return db;}-function ensureMemoryIndex(db: DatabaseSync): void {- db.exec(`- CREATE TABLE IF NOT EXISTS memory_files (- bot_id TEXT NOT NULL,- path TEXT NOT NULL,- text TEXT NOT NULL,- mtime_ms INTEGER NOT NULL,- bytes INTEGER NOT NULL,- PRIMARY KEY (bot_id, path)- );- CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(- text, content='memory_files', content_rowid='rowid', tokenize='unicode61'- );- CREATE TRIGGER IF NOT EXISTS memory_fts_ai AFTER INSERT ON memory_files BEGIN- INSERT INTO memory_fts(rowid, text) VALUES (new.rowid, new.text);- END;- CREATE TRIGGER IF NOT EXISTS memory_fts_ad AFTER DELETE ON memory_files BEGIN- INSERT INTO memory_fts(memory_fts, rowid, text) VALUES ('delete', old.rowid, old.text);- END;- CREATE TRIGGER IF NOT EXISTS memory_fts_au AFTER UPDATE ON memory_files BEGIN- INSERT INTO memory_fts(memory_fts, rowid, text) VALUES ('delete', old.rowid, old.text);- INSERT INTO memory_fts(rowid, text) VALUES (new.rowid, new.text);- END;- `);-}-export function describeMissingFts5(error: unknown): Error | null {const message = error instanceof Error ? error.message : String(error);if (!/no such module:\s*fts5/i.test(message)) return null;@@ -166,16 +145,32 @@ const UPSERT_MESSAGE ="ON CONFLICT(thread_id, id) DO UPDATE SET at = excluded.at, role = excluded.role, kind = excluded.kind, " +"text = excluded.text, json = excluded.json";+const ACTIVE_LEAF = "SELECT active_leaf_id FROM thread_state WHERE thread_id = ?";function db(): DatabaseSync {- if (handle && handlePath === DB_FILE() && existsSync(DB_FILE())) return handle;+ const file = DB_FILE();+ if (handle && handlePath === file && Date.now() - handleCheckedAt < FILE_RECHECK_MS) return handle;+ if (handle && handlePath === file && existsSync(file)) {+ handleCheckedAt = Date.now();+ return handle;+ }try {handle?.close();} catch {}+ statements = new Map();handle = open();- handlePath = DB_FILE();+ handlePath = file;+ handleCheckedAt = Date.now();return handle;}+/** One prepared statement per SQL text for the life of the open database. */+function prepared(sql: string): StatementSync {+ const database = db();+ let statement = statements.get(sql);+ if (!statement) statements.set(sql, statement = database.prepare(sql));+ return statement;+}+let transactionDepth = 0;function transaction<T>(fn: (database: DatabaseSync) => T): T {const database = db();@@ -386,13 +381,9 @@ export interface ThreadRows {}export function readThread(threadId: string, legacyFile: string): ThreadRows {- const rows = db()- .prepare("SELECT json FROM messages WHERE thread_id = ? ORDER BY rowid")- .all(threadId) as Array<{ json: string }>;+ const rows = prepared("SELECT json FROM messages WHERE thread_id = ? ORDER BY rowid").all(threadId) as Array<{ json: string }>;if (rows.length) {- const state = db()- .prepare("SELECT active_leaf_id FROM thread_state WHERE thread_id = ?")- .get(threadId) as { active_leaf_id: string | null } | undefined;+ const state = prepared(ACTIVE_LEAF).get(threadId) as { active_leaf_id: string | null } | undefined;return { messages: rows.map(rowToMessage), activeLeafId: state?.active_leaf_id ?? null };}return importLegacy(threadId, legacyFile);@@ -408,16 +399,12 @@ export interface ThreadTailRows extends ThreadRows {}export function readThreadTail(threadId: string, legacyFile: string, limit: number): ThreadTailRows {- const rows = db()- .prepare("SELECT json FROM messages WHERE thread_id = ? ORDER BY rowid DESC LIMIT ?")- .all(threadId, limit + 1) as Array<{ json: string }>;+ const rows = prepared("SELECT json FROM messages WHERE thread_id = ? ORDER BY rowid DESC LIMIT ?").all(threadId, limit + 1) as Array<{ json: string }>;if (rows.length) {const hasMore = rows.length > limit;if (hasMore) rows.length = limit;rows.reverse();- const state = db()- .prepare("SELECT active_leaf_id FROM thread_state WHERE thread_id = ?")- .get(threadId) as { active_leaf_id: string | null } | undefined;+ const state = prepared(ACTIVE_LEAF).get(threadId) as { active_leaf_id: string | null } | undefined;return { messages: rows.map(rowToMessage), activeLeafId: state?.active_leaf_id ?? null, hasMore };}return importLegacy(threadId, legacyFile);@@ -459,9 +446,7 @@ function importLegacy(threadId: string, legacyFile: string): ThreadRows {}export function insertMessage(threadId: string, message: Message): void {- db()- .prepare(UPSERT_MESSAGE)- .run(threadId, message.id, message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message));+ prepared(UPSERT_MESSAGE).run(threadId, message.id, message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message));}/** `relinked`: adds `messages` to a conversation that has rows; each row it names changes only its parentId, and an id it already has fails the whole import. */@@ -490,9 +475,7 @@ export function appendMessage(threadId: string, message: Message): void {}export function updateMessage(threadId: string, message: Message): void {- db()- .prepare("UPDATE messages SET at = ?, role = ?, kind = ?, text = ?, json = ? WHERE thread_id = ? AND id = ?")- .run(message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message), threadId, message.id);+ prepared("UPDATE messages SET at = ?, role = ?, kind = ?, text = ?, json = ? WHERE thread_id = ? AND id = ?").run(message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message), threadId, message.id);}export function workingGoalRunMessages(): Array<{ threadId: string; message: Message }> {@@ -600,12 +583,7 @@ export function requestSenders(keys: ReadonlyArray<{ threadId: string; id: strin}export function setActiveLeaf(threadId: string, leafId: string | null): void {- db()- .prepare(- "INSERT INTO thread_state (thread_id, active_leaf_id) VALUES (?, ?) " +- "ON CONFLICT(thread_id) DO UPDATE SET active_leaf_id = excluded.active_leaf_id",- )- .run(threadId, leafId);+ prepared("INSERT INTO thread_state (thread_id, active_leaf_id) VALUES (?, ?) ON CONFLICT(thread_id) DO UPDATE SET active_leaf_id = excluded.active_leaf_id").run(threadId, leafId);}/** Each conversation's newest stored row, by its row number, and how many rows it has: what Send to My Cloud compares with what it sent. */@@ -631,7 +609,7 @@ export function threadRowNumbers(threadId: string): Map<string, number> {/** The time on a conversation's last stored row, without reading the conversation. */export function lastRowAt(threadId: string): number | undefined {- const row = db().prepare("SELECT at FROM messages WHERE thread_id = ? ORDER BY rowid DESC LIMIT 1").get(threadId) as { at: number } | undefined;+ const row = prepared("SELECT at FROM messages WHERE thread_id = ? ORDER BY rowid DESC LIMIT 1").get(threadId) as { at: number } | undefined;return row?.at;}@@ -997,4 +975,5 @@ export function closeMessageDb(): void {} catch {}handle = null;handlePath = null;+ statements = new Map();}diff --git a/server/sessions.test.ts b/server/sessions.test.tsindex 13b40f56e2..c2a1d70c19 100644--- a/server/sessions.test.ts+++ b/server/sessions.test.ts@@ -332,6 +332,32 @@ describe("sessions", () => {expect(registry.isLive(email.session.id)).toBe(false);});+ it("with recheckMs, reads membership at most that often, at once after membershipChanged(): a removal still ends access promptly", () => {+ let allowed = true;+ const resolve = vi.fn((_email: string) => allowed ? ["client" as const] : null);+ registry = new SessionRegistry({ file: file(), now: () => clock, emailScopes: resolve, recheckMs: 2_000 });+ const email = registry.issue({ label: "browser", email: "[email protected]", scopes: ["client"] });+ resolve.mockClear();+ for (let i = 0; i < 1_000; i++) expect(registry.isLive(email.session.id)).toBe(true);+ expect(resolve.mock.calls.length).toBeLessThanOrEqual(1);+ allowed = false;+ registry.membershipChanged();+ expect(registry.isLive(email.session.id)).toBe(false);+ expect(registry.authenticate(email.token)).toBeNull();+ });++ it("with recheckMs, a sign-in list edited outside the app ends access within that time", () => {+ let allowed = true;+ registry = new SessionRegistry({ file: file(), now: () => clock, emailScopes: () => allowed ? ["client"] : null, recheckMs: 2_000 });+ const email = registry.issue({ label: "browser", email: "[email protected]", scopes: ["client"] });+ registry.recheckMembership();+ allowed = false;+ clock += 1_999;+ expect(registry.isLive(email.session.id)).toBe(true);+ clock += 1;+ expect(registry.isLive(email.session.id)).toBe(false);+ });+it("builds one membership resolver per pass and skips snapshots with no eligible account sessions", () => {const resolve = vi.fn((_email: string) => ["client" as const]);const snapshot = vi.fn(() => resolve);diff --git a/server/sessions.ts b/server/sessions.tsindex 7c133d4112..27e37fba7f 100644--- a/server/sessions.ts+++ b/server/sessions.ts@@ -180,6 +180,9 @@ export interface SessionStoreOptions {emailScopes?: EmailScopesResolver;emailScopesSnapshot?: () => EmailScopesResolver;portalMembership?: boolean;+ /** Between membershipChanged() calls, the hot paths (each request, stream frame and liveness check) recheck email+ * membership at most this often. Default 0: every call. */+ recheckMs?: number;}export class SessionRegistry {@@ -196,6 +199,7 @@ export class SessionRegistry {private readonly openMarker: string;private closed = false;private adminOnly: string | null = null;+ private membershipCheckedAt = -Infinity;// No parameter properties: Node's strip-only TypeScript mode only erases types.constructor(options: SessionStoreOptions) {@@ -257,7 +261,7 @@ export class SessionRegistry {}private prune(): void {- this.revalidateEmailSessions();+ this.recheckMembership();const now = this.now();this.pairings = this.pairings.filter((p) => p.expiresAt > now);this.replays = this.replays.filter((r) => r.expiresAt > now);@@ -508,9 +512,21 @@ export class SessionRegistry {this.failures.delete(source);}+ /** The sign-in lists may have changed: the next recheckMembership() reads them. */+ membershipChanged(): void {+ this.membershipCheckedAt = -Infinity;+ }++ /** revalidateEmailSessions(), unless one ran within `recheckMs` and membershipChanged() has not been called since. */+ recheckMembership(): void {+ if (this.now() - this.membershipCheckedAt < (this.options.recheckMs ?? 0)) return;+ this.revalidateEmailSessions();+ }+/** Email membership is live: losing any scope revokes the token and its streams; promotions never widen existing credentials. */revalidateEmailSessions(): void {if (this.closed) throw new Error("Session registry is closed.");+ this.membershipCheckedAt = this.now();// A team session's membership is the Admin's signed claim, checked at each pairing (cloud-team.ts), never the sign-in list.const eligible = this.sessions.filter(session => session.email !== undefined && session.membershipAuthority !== "team" && !(this.options.portalMembership && session.membershipAuthority === "portal"));if (!eligible.length) return;@@ -542,7 +558,7 @@ export class SessionRegistry {authenticate(token: string | undefined): SessionRecord | null {if (!token) return null;- this.revalidateEmailSessions();+ this.recheckMembership();const hash = sha256(token);const now = this.now();const record = this.sessions.find((s) => sameDigest(s.tokenHash, hash));@@ -558,7 +574,7 @@ export class SessionRegistry {/** Call only after origin and scope checks pass; never revives an expired session. */renew(sessionId: string): boolean {- this.revalidateEmailSessions();+ this.recheckMembership();const record = this.sessions.find((s) => s.id === sessionId);const now = this.now();if (!record || record.expiresAt <= now) return false;diff --git a/server/settled-file.test.ts b/server/settled-file.test.tsnew file mode 100644index 0000000000..6a0b333231--- /dev/null+++ b/server/settled-file.test.ts@@ -0,0 +1,54 @@+import { mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { settledFileCache, settledFileStamp } from "./settled-file.ts";++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function settledFile(text: string): string {+ const dir = mkdtempSync(join(tmpdir(), "omb-settled-"));+ dirs.push(dir);+ const path = join(dir, "config.json");+ writeFileSync(path, text);+ const past = new Date(Date.now() - 60_000);+ utimesSync(path, past, past);+ return path;+}++describe("settledFileCache", () => {+ it("parses once while the file is unchanged, again after it changes or forget()", () => {+ const path = settledFile('{"a":1}');+ const parse = vi.fn(() => JSON.parse(readFileSync(path, "utf8")) as { a: number });+ const cache = settledFileCache(() => path, parse);+ for (let i = 0; i < 100; i++) expect(cache.read()).toEqual({ a: 1 });+ expect(parse).toHaveBeenCalledTimes(1);+ cache.forget();+ cache.read();+ expect(parse).toHaveBeenCalledTimes(2);+ writeFileSync(path, '{"a":22}');+ const past = new Date(Date.now() - 30_000);+ utimesSync(path, past, past);+ expect(cache.read()).toEqual({ a: 22 });+ expect(parse).toHaveBeenCalledTimes(3);+ });++ it("never keeps a file written in the last two seconds, a missing file or a parse that threw", () => {+ const path = settledFile('{"a":1}');+ writeFileSync(path, '{"a":2}');+ expect(settledFileStamp(path)).toBeNull();+ const parse = vi.fn(() => 1);+ const fresh = settledFileCache(() => path, parse);+ fresh.read(); fresh.read();+ expect(parse).toHaveBeenCalledTimes(2);+ expect(settledFileStamp(join(path, "..", "missing.json"))).toBeNull();+ const old = settledFile("{}");+ let fail = true;+ const flaky = settledFileCache(() => old, () => { if (fail) throw new Error("bad"); return 3; });+ expect(() => flaky.read()).toThrow("bad");+ fail = false;+ expect(flaky.read()).toBe(3);+ });+});diff --git a/server/settled-file.ts b/server/settled-file.tsnew file mode 100644index 0000000000..64678461f2--- /dev/null+++ b/server/settled-file.ts@@ -0,0 +1,31 @@+import { statSync } from "node:fs";++/** A file's identity (inode, size, change times), or null when it is missing or was written in the last two seconds: a+ * coarse file system may not tick the mtime of a write that soon, so such a file is never trusted to be unchanged. */+export function settledFileStamp(path: string): string | null {+ try {+ const file = statSync(path, { bigint: true });+ return Date.now() - Number(file.mtimeMs) >= 2_000 ? `${file.ino}:${file.size}:${file.mtimeNs}:${file.ctimeNs}` : null;+ } catch {+ return null;+ }+}++/** `parse()` of the file at `path()`, run again only once the file's stamp changes or after forget(). A parse that+ * throws is never kept. */+export function settledFileCache<T>(path: () => string, parse: () => T): { read(): T; forget(): void } {+ let held: { stamp: string; value: T } | null = null;+ return {+ read() {+ const stamp = settledFileStamp(path());+ if (stamp !== null && held?.stamp === stamp) return held.value;+ held = null;+ const value = parse();+ if (stamp !== null) held = { stamp, value };+ return value;+ },+ forget() {+ held = null;+ },+ };+}diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 58a0554afa..8a240e72c3 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -11,7 +11,7 @@ import { ReactAction, ReactionChips } from "@/components/Reactions";import { useBotMessageMenu, userMessageMenu } from "@/components/message-menu";import { useSpeech } from "@/lib/tts/useSpeech";import { localSystemVoiceActive } from "@/lib/local-voice";-import { computerStartLine } from "@/lib/computer-start";+import { computerStartLine, useScreensWhile } from "@/lib/computer-start";import { rememberComputerPanelOpen } from "@/lib/computer-panel-focus";import { useCaptionChrome, useDesktopCapabilities } from "@/components/DesktopCapabilities";import {@@ -831,7 +831,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {const simpleHead = !advanced && !remoteClient;const canWrite = useCanWriteIn(bot.threadId, bot.yourAccess);- const computerStarting = computerStartLine(state.computerStarts[bot.id], bot.name);+ const computerStarting = computerStartLine(state.computerStarts[bot.id], bot.name); useScreensWhile(Boolean(computerStarting));const mascotMotion = state.mascotMotion?.botId === bot.id ? state.mascotMotion : null;const [findOpen, setFindOpen] = useState(false);const { replyTo, selectReply, clearReply, consumeReply, restoreReply } = useReplyDraft(diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsxindex 49c9c34b29..a36cced16b 100644--- a/src/components/ComputerPanel.tsx+++ b/src/components/ComputerPanel.tsx@@ -665,7 +665,7 @@ export function ComputerPanel({useEffect(() => {lastLiveAt.current = 0;if (!cloudPreviewReady) return;- return listenLiveFrames({+ return listenLiveFrames({ screens: true,onFrame: (frame) => {if (frame.kind !== "screen" || frame.botId !== bot.id || frame.threadId !== bot.threadId) return;lastLiveAt.current = Date.now();diff --git a/src/lib/computer-start.ts b/src/lib/computer-start.tsindex 487e2875d6..52ac5cd3e5 100644--- a/src/lib/computer-start.ts+++ b/src/lib/computer-start.ts@@ -1,4 +1,7 @@+import { useEffect } from "react";+import { t } from "@/lib/i18n";+import { listenLiveFrames } from "@/lib/live-events";import type { ServerFrame } from "../../shared/wire";export type ComputerStart = Pick<Extract<ServerFrame, { kind: "computer" }>, "state" | "place">;@@ -8,3 +11,8 @@ export function computerStartLine(start: ComputerStart | undefined, name: stringif (start.place !== "cloud") return t("chat.provisioning");return t(start.state === "waking" ? "chat.computerWaking" : "chat.computerStarting", { name });}++/** The computer's first screen ends its start line: while one is awaited, the stream carries screen frames. */+export function useScreensWhile(waiting: boolean): void {+ useEffect(() => (waiting ? listenLiveFrames({ screens: true, onFrame: () => {} }) : undefined), [waiting]);+}diff --git a/src/lib/live-events.test.ts b/src/lib/live-events.test.tsindex 3a65685683..c79afc69c4 100644--- a/src/lib/live-events.test.ts+++ b/src/lib/live-events.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {LIVE_EVENTS_STALE_MS,isLivePing,+ listenLiveFrames,liveEventsUrl,openLiveEvents,shouldReconnectLiveEvents,@@ -98,6 +99,8 @@ describe("live events URL", () => {it("builds cold and resumable stream URLs", () => {expect(liveEventsUrl()).toBe("/api/events");expect(liveEventsUrl({ since: "ab12cd34:9" })).toBe("/api/events?since=ab12cd34%3A9");+ expect(liveEventsUrl({ since: "ab12cd34:9", screens: false })).toBe("/api/events?since=ab12cd34%3A9&screens=off");+ expect(liveEventsUrl({ screens: true })).toBe("/api/events");});});@@ -141,7 +144,7 @@ describe("live events supervisor", () => {test.setNow(1_900);vi.advanceTimersByTime(500);expect(test.sources).toHaveLength(2);- expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4");+ expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off");expect(test.sources[0].close).toHaveBeenCalledOnce();stop();});@@ -183,19 +186,19 @@ describe("live events supervisor", () => {test.sources[0].message({ kind: "message" }, "oldrun00:10");test.sources[0].error();vi.advanceTimersByTime(100);- expect(test.sources[1].url).toBe("/api/events?since=oldrun00%3A10");+ expect(test.sources[1].url).toBe("/api/events?since=oldrun00%3A10&screens=off");test.sources[1].message({ kind: "hello", resumed: true, cursor: "oldrun00:13" });test.sources[1].error();vi.advanceTimersByTime(100);- expect(test.sources[2].url).toBe("/api/events?since=oldrun00%3A10");+ expect(test.sources[2].url).toBe("/api/events?since=oldrun00%3A10&screens=off");test.sources[2].message({ kind: "hello", resumed: false, cursor: "newrun00:7" });test.sources[2].message({ kind: "message", value: "behind failed snapshot" }, "newrun00:8");snapshotResolutions.shift()?.(false);await Promise.resolve();vi.advanceTimersByTime(100);- expect(test.sources[3].url).toBe("/api/events?since=oldrun00%3A10");+ expect(test.sources[3].url).toBe("/api/events?since=oldrun00%3A10&screens=off");test.sources[3].message({ kind: "hello", resumed: false, cursor: "newrun00:8" });test.sources[3].message({ kind: "message", value: "after snapshot" }, "newrun00:9");@@ -203,7 +206,7 @@ describe("live events supervisor", () => {await Promise.resolve();test.sources[3].error();vi.advanceTimersByTime(100);- expect(test.sources[4].url).toBe("/api/events?since=newrun00%3A9");+ expect(test.sources[4].url).toBe("/api/events?since=newrun00%3A9&screens=off");expect(frames).toEqual([{ kind: "message" },{ kind: "message", value: "behind failed snapshot" },@@ -368,7 +371,7 @@ describe("a Cloud home that goes to sleep", () => {expect(test.sources).toHaveLength(1);markCloudAwake();expect(test.sources).toHaveLength(2);- expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4");+ expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off");stop();});@@ -410,7 +413,7 @@ describe("a Cloud home that goes to sleep", () => {loading.sources[0].message(sleeping, "run00000:5");expect(cloudAsleep()).toBe(true);markCloudAwake();- expect(loading.sources[1].url).toBe("/api/events");+ expect(loading.sources[1].url).toBe("/api/events?screens=off");stopLoading();});@@ -423,3 +426,32 @@ describe("a Cloud home that goes to sleep", () => {stop();});});++describe("live screens", () => {+ it("leave screens out until a view that draws them listens, then reopen from the cursor both ways", async () => {+ const test = harness();+ const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, test.platform);+ expect(test.sources[0].url).toBe("/api/events?screens=off");+ test.sources[0].open();+ test.sources[0].message({ kind: "hello", resumed: true, cursor: "run00000:3" });+ test.sources[0].message({ kind: "message" }, "run00000:4");++ const quiet = listenLiveFrames({ onFrame: () => {} });+ await Promise.resolve();+ expect(test.sources).toHaveLength(1);+ const viewer = listenLiveFrames({ screens: true, onFrame: () => {} });+ const second = listenLiveFrames({ screens: true, onFrame: () => {} });+ await Promise.resolve();+ expect(test.sources.map((source) => source.url)).toEqual(["/api/events?screens=off", "/api/events?since=run00000%3A4"]);+ expect(test.sources[0].close).toHaveBeenCalledOnce();++ viewer();+ await Promise.resolve();+ expect(test.sources).toHaveLength(2);+ second();+ await Promise.resolve();+ expect(test.sources[2].url).toBe("/api/events?since=run00000%3A4&screens=off");+ quiet();+ stop();+ });+});diff --git a/src/lib/live-events.ts b/src/lib/live-events.tsindex 790e5113f2..c54c4b0470 100644--- a/src/lib/live-events.ts+++ b/src/lib/live-events.ts@@ -53,9 +53,11 @@ export interface LiveEventsHandlers {retryMaxMs?: number;}-export function liveEventsUrl(options?: { since?: string | null }): string {+/** `screens: false` asks the server to leave out live screen frames. */+export function liveEventsUrl(options?: { since?: string | null; screens?: boolean }): string {const params = new URLSearchParams();if (options?.since) params.set("since", options.since);+ if (options?.screens === false) params.set("screens", "off");const query = params.toString();return query ? `${LIVE_EVENTS_PATH}?${query}` : LIVE_EVENTS_PATH;}@@ -63,17 +65,32 @@ export function liveEventsUrl(options?: { since?: string | null }): string {export interface LiveFrameListener {onFrame: (frame: ServerFrame) => void;onMissedFrames?: () => void;+ /** Draws live screens: while a listener with this is registered the stream carries screen frames; with none it does not. */+ screens?: boolean;}const liveFrameListeners = new Set<LiveFrameListener>();+const screenWishListeners = new Set<() => void>();+const screensWanted = () => [...liveFrameListeners].some((listener) => listener.screens);export function listenLiveFrames(listener: LiveFrameListener): () => void {+ const before = screensWanted();liveFrameListeners.add(listener);+ if (screensWanted() !== before) for (const changed of screenWishListeners) changed();return () => {+ const wanted = screensWanted();liveFrameListeners.delete(listener);+ if (screensWanted() !== wanted) for (const changed of screenWishListeners) changed();};}+/** A frame kept for later (before the first snapshot is drawn) needs no pixels: viewers saw them as it arrived. */+export function withoutScreenPixels(frame: ServerFrame): ServerFrame {+ if (frame.kind !== "screen") return frame;+ const { png: _png, ...rest } = frame;+ return { ...rest, png: "" };+}+export function publishLiveFrame(frame: ServerFrame): void {for (const listener of liveFrameListeners) listener.onFrame(frame);}@@ -189,6 +206,7 @@ export function openLiveEvents(let stopped = false;let source: LiveEventSourceLike | null = null;+ let sourceScreens = screensWanted();let retryTimer: ReturnType<typeof setTimeout> | null = null;let retryAttempt = 0;let cursor: string | null = null;@@ -246,9 +264,8 @@ export function openLiveEvents(if (stopped || source || !platform.isOnline() || cloudAsleep()) return;let current: LiveEventSourceLike;try {- current = platform.createEventSource(- liveEventsUrl({ since: cursor }),- );+ sourceScreens = screensWanted();+ current = platform.createEventSource(liveEventsUrl({ since: cursor, screens: sourceScreens }));} catch {handlers.onError?.();scheduleReconnect();@@ -309,6 +326,7 @@ export function openLiveEvents(}cursor = pending.newestFrameCursor ?? pending.boundaryCursor;pendingSnapshot = null;+ onScreenWish();})();}} else if (event.lastEventId) {@@ -360,6 +378,10 @@ export function openLiveEvents(if (platform.isVisible()) recover();};+ const onScreenWish = () => queueMicrotask(() => {+ if (source && cursor && !pendingSnapshot && screensWanted() !== sourceScreens) reconnectNow(false);+ });+ screenWishListeners.add(onScreenWish);connect();const staleTimer = setInterval(recover, staleCheckMs);// The person is back after the Cloud slept: reconnect at once, which wakes it.@@ -371,6 +393,7 @@ export function openLiveEvents(return () => {if (stopped) return;stopped = true;+ screenWishListeners.delete(onScreenWish);stopPower();clearInterval(staleTimer);clearRetry();diff --git a/src/lib/map-computers.ts b/src/lib/map-computers.tsindex 181de4555b..0314fe2b43 100644--- a/src/lib/map-computers.ts+++ b/src/lib/map-computers.ts@@ -123,7 +123,7 @@ export function useMapComputers(enabled: boolean) {};void poll();const timer = window.setInterval(poll, MAP_COMPUTERS_POLL_MS);- const stopListening = listenLiveFrames({+ const stopListening = listenLiveFrames({ screens: true,onFrame: (frame) => {if (frame.kind !== "screen" || frame.surface !== "computer" || !frame.png) return;const computer = computerForBot(computersRef.current, frame.botId);diff --git a/src/state/live-frames.test.ts b/src/state/live-frames.test.tsindex c298e63804..cf068cde11 100644--- a/src/state/live-frames.test.ts+++ b/src/state/live-frames.test.ts@@ -69,7 +69,7 @@ afterAll(() => {describe("live frames the store does not keep", () => {it("come from the app's one stream", () => {expect(seen.bots.map((candidate) => candidate.id)).toEqual(["bot"]);- expect(FixtureEventSource.opened.map((source) => source.url)).toEqual(["/api/events"]);+ expect(FixtureEventSource.opened.map((source) => source.url)).toEqual(["/api/events?screens=off"]);});it("hand a screen frame to its listener without touching app state", async () => {diff --git a/src/state/store.tsx b/src/state/store.tsxindex fc21f2ce52..fc41d73106 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -67,7 +67,7 @@ import { t } from "@/lib/i18n";import { createBotPatchQueue, flushWhenLeaving, keepaliveFits, type BotUpdatePatch } from "./bot-patch-queue"; import { createNewTaskOnce } from "./new-task-once";import { liveCallFromFrame, nextLiveCallLookup } from "./live-call";import { useChatErrorClear } from "./chat-error";-import { openLiveEvents, publishLiveFrame, publishMissedFrames } from "@/lib/live-events";+import { openLiveEvents, publishLiveFrame, publishMissedFrames, withoutScreenPixels } from "@/lib/live-events";import { unlessRefused } from "@/lib/admin-scope";import { trimRoutineRuns } from "./routine-runs";import { reconcileSnapshotQueues, rememberConsumedQueueId, replaceBotQueues } from "./queue-receipts";@@ -3286,7 +3286,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {onFrame: (frame) => {publishLiveFrame(frame as ServerFrame);if (hydrated) handleFrame(frame as ServerFrame);- else pendingFrames.push(frame as ServerFrame);+ else pendingFrames.push(withoutScreenPixels(frame as ServerFrame));},});return () => {