Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Launch: a record of each real launch, and a server that starts listening about 45 ms sooner (#6662)
Milind Sonib5588a013cd0
diff --git a/electron/launch-probes.d.mts b/electron/launch-probes.d.mtsnew file mode 100644index 0000000000..09b189f426--- /dev/null+++ b/electron/launch-probes.d.mts@@ -0,0 +1,17 @@+export interface LaunchWorkCounts {+ children: Array<{ name: string; ms: number }>;+ net: Partial<Record<"accounts" | "cloud" | "updates" | "other", { n: number; ms: number }>>;+}+export function programName(command: unknown, options?: { shell?: boolean }): string;+export function hostKind(target: unknown): "accounts" | "cloud" | "updates" | "other" | null;+export function watchLaunchWork(deps?: {+ childProcess?: Record<string, unknown>;+ sync?: () => void;+ fetchOwners?: Array<{ fetch?: unknown }>;+ now?: () => number;+}): {+ child(command: unknown, ms: number, shell?: boolean): void;+ request(kind: "accounts" | "cloud" | "updates" | "other" | null, ms: number): void;+ counts(): LaunchWorkCounts;+ finish(): LaunchWorkCounts;+};diff --git a/electron/launch-probes.mjs b/electron/launch-probes.mjsnew file mode 100644index 0000000000..0dfcf00bad--- /dev/null+++ b/electron/launch-probes.mjs@@ -0,0 +1,118 @@+// What a launch pays outside our own code, for the launch record: each program a process starts (a fixed name and how+// long it ran) and each request to anything but this computer (the kind of host and how long it took). Plain ESM so the+// main process and the server count the same way. Privacy: a command line, a path, an address or a response never+// leaves here; a program outside PROGRAMS is "other", a host is one of four kinds.+import path from "node:path";+import { promisify } from "node:util";++const PROGRAMS = new Set([+ "sysctl", "ioreg", "scutil", "codesign", "spctl", "security", "open", "defaults", "osascript", "ps", "lsof", "launchctl", "sw_vers", "which", "where",+ "reg", "wmic", "powershell", "cmd", "tasklist", "xdg-mime", "xdg-settings", "gsettings", "dbus-send", "loginctl", "getent", "id",+ "cua-driver", "cloudflared", "tailscale", "git", "node", "claude", "codex", "opencode", "grok", "gemini", "pi", "cursor-agent",+]);+const STARTERS = /^(?:spawn|exec|execFile|fork)(?:Sync)?$/;+const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1", "[::1]", "0.0.0.0"]);+/** A launch that starts this many programs or requests is no longer being measured. */+const KEPT = 200;++/** The name a started program is kept under: its file name without folder or extension when it is a known one.+ * `shell`: the command is a whole command line (exec), whose first word is the program. */+export function programName(command, { shell = false } = {}) {+ if (typeof command !== "string") return "other";+ const file = shell ? command.trim().split(/\s+/)[0] ?? "" : command;+ const base = path.win32.basename(file).toLowerCase().replace(/\.(?:exe|cmd|bat|sh|js|mjs|ts)$/, "");+ return PROGRAMS.has(base) ? base : "other";+}++/** The kind of host a request went to; null for this computer. */+export function hostKind(target) {+ let host;+ try { host = new URL(typeof target === "string" ? target : target?.url ?? String(target)).hostname.toLowerCase(); } catch { return "other"; }+ if (LOOPBACK.has(host)) return null;+ if (host === "github.com" || host.endsWith(".github.com") || host.endsWith(".githubusercontent.com")) return "updates";+ if (host === "accounts.openmausbot.com") return "accounts";+ if (host.endsWith(".openmausbot.com") || host.endsWith(".mausbot.cloud") || host.endsWith(".fly.dev")) return "cloud";+ return "other";+}++/**+ * Counts until `finish()`, which puts everything back and returns the counts. `childProcess` is node:child_process's+ * default export and `sync` node:module's syncBuiltinESMExports, so named imports of it see the wrappers too. Nothing a+ * wrapper does can change or fail the call it wraps.+ * @param {{ childProcess?: Record<string, any>, sync?: () => void, fetchOwners?: Array<Record<string, any>>, now?: () => number }} deps+ */+export function watchLaunchWork({ childProcess, sync = () => {}, fetchOwners = [], now = () => performance.now() } = {}) {+ const children = [];+ const net = {};+ const restore = [];+ let open = true;+ const child = (command, ms, shell = false) => { if (open && children.length < KEPT) children.push({ name: programName(command, { shell }), ms: Math.max(0, ms) }); };+ const request = (kind, ms) => {+ if (!open || !kind) return;+ const entry = (net[kind] ??= { n: 0, ms: 0 });+ entry.n += 1; entry.ms += Math.max(0, ms);+ };+ const quietly = (work) => { try { work(); } catch {} };+ const whenOver = (command, at, started, shell) => quietly(() => {+ const over = () => child(command, now() - at, shell);+ if (typeof started?.once === "function") started.once("exit", over);+ else if (typeof started?.then === "function") started.then(over, over);+ });++ if (childProcess) {+ for (const name of Object.keys(childProcess)) {+ const original = childProcess[name];+ if (typeof original !== "function" || !STARTERS.test(name)) continue;+ const blocking = name.endsWith("Sync");+ const shell = name.startsWith("exec") && !name.startsWith("execFile");+ const wrapper = function (...args) {+ const at = now();+ let started;+ try { started = original.apply(this, args); return started; } finally {+ if (blocking) child(args[0], now() - at, shell); else whenOver(args[0], at, started, shell);+ }+ };+ quietly(() => Object.defineProperties(wrapper, Object.getOwnPropertyDescriptors(original)));+ const promised = original[promisify.custom];+ if (typeof promised === "function") {+ quietly(() => Object.defineProperty(wrapper, promisify.custom, { configurable: true, value(...args) {+ const at = now();+ const pending = promised.apply(this, args);+ whenOver(args[0], at, pending, shell);+ return pending;+ } }));+ }+ childProcess[name] = wrapper;+ restore.push(() => { if (childProcess[name] === wrapper) childProcess[name] = original; });+ }+ quietly(sync);+ }+ for (const owner of fetchOwners) {+ const original = owner?.fetch;+ if (typeof original !== "function") continue;+ const wrapper = function (...args) {+ const at = now();+ const pending = original.apply(this, args);+ quietly(() => { const kind = hostKind(args[0]); if (kind) pending.then(() => request(kind, now() - at), () => request(kind, now() - at)); });+ return pending;+ };+ try { owner.fetch = wrapper; } catch { continue; }+ restore.push(() => { if (owner.fetch === wrapper) owner.fetch = original; });+ }++ const counts = () => ({+ children: children.map((entry) => ({ ...entry, ms: Math.round(entry.ms) })),+ net: Object.fromEntries(Object.entries(net).map(([kind, entry]) => [kind, { n: entry.n, ms: Math.round(entry.ms) }])),+ });+ return {+ /** A program or request timed by the caller itself. */+ child,+ request,+ counts,+ finish() {+ if (open) { for (const undo of restore.splice(0)) quietly(undo); quietly(sync); }+ open = false;+ return counts();+ },+ };+}diff --git a/electron/launch-probes.node-test.mjs b/electron/launch-probes.node-test.mjsnew file mode 100644index 0000000000..e0b0af62c1--- /dev/null+++ b/electron/launch-probes.node-test.mjs@@ -0,0 +1,107 @@+import assert from "node:assert/strict";+import { EventEmitter } from "node:events";+import test from "node:test";+import { promisify } from "node:util";++import { hostKind, programName, watchLaunchWork } from "./launch-probes.mjs";++test("a started program is kept under a fixed name: never its folder, its arguments or a name of its own", () => {+ assert.equal(programName("/usr/sbin/ioreg"), "ioreg");+ assert.equal(programName("C:\\Windows\\System32\\reg.exe"), "reg");+ assert.equal(programName("scutil --proxy", { shell: true }), "scutil");+ assert.equal(programName("scutil --proxy"), "other");+ assert.equal(programName("/Users/ada/Library/Application Support/OpenMausBot/bin/cua-driver"), "cua-driver");+ assert.equal(programName("/Users/ada/Library/Application Support/ioreg helper/tool", { shell: true }), "other");+ assert.equal(programName("/Users/ada/Projects/acme-merger/bin/lookup_customer"), "other");+ assert.equal(programName("/Users/ada/ioreg-secrets/tool"), "other");+ assert.equal(programName(undefined), "other");+ assert.equal(programName({ toString: () => "ioreg" }), "other");+});++test("a request is kept as the kind of its host; this computer is not a request at all", () => {+ assert.equal(hostKind("http://127.0.0.1:8799/api/health"), null);+ assert.equal(hostKind("http://localhost:5173/"), null);+ assert.equal(hostKind("https://accounts.openmausbot.com/token?code=abc"), "accounts");+ assert.equal(hostKind("https://omb-u-1.fly.dev/api/bots"), "cloud");+ assert.equal(hostKind(new URL("https://c-opaque.openmausbot.com/x")), "cloud");+ assert.equal(hostKind({ url: "https://github.com/milind-soni/OpenMausBot/releases" }), "updates");+ assert.equal(hostKind("https://raw.githubusercontent.com/x/y"), "updates");+ assert.equal(hostKind("https://intranet.acme.test/q?token=abc"), "other");+ assert.equal(hostKind("https://github.com.evil.test/"), "other");+ assert.equal(hostKind("not a url"), "other");+});++function fakeChildProcess() {+ const calls = [];+ const execFile = (command, ...rest) => { calls.push(["execFile", command]); const child = new EventEmitter(); queueMicrotask(() => child.emit("exit", 0)); rest.at(-1)?.(null, "out"); return child; };+ execFile[promisify.custom] = (command) => { calls.push(["execFile.promise", command]); return Object.assign(Promise.resolve({ stdout: "out", stderr: "" }), { child: "the child" }); };+ return {+ calls,+ module: {+ execFile,+ spawn: (command) => { calls.push(["spawn", command]); return new EventEmitter(); },+ ["execFile" + "Sync"]: (command) => { calls.push(["blocking", command]); if (command === "fail") throw new Error("exit 1"); return "out"; },+ ChildProcess: class {}, notAStarter: () => "left alone",+ },+ };+}++test("programs are timed without changing what a caller gets back, and finish() puts everything back", async () => {+ const fake = fakeChildProcess();+ const originals = { ...fake.module };+ let clock = 0, synced = 0;+ const watch = watchLaunchWork({ childProcess: fake.module, sync: () => { synced += 1; }, now: () => clock });+ assert.equal(synced, 1);+ assert.notEqual(fake.module.execFile, originals.execFile);+ assert.equal(fake.module.notAStarter, originals.notAStarter);+ assert.equal(fake.module.ChildProcess, originals.ChildProcess);++ const blocking = fake.module["execFile" + "Sync"];+ assert.equal(blocking("/usr/sbin/ioreg"), "out");+ assert.throws(() => blocking("fail"), /exit 1/);+ const spawned = fake.module.spawn("/usr/sbin/scutil");+ clock = 40;+ spawned.emit("exit", 0);+ const promised = promisify(fake.module.execFile)("/Users/ada/bin/acme-tool");+ assert.equal(promised.child, "the child");+ assert.deepEqual(await promised, { stdout: "out", stderr: "" });+ await new Promise((resolve) => setImmediate(resolve));++ assert.deepEqual(watch.counts().children, [{ name: "ioreg", ms: 0 }, { name: "other", ms: 0 }, { name: "scutil", ms: 40 }, { name: "other", ms: 0 }]);+ const counted = watch.finish();+ assert.equal(synced, 2);+ assert.deepEqual({ ...fake.module }, originals);+ fake.module.spawn("ioreg").emit("exit", 0);+ assert.deepEqual(watch.finish(), counted);+ assert.deepEqual(fake.calls.map(([kind]) => kind), ["blocking", "blocking", "spawn", "execFile.promise", "spawn"]);+});++test("requests off this computer are counted by kind while the same promise is handed back; failures count too", async () => {+ let clock = 0;+ const answers = [];+ const owner = { fetch(url) { const answer = url.includes("down") ? Promise.reject(new Error("offline")) : Promise.resolve({ ok: true }); answers.push(answer); return answer; } };+ const original = owner.fetch;+ const frozen = Object.freeze({ fetch: () => Promise.resolve() });+ const watch = watchLaunchWork({ fetchOwners: [owner, frozen, {}, null], now: () => clock });+ const first = owner.fetch("https://accounts.openmausbot.com/token?code=abc");+ assert.equal(first, answers[0]);+ clock = 120;+ await first;+ await assert.rejects(owner.fetch("https://down.example.test/x"), /offline/);+ await owner.fetch("http://127.0.0.1:8799/api/health");+ await owner.fetch("https://omb-u-1.fly.dev/a");+ await owner.fetch("https://omb-u-1.fly.dev/b");+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(watch.finish().net, { accounts: { n: 1, ms: 120 }, other: { n: 1, ms: 0 }, cloud: { n: 2, ms: 0 } });+ assert.equal(owner.fetch, original);+});++test("a watch with nothing to watch counts what it is told and never throws", () => {+ const watch = watchLaunchWork();+ watch.child("/usr/sbin/sysctl", 3.4);+ watch.request("updates", 20.6);+ watch.request(null, 5);+ assert.deepEqual(watch.finish(), { children: [{ name: "sysctl", ms: 3 }], net: { updates: { n: 1, ms: 21 } } });+ watch.child("ioreg", 1);+ assert.equal(watch.finish().children.length, 1);+});diff --git a/electron/launch-record-main.mjs b/electron/launch-record-main.mjsnew file mode 100644index 0000000000..e0ecfe7c32--- /dev/null+++ b/electron/launch-record-main.mjs@@ -0,0 +1,19 @@+// This launch's record, made before anything else in the main process runs so the first mark is our code starting.+import { app, net } from "electron";+import childProcess from "node:child_process";+import { syncBuiltinESMExports } from "node:module";++import { watchLaunchWork } from "./launch-probes.mjs";+import { createLaunchRecord } from "./launch-record.mjs";++// Electron: process.getCreationTime() is null when the OS will not say; this module's own start stands in.+const processStart = process.getCreationTime() ?? performance.timeOrigin;++export const launchRecord = createLaunchRecord({+ processStart, appVersion: app.getVersion(), platform: process.platform, arch: process.arch,+ watch: watchLaunchWork({ childProcess, sync: syncBuiltinESMExports, fetchOwners: [globalThis, net] }),+});+// A launch whose record is not written by then (no server came up) stops being counted.+setTimeout(() => launchRecord.giveUp(), 120_000).unref();+launchRecord.mark("codeStart");+launchRecord.watchWindows(app);diff --git a/electron/launch-record.mjs b/electron/launch-record.mjsnew file mode 100644index 0000000000..03ecd3f64d--- /dev/null+++ b/electron/launch-record.mjs@@ -0,0 +1,109 @@+// The main process's part of the launch record: when each step of this start was reached, counted from the process's+// own start, and what the start paid for outside our code (launch-probes.mjs). Clock reads only; the part is handed to+// the local server once the window is up, and a launch whose hand-over fails loses its record and nothing else.+import { watchLaunchWork } from "./launch-probes.mjs";++/** After the main window shows, the page still draws the chat: the part is sent once that has had time to happen. */+export const SEND_AFTER_SHOWN_MS = 2_000;+/** Later tries, when the server was not there or had not written the record yet. */+export const RETRY_AFTER_MS = [10_000, 30_000, 90_000];++/**+ * @param {{+ * processStart: number, launchId?: string | null, appVersion: string, platform: string, arch: string,+ * now?: () => number, watch?: ReturnType<typeof watchLaunchWork>,+ * setTimer?: (run: () => void, ms: number) => unknown,+ * }} options `processStart` and `now` are epoch ms on one clock.+ */+export function createLaunchRecord({ processStart, launchId = null, appVersion, platform, arch, now = () => performance.timeOrigin + performance.now(), watch = watchLaunchWork(), setTimer = (run, ms) => setTimeout(run, ms).unref?.() }) {+ const marks = {};+ const spans = {};+ const begun = {};+ let hidden = false;+ let post = null;+ let tries = 0, sending = false, done = false, waiting = false;++ const mark = (name) => { marks[name] ??= Math.max(0, Math.round(now() - processStart)); };+ const part = () => ({ from: "main", launchId, processStart: Math.round(processStart), appVersion, platform, arch, hidden, marks: { ...marks }, spans: { ...spans }, ...watch.counts() });+ const stop = () => { done = true; watch.finish(); };++ async function send() {+ if (done || sending || !post) return;+ sending = true;+ tries += 1;+ let complete = false;+ try { complete = (await post(part()))?.complete === true; } catch {}+ sending = false;+ if (complete || tries > RETRY_AFTER_MS.length) { stop(); return; }+ waiting = true;+ setTimer(() => { waiting = false; void send(); }, RETRY_AFTER_MS[tries - 1]);+ }+ const sendSoon = () => {+ if (done || waiting || sending) return;+ waiting = true;+ setTimer(() => { waiting = false; void send(); }, SEND_AFTER_SHOWN_MS);+ };++ return {+ mark,+ begin(name) { begun[name] = now(); },+ end(name) { if (begun[name] !== undefined) spans[name] ??= Math.max(0, Math.round(now() - begun[name])); },+ /** Times one awaited step and hands back its result untouched. */+ span(name, work) {+ const at = now();+ const finish = () => { spans[name] ??= Math.max(0, Math.round(now() - at)); };+ const pending = Promise.resolve().then(work);+ pending.then(finish, finish);+ return pending;+ },+ /** The id the server child of this launch is given; the server takes a part under no other. */+ setLaunchId(id) { launchId = id; },+ /** Started out of sight: no window will show, so the part goes once the server is ready. */+ setHidden(value) { hidden = Boolean(value); },+ /** `send(body)` posts the part to the local server and resolves to its JSON answer. */+ deliverWith(send) { post = send; },+ /** The server is ready (again): a part not yet recorded is sent, a hidden start's for the first time. */+ serverReady() { mark("serverReady"); if (hidden || marks.windowShown !== undefined) sendSoon(); },+ /**+ * The splash is the window that loads a data: page, the main window the first that loads a web page. A window's+ * "shown" mark is the first call that shows it.+ * @param {{ on(event: string, listener: (...args: any[]) => void): unknown }} app+ */+ watchWindows(app) {+ const made = new Map();+ const role = new Map();+ const shown = (contents, name) => {+ if (!name || role.get(contents) !== name) return;+ mark(`${name}Shown`);+ if (name === "window") sendSoon();+ };+ app.on("browser-window-created", (_event, win) => {+ if (done) return;+ const contents = win.webContents;+ made.set(contents, Math.max(0, Math.round(now() - processStart)));+ let visible = false;+ const showing = () => { visible = true; shown(contents, role.get(contents)); };+ // Electron emits "show" only when the main thread is next free, which a busy launch delays: the call is the mark.+ for (const method of ["show", "showInactive"]) {+ const original = win[method];+ if (typeof original === "function") win[method] = function (...args) { try { showing(); } catch {} return original.apply(this, args); };+ }+ win.once("show", showing);+ contents.on("did-start-navigation", (details) => {+ if (done || role.has(contents) || !details?.isMainFrame || details.isSameDocument) return;+ const url = String(details.url ?? "");+ const name = url.startsWith("data:") ? "splash" : /^https?:/.test(url) ? "window" : null;+ if (!name || [...role.values()].includes(name)) return;+ role.set(contents, name);+ marks[`${name}Made`] ??= made.get(contents);+ if (name === "window") mark("windowNavigated");+ if (visible) shown(contents, name);+ });+ });+ },+ part,+ /** No record will be written for this launch: the probes are put back. */+ giveUp() { if (!done) stop(); },+ get done() { return done; },+ };+}diff --git a/electron/launch-record.node-test.mjs b/electron/launch-record.node-test.mjsnew file mode 100644index 0000000000..3713fa7233--- /dev/null+++ b/electron/launch-record.node-test.mjs@@ -0,0 +1,181 @@+import assert from "node:assert/strict";+import { EventEmitter } from "node:events";+import test from "node:test";++import { watchLaunchWork } from "./launch-probes.mjs";+import { createLaunchRecord, RETRY_AFTER_MS, SEND_AFTER_SHOWN_MS } from "./launch-record.mjs";++const START = 1_800_000_000_000;++function fixture({ answers = [] } = {}) {+ const state = { clock: START, timers: [], posts: [], finished: 0 };+ const watch = watchLaunchWork({ now: () => state.clock });+ const finish = watch.finish;+ watch.finish = () => { state.finished += 1; return finish(); };+ const record = createLaunchRecord({+ processStart: START, launchId: "launch-0001", appVersion: "0.1.170", platform: "darwin", arch: "arm64", now: () => state.clock, watch,+ setTimer: (run, ms) => { state.timers.push({ run, ms }); },+ });+ record.deliverWith(async (part) => {+ state.posts.push(part);+ const answer = answers.shift();+ if (answer instanceof Error) throw answer;+ return answer ?? { ok: true, complete: false };+ });+ const runTimer = async () => { const timer = state.timers.shift(); timer.run(); await new Promise((resolve) => setImmediate(resolve)); return timer.ms; };+ return { state, record, watch, runTimer };+}++function fakeWindow(app) {+ const win = new EventEmitter();+ win.webContents = new EventEmitter();+ win.shows = 0;+ win.show = () => { win.shows += 1; };+ app.emit("browser-window-created", {}, win);+ return win;+}+const navigate = (win, url, extra = {}) => win.webContents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false, url, ...extra });++test("a mark is the first time its step is reached, counted from the process's start", () => {+ const { state, record } = fixture();+ state.clock = START + 180.4;+ record.mark("ready");+ state.clock = START + 900;+ record.mark("ready");+ record.begin("lease");+ state.clock += 25;+ record.end("lease");+ record.end("never-begun");+ assert.deepEqual(record.part(), {+ from: "main", launchId: "launch-0001", processStart: START, appVersion: "0.1.170", platform: "darwin", arch: "arm64", hidden: false,+ marks: { ready: 180 }, spans: { lease: 25 }, children: [], net: {},+ });+});++test("a timed step hands back its own result or its own failure", async () => {+ const { state, record } = fixture();+ const pending = record.span("keychain", async () => { state.clock += 12; return { key: "kept" }; });+ assert.deepEqual(await pending, { key: "kept" });+ await assert.rejects(record.span("lease", () => { throw new Error("locked"); }), /locked/);+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(record.part().spans, { keychain: 12, lease: 0 });+});++test("the splash and the main window are told apart by what they load, and shown is the call that shows them", () => {+ const { state, record } = fixture();+ const app = new EventEmitter();+ record.watchWindows(app);+ state.clock = START + 250;+ const splash = fakeWindow(app);+ navigate(splash, "data:text/html;charset=utf-8,%3C!doctype");+ state.clock = START + 330;+ splash.show();+ state.clock = START + 420;+ splash.emit("show");+ state.clock = START + 850;+ const main = fakeWindow(app);+ navigate(main, "http://127.0.0.1:8799/#frame", { isMainFrame: false });+ navigate(main, "http://127.0.0.1:8799/#same", { isSameDocument: true });+ state.clock = START + 855;+ navigate(main, "http://127.0.0.1:8799/");+ state.clock = START + 990;+ main.show();+ state.clock = START + 5_000;+ const later = fakeWindow(app);+ navigate(later, "https://omb-u-1.fly.dev/");+ later.show();+ assert.deepEqual(record.part().marks, { splashMade: 250, splashShown: 330, windowMade: 850, windowNavigated: 855, windowShown: 990 });+ assert.deepEqual([splash.shows, main.shows, later.shows], [1, 1, 1]);+ assert.deepEqual(state.timers.map((timer) => timer.ms), [SEND_AFTER_SHOWN_MS]);+});++test("a window shown before it loads anything is marked once it is known to be the main window", () => {+ const { state, record } = fixture();+ const app = new EventEmitter();+ record.watchWindows(app);+ state.clock = START + 700;+ const main = fakeWindow(app);+ main.emit("show");+ state.clock = START + 760;+ navigate(main, "https://omb-u-1.fly.dev/");+ assert.deepEqual(record.part().marks, { windowMade: 700, windowNavigated: 760, windowShown: 760 });+});++test("the part goes once after the window shows; the server saying the record is written ends it", async () => {+ const { state, record, runTimer } = fixture({ answers: [{ ok: true, complete: true }] });+ const app = new EventEmitter();+ record.watchWindows(app);+ record.serverReady();+ assert.equal(state.timers.length, 0);+ const main = fakeWindow(app);+ navigate(main, "http://127.0.0.1:8799/");+ main.show();+ main.show();+ record.serverReady();+ assert.equal(state.timers.length, 1);+ assert.equal(await runTimer(), SEND_AFTER_SHOWN_MS);+ assert.equal(state.posts.length, 1);+ assert.equal(record.done, true);+ assert.equal(state.finished, 1);+ record.serverReady();+ fakeWindow(app).show();+ assert.equal(state.timers.length, 0);+});++test("a server that is late, or restarts before the record is written, is asked again a bounded number of times", async () => {+ const { state, record, runTimer } = fixture({ answers: [new Error("not running"), { ok: true, complete: false }, { ok: true, complete: true }] });+ record.setHidden(true);+ record.serverReady();+ const waits = [await runTimer(), await runTimer(), await runTimer()];+ assert.deepEqual(waits, [SEND_AFTER_SHOWN_MS, RETRY_AFTER_MS[0], RETRY_AFTER_MS[1]]);+ assert.equal(state.posts.length, 3);+ assert.equal(state.posts[2].hidden, true);+ assert.equal(record.done, true);+ assert.equal(state.timers.length, 0);+});++test("a launch whose hand-over never works stops trying, puts the probes back and throws nowhere", async () => {+ const failures = Array.from({ length: 10 }, () => new Error("not running"));+ const { state, record, runTimer } = fixture({ answers: failures });+ record.setHidden(true);+ record.serverReady();+ record.serverReady();+ const waits = [];+ while (state.timers.length) waits.push(await runTimer());+ assert.deepEqual(waits, [SEND_AFTER_SHOWN_MS, ...RETRY_AFTER_MS]);+ assert.equal(state.posts.length, RETRY_AFTER_MS.length + 1);+ assert.equal(record.done, true);+ assert.equal(state.finished, 1);+ record.serverReady();+ assert.equal(state.timers.length, 0);+});++test("the part carries the launch id it is given once the main process has made one", () => {+ const record = createLaunchRecord({ processStart: START, appVersion: "0.1.170", platform: "darwin", arch: "arm64" });+ assert.equal(record.part().launchId, null);+ record.setLaunchId("launch-0002");+ assert.equal(record.part().launchId, "launch-0002");+});++test("a launch given up on puts the probes back once and sends nothing more", async () => {+ const { state, record } = fixture();+ record.setHidden(true);+ record.giveUp();+ record.giveUp();+ assert.equal(state.finished, 1);+ assert.equal(record.done, true);+ record.serverReady();+ assert.equal(state.timers.length, 0);+ assert.equal(state.posts.length, 0);+});++test("with nowhere to send it, the record costs marks only", async () => {+ const state = { timers: [] };+ const record = createLaunchRecord({ processStart: START, launchId: "launch-0001", appVersion: "0.1.170", platform: "darwin", arch: "arm64", setTimer: (run, ms) => { state.timers.push({ run, ms }); } });+ record.setHidden(true);+ record.serverReady();+ state.timers.shift().run();+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(state.timers.length, 0);+ assert.equal(record.done, false);+});diff --git a/electron/main.mjs b/electron/main.mjsindex 59ad69c5d5..40753c488d 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -1,4 +1,4 @@-import { app, autoUpdater as nativeAutoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, Menu, nativeImage, Notification, net, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron";+import { launchRecord } from "./launch-record-main.mjs"; import { app, autoUpdater as nativeAutoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, Menu, nativeImage, Notification, net, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron";import { createRequire } from "node:module";import { randomBytes, randomUUID } from "node:crypto";import fs from "node:fs";@@ -289,12 +289,12 @@ let companyBackupConfigurationRevision = 0;const managedDesktopRelay = createManagedDesktopRelay();const includedX = createDesktopIncludedX({ account: () => cloudAccount, server: () => serverProc, log: slog }), includedPages = createDesktopIncludedPages({ account: () => cloudAccount, server: () => serverProc, log: slog }), phoneLinkFact = createPhoneLinkFact({ retired: () => companionTunnelRetired(secureCredentialState?.read() ?? secureCredentials), server: () => (serverReady ? serverProc : null), log: slog }), phonePushAccess = createPhonePushAccessSync({ server: () => (serverReady ? serverProc : null), credentials: () => secureCredentialState?.read() ?? secureCredentials, controlPlane: () => resolveCompanionControlPlaneURL({ isPackaged: app.isPackaged, environment: process.env }), log: slog });const cloudPower = createCloudPowerGate({ power: () => cloudAccount?.power() ?? null, wanted: () => Boolean(cloudSync?.running() || computerSharing?.lendingToCloud()) });-const utilityServerExits = new WeakMap(), systemProxy = createSystemProxyCache(), bootHeadStart = createBootHeadStart({ credentials: () => loadSecureCredentials(), proxy: () => systemProxy.refresh() }); // A Mac app opened from Finder never gets the shell's proxy.+const utilityServerExits = new WeakMap(), systemProxy = createSystemProxyCache(), bootHeadStart = createBootHeadStart({ credentials: () => launchRecord.span("keychain", () => loadSecureCredentials()), proxy: () => systemProxy.refresh() }); launchRecord.mark("mainImported"); // A Mac app opened from Finder never gets the shell's proxy.const UTILITY_SERVER_STOP_TIMEOUT_MS = 9_500; // the server's shutdown deadline (8 s, server/graceful-shutdown.ts) and its 1 s log flushconst trustedApprovalMode = createTrustedApprovalModeCoordinator({ randomId: randomUUID, t: (...args) => nativeT(...args) });const desktopMutationToken = randomBytes(32).toString("base64url");const desktopLaunchId = randomUUID();-const companionMutationToken = randomBytes(32).toString("base64url");+const companionMutationToken = randomBytes(32).toString("base64url"); launchRecord.setLaunchId(desktopLaunchId);const serverSupervisor = createServerSupervisor({restart: () => startServerOn(SERVER_PORT),stop: stopUtilityServer, keepTrying: () => alwaysOnHome.on(),@@ -302,7 +302,7 @@ const serverSupervisor = createServerSupervisor({serverProc = proc;serverReady = true;serverStartConflictOnly = false;- slog(`server ready pid=${proc.pid} port=${SERVER_PORT}`);+ slog(`server ready pid=${proc.pid} port=${SERVER_PORT}`); launchRecord.serverReady();void readCloudOfferBrand();syncManagedComposioCredentials(); includedX.serverStarted(); includedPages.serverStarted(); phoneLinkFact.serverStarted(); phonePushAccess.serverStarted(); railChanged(); void systemProxy.refresh();reportOwnListeners(proc);@@ -1130,7 +1130,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmendelete childEnv.OMB_BROWSER_CONNECTION;delete childEnv.OMB_SERVER_COMPILE_CACHE;if (compileCacheDir) childEnv.OMB_SERVER_COMPILE_CACHE = compileCacheDir;- slog(`fork ${entry} port=${port}`);+ slog(`fork ${entry} port=${port}`); launchRecord.mark("serverForked");const proc = utilityProcess.fork(entry, [], {env: childEnv,stdio: ["ignore", "pipe", "pipe"],@@ -1141,7 +1141,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen}));const listening = listeningSignal();proc.stdout?.on("data", (d) => {- listening.hear(String(d));+ listening.hear(String(d)); if (listening.heard()) launchRecord.mark("serverListening");slog(`[out] ${String(d).trimEnd()}`);});proc.stderr?.on("data", (d) => slog(`[err] ${String(d).trimEnd()}`));@@ -1157,7 +1157,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen}});proc.once("spawn", () => {- slog(`spawned pid=${proc.pid}`); launchAnalytics.stage("server_spawned");+ slog(`spawned pid=${proc.pid}`); launchAnalytics.stage("server_spawned"); launchRecord.mark("serverSpawned");if (!serverSupervisor.isCurrent(proc)) return;syncDesktopMutationToken(proc); void tailnetShare.attach(proc, port, companionSettings().routes.tailscale);syncPhoneSecretKey(proc); grantLocalComputer(proc, (child) => serverSupervisor.isCurrent(child));@@ -1176,7 +1176,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmenpid: () => proc.pid,bootTimeoutMs: SERVER_BOOT_TIMEOUT_MS,isExited: () => exited || desktopShutdownStarted,- isListening: listening.heard,+ isListening: listening.heard, listened: listening.announced,listeningGraceMs: SERVER_LISTENING_GRACE_MS,});if (identity.outcome === "ready" && serverSupervisor.isCurrent(proc)) return { proc };@@ -2576,7 +2576,7 @@ const savedWorkspace = id => {const cloudLook = createCloudLook({ store: lookFile(() => path.join(app.getPath("userData"), cloudTarget(process.env).look), fs), accountId: () => cloudAccount?.state().account?.id ?? null,homeEntry: cloudHomeEntry, saveEntry: (origin, look) => persistEnvironments(withEnvironmentLook(environmentsState, origin, look)) });const cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });-const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running")));+const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running"))); launchRecord.deliverWith((part) => localServerRequest("/api/diagnostics/launch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(part), signal: AbortSignal.timeout(5_000) }).then((res) => res.json()));const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, chooses: true, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); botLink = createBotLinkMain({ wanted: () => placesTogether.on(), pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep(), signedOut: cloudAccount?.state().status === "signed-out" }), cloudName: () => nativeT("cloudSetup.myCloud"), changed: () => placesTogether.linkChanged(), log: slog }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.@@ -2784,7 +2784,7 @@ setCuaStateListener((connection) => {});});-app.whenReady().then(async () => {+app.whenReady().then(async () => { launchRecord.mark("ready");await evictStartupCacheOnce({userData: app.getPath("userData"),currentVersion: app.getVersion(),@@ -2802,7 +2802,7 @@ app.whenReady().then(async () => {slog(`system tray unavailable: ${error?.message ?? error}`);}}- hiddenStart = loginItem.startedHidden() || reopenedOutOfSight(); launchAnalytics.stage("started", { hidden: hiddenStart });+ hiddenStart = loginItem.startedHidden() || reopenedOutOfSight(); launchAnalytics.stage("started", { hidden: hiddenStart }); launchRecord.setHidden(hiddenStart);startupScreen = hiddenStart ? null : createStartupScreen({BrowserWindow, iconPath: APP_ICON, isQuitting: () => desktopShutdownStarted, t: nativeT, lang: nativeText.intlTag(),onQuit: () => app.quit(),@@ -2831,12 +2831,12 @@ app.whenReady().then(async () => {bootDataDir = boot.dataDir;}if (app.isPackaged) {- try {+ try { launchRecord.begin("lease");// Acquire before either plaintext credential migration touches config.json.desktopDataDirLease = acquireDataDirLease(bootDataDir, { t: nativeT,legacyDataDir: path.join(app.getPath("home"), ".opengrokbot"),});- runningDataDir = bootDataDir;+ runningDataDir = bootDataDir; launchRecord.end("lease"); launchRecord.mark("leaseTaken");} catch (error) {dialog.showErrorBox(nativeT("native.boot.unsafe.title"),@@ -2850,7 +2850,7 @@ app.whenReady().then(async () => {ownerToken: () => (app.isPackaged && serverReady ? desktopMutationToken : null) });if (app.isPackaged) app.setAsDefaultProtocolClient("openmausbot");if (process.platform === "darwin") app.dock.setIcon(APP_ICON);- secureCredentials = await bootHeadStart.take("credentials");+ secureCredentials = await bootHeadStart.take("credentials"); launchRecord.mark("keysRead");// An orphaned third-party key with no clear handler left: drop it rather than keep it at rest.if (secureCredentials && Object.hasOwn(secureCredentials, "assemblyAiApiKey") && !credentialStoreUnavailable) {try {diff --git a/electron/server-boot-probe.mjs b/electron/server-boot-probe.mjsindex fb515812d1..3579913ead 100644--- a/electron/server-boot-probe.mjs+++ b/electron/server-boot-probe.mjs@@ -9,14 +9,19 @@ const LISTENING_LINE = "openmausbot server on ";export function listeningSignal() {let tail = "";let heard = false;+ let announce;+ const announced = new Promise((resolve) => { announce = resolve; });return {hear(chunk) {if (heard) return;const text = tail + chunk;tail = text.slice(-LISTENING_LINE.length);heard = text.includes(LISTENING_LINE);+ if (heard) announce();},heard: () => heard,+ /** Settles when the line is heard. */+ announced,};}@@ -38,6 +43,7 @@ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));* isExited?: () => boolean,* isListening?: () => boolean,* listeningGraceMs?: number,+ * listened?: Promise<void>,* now?: () => number,* sleep?: (ms: number) => Promise<void>,* fetchImpl?: typeof fetch,@@ -51,11 +57,14 @@ export async function pollServerIdentity({isExited = () => false,isListening = () => false,listeningGraceMs = 0,+ listened,now = Date.now,sleep = defaultSleep,fetchImpl = globalThis.fetch,}) {const startedAt = now();+ // The child's "listening" line cuts one wait short, so the probe that follows it is not up to an interval late.+ let wake = listened;const deadline = () => startedAt + bootTimeoutMs + (isListening() ? listeningGraceMs : 0);for (;;) {if (isExited()) return { outcome: "exited" };@@ -70,7 +79,8 @@ export async function pollServerIdentity({} catch {const intervalMs =now() - startedAt < BOOT_PROBE_FAST_WINDOW_MS ? BOOT_PROBE_FAST_INTERVAL_MS : BOOT_PROBE_INTERVAL_MS;- await sleep(Math.min(intervalMs, Math.max(1, deadline() - now())));+ const wait = sleep(Math.min(intervalMs, Math.max(1, deadline() - now())));+ await (wake ? Promise.race([wait, wake.then(() => { wake = null; })]) : wait);continue;}const body = await res.json().catch(() => null);diff --git a/electron/server-boot-probe.node-test.mjs b/electron/server-boot-probe.node-test.mjsindex 79347ba38b..d0f04369f4 100644--- a/electron/server-boot-probe.node-test.mjs+++ b/electron/server-boot-probe.node-test.mjs@@ -313,3 +313,30 @@ test("an answer in flight when the child starts listening gets the grace", async});assert.equal(outcome.outcome, "ready");});++test("the listening line ends the wait between probes once; later waits run their full interval", async () => {+ const listening = listeningSignal();+ const waits = [];+ let attempts = 0;+ const outcome = await pollServerIdentity({+ port: 8799,+ pid: () => 4242,+ bootTimeoutMs: 60_000,+ listened: listening.announced,+ now: () => 0,+ sleep: (ms) => new Promise((resolve) => {+ const wait = { ms, done: false, finish: () => { wait.done = true; resolve(); } };+ waits.push(wait);+ if (waits.length === 1) listening.hear("openmausbot server on http://127.0.0.1:8799\n");+ if (waits.length === 2) queueMicrotask(() => queueMicrotask(wait.finish));+ }),+ fetchImpl: async () => {+ attempts += 1;+ if (attempts < 3) throw new Error("refused");+ return { ok: true, status: 200, json: async () => OUR_BODY() };+ },+ });+ assert.equal(outcome.outcome, "ready");+ assert.equal(attempts, 3);+ assert.deepEqual(waits.map((wait) => wait.done), [false, true]);+});diff --git a/scripts/bench-launch.mjs b/scripts/bench-launch.mjsindex 623a02ceda..03773a800b 100644--- a/scripts/bench-launch.mjs+++ b/scripts/bench-launch.mjs@@ -4,12 +4,16 @@// seeded workspace, and one reused profile. Prints one JSON object, so a change can show before/after.// 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]+// [--seed 30,60,300] [--label NAME] [--out FILE] [--no-asar] [--dev] [--server-prof DIR [--server-prof-tail MS]] [--quiet-ms 1500]// --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// 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.+// --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// (the fixture's sealed PATH hides them), the computer-control and browser helpers (not staged), any network call// (all refused and counted in `egress`).@@ -27,7 +31,7 @@ const ROOT = join(HERE, "..");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 },+ 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" },} });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-)");@@ -97,7 +101,7 @@ 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",- OMB_BENCH_EGRESS_LOG: paths.egress,+ 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()); });const devChildren = [];@@ -120,7 +124,7 @@ function launch(name, { prime = false, screenshot = false } = {}) {const out = join(paths.results, `${values.label}-${name}.json`);rmSync(out, { force: true });const config = {- root, resources: staged.resources, blocker: staged.blocker, out, timeoutMs: 60_000, quietMs: 1500, dev: values.dev,+ root, resources: staged.resources, blocker: staged.blocker, out, timeoutMs: 60_000, quietMs: Number(values["quiet-ms"]), dev: values.dev,target: { rows: Math.min(10, Number(values.seed.split(",")[0])), lastMessageId: seeded.bigLastMessageId },...(prime ? { prime: { storage: STORAGE, botId: seeded.bigBotId } } : {}),...(screenshot ? { screenshot: join(paths.results, `${values.label}-${name}.png`) } : {}),diff --git a/scripts/bench-server-start.mjs b/scripts/bench-server-start.mjsnew file mode 100644index 0000000000..a0bf69fcea--- /dev/null+++ b/scripts/bench-server-start.mjs@@ -0,0 +1,130 @@+#!/usr/bin/env node+// The bundled server's start alone, on a fixture folder only: from the fork to its "listening" line and to its first+// answered request, on the Node that Electron ships (ELECTRON_RUN_AS_NODE) or on this one. Prints one JSON object.+// pnpm build:server+// node scripts/bench-server-start.mjs --data /tmp/openmausbot-bench-X/data [--app CHECKOUT] [--runs 15] [--source]+// [--node] [--no-cache] [--cpu-prof DIR] [--label NAME] [--stall-ms N] [--slow-engines N] [--against CHECKOUT]+// --source: server/index.ts under --experimental-strip-types instead of the bundle. --node: this Node, not Electron's.+// --no-cache: no compile cache (a first launch after an update). --cpu-prof: one V8 profile per run into DIR.+// --stall-ms: a refused outside connection fails only after N ms (a slow network). --slow-engines: every engine command+// on the PATH takes N ms to answer (a slow disk or a cold engine).+// --against: a second checkout started in turn with the first (A, B, A, B, ...), each with its own compile cache; the+// result then holds both and the median of the paired differences, which a busy machine disturbs least.+// Not measured: the desktop parent's part (lease, keys, the private connection); the server runs as a plain local one.+import { spawn } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { request } from "node:http";+import { Agent } from "node:http";+import { createRequire } from "node:module";+import { loadavg } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { parseArgs } from "node:util";++const HERE = dirname(fileURLToPath(import.meta.url));+const { values } = parseArgs({ options: {+ data: { type: "string" }, app: { type: "string", default: join(HERE, "..") }, runs: { type: "string", default: "15" }, source: { type: "boolean", default: false },+ node: { type: "boolean", default: false }, "no-cache": { type: "boolean", default: false }, "cpu-prof": { type: "string" }, label: { type: "string", default: "server-start" },+ port: { type: "string", default: "38811" },+ "stall-ms": { type: "string" }, "slow-engines": { type: "string" }, against: { type: "string" },+} });+if (!values.data || !values.data.includes("openmausbot-bench-")) throw new Error("--data must be a folder made for a bench (its path holds openmausbot-bench-)");+mkdirSync(join(values.data, "tmp"), { recursive: true });+const data = realpathSync(values.data);+const entryOf = (appRoot) => {+ const entry = values.source ? join(appRoot, "server", "index.ts") : join(appRoot, "dist-server", "desktop-entry.mjs");+ if (!existsSync(entry)) throw new Error(`${entry} is missing; run pnpm build:server in ${appRoot}`);+ return entry;+};+const apps = [resolve(values.app), ...(values.against ? [resolve(values.against)] : [])].map((appRoot, index) => ({+ appRoot, entry: entryOf(appRoot), cache: join(dirname(data), `compile-cache-${values.label}-${index}`),+}));+const cpuFile = join(dirname(data), `cpu-${values.label}.txt`);+const electron = createRequire(import.meta.url)("electron");+const runtime = values.node ? process.execPath : electron;+const port = Number(values.port);+const blocker = join(HERE, "testing", "bench-launch-block.cjs");++function slowEngines() {+ const bin = join(dirname(data), `slow-engines-${values["slow-engines"]}`);+ if (existsSync(bin)) return bin;+ mkdirSync(bin, { recursive: true });+ for (const name of ["claude", "codex", "opencode", "grok", "gemini", "pi", "cursor-agent"]) {+ writeFileSync(join(bin, name), `#!/bin/sh\nsleep ${Number(values["slow-engines"]) / 1000}\necho 1.0.0\n`);+ chmodSync(join(bin, name), 0o755);+ }+ return bin;+}++const agent = new Agent({ keepAlive: true });+const probe = () => new Promise((done) => {+ const req = request({ host: "127.0.0.1", port, path: "/api/health", agent }, (res) => { res.resume(); res.on("end", () => done(res.statusCode)); });+ req.on("error", () => done(0));+ req.end();+});++function once({ appRoot, entry, cache }) {+ return new Promise((done) => {+ const args = [+ "--require", blocker,+ ...(values.source ? ["--experimental-strip-types", "--disable-warning=ExperimentalWarning"] : []),+ ...(values["cpu-prof"] ? ["--cpu-prof", "--cpu-prof-dir", values["cpu-prof"]] : []),+ entry,+ ];+ const env = {+ PATH: dirname(process.execPath), HOME: data, TMPDIR: join(data, "tmp"), LANG: "en_US.UTF-8", OMB_DATA_DIR: data, OMB_PORT: String(port),+ OMB_WEBHOOK_PORT: String(port + 1), OMB_TEST_SEALED_PATH: "1", OMB_DISABLE_ANNOUNCEMENTS: "1", OMB_STATIC_DIR: join(appRoot, "dist"),+ OMB_BENCH_EGRESS_LOG: join(dirname(data), "egress-server-start.log"), OMB_BENCH_CPU_OUT: cpuFile,+ ...(values.node ? {} : { ELECTRON_RUN_AS_NODE: "1" }),+ ...(values["stall-ms"] ? { OMB_BENCH_EGRESS_STALL_MS: values["stall-ms"] } : {}),+ ...(values["slow-engines"] ? { PATH: `${slowEngines()}:${dirname(process.execPath)}` } : {}),+ ...(values["no-cache"] || values.source ? {} : { OMB_SERVER_COMPILE_CACHE: cache }),+ };+ const at = performance.now();+ const child = spawn(runtime, args, { env, cwd: join(data, "tmp"), stdio: ["ignore", "pipe", "pipe"] });+ let spawned, listening, output = "";+ child.once("spawn", () => { spawned = performance.now() - at; });+ const stop = (result) => { child.once("exit", () => done(result)); child.kill("SIGTERM"); setTimeout(() => child.kill("SIGKILL"), 5000).unref(); };+ const timer = setTimeout(() => stop({ failed: true, output: output.slice(-2000) }), 60_000);+ child.stderr.on("data", (chunk) => { output += chunk; });+ child.stdout.on("data", async (chunk) => {+ output += chunk;+ if (listening !== undefined || !String(chunk).includes("openmausbot server on ")) return;+ listening = performance.now() - at;+ const status = await probe();+ const answered = performance.now() - at;+ clearTimeout(timer);+ let cpu = NaN;+ try { cpu = Number(readFileSync(cpuFile, "utf8")); } catch {}+ stop({ spawned, listening, answered, status, cpu });+ });+ child.once("exit", (code) => { if (listening === undefined) { clearTimeout(timer); done({ failed: true, code, output: output.slice(-2000) }); } });+ });+}++const median = (list) => { const sorted = list.filter(Number.isFinite).sort((a, b) => a - b); return sorted.length ? Math.round(sorted[Math.floor(sorted.length / 2)]) : null; };+for (const app of apps) {+ if (values["no-cache"]) rmSync(app.cache, { recursive: true, force: true });+ else if (!values.source) await once(app);+}+const runs = apps.map(() => []);+for (let index = 0; index < Number(values.runs); index += 1) {+ for (const [which, app] of apps.entries()) {+ const run = await once(app);+ if (run.failed) { console.error(JSON.stringify(run)); process.exit(1); }+ runs[which].push({ ...run, load: Math.round(loadavg()[0] * 10) / 10 });+ await new Promise((r) => setTimeout(r, 150));+ }+}+agent.destroy();+const summary = (list) => ({+ listening: median(list.map((r) => r.listening)), answered: median(list.map((r) => r.answered)), cpu: median(list.map((r) => r.cpu)),+ minListening: Math.round(Math.min(...list.map((r) => r.listening))), maxListening: Math.round(Math.max(...list.map((r) => r.listening))),+});+const paired = (name) => median(runs[0].map((run, index) => run[name] - runs[1][index][name]));+process.stdout.write(`${JSON.stringify({+ label: values.label, entry: values.source ? "source" : "bundle", runtime: values.node ? `node ${process.version}` : "electron's node", cache: !values["no-cache"] && !values.source,+ runs: runs[0].length, status: runs[0].at(-1)?.status, load: loadavg().map((v) => Math.round(v * 10) / 10),+ medianMs: Object.fromEntries(apps.map((app, index) => [app.appRoot, summary(runs[index])])),+ ...(apps.length === 2 ? { firstMinusSecondMs: { listening: paired("listening"), answered: paired("answered"), cpu: paired("cpu") } } : {}),+})}\n`);diff --git a/scripts/testing/bench-launch-block.cjs b/scripts/testing/bench-launch-block.cjsindex b02fa3df2f..164c706724 100644--- a/scripts/testing/bench-launch-block.cjs+++ b/scripts/testing/bench-launch-block.cjs@@ -20,7 +20,45 @@ if (!globalThis[LOADED]) {const host = options.path ? null : String(options.host ?? "localhost").toLowerCase();if (host === null || LOCAL.has(host)) return connect.apply(this, args);note(`blocked ${host}:${options.port}`);- process.nextTick(() => this.destroy(new Error(`bench-launch: no connection to ${host} from a measured launch`)));+ const refuse = () => this.destroy(new Error(`bench-launch: no connection to ${host} from a measured launch`));+ const stallMs = Number(process.env.OMB_BENCH_EGRESS_STALL_MS) || 0;+ if (stallMs) setTimeout(refuse, stallMs); else process.nextTick(refuse);return this;};+ // The CPU a server has used when it says it listens: a start's cost that a busy machine does not stretch.+ const cpuOut = process.env.OMB_BENCH_CPU_OUT;+ if (cpuOut) {+ const write = process.stdout.write;+ process.stdout.write = function (chunk, ...rest) {+ if (String(chunk).includes("openmausbot server on ")) {+ const used = process.cpuUsage();+ try { fs.writeFileSync(cpuOut, String((used.user + used.system) / 1000)); } catch {}+ process.stdout.write = write;+ }+ return write.call(this, chunk, ...rest);+ };+ }+ // The server child's own V8 profile, from its first line to its "listening" line (scripts/bench-launch.mjs --server-prof).+ const profDir = process.env.OMB_BENCH_SERVER_PROF;+ if (profDir && process.type === "utility") {+ const { Session } = require("node:inspector");+ const session = new Session();+ session.connect();+ session.post("Profiler.enable");+ session.post("Profiler.setSamplingInterval", { interval: 250 });+ session.post("Profiler.start");+ const write = process.stdout.write;+ let done = false;+ process.stdout.write = function (chunk, ...rest) {+ if (!done && String(chunk).includes("openmausbot server on ")) {+ done = true;+ const stop = () => session.post("Profiler.stop", (error, result) => {+ if (!error) try { fs.mkdirSync(profDir, { recursive: true }); fs.writeFileSync(`${profDir}/server-${process.pid}.cpuprofile`, JSON.stringify(result.profile)); } catch {}+ });+ const tailMs = Number(process.env.OMB_BENCH_SERVER_PROF_TAIL_MS) || 0;+ if (tailMs) setTimeout(stop, tailMs); else stop();+ }+ return write.call(this, chunk, ...rest);+ };+ }}diff --git a/server/data/engine.test.ts b/server/data/engine.test.tsindex 91043bf527..c70fb2ad50 100644--- a/server/data/engine.test.ts+++ b/server/data/engine.test.ts@@ -107,6 +107,43 @@ describe("loading the binding", () => {expect(error.error.message).toBe(reason);});+ it("answers a status read from the binding's files, loading nothing, then confirms by loading", async () => {+ const loadedFrom = (dir: string) => Object.keys(createRequire(import.meta.url).cache).filter((file) => file.startsWith(realpathSync(dir)));+ const fresh = join(root, "duckdb-status");+ cpSync(outOfTree, fresh, { recursive: true });+ const changed = vi.fn();+ const e = engine({ env: { ...process.env, OMB_DUCKDB_DIR: fresh }, confirmInstalledMs: 0 });+ e.onInstalledChange(changed);+ expect(e.installed()).toBe(true);+ expect(loadedFrom(fresh)).toEqual([]);+ await vi.waitFor(() => expect(loadedFrom(fresh).some((file) => file.endsWith("duckdb.node"))).toBe(true));+ expect(e.installed()).toBe(true);+ expect(changed).not.toHaveBeenCalled();+ expect(engine({ env: { ...process.env, OMB_DUCKDB_DIR: join(root, "no-binding-here") } }).installed()).toBe(false);+ });++ it("tells its listeners when files that looked right do not load", async () => {+ const broken = join(root, "duckdb-broken");+ cpSync(outOfTree, broken, { recursive: true });+ writeFileSync(join(broken, "node_modules", "@duckdb", `node-bindings-${process.platform}-${process.arch}`, "duckdb.node"), "not a library");+ const changed = vi.fn();+ const e = engine({ env: { ...process.env, OMB_DUCKDB_DIR: broken }, confirmInstalledMs: 0 });+ e.onInstalledChange(changed);+ expect(e.installed()).toBe(true);+ await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));+ expect(e.installed()).toBe(false);+ expect(e.unavailable()).toContain(broken);+ });++ it("tells its listeners when a binding whose files were not found loads after all", async () => {+ const changed = vi.fn();+ const e = engine({ confirmInstalledMs: 0, filesFound: () => false });+ e.onInstalledChange(changed);+ expect(e.installed()).toBe(false);+ await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));+ expect(e.installed()).toBe(true);+ });+it("ships a default engine that loads nothing until asked", () => {expect(typeof dataEngine.forBot).toBe("function");expect(dataEngine.unavailable()).toBeNull();diff --git a/server/data/engine.ts b/server/data/engine.tsindex e326dcbfbb..9cd7850a06 100644--- a/server/data/engine.ts+++ b/server/data/engine.ts@@ -49,6 +49,10 @@ export interface DataEngineOptions {env?: NodeJS.ProcessEnv;idleMs?: number;binding?: Binding;+ /** Tests: the wait before a status read's answer is confirmed by loading the binding. */+ confirmInstalledMs?: number;+ /** Tests: the look for the binding's files. */+ filesFound?: (directory: string | null) => boolean;}/** Null means the server's own node_modules. */@@ -70,6 +74,21 @@ function loadBinding(directory: string | null): Binding {return nativeRequire(directory)("@duckdb/node-api") as Binding;}+/** A status read asks before anything needs the binding; this long after, the binding is loaded to confirm the answer. */+export const CONFIRM_INSTALLED_MS = 5_000;++/** Whether this platform's binding files are where the loader would look, found without loading them. */+export function bindingFilesFound(directory: string | null): boolean {+ try {+ const bindings = createRequire(nativeRequire(directory).resolve("@duckdb/node-api")).resolve("@duckdb/node-bindings");+ const from = createRequire(bindings);+ const native = `@duckdb/node-bindings-${process.platform}-${process.arch}`;+ return [native, `${native}-musl`].some((name) => { try { from.resolve(`${name}/duckdb.node`); return true; } catch { return false; } });+ } catch {+ return false;+ }+}+/** DuckDB's defaults assume it owns the machine (80 % of RAM, every core), and a native OOM takes the server down. A* container's limits count, not its host's: each thread also counts against the container's pids limit. */export function instanceSettings(folder: string, dataDir: string, duckdbVersion: string, env: NodeJS.ProcessEnv = process.env,@@ -713,6 +732,10 @@ FROM ${from} AS omb_source, omb_range WHERE ${finite} GROUP BY bin ORDER BY bin`class Engine implements DataEngine {private readonly databases = new Map<string, BotDb>();private loaded: { binding: Binding } | { reason: string } | null = null;+ private confirming: ReturnType<typeof setTimeout> | null = null;+ private readonly installedListeners = new Set<() => void>();+ private readonly confirmInstalledMs: number;+ private readonly filesFound: (directory: string | null) => boolean;readonly env: NodeJS.ProcessEnv;readonly dataDir: string;readonly idleMs: number;@@ -722,6 +745,8 @@ class Engine implements DataEngine {this.env = options.env ?? process.env;this.dataDir = options.dataDir ?? DATA_DIR;this.idleMs = options.idleMs ?? IDLE_CLOSE_MS;+ this.confirmInstalledMs = options.confirmInstalledMs ?? CONFIRM_INSTALLED_MS;+ this.filesFound = options.filesFound ?? bindingFilesFound;this.folder = options.botFolder ?? defaultBotFolder;if (options.binding) this.loaded = { binding: options.binding };}@@ -753,6 +778,20 @@ class Engine implements DataEngine {return "reason" in loaded ? loaded.reason : null;}+ installed(): boolean {+ if (this.loaded) return "binding" in this.loaded;+ const found = this.filesFound(duckdbDirectory(this.env));+ if (!this.confirming) {+ this.confirming = setTimeout(() => { if ((this.unavailable() === null) !== found) for (const listener of this.installedListeners) listener(); }, this.confirmInstalledMs);+ this.confirming.unref?.();+ }+ return found;+ }++ onInstalledChange(listener: () => void): void {+ this.installedListeners.add(listener);+ }+async forBot(botId: string): Promise<BotDatabase> {if (!botId || /[\\/]|^\.\.?$/.test(botId)) throw new DataFailure({ code: "invalid_input", message: `Not a bot id: "${botId}".` });this.binding();diff --git a/server/data/types.ts b/server/data/types.tsindex 7e18305f1f..61128bb474 100644--- a/server/data/types.ts+++ b/server/data/types.ts@@ -72,6 +72,11 @@ export interface BotDatabase {export interface DataEngine {unavailable(): string | null;+ /** What a status read shows: the loaded binding's state, or, before anything has loaded it, whether its files are in+ * place. Asking never loads the binding; it is loaded a little later to confirm, and `onInstalledChange` hears of an+ * answer that turned out wrong either way. */+ installed(): boolean;+ onInstalledChange(listener: () => void): void;forBot(botId: string): Promise<BotDatabase>;deleteBot(botId: string): Promise<void>;closeAll(): Promise<void>;diff --git a/server/enterprise.ts b/server/enterprise.tsindex 471be8a0d7..198e2509da 100644--- a/server/enterprise.ts+++ b/server/enterprise.ts@@ -115,7 +115,10 @@ function oss(notice?: string): EditionStatus {return current;}-/** Never throws: a broken layer or key degrades to the open-source edition with a notice saying what to fix. */+const LAYER_WITHOUT_KEY = "enterprise layer present but OMB_LICENSE_KEY is not set";++/** Never throws: a broken layer or key degrades to the open-source edition with a notice saying what to fix. With no key+ * and no hosted workspace nothing of the layer can be used, so it is not loaded. */export async function loadEnterpriseLayer(options: { dir?: string; licenseKey?: string; env?: NodeJS.ProcessEnv; serverRoot?: string } = {},): Promise<EditionStatus> {@@ -128,13 +131,14 @@ export async function loadEnterpriseLayer(licenseKey ? `OMB_LICENSE_KEY is set but no enterprise layer exists at ${dirs.join(" or ")}` : undefined,);}+ if (!licenseKey && !hostedWorkspaceConfigured(options.env)) return oss(LAYER_WITHOUT_KEY);try {const loaded: unknown = await import(pathToFileURL(entry).href);const access: unknown = Reflect.get(Object(loaded), "createWorkspaceAccess");if (typeof access === "function") workspaceAccessFactory = access as (options: WorkspaceAccessOptions) => WorkspaceAccess;const register: unknown = Reflect.get(Object(loaded), "register");if (typeof register !== "function") throw new Error(`${entry} does not export register()`);- if (!licenseKey) return oss("enterprise layer present but OMB_LICENSE_KEY is not set");+ if (!licenseKey) return oss(LAYER_WITHOUT_KEY);// A layer that ignores graceDays refuses an expired key at startup.const registered: unknown = await register({ licenseKey, graceDays: LICENSE_GRACE_DAYS });const layer = layerSchema.parse(registered);diff --git a/server/index.ts b/server/index.tsindex 8bd19b1db9..b4ca8d9958 100644--- a/server/index.ts+++ b/server/index.ts@@ -642,7 +642,7 @@ import { createPersonReplies } from "./person-replies.ts";import { lendingPerson, lendingPersonKey, personKey, relayedPersonKey } from "./person-key.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 { createPerfHost } from "./perf/perf-host.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 { 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 { 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 { 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";@@ -2780,7 +2780,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersconst imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });-const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });+const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME), ...(DESKTOP_MANAGED ? { launches: { launchId: process.env.OMB_DESKTOP_LAUNCH_ID ?? null, server: launchServerPart, counts: () => ({ bots: store.bots.length, threads: store.bots.reduce((sum, bot) => sum + (bot.tasks?.length ?? 0), 0) }) } } : {}) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,log: line => console.warn(line) });@@ -2806,7 +2806,7 @@ const teamComputers = new TeamComputers(join(DATA_DIR, "team-computers.json"), Elet followupsReady = false;const sendSequencer = new SendSequencer();// Before the new-bot default is read: a saved default may name the engine.-await retryComputerEngineMove(); mcpServersHost.boot();+await retryComputerEngineMove(); mcpServersHost.boot(); dataEngine.onInstalledChange(() => broadcast({ kind: "config", ...configStatus() }));if (store.needsSeed()) await Promise.race([cloudCreditStarted, new Promise(resolve => setTimeout(resolve, 15_000).unref())]);if (store.needsSeed()) { firstEngineRead(); await refreshUnsetModelSelections(); }else enginesRead = registry.readAtStart(enginesByUse([cfg.defaultModelSelection, ...store.bots.map((bot) => bot.modelSelection)]), firstEngineRead).then(async ({ engines, changed }) => {@@ -9441,7 +9441,7 @@ const appTriggers = createAppTriggerHost({ store, webhooks, webhookBase: () => waudit: (row) => appendDecision(DATA_DIR, { ...row, decision: "auto-approved", source: "routine" }) });tieAutomationsToBots(store, { routines: routines!, webhooks, apps: appTriggers.manager, waits: botWaits });ROUTES.push(appTriggers.routes); ROUTES.unshift(createMoveFreezeRoutes({ freeze: moveFreeze, automationsOff: () => switchAutomationsOff({ routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }), restart: () => { restartRequested = true; gracefulShutdown(); }, busy: createMoveWaits({ bots: () => store.bots, rooms: () => store.groups, answering: (id) => watchdog.answering(id), turn: botHasActiveTurn, runs: () => routines?.listRuns() ?? [], roomWorking: (id) => { const group = store.group(id); return Boolean(group && groupIsWorking(group)); }, handoffs: () => coordinator.active(), exists: (node) => !(!node.parentId && node.groupId ? roomRootProblem(node) : roomHandoffProblem(node)), signingIn: () => providerAuthSessions.active }) }));-ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text, bots: perf.bots })); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,+ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text, bots: perf.bots, launch: perf.noteLaunch })); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,threadTitle: (botId, threadId) => store.bot(botId) && !store.bot(botId)!.hidden ? store.taskByThread(botId, threadId)?.title ?? null : null,created: (id, auth) => cloudRoutineAuthors?.wrote(id, auth.kind === "session" ? actorKey(auth) : CLOUD_NOBODY_KEY) }));@@ -11669,7 +11669,7 @@ function configStatus() {anthropic: { ...keyStatus(cfg.anthropic?.key), everyClaudeBot: cfg.anthropic?.everyClaudeBot !== false },openai: keyStatus(cfg.openai?.key),openrouter: keyStatus(cfg.openrouter?.key),- fleet: { available: fleetAvailable(fleetSocketPath()) }, toolGroups: availableToolGroups({ meetings: boat.boatConfigured(cfg), data: dataEngine.unavailable() === null, images: imageGenerationReady(cfg), email: emailHost.available() }),+ fleet: { available: fleetAvailable(fleetSocketPath()) }, toolGroups: availableToolGroups({ meetings: boat.boatConfigured(cfg), data: dataEngine.installed(), images: imageGenerationReady(cfg), email: emailHost.available() }),edition: editionForSettings(editionStatus()),budgets: {...(cfg.budgets?.monthlyUsd !== undefined ? { monthlyUsd: cfg.budgets.monthlyUsd } : {}),@@ -15250,7 +15250,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATAbotLink.start(); let pausedSent = starterAwake.paused().join(); store.onChange((change) => { if (change.type === "bot.deleted") botHolds.forget("bot", change.botId); if (change.type !== "bot" && change.type !== "bot.deleted") return; const paused = starterAwake.paused().join(); if (paused !== pausedSent) { pausedSent = paused; broadcast({ kind: "config", ...configStatus() }); } });server.listen(PORT, listenHost(server), async () => {companyRuntimeReady(); cloudHealth?.speed.ready(); void tailnetShare.start(process.env);- console.log(`openmausbot server on http://127.0.0.1:${PORT}`);+ console.log(`openmausbot server on http://127.0.0.1:${PORT}`); launchListening();personWaits.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();diff --git a/server/perf/launch-probe.ts b/server/perf/launch-probe.tsnew file mode 100644index 0000000000..a7b95f6468--- /dev/null+++ b/server/perf/launch-probe.ts@@ -0,0 +1,23 @@+// This server's own part of the desktop app's launch record: when it started, when it listened, and the programs and+// outside requests it made meanwhile. Only under the desktop app; any other server is left exactly as it is.+import childProcess from "node:child_process";+import { syncBuiltinESMExports } from "node:module";++import { watchLaunchWork } from "../../electron/launch-probes.mjs";++/** With no launch record written by then, the counting stops anyway. */+const WATCH_AT_MOST_MS = 120_000;++const watch = process.env.OMB_DESKTOP_PARENT === "1"+ ? watchLaunchWork({ childProcess: childProcess as unknown as Record<string, unknown>, sync: syncBuiltinESMExports, fetchOwners: [globalThis] })+ : null;+if (watch) setTimeout(() => watch.finish(), WATCH_AT_MOST_MS).unref();+let listeningAt = 0;++export function launchListening(): void {+ listeningAt ||= Date.now();+}++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/launch-report.ts b/server/perf/launch-report.tsnew file mode 100644index 0000000000..70374eb35c--- /dev/null+++ b/server/perf/launch-report.ts@@ -0,0 +1,59 @@+// The launch record as people read it (plain lines in the desktop's diagnostics and a @devs report) and as the health+// read carries it (a few numbers). Built only from a LaunchRecord's checked fields.+import { LAUNCH_HOSTS, LAUNCH_MARKS, LAUNCH_PHASES, launchPhaseMs, type LaunchPhase, type LaunchPhaseStats, type LaunchRecord, type LaunchStats } from "./launch-timings.ts";+import { exactQuantile } from "./phases.ts";++/** `stats`: the days' histograms, whose percentiles are bucket edges. `recent`: the ring, newest last. */+export interface LaunchSources { stats: LaunchStats; recent: LaunchRecord[] }++/** Exact percentiles over the kept launches. */+export function recentLaunchStats(recent: readonly LaunchRecord[]): Partial<Record<LaunchPhase, LaunchPhaseStats>> {+ const out: Partial<Record<LaunchPhase, LaunchPhaseStats>> = {};+ for (const phase of LAUNCH_PHASES) {+ const values = recent.flatMap((launch) => { const ms = launchPhaseMs(launch)[phase]; return ms === undefined ? [] : [ms]; }).sort((left, right) => left - right);+ if (values.length) out[phase] = { p50: exactQuantile(values, 0.5), p90: exactQuantile(values, 0.9), max: values.at(-1)!, n: values.length };+ }+ return out;+}+const SHOWN = 3;+const PHASE_NAMES: Record<LaunchPhase, string> = { splashShown: "splash shown", windowShown: "window shown", chatDrawn: "chat drawn", forkToListening: "server fork to listening", keychain: "keychain read" };++const took = (ms: number) => (ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(ms < 10_000 ? 2 : 1)}s`);+const iso = (at: number) => new Date(at).toISOString().replace(/\.\d{3}Z$/, "Z");++export function launchLine(launch: LaunchRecord): string {+ const marks = LAUNCH_MARKS.flatMap((mark) => (launch.ms[mark] === undefined ? [] : [`${mark} ${took(launch.ms[mark])}`]));+ const spans = Object.entries(launch.spans).map(([span, ms]) => `${span} ${took(ms)}`);+ const children = launch.children.map((child) => `${child.name}${child.where === "server" ? " (server)" : ""}${child.n > 1 ? ` ${child.n}x` : ""} ${took(child.ms)}`);+ const net = LAUNCH_HOSTS.flatMap((host) => (launch.net[host] ? [`${host} ${launch.net[host].n} in ${took(launch.net[host].ms)}`] : []));+ return `${iso(launch.at)} ${launch.appVersion ?? "?"} ${launch.platform ?? "?"} ${launch.arch ?? "?"} ${launch.cold === null ? "" : launch.cold ? "cold " : "warm "}${launch.hidden ? "hidden " : ""}`+ + `(${launch.parts.join("+")}; ${launch.bots} bots, ${launch.threads} conversations): ${marks.join(", ")}`+ + (spans.length ? `; inside: ${spans.join(", ")}` : "") + (children.length ? `; programs started: ${children.join(", ")}` : "")+ + `; requests off this computer before the chat: ${net.length ? net.join(", ") : "none"}`;+}++const phaseLine = (phases: Partial<Record<LaunchPhase, LaunchPhaseStats>>, upTo = "") =>+ LAUNCH_PHASES.flatMap((phase) => { const one = phases[phase]; return one ? [`${PHASE_NAMES[phase]} p50 ${upTo}${took(one.p50)} p90 ${upTo}${took(one.p90)} max ${took(one.max)}`] : []; }).join("; ");++/** Plain lines: the kept launches' exact percentiles, the days' bucketed ones, then the latest few launches, newest last.+ * Empty where no launch was ever recorded. */+export function launchLines(sources: LaunchSources | null | undefined): string[] {+ if (!sources || (!sources.stats.launches && !sources.recent.length)) return [];+ const { stats, recent } = sources;+ const days = phaseLine(stats.phases, "under ");+ return [+ `App launches (times from process start): ${stats.launches} in the last ${stats.days} days, ${stats.cold} of them the first since the computer started`,+ ...(recent.length ? [` Latest ${recent.length}: ${phaseLine(recentLaunchStats(recent))}`] : []),+ ...(days ? [` By day, last ${stats.days} days (counted in steps, so each reads up to a quarter high): ${days}`] : []),+ ...recent.slice(-SHOWN).map((launch) => ` ${launchLine(launch)}`),+ ];+}++/** For the health read: the kept launches' percentiles, the days' counts and the latest launch's marks. */+export function launchHealth(sources: LaunchSources | null | undefined) {+ if (!sources || (!sources.stats.launches && !sources.recent.length)) return null;+ const last = sources.recent.at(-1);+ return { days: sources.stats.days, launches: sources.stats.launches, cold: sources.stats.cold, recent: recentLaunchStats(sources.recent), byDay: sources.stats.phases,+ last: last ? { at: last.at, cold: last.cold, ms: last.ms, spans: last.spans } : null };+}+export type LaunchHealth = ReturnType<typeof launchHealth>;diff --git a/server/perf/launch-timings.test.ts b/server/perf/launch-timings.test.tsnew file mode 100644index 0000000000..39162bc61c--- /dev/null+++ b/server/perf/launch-timings.test.ts@@ -0,0 +1,237 @@+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { launchHealth, launchLines } from "./launch-report.ts";+import { createLaunchTimings, LAUNCH_DAYS_KEPT, LAUNCH_FILE, LAUNCH_MARKS, LAUNCH_RING_CAP, LAUNCH_SETTLE_MS, parseLaunchPart } from "./launch-timings.ts";+import { createPerfDiagnosticsRoutes, LAUNCH_PATH } from "../routes/perf-diagnostics.ts";+import { PASS } from "../routes/table.ts";++const START = 1_800_000_000_000;+const DAY = 86_400_000;+const dirs: string[] = [];+afterEach(() => { vi.useRealTimers(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });+const folder = () => { const dir = mkdtempSync(join(tmpdir(), "launch-timings-")); dirs.push(dir); return dir; };++const mainPart = (processStart = START, extra: Record<string, unknown> = {}) => ({+ from: "main", launchId: "launch-0001", processStart, appVersion: "0.1.170", platform: "darwin", arch: "arm64", hidden: false,+ marks: { codeStart: 100, mainImported: 150, ready: 180, splashMade: 250, splashShown: 330, keysRead: 290, leaseTaken: 370, serverForked: 430, serverSpawned: 450, serverListening: 750, serverReady: 770, windowMade: 850, windowNavigated: 855, windowShown: 990 },+ spans: { keychain: 12, lease: 25 },+ children: [{ name: "sysctl", ms: 3 }, { name: "ioreg", ms: 18 }, { name: "scutil", ms: 20 }, { name: "scutil", ms: 22 }],+ net: { accounts: { n: 1, ms: 120 } },+ ...extra,+});+const pagePart = (timeOrigin = START + 860, extra: Record<string, unknown> = {}) => ({+ from: "page", timeOrigin, marks: { pageResponse: 28, firstPaint: 170, sidebarDrawn: 335, chatDrawn: 340, lastLongTaskEnd: 520 }, net: { other: { n: 3, ms: 57 } }, ...extra,+});+const serverPart = () => ({ startedAt: START + 452, listeningAt: START + 748, children: [{ name: "ioreg", ms: 14 }, { name: "/Users/ada/bin/acme-tool", ms: 40 }], net: { updates: { n: 1, ms: 24 } } });++describe("a launch's record", () => {+ it("joins the main process's, the page's and the server's parts on the process's own clock", () => {+ let now = START + 3_000;+ const timings = createLaunchTimings({ now: () => now, uptimeS: () => 3_600, launchId: "launch-0001", server: serverPart, counts: () => ({ bots: 31, threads: 62 }) });+ expect(timings.note(mainPart())).toEqual({ ok: true, complete: false });+ expect(timings.recent()).toEqual([]);+ now += 500;+ expect(timings.note(pagePart())).toEqual({ ok: true, complete: true });+ const [launch] = timings.recent();+ expect(launch).toEqual({+ at: START, appVersion: "0.1.170", platform: "darwin", arch: "arm64", cold: null, hidden: false, bots: 31, threads: 62,+ ms: { codeStart: 100, mainImported: 150, ready: 180, splashMade: 250, splashShown: 330, keysRead: 290, leaseTaken: 370, serverForked: 430, serverSpawned: 450,+ serverStarted: 452, serverListening: 750, serverReady: 770, windowMade: 850, windowNavigated: 855, windowShown: 990,+ pageResponse: 888, firstPaint: 1030, sidebarDrawn: 1195, chatDrawn: 1200, lastLongTaskEnd: 1380 },+ spans: { keychain: 12, lease: 25, serverBoot: 296 },+ children: [{ name: "scutil", where: "main", n: 2, ms: 42 }, { name: "ioreg", where: "main", n: 1, ms: 18 }, { name: "sysctl", where: "main", n: 1, ms: 3 },+ { name: "other", where: "server", n: 1, ms: 40 }, { name: "ioreg", where: "server", n: 1, ms: 14 }],+ net: { accounts: { n: 1, ms: 120 }, other: { n: 3, ms: 57 }, updates: { n: 1, ms: 24 } },+ parts: ["main", "page", "server"],+ });+ expect(Object.keys(launch!.ms).every((mark) => (LAUNCH_MARKS as readonly string[]).includes(mark))).toBe(true);+ expect(timings.stats().phases).toMatchObject({ splashShown: { n: 1, max: 330 }, windowShown: { n: 1, max: 990 }, chatDrawn: { n: 1, max: 1200 }, forkToListening: { n: 1, max: 320 }, keychain: { n: 1, max: 12 } });+ });++ it("is the same whichever part arrives first, and a sender asking again is told it is written", () => {+ const first = createLaunchTimings({ now: () => START, launchId: "launch-0001" });+ first.note(pagePart());+ expect(first.recent()).toEqual([]);+ expect(first.note(mainPart()).complete).toBe(true);+ const second = createLaunchTimings({ now: () => START, launchId: "launch-0001" });+ second.note(mainPart());+ second.note(pagePart());+ expect(first.recent()).toEqual(second.recent());+ expect(second.note(mainPart())).toEqual({ ok: true, complete: true });+ expect(second.note(pagePart(START + 99_000))).toEqual({ ok: true, complete: true });+ expect(second.recent()).toHaveLength(1);+ });++ it("is written without a page when none reports in time, or at a clean exit, and at once for a hidden start", () => {+ vi.useFakeTimers();+ const late = createLaunchTimings({ now: () => START, launchId: "launch-0001" });+ late.note(mainPart());+ vi.advanceTimersByTime(LAUNCH_SETTLE_MS - 1);+ expect(late.recent()).toEqual([]);+ vi.advanceTimersByTime(1);+ expect(late.recent()[0]).toMatchObject({ parts: ["main"], ms: { windowShown: 990 } });+ expect(late.recent()[0]!.ms.chatDrawn).toBeUndefined();+ expect(late.note(pagePart())).toEqual({ ok: true, complete: true });++ const quit = createLaunchTimings({ now: () => START, launchId: "launch-0001" });+ quit.note(mainPart());+ quit.flush();+ expect(quit.recent()).toHaveLength(1);+ const nothing = createLaunchTimings({ now: () => START });+ nothing.note(pagePart());+ nothing.flush();+ expect(nothing.recent()).toEqual([]);++ const hidden = createLaunchTimings({ now: () => START, launchId: "launch-0001" });+ expect(hidden.note(mainPart(START, { hidden: true, marks: { ready: 180, serverReady: 700 } }))).toEqual({ ok: true, complete: true });+ expect(hidden.recent()[0]).toMatchObject({ hidden: true, parts: ["main"] });+ });++ it("leaves out a page that is not this launch's window: a reload, or a window opened later", () => {+ const timings = createLaunchTimings({ now: () => START, launchId: "launch-0001" });+ timings.note(pagePart(START + 60_000));+ timings.note(mainPart());+ expect(timings.recent()[0]).toMatchObject({ parts: ["main"] });+ expect(timings.recent()[0]!.ms.chatDrawn).toBeUndefined();+ });++ it("refuses a part under another launch's id, and anything that is not a part", () => {+ const timings = createLaunchTimings({ now: () => START, launchId: "launch-0001" });+ expect(timings.note(mainPart(START, { launchId: "launch-9999" }))).toEqual({ ok: false, complete: false });+ for (const junk of [null, "main", 7, [], { from: "server" }, { from: "main" }, { from: "page", timeOrigin: "now" }, { from: "main", launchId: "../../etc", processStart: START }]) {+ expect(timings.note(junk).ok).toBe(false);+ }+ expect(timings.recent()).toEqual([]);+ });+});++describe("the saved launches", () => {+ it("are one owner-only file, read back by the next server, and a restarted server does not record a launch twice", () => {+ const dir = folder();+ const file = join(dir, LAUNCH_FILE);+ const first = createLaunchTimings({ file, now: () => START + 5_000, uptimeS: () => 60, launchId: "launch-0001" });+ first.note(mainPart());+ first.note(pagePart());+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);+ const restarted = createLaunchTimings({ file, now: () => START + 60_000, uptimeS: () => 120, launchId: "launch-0001" });+ expect(restarted.recent()).toEqual(first.recent());+ expect(restarted.note(mainPart())).toEqual({ ok: true, complete: true });+ expect(restarted.recent()).toHaveLength(1);+ expect(JSON.parse(readFileSync(file, "utf8")).ring).toHaveLength(1);+ });++ it("call a launch cold only when the computer started after the launch before it", () => {+ const dir = folder();+ const file = join(dir, LAUNCH_FILE);+ const launch = (at: number, uptimeS: number, id: string) => {+ const timings = createLaunchTimings({ file, now: () => at + 2_000, uptimeS: () => uptimeS, launchId: id });+ timings.note(mainPart(at, { launchId: id }));+ timings.note(pagePart(at + 860));+ return timings.recent().at(-1)!.cold;+ };+ expect(launch(START, 600, "launch-0001")).toBeNull();+ expect(launch(START + 3_600_000, 4_200, "launch-0002")).toBe(false);+ expect(launch(START + 7_200_000, 30, "launch-0003")).toBe(true);+ expect(createLaunchTimings({ file, now: () => START + 7_300_000 }).stats()).toMatchObject({ launches: 3, cold: 1 });+ });++ it("keep the latest launches and the latest days only", () => {+ const dir = folder();+ const file = join(dir, LAUNCH_FILE);+ let last = createLaunchTimings({ file });+ for (let index = 0; index < LAUNCH_RING_CAP + 5; index++) {+ const at = START + index * DAY;+ last = createLaunchTimings({ file, now: () => at + 2_000, uptimeS: () => 10, launchId: "launch-0001" });+ last.note(mainPart(at));+ last.note(pagePart(at + 860));+ }+ expect(last.recent()).toHaveLength(LAUNCH_RING_CAP);+ const saved = JSON.parse(readFileSync(file, "utf8"));+ expect(saved.days).toHaveLength(LAUNCH_DAYS_KEPT);+ expect(last.stats().launches).toBe(LAUNCH_DAYS_KEPT);+ expect(last.stats(7).launches).toBe(7);+ });++ it("read nothing from a file that is not theirs", () => {+ const dir = folder();+ const file = join(dir, LAUNCH_FILE);+ for (const body of ["", "not json", JSON.stringify({ v: 2, ring: [mainPart()] }), JSON.stringify({ v: 1, ring: "x", days: { day: 1 } })]) {+ writeFileSync(file, body);+ const timings = createLaunchTimings({ file });+ expect(timings.recent()).toEqual([]);+ expect(timings.stats().launches).toBe(0);+ }+ });+});++describe("the launch record in the reports", () => {+ it("is plain lines of numbers, and nothing at all where no launch was recorded", () => {+ const timings = createLaunchTimings({ now: () => START + 3_000, uptimeS: () => 3_600, launchId: "launch-0001", server: serverPart, counts: () => ({ bots: 31, threads: 62 }) });+ expect(launchLines({ stats: timings.stats(), recent: timings.recent() })).toEqual([]);+ expect(launchHealth({ stats: timings.stats(), recent: timings.recent() })).toBeNull();+ timings.note(mainPart());+ timings.note(pagePart());+ const lines = launchLines({ stats: timings.stats(), recent: timings.recent() });+ expect(lines.slice(0, 3)).toEqual([+ "App launches (times from process start): 1 in the last 30 days, 0 of them the first since the computer started",+ " Latest 1: splash shown p50 330ms p90 330ms max 330ms; window shown p50 990ms p90 990ms max 990ms; chat drawn p50 1.20s p90 1.20s max 1.20s; "+ + "server fork to listening p50 320ms p90 320ms max 320ms; keychain read p50 12ms p90 12ms max 12ms",+ " By day, last 30 days (counted in steps, so each reads up to a quarter high): splash shown p50 under 330ms p90 under 330ms max 330ms; "+ + "window shown p50 under 990ms p90 under 990ms max 990ms; chat drawn p50 under 1.20s p90 under 1.20s max 1.20s; "+ + "server fork to listening p50 under 320ms p90 under 320ms max 320ms; keychain read p50 under 12ms p90 under 12ms max 12ms",+ ]);+ expect(lines[3]).toContain("2027-01-15T08:00:00Z 0.1.170 darwin arm64 (main+page+server; 31 bots, 62 conversations): codeStart 100ms");+ expect(lines[3]).toContain("chatDrawn 1.20s");+ expect(lines[3]).toContain("inside: keychain 12ms, lease 25ms, serverBoot 296ms; programs started: scutil 2x 42ms, ioreg 18ms, sysctl 3ms, other (server) 40ms, ioreg (server) 14ms");+ expect(lines[3]).toContain("requests off this computer before the chat: accounts 1 in 120ms, updates 1 in 24ms, other 3 in 57ms");+ expect(launchHealth({ stats: timings.stats(), recent: timings.recent() })).toMatchObject({ launches: 1, cold: 0, recent: { chatDrawn: { p50: 1200, p90: 1200, max: 1200, n: 1 } }, last: { at: START, ms: { chatDrawn: 1200 } } });+ });+});++describe("POST /api/diagnostics/launch", () => {+ const call = async (launch: ((part: unknown) => { ok: boolean; complete: boolean } | null) | undefined, body: unknown, method = "POST") => {+ const sent: Array<{ status: number; body: unknown }> = [];+ const route = createPerfDiagnosticsRoutes({ text: () => "", ...(launch ? { launch } : {}) });+ const out = await route({+ req: {} as never, res: { setHeader() {} } as never, url: new URL(`http://127.0.0.1${LAUNCH_PATH}`), path: LAUNCH_PATH, method, auth: {} as never,+ json: ((_res: unknown, status: number, payload: unknown) => { sent.push({ status, body: payload }); }) as never,+ readBody: (async () => { if (body instanceof Error) throw body; return body; }) as never,+ });+ return { out, sent };+ };++ it("hands the part to the recorder and answers whether the record is written", async () => {+ const timings = createLaunchTimings({ now: () => START, launchId: "launch-0001" });+ expect((await call(timings.note, mainPart())).sent).toEqual([{ status: 200, body: { ok: true, complete: false } }]);+ expect((await call(timings.note, pagePart())).sent).toEqual([{ status: 200, body: { ok: true, complete: true } }]);+ });++ it("is not there on a server no desktop app started, takes a broken body as no part, and leaves other methods alone", async () => {+ expect((await call(undefined, mainPart())).sent).toEqual([{ status: 404, body: { ok: false, complete: false } }]);+ expect((await call(() => null, mainPart())).sent[0]!.status).toBe(404);+ const timings = createLaunchTimings({ now: () => START });+ expect((await call(timings.note, new Error("too large"))).sent).toEqual([{ status: 200, body: { ok: false, complete: false } }]);+ expect((await call(timings.note, mainPart(), "GET")).out).toBe(PASS);+ });+});++describe("parseLaunchPart", () => {+ it("keeps numbers in range and names it knows; everything else is dropped or becomes other", () => {+ const part = parseLaunchPart(mainPart(START, {+ marks: { ready: 180, chatDrawn: 5, serverStarted: 9, splashShown: -1, windowShown: 1e12, keysRead: "290", __proto__: { polluted: 1 }, "/Users/ada": 4 },+ spans: { keychain: 12, serverBoot: 9, "[email protected]": 3 },+ children: [{ name: "ioreg", ms: 5 }, { name: "IOREG", ms: 5 }, { name: "constructor", ms: 1 }, { name: "ioreg", ms: "9" }, "x", null],+ net: { accounts: { n: 2, ms: 9 }, "intranet.acme.test": { n: 1, ms: 1 }, cloud: { n: 0, ms: 5 }, other: { n: 1, ms: -4 } },+ appVersion: "0.1.170 /Users/ada", platform: "plan9", arch: "arm64; rm -rf",+ }));+ expect(part).toEqual({+ from: "main", launchId: "launch-0001", processStart: START, marks: { ready: 180 }, spans: { keychain: 12 },+ children: [{ name: "other", where: "main", n: 2, ms: 6 }, { name: "ioreg", where: "main", n: 1, ms: 5 }],+ net: { accounts: { n: 2, ms: 9 }, other: { n: 1, ms: 0 } }, appVersion: null, platform: null, arch: null, hidden: false,+ });+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();+ });+});diff --git a/server/perf/launch-timings.ts b/server/perf/launch-timings.tsnew file mode 100644index 0000000000..9b25a29b19--- /dev/null+++ b/server/perf/launch-timings.ts@@ -0,0 +1,330 @@+// Where each start of the desktop app spent its time: the main process, the page and this server each hand in their+// part once, the parts become one record of numbers and fixed codes, and a ring of recent launches plus a histogram per+// day is kept in the data folder. Never sent anywhere. Privacy invariant: only `parseLaunchPart`'s checked fields enter+// a record, and only `parseLaunch`'s leave the file.+import { readFileSync } from "node:fs";+import { uptime } from "node:os";++import { writeFileAtomic } from "../atomic.ts";+import { addTo, countOf, emptyHistogram, histogramQuantile, mergeInto, parseHistogram, type Histogram } from "./phases.ts";++export const LAUNCH_FILE = "launch-timings.json";+export const LAUNCH_RING_CAP = 50;+export const LAUNCH_DAYS_KEPT = 30;+/** A launch whose page never reports (hidden at login, no chat open) is recorded without it after this long. */+export const LAUNCH_SETTLE_MS = 90_000;+const DAY = 86_400_000;+/** No phase of a launch is believed past this. */+const MAX_MS = 600_000;+const CHILDREN_KEPT = 16;++/** Offsets from the app's process start, ms. In the order a launch reaches them. */+export const LAUNCH_MARKS = [+ "codeStart", "mainImported", "ready", "splashMade", "splashShown", "keysRead", "leaseTaken", "serverForked", "serverSpawned",+ "serverStarted", "serverListening", "serverReady", "windowMade", "windowNavigated", "windowShown", "pageResponse", "firstPaint",+ "sidebarDrawn", "chatDrawn", "lastLongTaskEnd",+] as const;+export type LaunchMark = (typeof LAUNCH_MARKS)[number];+const MAIN_MARKS = new Set<string>(LAUNCH_MARKS.slice(0, LAUNCH_MARKS.indexOf("pageResponse")).filter((mark) => mark !== "serverStarted"));+const PAGE_MARKS = ["pageResponse", "firstPaint", "sidebarDrawn", "chatDrawn", "lastLongTaskEnd"] as const;++/** Time inside one awaited step, ms. */+export const LAUNCH_SPANS = ["keychain", "lease", "serverBoot"] as const;+export type LaunchSpan = (typeof LAUNCH_SPANS)[number];++/** The programs a launch may start, by the name they are kept under; any other is "other". */+export const LAUNCH_CHILDREN = [+ "sysctl", "ioreg", "scutil", "codesign", "spctl", "security", "open", "defaults", "osascript", "ps", "lsof", "launchctl", "sw_vers", "which", "where",+ "reg", "wmic", "powershell", "cmd", "tasklist", "xdg-mime", "xdg-settings", "gsettings", "dbus-send", "loginctl", "getent", "id",+ "cua-driver", "cloudflared", "tailscale", "git", "node", "claude", "codex", "opencode", "grok", "gemini", "pi", "cursor-agent", "other",+] as const;+const CHILD_NAMES = new Set<string>(LAUNCH_CHILDREN);+export const LAUNCH_HOSTS = ["accounts", "cloud", "updates", "other"] as const;+export type LaunchHost = (typeof LAUNCH_HOSTS)[number];+const PLATFORMS = new Set(["darwin", "win32", "linux"]), ARCHES = new Set(["arm64", "x64", "ia32"]);+const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}(?:-[a-z0-9.]{1,24})?$/;+const LAUNCH_ID = /^[A-Za-z0-9_-]{8,64}$/;++export interface LaunchChild { name: string; where: "main" | "server"; n: number; ms: number }+export interface LaunchNet { n: number; ms: number }+export interface LaunchRecord {+ /** The app's process start, epoch ms. */+ at: number;+ appVersion: string | null;+ platform: string | null;+ arch: string | null;+ /** The first launch since the computer started; null when that could not be told. */+ cold: boolean | null;+ /** Started out of sight (at login): no window, so no page marks. */+ hidden: boolean;+ bots: number;+ threads: number;+ ms: Partial<Record<LaunchMark, number>>;+ spans: Partial<Record<LaunchSpan, number>>;+ children: LaunchChild[];+ /** Requests to anything but this computer before the chat was drawn, by kind of host. */+ net: Partial<Record<LaunchHost, LaunchNet>>;+ parts: Array<"main" | "page" | "server">;+}++const ms = (value: unknown): number | undefined =>+ typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_MS ? Math.round(value) : undefined;+const count = (value: unknown, cap = 1_000_000): number => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? Math.min(value, cap) : 0);+const epoch = (value: unknown): number | undefined =>+ typeof value === "number" && Number.isFinite(value) && value > 1_500_000_000_000 && value < 10_000_000_000_000 ? Math.round(value) : undefined;+const fields = (value: unknown): Record<string, unknown> => (value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {});++function childrenOf(raw: unknown, where: "main" | "server"): LaunchChild[] {+ const merged = new Map<string, LaunchChild>();+ for (const entry of Array.isArray(raw) ? raw.slice(0, 200) : []) {+ const one = fields(entry);+ const took = ms(one.ms);+ if (took === undefined) continue;+ const name = typeof one.name === "string" && CHILD_NAMES.has(one.name) ? one.name : "other";+ const kept = merged.get(name) ?? { name, where, n: 0, ms: 0 };+ kept.n += Math.max(1, count(one.n, 1_000));+ kept.ms = Math.min(MAX_MS, kept.ms + took);+ merged.set(name, kept);+ }+ return [...merged.values()].sort((left, right) => right.ms - left.ms).slice(0, CHILDREN_KEPT);+}++function netOf(raw: unknown): Partial<Record<LaunchHost, LaunchNet>> {+ const out: Partial<Record<LaunchHost, LaunchNet>> = {};+ const given = fields(raw);+ for (const host of LAUNCH_HOSTS) {+ if (!Object.hasOwn(given, host)) continue;+ const one = fields(given[host]);+ const n = count(one.n, 100_000);+ if (n) out[host] = { n, ms: ms(one.ms) ?? 0 };+ }+ return out;+}++const addNet = (into: Partial<Record<LaunchHost, LaunchNet>>, from: Partial<Record<LaunchHost, LaunchNet>>) => {+ for (const host of LAUNCH_HOSTS) {+ const one = from[host];+ if (one) into[host] = { n: (into[host]?.n ?? 0) + one.n, ms: Math.min(MAX_MS, (into[host]?.ms ?? 0) + one.ms) };+ }+};++export interface MainPart {+ from: "main"; launchId: string; processStart: number; marks: Partial<Record<LaunchMark, number>>; spans: Partial<Record<LaunchSpan, number>>;+ children: LaunchChild[]; net: Partial<Record<LaunchHost, LaunchNet>>; appVersion: string | null; platform: string | null; arch: string | null; hidden: boolean;+}+export interface PagePart {+ from: "page"; timeOrigin: number; marks: Partial<Record<(typeof PAGE_MARKS)[number], number>>; net: Partial<Record<LaunchHost, LaunchNet>>;+}+export interface ServerPart { startedAt: number; listeningAt: number; children: LaunchChild[]; net: Partial<Record<LaunchHost, LaunchNet>> }++/** What the main process or the page posted, reduced to its checked fields; null when it is neither. */+export function parseLaunchPart(raw: unknown): MainPart | PagePart | null {+ const body = fields(raw);+ if (body.from === "page") {+ const timeOrigin = epoch(body.timeOrigin);+ if (timeOrigin === undefined) return null;+ const given = fields(body.marks), marks: PagePart["marks"] = {};+ for (const mark of PAGE_MARKS) { const at = Object.hasOwn(given, mark) ? ms(given[mark]) : undefined; if (at !== undefined) marks[mark] = at; }+ return { from: "page", timeOrigin, marks, net: netOf(body.net) };+ }+ if (body.from !== "main") return null;+ const processStart = epoch(body.processStart);+ if (processStart === undefined || typeof body.launchId !== "string" || !LAUNCH_ID.test(body.launchId)) return null;+ const given = fields(body.marks), marks: MainPart["marks"] = {};+ for (const mark of MAIN_MARKS) { const at = Object.hasOwn(given, mark) ? ms(given[mark]) : undefined; if (at !== undefined) marks[mark as LaunchMark] = at; }+ const givenSpans = fields(body.spans), spans: MainPart["spans"] = {};+ for (const span of ["keychain", "lease"] as const) { const took = Object.hasOwn(givenSpans, span) ? ms(givenSpans[span]) : undefined; if (took !== undefined) spans[span] = took; }+ return {+ from: "main", launchId: body.launchId, processStart, marks, spans, children: childrenOf(body.children, "main"), net: netOf(body.net),+ appVersion: typeof body.appVersion === "string" && VERSION.test(body.appVersion) ? body.appVersion : null,+ platform: typeof body.platform === "string" && PLATFORMS.has(body.platform) ? body.platform : null,+ arch: typeof body.arch === "string" && ARCHES.has(body.arch) ? body.arch : null, hidden: body.hidden === true,+ };+}++/** A record read back from the file: anything unchecked is dropped, anything malformed is no record. */+export function parseLaunch(raw: unknown): LaunchRecord | null {+ const body = fields(raw);+ const at = epoch(body.at);+ if (at === undefined) return null;+ const given = fields(body.ms), marks: LaunchRecord["ms"] = {};+ for (const mark of LAUNCH_MARKS) { const value = Object.hasOwn(given, mark) ? ms(given[mark]) : undefined; if (value !== undefined) marks[mark] = value; }+ const givenSpans = fields(body.spans), spans: LaunchRecord["spans"] = {};+ for (const span of LAUNCH_SPANS) { const took = Object.hasOwn(givenSpans, span) ? ms(givenSpans[span]) : undefined; if (took !== undefined) spans[span] = took; }+ const children = (Array.isArray(body.children) ? body.children : []).flatMap((entry) => {+ const one = fields(entry);+ return one.where === "main" || one.where === "server" ? childrenOf([one], one.where) : [];+ }).slice(0, CHILDREN_KEPT * 2);+ return {+ at, appVersion: typeof body.appVersion === "string" && VERSION.test(body.appVersion) ? body.appVersion : null,+ platform: typeof body.platform === "string" && PLATFORMS.has(body.platform) ? body.platform : null,+ arch: typeof body.arch === "string" && ARCHES.has(body.arch) ? body.arch : null,+ cold: typeof body.cold === "boolean" ? body.cold : null, hidden: body.hidden === true, bots: count(body.bots), threads: count(body.threads),+ ms: marks, spans, children, net: netOf(body.net),+ parts: (["main", "page", "server"] as const).filter((part) => Array.isArray(body.parts) && body.parts.includes(part)),+ };+}++/** The phases a day's histograms are kept for: three marks, and two gaps between marks. */+export const LAUNCH_PHASES = ["splashShown", "windowShown", "chatDrawn", "forkToListening", "keychain"] as const;+export type LaunchPhase = (typeof LAUNCH_PHASES)[number];+export function launchPhaseMs(launch: LaunchRecord): Partial<Record<LaunchPhase, number>> {+ const { serverForked, serverListening } = launch.ms;+ return {+ splashShown: launch.ms.splashShown, windowShown: launch.ms.windowShown, chatDrawn: launch.ms.chatDrawn,+ forkToListening: serverForked !== undefined && serverListening !== undefined && serverListening >= serverForked ? serverListening - serverForked : undefined,+ keychain: launch.spans.keychain,+ };+}++interface DaySlot { day: number; launches: number; cold: number; phases: Partial<Record<LaunchPhase, Histogram>> }+export interface LaunchPhaseStats { p50: number; p90: number; max: number; n: number }+export interface LaunchStats { days: number; launches: number; cold: number; phases: Partial<Record<LaunchPhase, LaunchPhaseStats>> }++export interface LaunchTimingsOptions {+ /** The saved ring and days; absent: memory only. */+ file?: string;+ now?: () => number;+ /** Seconds since the computer started. */+ uptimeS?: () => number;+ counts?: () => { bots: number; threads: number };+ /** This server's own start and what it started and asked for, read once when the record is written. */+ server?: () => { startedAt: number; listeningAt: number; children?: unknown; net?: unknown } | null;+ /** This server's launch id (the one its parent gave it); a main part under another id is not this launch. */+ launchId?: string | null;+ settleMs?: number;+}++export function createLaunchTimings(options: LaunchTimingsOptions = {}) {+ const now = options.now ?? Date.now;+ const settleMs = options.settleMs ?? LAUNCH_SETTLE_MS;+ const ring: LaunchRecord[] = [];+ const days = new Map<number, DaySlot>();+ let lastLaunchAt = 0;+ let main: MainPart | null = null, page: PagePart | null = null;+ let recorded = false, settle: ReturnType<typeof setTimeout> | null = null;++ if (options.file) {+ try {+ const saved = JSON.parse(readFileSync(options.file, "utf8")) as { v?: number; ring?: unknown[]; days?: unknown[]; lastLaunchAt?: unknown };+ if (saved?.v === 1) {+ for (const raw of (Array.isArray(saved.ring) ? saved.ring : []).slice(-LAUNCH_RING_CAP)) { const launch = parseLaunch(raw); if (launch) ring.push(launch); }+ for (const raw of (Array.isArray(saved.days) ? saved.days : []).slice(-LAUNCH_DAYS_KEPT)) {+ const one = fields(raw);+ if (typeof one.day !== "number" || !Number.isSafeInteger(one.day) || one.day < 0) continue;+ const given = fields(one.phases), phases: DaySlot["phases"] = {};+ for (const phase of LAUNCH_PHASES) if (Object.hasOwn(given, phase)) phases[phase] = parseHistogram(given[phase]);+ days.set(one.day, { day: one.day, launches: count(one.launches), cold: count(one.cold), phases });+ }+ lastLaunchAt = epoch(saved.lastLaunchAt) ?? 0;+ }+ } catch {}+ }++ const save = () => {+ if (!options.file) return;+ try { writeFileAtomic(options.file, JSON.stringify({ v: 1, lastLaunchAt, ring, days: [...days.values()] }), { mode: 0o600, durable: false }); } catch {}+ };++ const serverPart = (): ServerPart | null => {+ let part: ReturnType<NonNullable<LaunchTimingsOptions["server"]>> = null;+ try { part = options.server?.() ?? null; } catch {}+ const startedAt = epoch(part?.startedAt), listeningAt = epoch(part?.listeningAt);+ return part && startedAt !== undefined && listeningAt !== undefined ? { startedAt, listeningAt, children: childrenOf(part.children, "server"), net: netOf(part.net) } : null;+ };+ const record = () => {+ if (recorded || !main) return;+ recorded = true;+ if (settle) clearTimeout(settle);+ settle = null;+ const start = main.processStart;+ const marks: LaunchRecord["ms"] = { ...main.marks };+ const spans: LaunchRecord["spans"] = { ...main.spans };+ const net: LaunchRecord["net"] = {};+ addNet(net, main.net);+ const parts: LaunchRecord["parts"] = ["main"];+ // A page that began long before or after this launch's window did is another load (a reload, another window).+ const navigated = main.marks.windowNavigated;+ const ours = page && navigated !== undefined && Math.abs(page.timeOrigin - (start + navigated)) <= 5_000 ? page : null;+ if (ours) {+ for (const mark of PAGE_MARKS) { const at = ours.marks[mark]; const offset = at === undefined ? undefined : ms(ours.timeOrigin + at - start); if (offset !== undefined) marks[mark] = offset; }+ addNet(net, ours.net);+ parts.push("page");+ }+ const children = [...main.children];+ const server = serverPart();+ if (server) {+ const started = ms(server.startedAt - start), listening = ms(server.listeningAt - start);+ if (started !== undefined) marks.serverStarted = started;+ if (listening !== undefined) marks.serverListening ??= listening;+ const boot = ms(server.listeningAt - server.startedAt);+ if (boot !== undefined) spans.serverBoot = boot;+ children.push(...server.children);+ addNet(net, server.net);+ parts.push("server");+ }+ const bootedAt = now() - (options.uptimeS ?? uptime)() * 1000;+ const counts = (() => { try { return options.counts?.() ?? { bots: 0, threads: 0 }; } catch { return { bots: 0, threads: 0 }; } })();+ const launch: LaunchRecord = {+ at: start, appVersion: main.appVersion, platform: main.platform, arch: main.arch,+ // With no earlier launch on record there is nothing to compare the computer's start with.+ cold: lastLaunchAt > 0 && Number.isFinite(bootedAt) && bootedAt > 0 ? lastLaunchAt < bootedAt : null, hidden: main.hidden,+ bots: count(counts.bots), threads: count(counts.threads), ms: marks, spans, children, net, parts,+ };+ lastLaunchAt = Math.max(lastLaunchAt, start);+ ring.push(launch);+ if (ring.length > LAUNCH_RING_CAP) ring.splice(0, ring.length - LAUNCH_RING_CAP);+ const day = Math.floor(start / DAY);+ const slot = days.get(day) ?? { day, launches: 0, cold: 0, phases: {} };+ slot.launches += 1;+ if (launch.cold) slot.cold += 1;+ for (const [phase, value] of Object.entries(launchPhaseMs(launch)) as Array<[LaunchPhase, number | undefined]>) {+ if (value !== undefined) addTo(slot.phases[phase] ??= emptyHistogram(), value);+ }+ days.set(day, slot);+ for (const old of [...days.keys()].sort((left, right) => left - right).slice(0, Math.max(0, days.size - LAUNCH_DAYS_KEPT))) days.delete(old);+ save();+ };+ const settleSoon = () => {+ if (recorded || settle) return;+ settle = setTimeout(record, settleMs);+ settle.unref?.();+ };++ return {+ /** A part from the main process or the page. `complete` once this launch's record is written: the sender may stop. */+ note(raw: unknown): { ok: boolean; complete: boolean } {+ const part = parseLaunchPart(raw);+ if (!part) return { ok: false, complete: recorded };+ if (recorded) return { ok: true, complete: true };+ if (part.from === "main") {+ if (options.launchId && part.launchId !== options.launchId) return { ok: false, complete: false };+ if (ring.some((launch) => launch.at === part.processStart)) { recorded = true; return { ok: true, complete: true }; }+ main = part;+ } else page ??= part;+ // A hidden start has no page to wait for.+ if (main && (page || main.hidden)) record(); else settleSoon();+ return { ok: true, complete: recorded };+ },+ recent: (limit = LAUNCH_RING_CAP): LaunchRecord[] => ring.slice(-limit).map((launch) => ({ ...launch, ms: { ...launch.ms }, spans: { ...launch.spans }, children: launch.children.map((child) => ({ ...child })), net: { ...launch.net }, parts: [...launch.parts] })),+ stats(windowDays = LAUNCH_DAYS_KEPT): LaunchStats {+ const from = Math.floor(now() / DAY) - windowDays;+ const merged: Partial<Record<LaunchPhase, Histogram>> = {};+ let launches = 0, cold = 0;+ for (const slot of days.values()) {+ if (slot.day <= from) continue;+ launches += slot.launches; cold += slot.cold;+ for (const phase of LAUNCH_PHASES) if (slot.phases[phase]) mergeInto(merged[phase] ??= emptyHistogram(), slot.phases[phase]);+ }+ const phases: LaunchStats["phases"] = {};+ for (const phase of LAUNCH_PHASES) {+ const histogram = merged[phase];+ if (histogram && countOf(histogram)) phases[phase] = { p50: histogramQuantile(histogram, 0.5), p90: histogramQuantile(histogram, 0.9), max: histogram.max, n: countOf(histogram) };+ }+ return { days: windowDays, launches, cold, phases };+ },+ /** A clean exit: a launch still waiting for its page is recorded as it stands. */+ flush() { record(); },+ };+}+export type LaunchTimings = ReturnType<typeof createLaunchTimings>;diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.tsindex f12bad7e24..788799f0ac 100644--- a/server/perf/perf-host.ts+++ b/server/perf/perf-host.ts@@ -14,6 +14,7 @@ import { createProcessSampler, linuxProcessList, LINUX_SAMPLE_MS, nodeUtilizatioimport { createSetupClock, type SetupClock, type SetupMs } from "./setup-steps.ts";import 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";export const PERF_FILE = "perf-timings.json";/** One line per kind of slow event at most this often; the ones held back are counted on the next. */@@ -45,6 +46,8 @@ export interface PerfHostDeps {pruneOwners?: (rows: readonly ProcessRow[]) => void;/** The memory one bot may use and how it is enforced (bot-memory-cap.ts). */cap?: () => BotCapReport;+ /** The desktop app started this server: its launches are recorded (launch-timings.ts). */+ launches?: Pick<NonNullable<Parameters<typeof createLaunchTimings>[0]>, "launchId" | "counts" | "server">;}/** The health report shows this many bots, the ones using the most memory first; the admin's read shows every one. */@@ -77,6 +80,7 @@ export function createPerfHost(deps: PerfHostDeps) {file: join(deps.dataDir, PERF_FILE), now, botOf: (threadId) => deps.store.botByThread(threadId)?.id ?? null,slow: (note) => say(note.kind, slowLine(note, now())),});+ const launches: LaunchTimings | null = deps.launches ? createLaunchTimings({ file: join(deps.dataDir, LAUNCH_FILE), now, ...deps.launches }) : null;/** Runs `read`, or logs once a minute and returns `fallback`: nothing the recorder does may fail its caller. */const guarded = <T>(what: string, read: () => T, fallback: T): T => {try { return read(); } catch (error) { say(`failed:${what}`, `the performance recorder failed (${what}): ${error instanceof Error ? error.name : "error"}`); return fallback; }@@ -111,7 +115,8 @@ export function createPerfHost(deps: PerfHostDeps) {if (deps.timer !== false && linux) guarded("limits", () => (deps.log ?? ((line: string) => console.warn(line)))(processes.startLine()), undefined);const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report(), stalls: guarded("stalls", () => stalls.report(), null), processes: processes.report(),- bots: windows ? null : guarded("bots", () => botReport(BOTS_IN_HEALTH), null) });+ bots: windows ? null : guarded("bots", () => botReport(BOTS_IN_HEALTH), null),+ launches: launches ? guarded("launches", () => ({ stats: launches.stats(), recent: launches.recent() }), null) : null });return {timings,sampler,@@ -124,6 +129,8 @@ export function createPerfHost(deps: PerfHostDeps) {/** Times one direct turn's setup; its laps go to `noteSetup` just before the engine is asked. */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),/** 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),@@ -136,7 +143,7 @@ export function createPerfHost(deps: PerfHostDeps) {return guarded("text", () => perfLines(sources(), timings.recent({ limit: RECENT_IN_REPORT }), "Latest turns, newest last:"), PERF_UNAVAILABLE).join("\n");},/** The graceful shutdown: no more samples, and the turns since the last save written now. */- stop() { sampler.stop(); stalls.stop(); guarded("save", () => timings.flush(), undefined); },+ stop() { sampler.stop(); stalls.stop(); guarded("save", () => timings.flush(), undefined); if (launches) guarded("launch", () => launches.flush(), undefined); },};}export type PerfHost = ReturnType<typeof createPerfHost>;diff --git a/server/perf/perf-privacy.test.ts b/server/perf/perf-privacy.test.tsindex 6117ff13e5..f02861514c 100644--- a/server/perf/perf-privacy.test.ts+++ b/server/perf/perf-privacy.test.ts@@ -8,6 +8,7 @@ import type { RuntimeEvent } from "../contracts.ts";import { buildDevsReport } from "../devs-report.ts";import type { StoreChange } from "../store.ts";import { createPerfHost, PERF_FILE } from "./perf-host.ts";+import { createLaunchTimings, LAUNCH_CHILDREN, LAUNCH_FILE, LAUNCH_HOSTS, LAUNCH_MARKS, LAUNCH_SPANS } from "./launch-timings.ts";import { PERF_HEALTH_MAX_BYTES, perfHealth } from "./perf-report.ts";import { SETUP_STEPS } from "./setup-steps.ts";import { createProcessSampler, type ProcessList } from "./process-sampler.ts";@@ -156,6 +157,58 @@ describe("a tampered file read back", () => {});});+describe("the launch record carries no content", () => {+ const bad = SECRETS.join(" ");+ const poisoned = (from: "main" | "page") => ({+ from, launchId: "launch-0001", processStart: START, timeOrigin: START + 800, hidden: false,+ appVersion: bad, platform: "/Users/ada/Projects/acme-merger/plan.md", arch: "[email protected]", [bad]: bad, url: "https://intranet.acme.test/q?token=abc",+ marks: { ready: 100, windowNavigated: 790, windowShown: 900, chatDrawn: 300, [bad]: 5, "/Users/ada/Projects/acme-merger/plan.md": 6, note: bad },+ spans: { keychain: 9, [bad]: 4, "Ada's Claude": 2 },+ children: [{ name: "/Users/ada/Projects/acme-merger/bin/lookup_customer --token sk-ant-api03-PRIVATEPRIVATEPRIVATE1234567890", ms: 30, cwd: "/Users/ada/Projects/acme-merger", args: [bad] },+ { name: "Tallyspoon", ms: 4 }, { name: "ioreg", ms: 12, [bad]: bad }],+ net: { other: { n: 2, ms: 40, urls: ["https://intranet.acme.test/q?token=abc"] }, "intranet.acme.test": { n: 1, ms: 9 }, [bad]: { n: 1, ms: 1 } },+ });++ it("the saved file, the copied text, the health field and the log hold none of the seeded secrets, whatever the app and the page post", async () => {+ const dir = mkdtempSync(join(tmpdir(), "perf-launch-privacy-"));+ dirs.push(dir);+ const logged: string[] = [];+ const perf = createPerfHost({+ dataDir: dir, timer: false, now: () => START + 5_000, wholeMachine: false, log: (line) => logged.push(line),+ bus: { subscribe: () => () => {} }, store: { onChange: () => () => {}, botByThread: () => null },+ launches: { launchId: "launch-0001", counts: () => ({ bots: 3, threads: 7 }),+ server: () => ({ startedAt: START + 400, listeningAt: START + 700, children: poisoned("main").children, net: poisoned("main").net }) },+ });+ expect(perf.noteLaunch(poisoned("main"))).toEqual({ ok: true, complete: false });+ expect(perf.noteLaunch(poisoned("page"))).toEqual({ ok: true, complete: true });+ const saved = readFileSync(join(dir, LAUNCH_FILE), "utf8");+ const text = perf.text(), health = JSON.stringify(perf.health());+ expect(text).toContain("App launches (times from process start): 1 in the last 30 days");+ expect(text).toContain("programs started: other 2x 34ms, ioreg 12ms, other (server) 2x 34ms, ioreg (server) 12ms");+ expect(health).toContain('"launches":{');+ for (const [where, body] of Object.entries({ saved, text, health, log: logged.join("\n") })) expect(leaks(body), where).toEqual([]);+ const allowed = new Set<string>([...LAUNCH_MARKS, ...LAUNCH_SPANS, ...LAUNCH_CHILDREN, ...LAUNCH_HOSTS, "main", "server", "page", "darwin", "win32", "linux", "arm64", "x64", "ia32"]);+ const strings: string[] = [];+ JSON.stringify(JSON.parse(saved).ring, (_key, value) => { if (typeof value === "string") strings.push(value); return value; });+ expect(strings.filter((value) => !allowed.has(value))).toEqual([]);+ });++ it("a tampered file read back passes nothing but checked fields", () => {+ const dir = mkdtempSync(join(tmpdir(), "perf-launch-tampered-"));+ dirs.push(dir);+ const file = join(dir, LAUNCH_FILE);+ writeFileSync(file, JSON.stringify({ v: 1, lastLaunchAt: bad, ring: [{ at: START, appVersion: bad, platform: bad, arch: bad, cold: bad, hidden: bad, bots: bad, threads: -4,+ ms: { ready: 100, [bad]: 5, chatDrawn: bad }, spans: { keychain: 3, [bad]: 2 }, children: [{ name: bad, where: bad, n: 1, ms: 5 }, { name: bad, where: "main", n: 1, ms: 5 }, { name: "ioreg", where: "server", n: 2, ms: 9, extra: bad }],+ net: { [bad]: { n: 1, ms: 1 }, other: { n: 1, ms: 2, extra: bad } }, parts: ["main", bad], extra: bad }],+ days: [{ day: Math.floor(START / 86_400_000), launches: 2, cold: bad, phases: { chatDrawn: { counts: [bad], max: 1, sum: 1 }, [bad]: {} }, [bad]: bad }] }));+ const timings = createLaunchTimings({ file, now: () => START });+ expect(leaks(JSON.stringify({ recent: timings.recent(), stats: timings.stats() }))).toEqual([]);+ expect(timings.recent()).toEqual([{ at: START, appVersion: null, platform: null, arch: null, cold: null, hidden: false, bots: 0, threads: 0, ms: { ready: 100 }, spans: { keychain: 3 },+ children: [{ name: "other", where: "main", n: 1, ms: 5 }, { name: "ioreg", where: "server", n: 2, ms: 9 }], net: { other: { n: 1, ms: 2 } }, parts: ["main"] }]);+ expect(timings.stats()).toMatchObject({ launches: 2, cold: 0, phases: {} });+ });+});+describe("the perf field's size", () => {it("stays under PERF_HEALTH_MAX_BYTES with every part at its fullest", () => {let clock = START;@@ -178,7 +231,11 @@ describe("the perf field's size", () => {loop: { eluPct: 100, eluMaxPct: 100, driftP95Ms: 123_456, driftMaxMs: 1_234_567 } };const limits: EngineLimitsReport = { checkedAt: 0, engines: Array.from({ length: 20 }, (_, index) => ({ engine: `e${index}`, name: "n", driver: "claude" as const,window: "weekly" as const, usedPercent: 100, resetsAt: START + index, blocked: true, held: true })) };- const body = perfHealth({ hour: big.window(), day: big.day(), live: big.live(), limits, process: proc });+ const launchTimings = createLaunchTimings({ now: () => clock, uptimeS: () => 1, launchId: "launch-0001" });+ launchTimings.note({ from: "main", launchId: "launch-0001", processStart: clock - 600_000, appVersion: "0.1.170", platform: "darwin", arch: "arm64", hidden: true,+ marks: Object.fromEntries(LAUNCH_MARKS.map((mark, index) => [mark, 123_456 + index])), spans: { keychain: 123_456, lease: 123_456 } });+ const launches = { stats: launchTimings.stats(), recent: launchTimings.recent() };+ const body = perfHealth({ hour: big.window(), day: big.day(), live: big.live(), limits, process: proc, launches });const bytes = JSON.stringify(body).length;console.log(`perf health, every part full: ${bytes} bytes (budget ${PERF_HEALTH_MAX_BYTES})`);expect(bytes).toBeLessThanOrEqual(PERF_HEALTH_MAX_BYTES);diff --git a/server/perf/perf-report.ts b/server/perf/perf-report.tsindex d2406eb9e6..534bdc409c 100644--- a/server/perf/perf-report.ts+++ b/server/perf/perf-report.ts@@ -11,6 +11,7 @@ import { processHealthLines, trimmedProcessHealth, type ProcessHealth } from "./import type { ProcessReport } from "./process-sampler.ts";import { SETUP_STEPS, slowestSetupSteps, type SetupStats } from "./setup-steps.ts";import { RING_CAP, type LiveTurnView, type WindowStats } from "./turn-timings.ts";+import { launchHealth, launchLines, type LaunchSources } from "./launch-report.ts";import type { TurnTiming } from "./turn-record.ts";/** The health report's `perf` field is at most this many bytes of JSON; parts are dropped, least useful first, to fit. */@@ -34,6 +35,8 @@ export interface PerfSources {processes?: ProcessHealth | null;/** Each bot's processes, threads, memory and CPU, the most memory first (bot-footprint.ts); null where not sampled. */bots?: BotFootprintReport | null;+ /** The desktop app's own starts (launch-timings.ts); null where no app starts this server. */+ launches?: LaunchSources | null;}/** Engines refusing work, or within 10 points of their limit: driver kind, window, use and reset time only. */@@ -62,6 +65,7 @@ export function perfHealth(sources: PerfSources) {stalls: sources.stalls ?? null,processes: sources.processes ?? null,bots: sources.bots ?? null,+ launches: launchHealth(sources.launches),};const size = () => JSON.stringify(body).length;if (size() > PERF_HEALTH_MAX_BYTES) { body.h1.setup = setupOf(hour.setup, 2); body.h24.setup = setupOf(day.setup, 2); }@@ -70,6 +74,7 @@ export function perfHealth(sources: PerfSources) {if (size() > PERF_HEALTH_MAX_BYTES) body.h24.tools = body.h24.tools.slice(0, 4);if (size() > PERF_HEALTH_MAX_BYTES) body.live = body.live.slice(0, 2);if (size() > PERF_HEALTH_MAX_BYTES && body.processes) body.processes = trimmedProcessHealth(body.processes);+ if (size() > PERF_HEALTH_MAX_BYTES) body.launches = null;if (size() > PERF_HEALTH_MAX_BYTES) body.process = null;if (size() > PERF_HEALTH_MAX_BYTES) body.stalls = null;if (size() > PERF_HEALTH_MAX_BYTES) body.processes = null;@@ -149,6 +154,7 @@ export function perfLines(sources: PerfSources, recent: readonly TurnTiming[], rif (sources.stalls) lines.push(...stallLines(sources.stalls));if (sources.processes) lines.push(...processHealthLines(sources.processes));if (sources.bots) lines.push(...botFootprintLines(sources.bots));+ lines.push(...launchLines(sources.launches));lines.push(recentTitle);lines.push(...(recent.length ? recent.map((turn) => ` ${turnLine(turn)}`) : [" (none)"]));return lines;diff --git a/server/routes/perf-diagnostics.ts b/server/routes/perf-diagnostics.tsindex d7b0e639a8..07c8fb4ab2 100644--- a/server/routes/perf-diagnostics.ts+++ b/server/routes/perf-diagnostics.ts@@ -1,6 +1,7 @@// GET /api/diagnostics/performance: the performance recorder's plain lines for the desktop's diagnostics export.// GET /api/diagnostics/bots: every bot's processes, threads, memory and CPU at the last sample (perf/bot-footprint.ts), bot-// ids and numbers only. Both admin scope (request-auth's default), so on a Cloud home a bot's shell, a service-trust+// ids and numbers only. POST /api/diagnostics/launch: the desktop app's main process and its page each hand in their part+// of the launch record (perf/launch-timings.ts), which keeps only checked numbers and fixed codes. All admin scope (request-auth's default), so on a Cloud home a bot's shell, a service-trust// loopback caller, never reaches them.import type { BotFootprintReport } from "../perf/bot-footprint.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -8,8 +9,16 @@ import { PASS, type RouteHandler } from "./table.ts";export const PERF_DIAGNOSTICS_PATH = "/api/diagnostics/performance";export const BOT_FOOTPRINT_PATH = "/api/diagnostics/bots";-export function createPerfDiagnosticsRoutes(deps: { text(): string; bots?(): BotFootprintReport | null }): RouteHandler {- return async ({ res, path, method, json }) => {+export const LAUNCH_PATH = "/api/diagnostics/launch";+const LAUNCH_BODY_MAX = 16 * 1024;++export function createPerfDiagnosticsRoutes(deps: { text(): string; bots?(): BotFootprintReport | null; launch?(part: unknown): { ok: boolean; complete: boolean } | null }): RouteHandler {+ return async ({ req, res, path, method, json, readBody }) => {+ if (method === "POST" && path === LAUNCH_PATH) {+ res.setHeader("cache-control", "no-store");+ const noted = deps.launch ? deps.launch(await readBody(req, LAUNCH_BODY_MAX).catch(() => null)) : null;+ return json(res, noted ? 200 : 404, noted ?? { ok: false, complete: false });+ }if (method !== "GET" || (path !== PERF_DIAGNOSTICS_PATH && path !== BOT_FOOTPRINT_PATH)) return PASS;res.setHeader("cache-control", "no-store");if (path === BOT_FOOTPRINT_PATH) return json(res, 200, { bots: deps.bots?.() ?? null });diff --git a/src/lib/launch-marks.test.ts b/src/lib/launch-marks.test.tsnew file mode 100644index 0000000000..25cd217764--- /dev/null+++ b/src/lib/launch-marks.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "vitest";++import { GIVE_UP_AFTER_MS, pageHostKind, SETTLE_AFTER_CHAT_MS, startLaunchMarks, type LaunchMarkDeps, type PageLaunchPart } from "./launch-marks";++const OWN = "http://127.0.0.1:8799";++function page(overrides: Partial<LaunchMarkDeps> = {}) {+ const state = { clock: 0, present: new Set<string>(), changed: () => {}, watching: false, timers: [] as Array<{ run: () => void; ms: number }>, posts: [] as PageLaunchPart[] };+ const entries: Record<string, Array<{ name: string; startTime: number; duration: number; responseStart?: number; responseEnd?: number }>> = {+ navigation: [{ name: `${OWN}/`, startTime: 0, duration: 60, responseStart: 28 }],+ paint: [{ name: "first-paint", startTime: 150, duration: 0 }, { name: "first-contentful-paint", startTime: 170, duration: 0 }],+ longtask: [{ name: "self", startTime: 176, duration: 119 }, { name: "self", startTime: 400, duration: 120 }],+ resource: [+ { name: `${OWN}/api/bots?messages=200`, startTime: 170, duration: 6, responseEnd: 176 },+ { name: "https://www.google.com/s2/favicons?domain=intranet.acme.test&sz=64", startTime: 128, duration: 19, responseEnd: 147 },+ { name: "https://accounts.openmausbot.com/session?token=abc", startTime: 200, duration: 80, responseEnd: 280 },+ { name: "https://omb-u-1.fly.dev/api/health", startTime: 900, duration: 10, responseEnd: 910 },+ { name: "data:image/png;base64,AAAA", startTime: 10, duration: 1, responseEnd: 11 },+ ],+ };+ startLaunchMarks({+ has: (selector) => state.present.has(selector),+ watch(changed) { state.changed = changed; state.watching = true; return () => { state.watching = false; }; },+ now: () => state.clock, timeOrigin: 1_800_000_000_860, origin: OWN,+ entries: (type) => entries[type] ?? [],+ later: (run, ms) => { state.timers.push({ run, ms }); },+ post: (part) => { state.posts.push(part); },+ ...overrides,+ });+ return state;+}++describe("the page's launch marks", () => {+ it("are posted once, a moment after the chat is drawn: times and counts by kind of host, never an address", () => {+ const state = page();+ expect(state.timers.map((timer) => timer.ms)).toEqual([GIVE_UP_AFTER_MS]);+ state.clock = 335;+ state.present.add("[data-sidebar-bot-row]");+ state.changed();+ expect(state.watching).toBe(true);+ state.clock = 340;+ state.present.add("[data-mid]");+ state.changed();+ expect(state.watching).toBe(false);+ expect(state.posts).toEqual([]);+ expect(state.timers.map((timer) => timer.ms)).toEqual([GIVE_UP_AFTER_MS, SETTLE_AFTER_CHAT_MS]);+ state.clock = 1_840;+ state.timers[1]!.run();+ state.timers[0]!.run();+ expect(state.posts).toEqual([{+ from: "page", timeOrigin: 1_800_000_000_860,+ marks: { sidebarDrawn: 335, chatDrawn: 340, pageResponse: 28, firstPaint: 170, lastLongTaskEnd: 520 },+ net: { other: { n: 1, ms: 19 }, accounts: { n: 1, ms: 80 } },+ }]);+ expect(JSON.stringify(state.posts)).not.toMatch(/acme|token|google|fly\.dev|https?:/);+ });++ it("go without a chat mark when no chat is drawn in time, and a chat already drawn is seen at once", () => {+ const none = page();+ none.clock = GIVE_UP_AFTER_MS;+ none.timers[0]!.run();+ expect(none.watching).toBe(false);+ expect(none.posts).toHaveLength(1);+ expect(none.posts[0]!.marks.chatDrawn).toBeUndefined();+ expect(none.posts[0]!.net).toEqual({ other: { n: 1, ms: 19 }, accounts: { n: 1, ms: 80 }, cloud: { n: 1, ms: 10 } });++ const state = { present: true };+ const drawn = page({ has: () => state.present });+ expect(drawn.watching).toBe(false);+ expect(drawn.timers.map((timer) => timer.ms)).toEqual([GIVE_UP_AFTER_MS, SETTLE_AFTER_CHAT_MS]);+ });++ it("cost nothing when the page cannot read its own timings or cannot post", () => {+ const broken = page({ entries: () => { throw new Error("no timings"); } });+ broken.timers[0]!.run();+ expect(broken.posts).toEqual([]);+ const refused = page({ post: () => { throw new Error("offline"); } });+ expect(() => refused.timers[0]!.run()).not.toThrow();+ });+});++describe("pageHostKind", () => {+ it("names a kind of host, and nothing for the page's own server", () => {+ expect(pageHostKind("/api/bots", OWN)).toBeNull();+ expect(pageHostKind("http://localhost:5173/x", OWN)).toBeNull();+ expect(pageHostKind("blob:http://127.0.0.1:8799/abc", OWN)).toBeNull();+ expect(pageHostKind("https://accounts.openmausbot.com/x", OWN)).toBe("accounts");+ expect(pageHostKind("https://c-opaque.openmausbot.com/x", OWN)).toBe("cloud");+ expect(pageHostKind("https://objects.githubusercontent.com/x", OWN)).toBe("updates");+ expect(pageHostKind("https://intranet.acme.test/q?token=abc", OWN)).toBe("other");+ });+});diff --git a/src/lib/launch-marks.ts b/src/lib/launch-marks.tsnew file mode 100644index 0000000000..30895209f3--- /dev/null+++ b/src/lib/launch-marks.ts@@ -0,0 +1,106 @@+// The page's part of the desktop app's launch record: when it first painted, when the sidebar and the open chat were+// drawn, and how many requests left this computer before then. Marks and counts only, posted once to the local server;+// a page that cannot post loses the record and nothing else.++/** With no chat drawn by then (none open, or a slow start), what there is goes anyway. */+export const GIVE_UP_AFTER_MS = 20_000;+/** After the chat is drawn, long tasks still finishing are waited for this long before the part is sent. */+export const SETTLE_AFTER_CHAT_MS = 1_500;+const SIDEBAR_ROW = "[data-sidebar-bot-row]", CHAT_ROW = "[data-mid]";++type HostKind = "accounts" | "cloud" | "updates" | "other";+export interface PageLaunchPart {+ from: "page";+ timeOrigin: number;+ marks: Partial<Record<"pageResponse" | "firstPaint" | "sidebarDrawn" | "chatDrawn" | "lastLongTaskEnd", number>>;+ net: Partial<Record<HostKind, { n: number; ms: number }>>;+}++/** The kind of host a request went to; null for this page's own server. */+export function pageHostKind(url: string, own: string): HostKind | null {+ let host: string;+ try {+ const parsed = new URL(url, own);+ if (parsed.origin === own || !/^https?:$/.test(parsed.protocol)) return null;+ host = parsed.hostname.toLowerCase();+ } catch { return "other"; }+ if (host === "127.0.0.1" || host === "localhost") return null;+ if (host === "github.com" || host.endsWith(".github.com") || host.endsWith(".githubusercontent.com")) return "updates";+ if (host === "accounts.openmausbot.com") return "accounts";+ if (host.endsWith(".openmausbot.com") || host.endsWith(".mausbot.cloud") || host.endsWith(".fly.dev")) return "cloud";+ return "other";+}++export interface LaunchMarkDeps {+ has(selector: string): boolean;+ /** Calls `changed` whenever the document's tree changes; returns how to stop. */+ watch(changed: () => void): () => void;+ now(): number;+ timeOrigin: number;+ origin: string;+ entries(type: "navigation" | "paint" | "longtask" | "resource"): ReadonlyArray<{ name: string; startTime: number; duration: number; responseStart?: number; responseEnd?: number }>;+ later(run: () => void, ms: number): void;+ post(part: PageLaunchPart): void;+}++/** Watches until the chat is drawn (or GIVE_UP_AFTER_MS), then posts once. */+export function startLaunchMarks(deps: LaunchMarkDeps): void {+ const marks: PageLaunchPart["marks"] = {};+ let sent = false;+ let stop = () => {};+ const send = () => {+ if (sent) return;+ sent = true;+ stop();+ try {+ const until = marks.chatDrawn ?? deps.now();+ const response = deps.entries("navigation")[0]?.responseStart;+ if (response !== undefined) marks.pageResponse = response;+ const paint = deps.entries("paint").find((entry) => entry.name === "first-contentful-paint");+ if (paint) marks.firstPaint = paint.startTime;+ const longEnd = Math.max(0, ...deps.entries("longtask").map((entry) => entry.startTime + entry.duration));+ if (longEnd > 0) marks.lastLongTaskEnd = longEnd;+ const net: PageLaunchPart["net"] = {};+ for (const entry of deps.entries("resource")) {+ if (entry.startTime > until) continue;+ const kind = pageHostKind(entry.name, deps.origin);+ if (!kind) continue;+ const kept = (net[kind] ??= { n: 0, ms: 0 });+ kept.n += 1; kept.ms += Math.round(Math.max(0, (entry.responseEnd || entry.startTime + entry.duration) - entry.startTime));+ }+ deps.post({ from: "page", timeOrigin: deps.timeOrigin, marks, net });+ } catch {}+ };+ const check = () => {+ if (marks.sidebarDrawn === undefined && deps.has(SIDEBAR_ROW)) marks.sidebarDrawn = deps.now();+ if (marks.chatDrawn === undefined && deps.has(CHAT_ROW)) {+ marks.chatDrawn = deps.now();+ stop();+ deps.later(send, SETTLE_AFTER_CHAT_MS);+ }+ };+ stop = deps.watch(check);+ deps.later(send, GIVE_UP_AFTER_MS);+ check();+}++/** In the desktop app's own window only: a browser tab and a remote home's page record nothing. */+export function startDesktopLaunchMarks(): void {+ if (!("ogb" in window) || !/^(127\.0\.0\.1|localhost)$/.test(location.hostname)) return;+ try {+ const longtasks: PerformanceEntry[] = [];+ try { new PerformanceObserver((list) => { longtasks.push(...list.getEntries()); }).observe({ type: "longtask", buffered: true }); } catch {}+ startLaunchMarks({+ has: (selector) => document.querySelector(selector) !== null,+ watch(changed) {+ const observer = new MutationObserver(changed);+ observer.observe(document.body, { childList: true, subtree: true });+ return () => observer.disconnect();+ },+ now: () => performance.now(), timeOrigin: performance.timeOrigin, origin: location.origin,+ entries: (type) => (type === "longtask" ? longtasks : performance.getEntriesByType(type)) as ReturnType<LaunchMarkDeps["entries"]>,+ later: (run, ms) => { setTimeout(run, ms); },+ post: (part) => { void fetch("/api/diagnostics/launch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(part), keepalive: true }).catch(() => {}); },+ });+ } catch {}+}diff --git a/src/main.tsx b/src/main.tsxindex 620b7fa75a..e098e7bb71 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -19,6 +19,7 @@ import { HomeScreen, SignedOutAtHome } from "./components/HomeScreen";import { PageBoundary } from "./components/PageBoundary";import { endedBeforeReload, forgetEndedSession } from "./lib/session-ended";import { signInGateShown } from "./lib/sign-in-gate";+import { startDesktopLaunchMarks } from "./lib/launch-marks";import "./styles.css";// Before first paint; settleInterfaceMode must run before applySkin writes omb-skin.@@ -35,6 +36,7 @@ const pageLanguage = loadPageLanguage();const PAGES_WITHOUT_THE_APP = new Set(["/home", "/pair", "/desktop-viewer"]);const loadApp = () => import("./App").catch((error: unknown) => ({ default: (): never => { throw error; } }));const appPage = PAGES_WITHOUT_THE_APP.has(location.pathname) ? null : loadApp();+if (appPage) startDesktopLaunchMarks();/** A team's name as its server describes itself to anyone (the descriptor's label), null when it can't say. */const teamName = () => fetch("/.well-known/openmausbot/environment").then((res) => res.json() as Promise<{ label?: unknown; capabilities?: { cloudTeam?: unknown } }>)