Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Launch: probes and downloads wait for the window, engine probe answers are kept, main gets a compile cache
milind-sonife8106124208
diff --git a/electron/boot.mjs b/electron/boot.mjsnew file mode 100644index 0000000000..1500374dcd--- /dev/null+++ b/electron/boot.mjs@@ -0,0 +1,19 @@+// The desktop app's entry (package.json "main"): Node's compile cache for this process first (main-compile-cache.mjs),+// then the app itself. main.mjs is one static module graph, compiled as it loads, so the cache must be on before it.+import module from "node:module";+import { app } from "electron";++import { mainCompileCacheDir, settleCompileCache } from "./main-compile-cache.mjs";++const root = mainCompileCacheDir({ packaged: app.isPackaged, userData: app.getPath("userData"), resourcesPath: process.resourcesPath });+let enabled = false;+if (root) {+ try {+ enabled = module.enableCompileCache(root).status === module.constants.compileCacheStatus.ENABLED;+ } catch {+ }+}++await import("./main.mjs");++if (enabled) setTimeout(() => settleCompileCache({ module, root }), 10_000).unref();diff --git a/electron/data-dir-lease-host.node-test.mjs b/electron/data-dir-lease-host.node-test.mjsnew file mode 100644index 0000000000..469e6c58f5--- /dev/null+++ b/electron/data-dir-lease-host.node-test.mjs@@ -0,0 +1,80 @@+// The desktop's server child and the lease its parent hands it: the parent's boot and machine ids travel with the+// capability, so the child does not read them again, and Windows does not match its own parent to the lease by creation time.+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { randomUUID } from "node:crypto";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import test from "node:test";++import { acquireDataDirLease, consumeHostIdentity, creationTimeNeeded } from "./data-dir-lease.mjs";++const MODULE_URL = new URL("./data-dir-lease.mjs", import.meta.url).href;+const LEASE_NAME = "openmausbot-server.lease";+const roots = [];+test.after(() => { for (const root of roots) rmSync(root, { recursive: true, force: true }); });++function temporaryDirectory() {+ const root = mkdtempSync(path.join(tmpdir(), "omb-electron-lease-host-"));+ roots.push(root);+ return { dataDir: path.join(root, "data") };+}++function runNode(source, environment) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, ["--input-type=module", "--eval", source], { env: { ...process.env, ...environment }, stdio: ["ignore", "pipe", "pipe"] });+ let stdout = "", stderr = "";+ child.stdout.setEncoding("utf8");+ child.stderr.setEncoding("utf8");+ child.stdout.on("data", (chunk) => (stdout += chunk));+ child.stderr.on("data", (chunk) => (stderr += chunk));+ child.once("error", reject);+ child.once("close", (code) => resolve({ code, stdout, stderr }));+ });+}++test("a delegated child takes the parent's boot and machine ids from its environment, once, instead of reading them again", async () => {+ const { dataDir } = temporaryDirectory();+ const parent = acquireDataDirLease(dataDir);+ try {+ const handed = parent.utilityServerLeaseEnvironment();+ const [hostName, host] = Object.entries(handed).find(([name]) => name.endsWith("_HOST"));+ const record = JSON.parse(readFileSync(path.join(dataDir, LEASE_NAME), "utf8"));+ assert.equal(host, `${record.boot ?? "-"} ${record.machine ?? "-"}`);+ // The child reads the ids from the environment, then the lease it writes carries the parent's; both variables are gone.+ const child = await runNode(`+ const { acquireDataDirLeaseForProcess } = await import(${JSON.stringify(MODULE_URL)});+ const lease = acquireDataDirLeaseForProcess(${JSON.stringify(dataDir)});+ const { readFileSync } = await import("node:fs");+ const own = JSON.parse(readFileSync(${JSON.stringify(path.join(dataDir, ".openmausbot-server-child", LEASE_NAME))}, "utf8"));+ process.stdout.write(JSON.stringify({ boot: own.boot, machine: own.machine, left: Object.keys(process.env).filter((name) => name.startsWith("OPENMAUSBOT_INTERNAL")) }));+ lease.release();+ `, handed);+ assert.equal(child.code, 0, child.stderr);+ assert.deepEqual(JSON.parse(child.stdout), { boot: record.boot ?? null, machine: record.machine ?? null, left: [] });+ assert.ok(hostName);+ } finally {+ parent.release();+ }+});++test("a handed host identity is taken only when well formed, and is removed from the environment", () => {+ const name = "OPENMAUSBOT_INTERNAL_DATA_DIR_HOST";+ const boot = randomUUID(), machine = "a".repeat(32);+ const environment = { [name]: `${boot} ${machine}` };+ assert.deepEqual(consumeHostIdentity(environment), { boot, machine });+ assert.equal(name in environment, false);+ assert.deepEqual(consumeHostIdentity({ [name]: "- -" }), { boot: null, machine: null });+ assert.deepEqual(consumeHostIdentity({ [name]: "bad/boot nothex" }), { boot: undefined, machine: undefined });+ assert.equal(consumeHostIdentity({ [name]: `${boot} ${machine} extra` }), null);+ assert.equal(consumeHostIdentity({}), null);+});++test("Windows matches a live pid to a record by its creation time, except for the parent that handed this process the record", () => {+ assert.equal(creationTimeNeeded("win32", 4242, null), true);+ assert.equal(creationTimeNeeded("win32", 4242, 77), true);+ assert.equal(creationTimeNeeded("win32", 4242, 4242), false);+ assert.equal(creationTimeNeeded("win32", 4242, 0), true);+ for (const platform of ["darwin", "linux"]) assert.equal(creationTimeNeeded(platform, 4242, null), false);+});diff --git a/electron/data-dir-lease.d.mts b/electron/data-dir-lease.d.mtsindex 5026db4bc8..45db932934 100644--- a/electron/data-dir-lease.d.mts+++ b/electron/data-dir-lease.d.mts@@ -31,6 +31,12 @@ export declare function clearRecordsFromOtherMachines(dataDir: string,): { path: string; host: string; pid: number }[];+export declare function creationTimeNeeded(platform: NodeJS.Platform, ownerPid: number, parentPid: number | null): boolean;++export declare function consumeHostIdentity(environment: Record<string, string | undefined>): { boot: string | null | undefined; machine: string | null | undefined } | null;++export declare function hostBootSession(): string | null;+export declare function macMountIsLocal(dfOutput: string, mountTable: string): boolean;export declare function inMacSyncedFolder(path: string, home: string): boolean;diff --git a/electron/data-dir-lease.mjs b/electron/data-dir-lease.mjsindex dd4f0863a4..c00818b652 100644--- a/electron/data-dir-lease.mjs+++ b/electron/data-dir-lease.mjs@@ -8,6 +8,9 @@ const LEASE_NAME = "openmausbot-server.lease";const DELEGATED_CHILD_DIR = ".openmausbot-server-child";// Internal parent-to-child capability, obtained only from utilityServerLeaseEnvironment(); never public configuration.const CHILD_LEASE_ENV = "OPENMAUSBOT_INTERNAL_DATA_DIR_LEASE";+// Beside it, the parent's boot session and hashed machine id: its child runs on the same machine in the same boot, so it+// does not start `sysctl` and `ioreg` (macOS) or `reg.exe` (Windows) again before it can listen.+const CHILD_HOST_ENV = "OPENMAUSBOT_INTERNAL_DATA_DIR_HOST";const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;const MAX_PID = 0x7fffffff;const MAX_BOOT_ID = 128;@@ -56,6 +59,11 @@ function bootSession() {return cachedBootSession;}+/** This boot's id (Linux boot_id, macOS kern.bootsessionuuid), read once per process; null where there is none. */+export function hostBootSession() {+ return bootSession();+}+function uptimeMs() {const seconds = uptime();return Number.isFinite(seconds) && seconds >= 0 ? Math.floor(seconds * 1000) : 0;@@ -129,9 +137,20 @@ function ownerPredatesThisBoot(owner) {return false;}-/** The only liveness question this module should ever ask about a record. */-function ownerIsAlive(owner) {- return !ownerPredatesThisBoot(owner) && processIsAlive(owner.pid) && ownerIdentityMatches(owner);+/** The only liveness question this module should ever ask about a record. `parentPid`: the pid of the process that started+ * this one, when the record is that parent's own (a delegated child checking the lease it was handed). */+function ownerIsAlive(owner, parentPid = null) {+ return !ownerPredatesThisBoot(owner) && processIsAlive(owner.pid) && (!creationTimeNeeded(process.platform, owner.pid, parentPid) || ownerIdentityMatches(owner));+}++/**+ * Whether a live pid must still be matched to the record by its creation time (Windows reuses pids). Not for the process+ * that started this one and handed it the record's own token: it is alive (it answered) and it is this process' parent,+ * and Chromium ends a utility process with its browser process. That query is `wmic`, or on Windows 11, where wmic is+ * gone, a PowerShell start that takes a second or more, run twice before the desktop's server could listen.+ */+export function creationTimeNeeded(platform, ownerPid, parentPid) {+ return platform === "win32" && !(isPid(parentPid) && ownerPid === parentPid);}/**@@ -635,7 +654,7 @@ function validateChildDelegation(dataDir, encoded) {&& owner.pid === capability.pid&& owner.token === capability.token&& sameMachine(owner, dataDir)- && ownerIsAlive(owner));+ && ownerIsAlive(owner, process.ppid));if (!matchesLiveParent(readOwner(parentLeasePath))) {throw invalid();}@@ -732,7 +751,7 @@ function acquireDataDirLeaseInternal(dataDir, options = {}) {},utilityServerLeaseEnvironment() {if (released) throw leaseError("OpenMausBot cannot delegate a released data-directory lease.");- return Object.freeze({ [CHILD_LEASE_ENV]: capabilityFor(owner) });+ return Object.freeze({ [CHILD_LEASE_ENV]: capabilityFor(owner), [CHILD_HOST_ENV]: hostIdentityFor(owner) });},});}@@ -815,8 +834,30 @@ export function describeDataDirLease(dataDir) {}}+function hostIdentityFor(owner) {+ return `${owner.boot ?? "-"} ${owner.machine ?? "-"}`;+}++/** The parent's boot session and machine id, each kept only when well formed; read once and removed, like the capability. */+export function consumeHostIdentity(environment) {+ const value = environment[CHILD_HOST_ENV];+ if (value === undefined) return null;+ try { delete environment[CHILD_HOST_ENV]; } catch {}+ const [boot, machine, extra] = String(value).split(" ");+ if (extra !== undefined) return null;+ return {+ boot: boot === "-" ? null : normalizeBootId(boot) === boot ? boot : undefined,+ machine: machine === "-" ? null : MACHINE_ID.test(machine ?? "") ? machine : undefined,+ };+}+export function acquireDataDirLeaseForProcess(dataDir, environment = process.env) {+ const host = consumeHostIdentity(environment);const encoded = consumeChildCapability(environment);+ if (encoded !== null && host) {+ if (cachedBootSession === undefined && host.boot !== undefined) cachedBootSession = host.boot;+ if (cachedMachineId === undefined && host.machine !== undefined) cachedMachineId = host.machine;+ }return encoded === null? acquireDataDirLease(dataDir): validateChildDelegation(dataDir, encoded);diff --git a/electron/data-dir-lease.node-test.mjs b/electron/data-dir-lease.node-test.mjsindex afa3051fb4..52e2161caa 100644--- a/electron/data-dir-lease.node-test.mjs+++ b/electron/data-dir-lease.node-test.mjs@@ -28,7 +28,7 @@ function temporaryDirectory(name = "data") {}function delegationEntry(lease) {- const entries = Object.entries(lease.utilityServerLeaseEnvironment());+ const entries = Object.entries(lease.utilityServerLeaseEnvironment()).filter(([name]) => !name.endsWith("_HOST"));assert.equal(entries.length, 1);assert.match(entries[0][0], /INTERNAL.*LEASE/);assert.match(entries[0][1], /^v1:[1-9][0-9]*:[0-9a-f-]{36}$/);diff --git a/electron/main-compile-cache.mjs b/electron/main-compile-cache.mjsnew file mode 100644index 0000000000..6d8058d0c6--- /dev/null+++ b/electron/main-compile-cache.mjs@@ -0,0 +1,36 @@+// Node's compile cache for the desktop app's own main process (electron/boot.mjs turns it on before main.mjs loads), as+// scripts/desktop-server-entry.mjs does for its server: a relaunch reuses the compiled code of the ~100 modules main+// imports instead of compiling them again. Kept in the app's own folder (userData), never the data folder. Node checks each+// entry against its source, so code an update changed is compiled afresh; its directory per Node version (one is left+// behind by each Electron upgrade) is removed once no launch has used it for a day.+import fs from "node:fs";+import path from "node:path";++export const MAIN_COMPILE_CACHE = "main-compile-cache";+const STALE_AFTER_MS = 24 * 60 * 60 * 1000;++/** Where the main process keeps its cache, or null: an unpackaged run, or an app whose path changes each launch (an+ * AppImage, a translocated macOS app), since Node keys entries by full path. */+export function mainCompileCacheDir({ packaged, userData, resourcesPath, env = process.env }) {+ if (!packaged || !userData || Boolean(env.APPIMAGE) || String(resourcesPath ?? "").includes("/AppTranslocation/")) return null;+ return path.join(userData, MAIN_COMPILE_CACHE);+}++/** After the window is up: writes what this launch compiled (a crash or a Windows kill skips Node's write at exit) and+ * removes other Node versions' directories unused for a day. Only `v<node version>-…` directories inside `root`. */+export function settleCompileCache({ module, root, now = Date.now(), fsImpl = fs }) {+ try {+ module.flushCompileCache();+ const current = module.getCompileCacheDir();+ if (!current || path.dirname(current) !== path.resolve(root)) return;+ const stamp = new Date(now);+ fsImpl.utimesSync(current, stamp, stamp);+ for (const name of fsImpl.readdirSync(root)) {+ if (name === path.basename(current) || !/^v\d+\.\d+\.\d+-/.test(name)) continue;+ const stale = path.join(root, name);+ const stat = fsImpl.lstatSync(stale);+ if (stat.isDirectory() && now - stat.mtimeMs > STALE_AFTER_MS) fsImpl.rmSync(stale, { recursive: true, force: true });+ }+ } catch {+ }+}diff --git a/electron/main-compile-cache.node-test.mjs b/electron/main-compile-cache.node-test.mjsnew file mode 100644index 0000000000..1ef9d659c6--- /dev/null+++ b/electron/main-compile-cache.node-test.mjs@@ -0,0 +1,53 @@+import assert from "node:assert/strict";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import test from "node:test";++import { MAIN_COMPILE_CACHE, mainCompileCacheDir, settleCompileCache } from "./main-compile-cache.mjs";++test("the packaged main process keeps its compile cache in the app's own folder, never where the path changes each launch", () => {+ const userData = path.join(tmpdir(), "omb-user-data");+ assert.equal(mainCompileCacheDir({ packaged: true, userData, resourcesPath: "/Applications/OpenMausBot.app/Contents/Resources", env: {} }), path.join(userData, MAIN_COMPILE_CACHE));+ assert.equal(mainCompileCacheDir({ packaged: false, userData, resourcesPath: "/x", env: {} }), null);+ assert.equal(mainCompileCacheDir({ packaged: true, userData, resourcesPath: "/tmp/.mount_x/resources", env: { APPIMAGE: "/home/a/OpenMausBot.AppImage" } }), null);+ assert.equal(mainCompileCacheDir({ packaged: true, userData, resourcesPath: "/private/var/folders/x/AppTranslocation/y/d/OpenMausBot.app/Contents/Resources", env: {} }), null);+});++test("settling writes this launch's entries and removes only other Node versions' directories a day unused", (t) => {+ const root = mkdtempSync(path.join(tmpdir(), "omb-main-cc-"));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ const now = Date.now();+ const current = path.join(root, "v24.21.0-arm64-aaaa-501");+ const old = path.join(root, "v24.11.0-arm64-bbbb-501");+ const recent = path.join(root, "v24.12.0-arm64-cccc-501");+ const other = path.join(root, "not-a-cache");+ for (const dir of [current, old, recent, other]) mkdirSync(dir);+ const dayAgo = new Date(now - 25 * 60 * 60 * 1000);+ for (const dir of [old, other, current]) utimesSync(dir, dayAgo, dayAgo);+ let flushed = 0;+ settleCompileCache({ module: { flushCompileCache: () => { flushed += 1; }, getCompileCacheDir: () => current }, root, now });+ assert.equal(flushed, 1);+ const left = (dir) => { try { statSync(dir); return true; } catch { return false; } };+ assert.deepEqual([current, old, recent, other].map(left), [true, false, true, true]);+ assert.ok(Math.abs(statSync(current).mtimeMs - now) < 2000);+});++test("a cache directory Node placed elsewhere (NODE_COMPILE_CACHE from the shell) is flushed but nothing is removed", (t) => {+ const root = mkdtempSync(path.join(tmpdir(), "omb-main-cc-"));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ const old = path.join(root, "v24.11.0-arm64-bbbb-501");+ mkdirSync(old);+ const dayAgo = new Date(Date.now() - 48 * 60 * 60 * 1000);+ utimesSync(old, dayAgo, dayAgo);+ settleCompileCache({ module: { flushCompileCache() {}, getCompileCacheDir: () => path.join(tmpdir(), "elsewhere", "v24.21.0-x") }, root });+ assert.ok(statSync(old).isDirectory());+});++test("the app's entry turns the cache on before it loads main.mjs, and package.json starts there", () => {+ const boot = readFileSync(new URL("./boot.mjs", import.meta.url), "utf8");+ assert.ok(boot.indexOf("enableCompileCache(") < boot.indexOf('await import("./main.mjs")'));+ assert.doesNotMatch(boot.slice(0, boot.indexOf('await import("./main.mjs")')), /from "\.\/main\.mjs"/);+ const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));+ assert.equal(manifest.main, "electron/boot.mjs");+});diff --git a/package.json b/package.jsonindex e0c0f26e24..f56d546c56 100644--- a/package.json+++ b/package.json@@ -15,7 +15,7 @@"license": "Apache-2.0","desktopName": "com.openmausbot.app.desktop","type": "module",- "main": "electron/main.mjs",+ "main": "electron/boot.mjs","engines": {"node": ">=24"},diff --git a/scripts/bench-launch.mjs b/scripts/bench-launch.mjsindex 03773a800b..ce27bce787 100644--- a/scripts/bench-launch.mjs+++ b/scripts/bench-launch.mjs@@ -5,13 +5,16 @@// pnpm build && pnpm build:server// node scripts/bench-launch.mjs --root /tmp/openmausbot-bench-launch.XXXXXX [--app CHECKOUT] [--runs 7] [--cold]// [--seed 30,60,300] [--label NAME] [--out FILE] [--no-asar] [--dev] [--server-prof DIR [--server-prof-tail MS]] [--quiet-ms 1500]+// [--engines]// --app: the checkout whose electron/, dist/ and dist-server/ are measured (this one by default), so two checkouts run-// under the same bench. --cold: the page cache, its code cache and the server's compile cache are emptied before each+// under the same bench. --cold: the page cache, its code cache and the main and server compile caches are emptied before each// launch (what the first launch after an update does); otherwise one primed profile is reused. --dev: what// `pnpm dev:desktop` starts instead: electron/ from loose files, unpackaged, its page from a Vite dev server already// running in front of a source server (both started here, on the bench's own ports and folders).// --server-prof: the server child of each launch writes a V8 CPU profile into DIR, up to its "listening" line or// --server-prof-tail ms past it; those launches are slower for it.+// --engines: this computer's PATH instead of the sealed one, so the engines installed here are found and probed as at a+// real launch (their probes run in the bench's own HOME).// --quiet-ms: how long the page must stay free of long tasks after the chat is drawn before the app is quit; 4000 or// more lets the app write its own launch record (launch-timings.json in the data folder) first.// Not measured: a signed app's signature and keychain checks (a mock keychain stands in), the real engines' probes@@ -32,6 +35,7 @@ const require = createRequire(import.meta.url);const { values } = parseArgs({ options: {root: { type: "string" }, app: { type: "string", default: ROOT }, runs: { type: "string", default: "7" }, cold: { type: "boolean", default: false },seed: { type: "string", default: "30,60,300" }, label: { type: "string", default: "launch" }, out: { type: "string" }, "no-asar": { type: "boolean", default: false }, dev: { type: "boolean", default: false }, "server-prof": { type: "string" }, "quiet-ms": { type: "string", default: "1500" }, "server-prof-tail": { type: "string", default: "0" },+ engines: { type: "boolean", default: false },} });const log = (line) => process.stderr.write(`bench-launch: ${line}\n`);if (!values.root || !values.root.includes("openmausbot-bench-")) throw new Error("--root must be a folder made for this bench (its name holds openmausbot-bench-)");@@ -99,8 +103,8 @@ const STORAGE = { "omb-analytics-opt-out": "1", "omb-email-gate": "skipped", "omconst electron = require("electron");const DEV_PAGE_PORT = BENCH_PORTS[0] - 3600;const fixtureEnv = () => ({- PATH: dirname(process.execPath), HOME: paths.home, CFFIXED_USER_HOME: paths.home, TMPDIR: paths.tmp, LANG: process.env.LANG ?? "en_US.UTF-8",- OMB_DATA_DIR: paths.data, OMB_WEBHOOK_PORT: String(BENCH_PORTS[0] + 1), OMB_TEST_SEALED_PATH: "1", OMB_DISABLE_ANNOUNCEMENTS: "1", FAKE_CLAUDE_MODE: "happy",+ PATH: values.engines ? process.env.PATH : dirname(process.execPath), HOME: paths.home, CFFIXED_USER_HOME: paths.home, TMPDIR: paths.tmp, LANG: process.env.LANG ?? "en_US.UTF-8",+ OMB_DATA_DIR: paths.data, OMB_WEBHOOK_PORT: String(BENCH_PORTS[0] + 1), ...(values.engines ? {} : { OMB_TEST_SEALED_PATH: "1" }), OMB_DISABLE_ANNOUNCEMENTS: "1", FAKE_CLAUDE_MODE: "happy",OMB_BENCH_EGRESS_LOG: paths.egress, ...(values["server-prof"] ? { OMB_BENCH_SERVER_PROF: resolve(values["server-prof"]), OMB_BENCH_SERVER_PROF_TAIL_MS: values["server-prof-tail"] } : {}),});const answers = (url) => new Promise((done) => { const request = httpGet(url, (response) => { response.resume(); done(response.statusCode < 500); }); request.on("error", () => done(false)); request.setTimeout(2000, () => request.destroy()); });@@ -199,7 +203,7 @@ function phases(run) {}function wipeCaches() {- for (const name of ["Cache", "Code Cache", "GPUCache", "DawnGraphiteCache", "DawnWebGPUCache", "server-compile-cache", "Shared Dictionary"]) rmSync(join(paths.userData, name), { recursive: true, force: true });+ for (const name of ["Cache", "Code Cache", "GPUCache", "DawnGraphiteCache", "DawnWebGPUCache", "server-compile-cache", "main-compile-cache", "Shared Dictionary"]) rmSync(join(paths.userData, name), { recursive: true, force: true });}const runs = [];diff --git a/scripts/testing/bench-launch-entry.mjs b/scripts/testing/bench-launch-entry.mjsindex 7404ee0260..dccafb3a53 100644--- a/scripts/testing/bench-launch-entry.mjs+++ b/scripts/testing/bench-launch-entry.mjs@@ -6,6 +6,7 @@ import childProcess from "node:child_process";import fs from "node:fs";import { createRequire, syncBuiltinESMExports } from "node:module";import path from "node:path";+import { fileURLToPath } from "node:url";const config = JSON.parse(process.env.OMB_BENCH_LAUNCH ?? "null");if (!config) { console.error("bench-launch-entry runs only under scripts/bench-launch.mjs"); app.exit(64); await new Promise(() => {}); }@@ -219,7 +220,9 @@ void app.whenReady().then(finish);mark("main-import:start"); snapshot("importStart");try {- await import(new URL("./electron/main.mjs", import.meta.url).href);+ // The app's own entry, which turns on the main process' compile cache before main.mjs loads; main.mjs where there is none.+ const boot = new URL("./electron/boot.mjs", import.meta.url);+ await import((fs.existsSync(fileURLToPath(boot)) ? boot : new URL("./electron/main.mjs", import.meta.url)).href);} catch (error) {console.error(`bench-launch-entry: the app's main module did not load: ${error?.stack ?? error}`);app.exit(66);diff --git a/server/cli-probe-cache.test.ts b/server/cli-probe-cache.test.tsnew file mode 100644index 0000000000..208285e307--- /dev/null+++ b/server/cli-probe-cache.test.ts@@ -0,0 +1,135 @@+import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { createCliProbeCache, probeCacheFile, probedProgram } from "./cli-probe-cache.ts";++const roots: string[] = [];+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });++function place() {+ const root = mkdtempSync(join(tmpdir(), "omb-probe-cache-"));+ roots.push(root);+ const bin = join(root, "bin");+ mkdirSync(bin);+ return { root, bin, file: join(root, "user-data", "engine-probes.json") };+}++function program(bin: string, name: string, body = "#!/usr/bin/env node\nconsole.log('1.0.0');\n"): string {+ const path = join(bin, name);+ writeFileSync(path, body);+ chmodSync(path, 0o755);+ return path;+}++/** A stand-in for execCli that counts its runs and answers what `answer` says. */+function runner(answer: (args: string[]) => { err?: Error; stdout: string; stderr?: string } = () => ({ stdout: "1.0.0\n" })) {+ const calls: string[][] = [];+ const run = ((_cli: string, args: string[], _opts: unknown, cb: (err: Error | null, stdout: string, stderr?: string) => void) => {+ calls.push(args);+ const { err, stdout, stderr } = answer(args);+ queueMicrotask(() => cb(err ?? null, stdout, stderr ?? ""));+ }) as Parameters<typeof createCliProbeCache>[0]["run"];+ return { run, calls };+}++const ask = (exec: ReturnType<typeof createCliProbeCache>["exec"], cli: string, args: string[], path: string) =>+ new Promise<{ err: Error | null; stdout: string; stderr?: string }>((resolve) => exec(cli, args, { env: { PATH: path } }, (err, stdout, stderr) => resolve({ err, stdout, stderr })));++describe("engine probe answers kept between desktop starts", () => {+ it("is kept only under the desktop app, in its own folder", () => {+ expect(probeCacheFile({})).toBeNull();+ expect(probeCacheFile({ OMB_USER_DATA: "/tmp/u" })).toBeNull();+ expect(probeCacheFile({ OMB_DESKTOP_PARENT: "1" })).toBeNull();+ expect(probeCacheFile({ OMB_DESKTOP_PARENT: "1", OMB_USER_DATA: "relative" })).toBeNull();+ expect(probeCacheFile({ OMB_DESKTOP_PARENT: "1", OMB_USER_DATA: join(tmpdir(), "u") })).toBe(join(tmpdir(), "u", "engine-probes.json"));+ });++ it("answers an unchanged program's --version and --help from the kept copy, also in the next start", async () => {+ const { bin, file } = place();+ program(bin, "engine");+ const first = runner((args) => ({ stdout: args[0] === "--help" ? "usage: engine --autocompact\n" : "1.0.0\n" }));+ const cache = createCliProbeCache({ file, appVersion: "0.1.180", run: first.run });+ expect(await ask(cache.exec, "engine", ["--version"], bin)).toEqual({ err: null, stdout: "1.0.0\n", stderr: "" });+ expect(await ask(cache.exec, "engine", ["--version"], bin)).toEqual({ err: null, stdout: "1.0.0\n", stderr: "" });+ expect(await ask(cache.exec, "engine", ["--help"], bin)).toMatchObject({ stdout: "usage: engine --autocompact\n" });+ expect(await ask(cache.exec, "engine", ["--help"], bin)).toMatchObject({ stdout: "usage: engine --autocompact\n" });+ expect(first.calls).toEqual([["--version"], ["--help"]]);++ const next = runner();+ const restarted = createCliProbeCache({ file, appVersion: "0.1.180", run: next.run });+ expect(await ask(restarted.exec, "engine", ["--version"], bin)).toMatchObject({ stdout: "1.0.0\n" });+ expect(next.calls).toEqual([]);+ });++ it("asks again once the program file changes, or the app is another version", async () => {+ const { bin, file } = place();+ const npmTime = new Date("1985-10-26T08:15:00Z");+ const path = program(bin, "engine");+ utimesSync(path, npmTime, npmTime);+ const counted = runner();+ const cache = createCliProbeCache({ file, appVersion: "0.1.180", run: counted.run });+ await ask(cache.exec, "engine", ["--version"], bin);+ // Same size and modification time npm gives every file, but a new file: still asked again.+ rmSync(path);+ utimesSync(program(bin, "engine"), npmTime, npmTime);+ await ask(cache.exec, "engine", ["--version"], bin);+ expect(counted.calls).toHaveLength(2);+ program(bin, "engine", "#!/usr/bin/env node\nconsole.log('2.0.0');\n");+ await ask(cache.exec, "engine", ["--version"], bin);+ expect(counted.calls).toHaveLength(3);+ const upgraded = createCliProbeCache({ file, appVersion: "0.1.181", run: counted.run });+ await ask(upgraded.exec, "engine", ["--version"], bin);+ expect(counted.calls).toHaveLength(4);+ });++ it("never keeps a failure, an empty answer, a sign-in check, or a program that is not on the PATH", async () => {+ const { bin, file } = place();+ program(bin, "engine");+ let answer: { err?: Error; stdout: string } = { err: new Error("exit 1"), stdout: "" };+ const counted = runner(() => answer);+ const cache = createCliProbeCache({ file, appVersion: "1", run: counted.run });+ expect((await ask(cache.exec, "engine", ["--version"], bin)).err?.message).toBe("exit 1");+ answer = { stdout: " \n" };+ await ask(cache.exec, "engine", ["--version"], bin);+ answer = { stdout: "Logged in\n" };+ await ask(cache.exec, "engine", ["auth", "status"], bin);+ await ask(cache.exec, "engine", ["auth", "status"], bin);+ await ask(cache.exec, "missing", ["--version"], bin);+ await ask(cache.exec, "missing", ["--version"], bin);+ await ask(cache.exec, "engine", ["--version"], bin);+ await ask(cache.exec, "engine", ["--version"], bin);+ expect(counted.calls).toHaveLength(7);+ });++ it("does not keep a shell script or a version manager's shim, whose file stays while the version it runs changes", () => {+ const { root, bin } = place();+ program(bin, "viaShell", "#!/bin/bash\nexec real-engine \"$@\"\n");+ program(bin, "viaEnvShell", "#!/usr/bin/env -S bash -e\nexec real-engine \"$@\"\n");+ const manager = program(join(root), "mise", "\u007fELF");+ symlinkSync(manager, join(bin, "engine"));+ const shims = join(root, "shims");+ mkdirSync(shims);+ program(shims, "other");+ program(bin, "native", "\u007fELF binary");+ program(bin, "node-cli");+ expect(probedProgram("viaShell", bin)).toBeNull();+ expect(probedProgram("viaEnvShell", bin)).toBeNull();+ expect(probedProgram("engine", bin)).toBeNull();+ expect(probedProgram("other", shims)).toBeNull();+ expect(probedProgram("engine --flag", bin)).toBeNull();+ expect(probedProgram("native", bin)).toMatch(/native$/);+ expect(probedProgram("node-cli", bin)).toMatch(/node-cli$/);+ });++ it("runs every probe where nothing may be kept", async () => {+ const { bin } = place();+ program(bin, "engine");+ const counted = runner();+ const cache = createCliProbeCache({ file: null, appVersion: "1", run: counted.run });+ await ask(cache.exec, "engine", ["--version"], bin);+ await ask(cache.exec, "engine", ["--version"], bin);+ expect(counted.calls).toHaveLength(2);+ });+});diff --git a/server/cli-probe-cache.ts b/server/cli-probe-cache.tsnew file mode 100644index 0000000000..0cb9392866--- /dev/null+++ b/server/cli-probe-cache.ts@@ -0,0 +1,137 @@+// An engine CLI's `--version` and `--help` answers, kept between starts of the desktop app: they cannot change while the+// program file is the same, and each start used to run them again (a process each, hundreds of ms for a Node CLI, more on+// Windows). Only under the desktop app (its own folder, OMB_USER_DATA, never the data folder); any other server runs every+// probe as before. Only successful answers are kept, never a sign-in check (`auth status`), whose answer changes.+//+// The key is the program file itself: its real path, size, modification and change times and inode, plus the app's+// version, the platform and the arguments. An update writes a new file (npm and Homebrew both do, and a reinstall gets a+// new change time even when the package keeps the 1985 modification time npm gives every file), so it is asked again. Not+// kept: a program that is a shell script or a version manager's shim (asdf, mise, volta and the like), whose file stays+// the same while the version it runs changes.+import { createHash } from "node:crypto";+import { closeSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, statSync } from "node:fs";+import { basename, dirname, isAbsolute, join } from "node:path";+import type { ExecFileOptions } from "node:child_process";++import { writeFileAtomic } from "./atomic.ts";+import { findCliCandidates, resolveCliSpawn, splitCliString } from "./env-path.ts";+import { execCli } from "./procs.ts";++export const PROBE_CACHE_FILE = "engine-probes.json";+const KEPT = 64;+const OUTPUT_MAX = 64 * 1024;+const CACHED_ARGS = new Set(["--version", "--help"]);+const SHIM_PROGRAMS = new Set(["mise", "rtx", "asdf", "volta", "volta-shim", "proto", "fnm", "nodenv", "pyenv", "rbenv", "goenv", "aqua", "nvm", "pkgx", "devbox"]);+const SHELL_INTERPRETERS = /^#!\s*(?:\S*\/)?(?:env\s+(?:-\S+\s+)*)?(?:sh|bash|zsh|dash|ksh|fish|csh|tcsh)\b/;++type Entry = { stdout: string; stderr: string };+type ExecCli = typeof execCli;++/** The file the desktop app keeps the answers in; null on any other server. */+export function probeCacheFile(env: NodeJS.ProcessEnv = process.env): string | null {+ return env.OMB_DESKTOP_PARENT === "1" && env.OMB_USER_DATA && isAbsolute(env.OMB_USER_DATA) ? join(env.OMB_USER_DATA, PROBE_CACHE_FILE) : null;+}++/** The file a probe of `cli` actually runs (a Windows .cmd shim's script, not the shim), or null when it is not one whose+ * answer may be kept. */+export function probedProgram(cli: string, path: string, platform: NodeJS.Platform = process.platform): string | null {+ if (splitCliString(cli).length !== 1) return null;+ const found = findCliCandidates(cli, path)[0];+ if (!found) return null;+ let file = found;+ if (platform === "win32" && /\.(?:cmd|bat)$/i.test(found)) {+ const resolved = resolveCliSpawn(found, []);+ const script = resolved.args[0];+ if (resolved.command === found || !script || !isAbsolute(script)) return null;+ file = script;+ }+ let real: string;+ try { real = realpathSync(file); } catch { return null; }+ const name = basename(real).toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/, "");+ if (SHIM_PROGRAMS.has(name) || real.toLowerCase().split(/[\\/]/).includes("shims")) return null;+ if (/\.(?:ps1|sh)$/i.test(real) || shellScript(real)) return null;+ return real;+}++function shellScript(file: string): boolean {+ let fd: number | undefined;+ try {+ fd = openSync(file, "r");+ const head = Buffer.alloc(128);+ const read = readSync(fd, head, 0, head.length, 0);+ return SHELL_INTERPRETERS.test(head.subarray(0, read).toString("utf8").split("\n")[0] ?? "");+ } catch {+ return true;+ } finally {+ if (fd !== undefined) try { closeSync(fd); } catch {}+ }+}++/** The key one answer is kept under, or null when the program cannot be read. */+export function probeKey(program: string, args: readonly string[], appVersion: string, platform: NodeJS.Platform = process.platform): string | null {+ let stat;+ try { stat = statSync(program, { bigint: true }); } catch { return null; }+ if (!stat.isFile()) return null;+ return createHash("sha256").update(JSON.stringify([appVersion, platform, program, String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs), String(stat.ino), String(stat.dev), args])).digest("hex").slice(0, 40);+}++function readEntries(file: string): Map<string, Entry> {+ try {+ const raw = JSON.parse(readFileSync(file, "utf8")) as { v?: unknown; entries?: unknown };+ if (raw?.v !== 1 || !Array.isArray(raw.entries)) return new Map();+ const entries = new Map<string, Entry>();+ for (const item of raw.entries.slice(-KEPT)) {+ if (!Array.isArray(item) || typeof item[0] !== "string" || !item[1] || typeof item[1].stdout !== "string" || typeof item[1].stderr !== "string") continue;+ entries.set(item[0], { stdout: item[1].stdout, stderr: item[1].stderr });+ }+ return entries;+ } catch {+ return new Map();+ }+}++/**+ * execCli for a probe whose answer is fixed by the program file: answered from the desktop app's kept copy when the file+ * is unchanged, else run, and kept when it succeeds with some output. The callback gets exactly what a run would give.+ */+export function createCliProbeCache(options: { file: string | null; appVersion: string; run?: ExecCli; platform?: NodeJS.Platform }) {+ const run = options.run ?? execCli;+ const platform = options.platform ?? process.platform;+ let entries: Map<string, Entry> | null = null;+ const loaded = () => (entries ??= options.file ? readEntries(options.file) : new Map());+ const save = () => {+ if (!options.file) return;+ try {+ mkdirSync(dirname(options.file), { recursive: true });+ writeFileAtomic(options.file, JSON.stringify({ v: 1, entries: [...loaded()].slice(-KEPT) }), { durable: false });+ } catch {}+ };+ const exec: ExecCli = (cli, args, opts, cb) => {+ const program = options.file && args.length === 1 && CACHED_ARGS.has(args[0]!) ? probedProgram(cli, String((opts.env ?? process.env).PATH ?? ""), platform) : null;+ const key = program ? probeKey(program, args, options.appVersion, platform) : null;+ const kept = key ? loaded().get(key) : undefined;+ if (kept) {+ queueMicrotask(() => cb(null, kept.stdout, kept.stderr));+ return;+ }+ run(cli, args, opts, (err, stdout, stderr) => {+ if (key && !err && typeof stdout === "string" && `${stdout}${stderr ?? ""}`.trim() && stdout.length <= OUTPUT_MAX && (stderr ?? "").length <= OUTPUT_MAX && probeKey(program!, args, options.appVersion, platform) === key) {+ const map = loaded();+ map.delete(key);+ map.set(key, { stdout, stderr: stderr ?? "" });+ while (map.size > KEPT) map.delete(map.keys().next().value!);+ save();+ }+ cb(err, stdout, stderr);+ });+ };+ return { exec, forget() { entries = new Map(); save(); } };+}++let shared: ReturnType<typeof createCliProbeCache> | null = null;++/** execCli for `--version` and `--help` probes: the desktop app's kept answer when the program is unchanged. */+export const execCliProbe: ExecCli = (cli, args, opts: ExecFileOptions, cb) => {+ shared ??= createCliProbeCache({ file: probeCacheFile(), appVersion: process.env.OMB_APP_VERSION ?? "dev" });+ shared.exec(cli, args, opts, cb);+};diff --git a/server/cli-version-probe.ts b/server/cli-version-probe.tsindex 21cd1520e6..cc517e255a 100644--- a/server/cli-version-probe.ts+++ b/server/cli-version-probe.ts@@ -1,5 +1,6 @@import { findCliCandidates } from "./env-path.ts";-import { CLI_VERSION_TIMEOUT_MS, cliVersionReader, execCli } from "./procs.ts";+import { execCliProbe } from "./cli-probe-cache.ts";+import { CLI_VERSION_TIMEOUT_MS, cliVersionReader, type execCli } from "./procs.ts";/** What to launch: on Windows the checked copy's own path, since spawn-time resolution reads the app's PATH, not the turn's (POSIX spawn already looks up the turn's PATH). */export function cliToLaunch(cli: string, checked: string | undefined, platform: NodeJS.Platform = process.platform): string {@@ -8,7 +9,7 @@ export function cliToLaunch(cli: string, checked: string | undefined, platform:// Shares version checks and retries empty responses. A failed check falls back to the last version only while PATH// still finds the same copy of the CLI, so a newly found copy is never reported with another copy's version.-export function cliVersionProbe(cli: string, run: typeof execCli = execCli, platform: NodeJS.Platform = process.platform) {+export function cliVersionProbe(cli: string, run: typeof execCli = execCliProbe, platform: NodeJS.Platform = process.platform) {let read = cliVersionReader(cli), readAt: string | undefined;let pending: { path: string | undefined; probe: Promise<ReturnType<typeof read>> } | undefined; // shared only by callers with the same PATHreturn (env: NodeJS.ProcessEnv): Promise<ReturnType<typeof read>> => {diff --git a/server/container-computer.ts b/server/container-computer.tsindex 5cbfc86c6b..b72081f431 100644--- a/server/container-computer.ts+++ b/server/container-computer.ts@@ -242,11 +242,11 @@ export interface ContainerRuntimeStatus {daemonUp: boolean;}-/** Inspects only the host runtime: never opens a container, calls Cua, or reads a screenshot. */-export async function containerRuntimeStatus(- runner: CommandRunner = sh,- platform: NodeJS.Platform = process.platform,-): Promise<ContainerRuntimeStatus> {+let hostRuntimeRead: Promise<ContainerRuntimeStatus> | null = null; /** Inspects only the host runtime: never opens a container, calls Cua, or reads a screenshot. Callers at one moment share one read (the Local VM's availability and its recovery both ask at start). */+export function containerRuntimeStatus(runner: CommandRunner = sh, platform: NodeJS.Platform = process.platform): Promise<ContainerRuntimeStatus> {+ return runner !== sh || platform !== process.platform ? readContainerRuntimeStatus(runner, platform) : (hostRuntimeRead ??= readContainerRuntimeStatus(runner, platform).finally(() => { hostRuntimeRead = null; }));+}+async function readContainerRuntimeStatus(runner: CommandRunner, platform: NodeJS.Platform): Promise<ContainerRuntimeStatus> {// Podman is the supported Windows VM lane and owns the pinned image; Docker-first would pick an unrelated image store.const candidates: Runtime[] = platform === "win32"? ["podman", "docker"]diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex c0393b079e..ba4b3962e2 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -20,7 +20,7 @@ import { DeviceAuthController, deviceAuthInstanceSurface, type DeviceSignIn } frimport { AcpBrowserAuth, acpBrowserAuthInstanceSurface, type AcpBrowserSignInSpec } from "./browser-auth.ts";import { commitPromptSplitReceipt, deletePromptSplitReceipt, type PendingPromptSplitReceipt } from "../prompt-split.ts";import { liveSessionKey, sessionSystem, turnPrompt } from "./session-system.ts";-import { boxAudienceKey, describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../../engine-stop.ts";+import { boxAudienceKey, describeSpawnFailure, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts"; import { execCliProbe } from "../../cli-probe-cache.ts"; import { stopEngineTree, stopEngineTrees } from "../../engine-stop.ts";import { applyOneShotEnv, oneShotTurnModel, runAcpOneShot } from "./background-text.ts"; import type { AcpBackgroundWork } from "./background-work.ts";import { acpCapabilities } from "./capabilities.ts"; import { readAcpMediaLinks } from "./media-links.ts";import { acpNativeLogMessage } from "./tool-log.ts";@@ -1409,7 +1409,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>const env = childEnv();if (support.snapshot) return support.snapshot(env, config, instanceId);const probe = await new Promise<{ version?: string; reason?: string; other?: true }>((resolve) => {- execCli(config.cli, ["--version"], { timeout: 8000, env }, (err, stdout, stderr) => {+ execCliProbe(config.cli, ["--version"], { timeout: 8000, env }, (err, stdout, stderr) => {if (err) {const failure = err as NodeJS.ErrnoException & { killed?: boolean };const reason = failure.code === "ENOENT"diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 7325002e34..e34ccf7ace 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -10,8 +10,8 @@ import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";import { openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";import { writeFileAtomicIfChanged } from "../atomic.ts";import { augmentedPath, findCliCandidates } from "../env-path.ts"; import { BASH_MAX_TIMEOUT_MS } from "../system-prompt.ts";-import { boxAudienceKey, brokerSocketPath, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../engine-stop.ts";-import { cliToLaunch, cliVersionProbe } from "../cli-version-probe.ts";+import { boxAudienceKey, brokerSocketPath, describeSpawnFailure, killCliTree, spawnCli } from "../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../engine-stop.ts";+import { execCliProbe } from "../cli-probe-cache.ts"; import { cliToLaunch, cliVersionProbe } from "../cli-version-probe.ts";import { claudeAuthStatus } from "./claude-auth-status.ts";import { projectMcpServers } from "./claude-project-mcp.ts";import { botSettingsFor, folderSettingsEnv, withBotSettings } from "./claude-bot-settings.ts"; import { claudeHookSettings } from "./claude-hooks.ts";@@ -751,7 +751,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {const read = {version,done: new Promise<string | null>((resolve) => {- execCli(cliToLaunch(config.cli, findCliCandidates(config.cli, env.PATH ?? "")[0]), ["--help"], { timeout: 8000, env }, (err, stdout) => resolve(err ? null : stdout)); // on Windows the copy this env finds, not the app PATH's+ execCliProbe(cliToLaunch(config.cli, findCliCandidates(config.cli, env.PATH ?? "")[0]), ["--help"], { timeout: 8000, env }, (err, stdout) => resolve(err ? null : stdout)); // on Windows the copy this env finds, not the app PATH's}).then((help) => { // a read another copy's read or a failed re-probe replaced since must not bring back its flagsif (helpRead === read) [cliHasAutocompact, cliHelpVersion, helpRead] = [help === null ? null : !autocompactRefusedBy.has(version) && /^\s*--autocompact\b/m.test(help), version, null];}),diff --git a/server/engine-records.ts b/server/engine-records.tsindex f9a3809b2a..3899da2020 100644--- a/server/engine-records.ts+++ b/server/engine-records.ts@@ -13,6 +13,8 @@ import { execFile, execFileSync, type ChildProcess } from "node:child_process";import { existsSync, mkdirSync, readdirSync, readFileSync, readlinkSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";+import { hostBootSession } from "../electron/data-dir-lease.mjs";+export const ENGINE_TAG_ENV = "OMB_ENGINE_TAG";/** In the data folder; this machine's own, never backed up or moved. */export const ENGINE_RUNS_DIR = "engine-runs";@@ -87,11 +89,7 @@ function startOf(pid: number): string | null {/** Random per boot (Linux boot_id, macOS kern.bootsessionuuid): a pid and its start tick mean nothing across a reboot, as a* restarted VM with its volume restored has. */function bootId(): string | null {- try {- if (process.platform === "linux") return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() || null;- if (process.platform === "darwin") return execFileSync("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], { encoding: "utf8", timeout: 5_000, stdio: ["ignore", "pipe", "ignore"] }).trim() || null;- } catch {}- return null;+ return hostBootSession(); // the lease's reading: one `sysctl` per server, or none when the desktop handed it over}/** A container's processes live in a pid namespace of their own; one container cannot see or signal another's. */diff --git a/server/index.ts b/server/index.tsindex adffe7d40b..c3ce6083f0 100644--- a/server/index.ts+++ b/server/index.ts@@ -636,7 +636,7 @@ import { createPersonReplies } from "./person-replies.ts";import { handedOwnServerLender, lendingPerson, lendingPersonKey, OWN_SERVER_LENDER, ownWindowLender, personKey, relayedPersonKey } from "./person-key.ts"; import { ownWindowLine } from "./own-window-sends.ts"; import { ownServerLendingRefusal } from "./own-server-lending-refusal.ts";import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";-import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { cloudStorage, createPerfHost } from "./perf/perf-host.ts"; import { launchListening, launchServerPart } from "./perf/launch-probe.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { createCachesRoutes } from "./routes/caches.ts"; import { botEnginesLive, createCacheSweepHost, withCacheCounters } from "./cache-sweep/host.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";+import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { cloudStorage, createPerfHost } from "./perf/perf-host.ts"; import { afterLaunchSettles, launchListening, launchServerPart } from "./perf/launch-probe.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { createCachesRoutes } from "./routes/caches.ts"; import { botEnginesLive, createCacheSweepHost, withCacheCounters } from "./cache-sweep/host.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";import { createThreadRoutes } from "./routes/threads.ts";import { createWebhookRoutes } from "./routes/webhooks.ts"; import { createRemoteTeammateRoutes } from "./routes/remote-teammates.ts"; import { RemoteTeammates } from "./remote-teammates.ts"; import { createRemoteHandoff, isRemoteBotId } from "./host/remote-teammate-handoff.ts";@@ -1786,7 +1786,7 @@ const MAX_COMMS_DEPTH = 1;const MAX_WORKSPACE_BOTS = 100;const phoneProxyPath = SPAWNED_PROXIES.phone;-const researchAvailability = createResearchAvailability({ credential: () => researchCredential(cfg.treg?.key) }); researchAvailability.available(); const localVmAvailability = createLocalVmAvailability(() => containerRuntimeStatus());+const researchAvailability = createResearchAvailability({ credential: () => researchCredential(cfg.treg?.key) }); researchAvailability.available(); const localVmAvailability = createLocalVmAvailability(() => containerRuntimeStatus(), Date.now, afterLaunchSettles);function agentsIntegration(botId: string,threadId: string,@@ -6212,11 +6212,11 @@ function releaseLocalVmThread(threadId: string): void {localVmThreadTargets.delete(threadId);}-void recoverLocalVms({+afterLaunchSettles(() => void recoverLocalVms({mode: localVmMode(cfg), seats: localVmMaxInstances(cfg), bots: store.bots, seen: localVmSeen,status: (target) => containerComputerStatus(undefined, undefined, target).catch(() => null),note: noteLocalVmSeen, armIdle: (target) => localVmIdleFor(target).touch(),-}).then(() => localVmUpdates.sweep()).catch(() => {});+}).then(() => localVmUpdates.sweep()).catch(() => {}));async function localVmInventoryPayload() {const runtime = await containerRuntimeStatus();@@ -15126,7 +15126,7 @@ server.listen(PORT, listenHost(server), async () => {console.log(`openmausbot server on http://127.0.0.1:${PORT}`); launchListening();personWaits.boot(); handoffRequests.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); startCloudTeamRoster({ cloudHome: CLOUD_HOME, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, ownKey: () => composio.connectionMode(cfg) === "self-hosted", apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); checkpointSeeds.start(); });- followupsReady = true; engineUpdates.start();+ followupsReady = true; afterLaunchSettles(() => engineUpdates.start());drainQueuedSends();drainQueuedChannelSends();void cloudComputerPower.armRunning();diff --git a/server/local-vm-availability.test.ts b/server/local-vm-availability.test.tsindex b63f2d0cc2..b88d46ff2f 100644--- a/server/local-vm-availability.test.ts+++ b/server/local-vm-availability.test.ts@@ -53,4 +53,17 @@ describe("whether this server can give a bot a Local VM", () => {await flush();expect(availability.available()).toBe(true);});++ it("holds its first read until the caller starts it (the desktop window in use), reading as usable meanwhile", async () => {+ let probes = 0;+ let start: (() => void) | null = null;+ const availability = createLocalVmAvailability(async () => { probes += 1; return { available: [] }; }, Date.now, (first) => { start = first; });+ await flush();+ expect(probes).toBe(0);+ expect(availability.available()).toBe(true);+ start!();+ await flush();+ expect(probes).toBe(1);+ expect(availability.available()).toBe(false);+ });});diff --git a/server/local-vm-availability.ts b/server/local-vm-availability.tsindex cf050b9ae6..16aa27dbcd 100644--- a/server/local-vm-availability.ts+++ b/server/local-vm-availability.ts@@ -9,7 +9,8 @@ export interface LocalVmRuntimeStatus {const RECHECK_MS = 60_000;-export function createLocalVmAvailability(probe: () => Promise<LocalVmRuntimeStatus>, now: () => number = Date.now) {+/** `start`: when the first check runs (the desktop app holds it until its window is in use); until then it reads as usable. */+export function createLocalVmAvailability(probe: () => Promise<LocalVmRuntimeStatus>, now: () => number = Date.now, start: (first: () => void) => void = (first) => first()) {let usable = true;let checkedAt = 0;let checking = false;@@ -25,7 +26,7 @@ export function createLocalVmAvailability(probe: () => Promise<LocalVmRuntimeSta.catch(() => {}).finally(() => { checking = false; });};- check();+ start(check);return {available: () => {if (!usable && now() - checkedAt >= RECHECK_MS) check();diff --git a/server/model-manifest/manifest.ts b/server/model-manifest/manifest.tsindex 9a462858b6..cada43f830 100644--- a/server/model-manifest/manifest.ts+++ b/server/model-manifest/manifest.ts@@ -8,6 +8,7 @@ import { writeFileAtomic } from "../atomic.ts";import { DATA_DIR } from "../config.ts";import type { ModelCatalog } from "../contracts.ts";import { parseVersionTriple, versionAtLeast, type VersionTriple } from "../drivers/acp/version-probe.ts";+import { afterLaunchSettles } from "../perf/launch-probe.ts";import { BUNDLED_MODEL_MANIFEST, bundledEngineCatalog, engineCatalogFrom } from "./bundled.ts";import { parseModelManifest, type ManifestEngine, type ManifestPrice, type ModelManifestData } from "./schema.ts";@@ -231,7 +232,7 @@ let backgroundTimer: ReturnType<typeof setInterval> | undefined;/** A sleeping machine's timers pause; the on-demand refresh covers the picker when it wakes. */export function startModelManifestRefresh(): void {if (backgroundTimer) return;- modelManifest().refreshInBackground();+ afterLaunchSettles(() => modelManifest().refreshInBackground()); // a download, after the desktop window is in usebackgroundTimer = setInterval(() => modelManifest().refreshInBackground(), MANIFEST_TTL_MS);backgroundTimer.unref();}diff --git a/server/perf/launch-probe.test.ts b/server/perf/launch-probe.test.tsnew file mode 100644index 0000000000..c49c9788f1--- /dev/null+++ b/server/perf/launch-probe.test.ts@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from "vitest";++const saved = process.env.OMB_DESKTOP_PARENT;+afterEach(() => {+ if (saved === undefined) delete process.env.OMB_DESKTOP_PARENT; else process.env.OMB_DESKTOP_PARENT = saved;+ vi.useRealTimers();+ vi.resetModules();+});++async function probe(desktop: boolean) {+ vi.resetModules();+ if (desktop) process.env.OMB_DESKTOP_PARENT = "1"; else delete process.env.OMB_DESKTOP_PARENT;+ return import("./launch-probe.ts");+}++describe("start-up work the desktop window does not need", () => {+ it("runs at once on any server the desktop app did not start (a Cloud home, a self-hosted one)", async () => {+ const { afterLaunchSettles } = await probe(false);+ const ran: string[] = [];+ afterLaunchSettles(() => ran.push("sampler"));+ expect(ran).toEqual(["sampler"]);+ });++ it("waits under the desktop app until a launch part says the window is in use, then runs in order, and later work at once", async () => {+ const { afterLaunchSettles, launchSettled } = await probe(true);+ const ran: string[] = [];+ afterLaunchSettles(() => ran.push("runtime check"));+ afterLaunchSettles(() => { throw new Error("one failing step"); });+ afterLaunchSettles(() => ran.push("update check"));+ expect(ran).toEqual([]);+ vi.spyOn(console, "warn").mockImplementation(() => {});+ launchSettled();+ expect(ran).toEqual(["runtime check", "update check"]);+ launchSettled();+ afterLaunchSettles(() => ran.push("later"));+ expect(ran).toEqual(["runtime check", "update check", "later"]);+ });++ it("runs anyway a while after listening when no window ever reports in", async () => {+ vi.useFakeTimers();+ const { afterLaunchSettles, launchListening, SETTLE_AT_MOST_MS } = await probe(true);+ const ran: string[] = [];+ afterLaunchSettles(() => ran.push("runtime check"));+ launchListening();+ vi.advanceTimersByTime(SETTLE_AT_MOST_MS - 1);+ expect(ran).toEqual([]);+ vi.advanceTimersByTime(1);+ expect(ran).toEqual(["runtime check"]);+ });+});diff --git a/server/perf/launch-probe.ts b/server/perf/launch-probe.tsindex a7b95f6468..1ef8e1c781 100644--- a/server/perf/launch-probe.ts+++ b/server/perf/launch-probe.ts@@ -14,10 +14,36 @@ const watch = process.env.OMB_DESKTOP_PARENT === "1"if (watch) setTimeout(() => watch.finish(), WATCH_AT_MOST_MS).unref();let listeningAt = 0;+/** A desktop launch whose window never reports in (a start into a Cloud's page, a crashed page) still lets its waiting+ * work run this long after the server listens. */+export const SETTLE_AT_MOST_MS = 15_000;+let settled = watch === null;+const waiting: Array<() => void> = [];+const run = (work: () => void) => { try { work(); } catch (error) { console.warn("launch: deferred start-up work failed", error); } };+export function launchListening(): void {+ if (!listeningAt && !settled) setTimeout(launchSettled, SETTLE_AT_MOST_MS).unref();listeningAt ||= Date.now();}+/**+ * Start-up work the first window does not need (container runtime checks, the process sampler, update and model-list+ * downloads): under the desktop app it waits until the app's window is in use, so it does not compete with the page+ * the person is waiting for. That is when a part of the launch record arrives (the main process sends its part two+ * seconds after the window shows, or at once for a start out of sight; the page sends its part once the chat is drawn),+ * or SETTLE_AT_MOST_MS after listening. Any other server (a Cloud home, a self-hosted one) runs it at once, as before.+ */+export function afterLaunchSettles(work: () => void): void {+ if (settled) run(work); else waiting.push(work);+}++/** The window is in use (perf-host calls this for each launch part it takes): everything waiting runs, in order. */+export function launchSettled(): void {+ if (settled) return;+ settled = true;+ for (const work of waiting.splice(0)) run(work);+}+export function launchServerPart(): { startedAt: number; listeningAt: number; children: unknown; net: unknown } | null {return watch && listeningAt ? { startedAt: performance.timeOrigin, listeningAt, ...watch.finish() } : null;}diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.tsindex e5fb36385f..b896080516 100644--- a/server/perf/perf-host.ts+++ b/server/perf/perf-host.ts@@ -17,6 +17,7 @@ import { createSetupClock, type SetupClock, type SetupMs } from "./setup-steps.timport type { FailoverWhy } from "./turn-record.ts";import { createTurnTimings, type Refusal, type SlowNote, type TurnTimings } from "./turn-timings.ts";import { createLaunchTimings, LAUNCH_FILE, type LaunchTimings } from "./launch-timings.ts";+import { afterLaunchSettles, launchSettled } from "./launch-probe.ts";import { startStallWatch, stallReportLines, type StallWatch } from "./stall-watch.ts";import { turnStartsSection } from "./turn-starts.ts";@@ -130,7 +131,8 @@ export function createPerfHost(deps: PerfHostDeps) {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();+ let stopped = false; // the first sample's `ps` waits for the desktop window (launch-probe.ts); elsewhere it starts at once+ if (deps.timer !== false && !windows) afterLaunchSettles(() => { if (!stopped) sampler.start(); });const stalls = deps.stalls ?? createLoopStalls({ resumed: (ms) => say("sleep", `the computer slept or the server was paused: the event loop waited through a ${duration(ms)} gap, not counted as a stall`) });if (deps.timer !== false) stalls.start();const watch: StallWatch | null = deps.timer !== false && deps.watchStalls === true@@ -161,7 +163,11 @@ export function createPerfHost(deps: PerfHostDeps) {setupClock: (): SetupClock => createSetupClock(),noteSetup: (threadId: string, ms: SetupMs) => guarded("setup", () => timings.noteSetup(threadId, ms), undefined),/** A part of the app's launch from its main process or its page; null where no app starts this server. */- noteLaunch: (part: unknown) => (launches ? guarded("launch", () => launches.note(part), { ok: false, complete: false }) : null),+ noteLaunch: (part: unknown) => {+ const noted = launches ? guarded("launch", () => launches.note(part), { ok: false, complete: false }) : null;+ if (noted?.ok) launchSettled();+ return noted;+ },/** Logs a usage-limit hold that started or ended since the last check; the sampler runs it after each sample. */checkHolds: watchHolds,health: (): PerfHealth | null => guarded("health", () => perfHealth(sources()), null),@@ -182,7 +188,7 @@ export function createPerfHost(deps: PerfHostDeps) {...guarded("turn-starts", () => turnStartsSection(), [])].join("\n");},/** The graceful shutdown: no more samples, and the turns since the last save written now. */- stop() { sampler.stop(); stalls.stop(); watch?.stop(); void disk?.stop(); guarded("save", () => timings.flush(), undefined); if (launches) guarded("launch", () => launches.flush(), undefined); },+ stop() { stopped = true; sampler.stop(); stalls.stop(); watch?.stop(); void disk?.stop(); guarded("save", () => timings.flush(), undefined); if (launches) guarded("launch", () => launches.flush(), undefined); },};}export type PerfHost = ReturnType<typeof createPerfHost>;diff --git a/src/components/PageBoundary.tsx b/src/components/PageBoundary.tsxindex b5afe14568..ce0f99a363 100644--- a/src/components/PageBoundary.tsx+++ b/src/components/PageBoundary.tsx@@ -1,6 +1,7 @@-import { Component, type ReactNode } from "react";+import { Component, type ErrorInfo, type ReactNode } from "react";import { initAnalytics, track } from "@/lib/analytics";+import { crashArea } from "@/lib/crash-area";import { t } from "@/lib/i18n";// React unmounts everything below a root that has no error boundary when a render or an effect throws (react.dev,@@ -12,9 +13,10 @@ export class PageBoundary extends Component<{ children: ReactNode }, { error: Erreturn { error: error instanceof Error ? error : new Error(String(error)) };}- componentDidCatch() {+ componentDidCatch(_error: unknown, info: ErrorInfo) {void initAnalytics();- track("app_load", { stage: "error" });+ // The area the failing component came from, from a fixed list (crash-area.ts); never the error's text.+ track("app_load", { stage: "error", component: crashArea(info.componentStack) });}render() {diff --git a/src/lib/app-load.ts b/src/lib/app-load.tsindex 415f4bb919..7fd50bbda3 100644--- a/src/lib/app-load.ts+++ b/src/lib/app-load.ts@@ -1,6 +1,7 @@import { useEffect, useRef } from "react";import { track } from "@/lib/analytics";import { allow, APP_LOAD_WAITING } from "@/lib/analytics-allowlist";+import { LIVE_PHASES, livePhase } from "@/lib/live-events";import { useStore } from "@/state/store";export const SLOW_LOAD_MS = 30_000;@@ -16,7 +17,7 @@ export function loadWaitingFor(state: LoadState): (typeof APP_LOAD_WAITING)[numbconst sincePageStart = () => Math.round(performance.now() / 100) / 10;/** Once per page: when the app has its server, its data and its settings (`ready`), or that it still waits for one of- * them SLOW_LOAD_MS after the page started (`slow`). */+ * them SLOW_LOAD_MS after the page started (`slow`), with what its live connection is doing then (`phase`). */export function useAppLoadSignal(): void {const { state } = useStore();const waiting = loadWaitingFor(state);@@ -32,7 +33,7 @@ export function useAppLoadSignal(): void {const timer = setTimeout(() => {if (sent.current.ready || sent.current.slow) return;sent.current.slow = true;- track("app_load", { stage: "slow", waiting: allow(waiting, APP_LOAD_WAITING) });+ track("app_load", { stage: "slow", waiting: allow(waiting, APP_LOAD_WAITING), phase: allow(livePhase(), LIVE_PHASES) });}, Math.max(0, SLOW_LOAD_MS - performance.now()));return () => clearTimeout(timer);}, [waiting]);diff --git a/src/lib/crash-area.test.ts b/src/lib/crash-area.test.tsnew file mode 100644index 0000000000..d7c54eba48--- /dev/null+++ b/src/lib/crash-area.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";++import { crashArea } from "./crash-area";++describe("the area a page crash came from", () => {+ it("names the built file of the component that threw, never the minified component name", () => {+ const stack = "\n at Xt (http://127.0.0.1:8799/assets/SettingsModal-Bq3x_9aZ.js:3:1204)\n at div\n at Ve (http://127.0.0.1:8799/assets/App-BM6OOWwA.js:12:345)";+ expect(crashArea(stack)).toBe("SettingsModal");+ expect(crashArea("\n at div\n at Suspense\n at Ve (http://127.0.0.1:8799/assets/App-BM6OOWwA.js:12:345)")).toBe("App");+ expect(crashArea("\n at Ve (https://tenant.mausbot.cloud/assets/index-AbCdEf12.js:1:2)")).toBe("index");+ });++ it("names a source module in development", () => {+ expect(crashArea("\n at ChatPane (http://localhost:5173/src/components/SettingsModal.tsx?t=1732000000000:44:9)")).toBe("SettingsModal");+ });++ it("says other for anything not on its list: a library chunk, a page from elsewhere, no stack", () => {+ expect(crashArea("\n at q (http://127.0.0.1:8799/assets/mermaid.core-AbCdEf12.js:1:2)")).toBe("other");+ expect(crashArea("\n at q (https://example.test/assets/PrivateThing-AbCdEf12.js:1:2)")).toBe("other");+ expect(crashArea("\n at Something (http://localhost:5173/src/components/Not-A-Known-File.tsx:1:2)")).toBe("other");+ expect(crashArea(undefined)).toBe("other");+ expect(crashArea("")).toBe("other");+ });+});diff --git a/src/lib/crash-area.ts b/src/lib/crash-area.tsnew file mode 100644index 0000000000..25d3b77472--- /dev/null+++ b/src/lib/crash-area.ts@@ -0,0 +1,32 @@+// Where a page crash happened, by a fixed word: the script file the failing component came from. A built page's+// component names are shortened by the minifier, but its files keep their module's name (App, SettingsModal, ...), and a+// component stack names the file each component came from. Only a name from CRASH_AREAS leaves; any other is "other".+export const CRASH_AREAS = [+ "App", "index", "rail", "ActivityPanel", "AnnouncementsPage", "AppEventEditor", "BotSettingsDialog",+ "BrowserDesktop", "BrowserPanel", "BrowserProfilesManager", "CloudAddDialog", "CommandAllowlistDialog",+ "ComputerFilesPane", "ComputerPanel", "CookieImportDialog", "DataPanel", "DesktopViewer", "EnginesSettings",+ "FilesView", "GrokMoveDialog", "ImportDialog", "InboxPanel", "InspectorPanel", "KeyboardShortcutsModal",+ "LiveDesktop", "LocalVmWorkspace", "MacLocalControl", "MarkdownFilePreview", "MenuMotion", "NewBotDialog",+ "PhoneAppDialog", "PlacesRail", "PluginsPanel", "ProIntroduction", "PublishedAppsPage",+ "RemoteAgentSettingsPanel", "RoomPanel", "RoutinesPage", "SavedWorkflowsCard", "ServerPairingCard",+ "SettingsModal", "ShareBotDialog", "ShareDepartmentDialog", "SignedInSites", "SkillBurgersPage",+ "TailnetComputers", "TeamDialog", "TeamFilesPage", "TeamLibraryPanel", "TeamMapPage", "TeamSettingsDialog",+ "ToolPageShell", "TraceView", "TriggersPage", "VisibilitySection", "VoiceSettings", "VoiceSetupDialog",+ "WebhookTrigger", "WhatChangedView", "WorksOnGrid",+] as const;+export type CrashArea = (typeof CRASH_AREAS)[number];++const KNOWN = new Set<string>(CRASH_AREAS);+/** A built chunk (`/assets/App-BM6OOWwA.js`) or a source module in development (`/src/components/App.tsx?t=1`). */+const FRAME_FILE = /\/(?:assets\/([A-Za-z][\w.]*?)-[\w-]{8}\.js|src\/(?:[\w-]+\/)*([A-Za-z][\w.-]*?)\.tsx?)(?:[?#][^:)\s]*)?:\d+(?::\d+)?\)?\s*$/;++/** The area of the component that threw: the first frame of React's component stack whose file it can name. */+export function crashArea(componentStack: string | null | undefined): CrashArea | "other" {+ for (const line of String(componentStack ?? "").split("\n")) {+ const match = FRAME_FILE.exec(line.trim());+ if (!match) continue;+ const name = match[1] ?? match[2] ?? "";+ return KNOWN.has(name) ? (name as CrashArea) : "other";+ }+ return "other";+}diff --git a/src/lib/live-events.test.ts b/src/lib/live-events.test.tsindex 516366c998..2bba8a4b51 100644--- a/src/lib/live-events.test.ts+++ b/src/lib/live-events.test.ts@@ -5,6 +5,7 @@ import {isLivePing,listenLiveFrames,liveEventsUrl,+ livePhase,openLiveEvents,retryLiveEvents,shouldReconnectLiveEvents,@@ -507,3 +508,22 @@ describe("live screens", () => {stop();});});++describe("the live connection's phase, which the 30-second still-waiting event names", () => {+ it("is opening until the stream opens, open after, retrying once it is lost, offline while the computer is", () => {+ const test = harness();+ const stop = openLiveEvents({ onFrame: () => {}, onSnapshotRequired: async () => true }, test.platform);+ expect(livePhase()).toBe("opening");+ test.sources[0]!.open();+ expect(livePhase()).toBe("open");+ test.setOnline(false);+ test.sources[0]!.error();+ expect(livePhase()).toBe("offline");+ test.setOnline(true);+ test.windowTarget.emit("online");+ expect(livePhase()).toBe("opening");+ test.sources.at(-1)!.error();+ expect(livePhase()).toBe("retrying");+ stop();+ });+});diff --git a/src/lib/live-events.ts b/src/lib/live-events.tsindex 3536d0f79b..5600f0ff82 100644--- a/src/lib/live-events.ts+++ b/src/lib/live-events.ts@@ -12,6 +12,16 @@ export const LIVE_EVENTS_RETRY_MIN_MS = 500;export const LIVE_EVENTS_RETRY_MAX_MS = 10_000;const RETRY_LIVE_EVENTS = "omb:retry-live-events";+/** What the page's live connection is doing, by a fixed word: the app's 30-second "still waiting" event names it. */+export const LIVE_PHASES = ["idle", "opening", "open", "retrying", "offline", "hidden", "asleep"] as const;+export type LivePhase = (typeof LIVE_PHASES)[number];+let livePhaseNow: LivePhase = "idle";+export function livePhase(): LivePhase {+ return livePhaseNow;+}+const holdReason = (platform: Pick<LiveEventsPlatform, "isOnline" | "isVisible">): LivePhase | null =>+ !platform.isOnline() ? "offline" : !platform.isVisible() ? "hidden" : cloudAsleep() ? "asleep" : null;+export function retryLiveEvents(): void {window.dispatchEvent(new Event(RETRY_LIVE_EVENTS));}@@ -245,6 +255,7 @@ export function openLiveEvents(let connect: () => void;const scheduleReconnect = () => {// A Cloud home that went to sleep: reconnecting would wake it. The person's next action does (src/lib/cloud-power.ts).+ if (!stopped) livePhaseNow = holdReason(platform) ?? "retrying";if (stopped || retryTimer !== null || !platform.isOnline() || !platform.isVisible() || cloudAsleep()) return;const exponent = Math.min(retryAttempt, 20);const delay = Math.min(retryMaxMs, retryMinMs * 2 ** exponent);@@ -264,6 +275,7 @@ export function openLiveEvents(};connect = () => {+ if (!stopped && !source) livePhaseNow = (!platform.isOnline() ? "offline" : cloudAsleep() ? "asleep" : null) ?? "opening";if (stopped || source || !platform.isOnline() || cloudAsleep()) return;let current: LiveEventSourceLike;try {@@ -280,6 +292,7 @@ export function openLiveEvents(current.onopen = () => {if (stopped || source !== current) return;lastHeardAt = platform.now();+ livePhaseNow = "open";handlers.onOpen?.();};current.onerror = () => connectionLost(current);