Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Desktop launch: read saved keys and the system proxy while the splash loads; a launch bench (#6651)
Milind Soni684eff585b2e
diff --git a/electron/boot-head-start.mjs b/electron/boot-head-start.mjsnew file mode 100644index 0000000000..c976a3a3b3--- /dev/null+++ b/electron/boot-head-start.mjs@@ -0,0 +1,16 @@+/** Launch work that waits on nothing before it, begun early and handed over when its turn in the boot order comes. A result is taken once: a later take runs the work afresh. */+export function createBootHeadStart(work) {+ const begun = new Map();+ const run = (name) => new Promise((resolve) => resolve(work[name]()));+ const quietUntilTaken = (pending) => { pending.catch(() => {}); return pending; };+ return {+ start() {+ for (const name of Object.keys(work)) if (!begun.has(name)) begun.set(name, quietUntilTaken(run(name)));+ },+ take(name) {+ const pending = begun.get(name);+ begun.delete(name);+ return pending ?? run(name);+ },+ };+}diff --git a/electron/boot-head-start.node-test.mjs b/electron/boot-head-start.node-test.mjsnew file mode 100644index 0000000000..403c5ac554--- /dev/null+++ b/electron/boot-head-start.node-test.mjs@@ -0,0 +1,38 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createBootHeadStart } from "./boot-head-start.mjs";++test("work begins at start and its one result is handed to the first taker", async () => {+ let runs = 0;+ const head = createBootHeadStart({ keys: async () => ({ run: (runs += 1) }) });+ head.start();+ head.start();+ assert.equal(runs, 1);+ assert.deepEqual(await head.take("keys"), { run: 1 });+ assert.equal(runs, 1);+});++test("a second take, and a take with no start, run the work afresh", async () => {+ let runs = 0;+ const head = createBootHeadStart({ proxy: async () => (runs += 1) });+ assert.equal(await head.take("proxy"), 1);+ head.start();+ assert.equal(await head.take("proxy"), 2);+ assert.equal(await head.take("proxy"), 3);+});++test("a failure waits for its taker, whether the work throws or rejects", async () => {+ const unhandled = [];+ const listen = (reason) => unhandled.push(reason);+ process.on("unhandledRejection", listen);+ try {+ const head = createBootHeadStart({ rejects: async () => { throw new Error("store busy"); }, throws: () => { throw new Error("no file"); } });+ head.start();+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(unhandled, []);+ await assert.rejects(head.take("rejects"), /store busy/);+ await assert.rejects(head.take("throws"), /no file/);+ } finally {+ process.off("unhandledRejection", listen);+ }+});diff --git a/electron/main.mjs b/electron/main.mjsindex 42de561661..59ad69c5d5 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -110,7 +110,7 @@ import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";import { createHomeWindow, installHomeWindowIpc, HOME_SCREEN_PATH } from "./home-window.mjs";import { createTeamProfileSeeds } from "./team-profile-seed.mjs";import { createHomePlaces } from "./home-places.mjs"; import { openStartPlace } from "./start-place.mjs"; import { createDesktopRing, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs"; import { openComputerSettings } from "./open-computer-settings.mjs"; import { createPlacesTogether, installPlacesTogether, PLACES_TOGETHER_FILE } from "./places-together.mjs"; import { createBotLinkMain } from "./bot-link-main.mjs";-import { createWindowStateFile } from "./window-state-file.mjs"; import { createSystemProxyCache } from "./system-proxy.mjs";+import { createWindowStateFile } from "./window-state-file.mjs"; import { createSystemProxyCache } from "./system-proxy.mjs"; import { createBootHeadStart } from "./boot-head-start.mjs";import { createEnvironmentsFile, ENVIRONMENTS_SAVE_FAILED } from "./environments-file.mjs";import { createOrgLibrary } from "./org-library.mjs";import { createCompanyBackups } from "./company-backups.mjs";@@ -289,7 +289,7 @@ 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(); // A Mac app opened from Finder never gets the shell's proxy.+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 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");@@ -1190,7 +1190,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmenasync function startServerPackaged() {let everyPortForeignOwned = true;- await systemProxy.refresh();+ await bootHeadStart.take("proxy");for (let attempt = 0; attempt < 2; attempt++) {for (const port of DESKTOP_PORTS) {if (desktopShutdownStarted) return false;@@ -2811,7 +2811,7 @@ app.whenReady().then(async () => {onShow: (win) => desktopTray?.windowShown(win),onFinished: () => { startupScreen = null; }, onReveal: via => launchAnalytics.stage("window_shown", { reason: via }),});- await startupScreen?.ready;+ bootHeadStart.start(); await startupScreen?.ready;if (desktopShutdownStarted) return;session.defaultSession.on("will-download", (_event, item) => {if (mediaDownloads.claim(item)) return;@@ -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 loadSecureCredentials();+ secureCredentials = await bootHeadStart.take("credentials");// 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/scripts/bench-launch.mjs b/scripts/bench-launch.mjsnew file mode 100644index 0000000000..623a02ceda--- /dev/null+++ b/scripts/bench-launch.mjs@@ -0,0 +1,238 @@+#!/usr/bin/env node+// The desktop app's launch, phase by phase, on isolated folders only: Electron's own main module packed as an asar and+// run in packaged mode on this checkout's Electron, the bundled server (dist-server) and the built pages (dist), a+// 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]+// --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).+// 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`).+import { spawn, execFileSync } from "node:child_process";+import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { get as httpGet } 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 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 },+} });+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-)");+mkdirSync(values.root, { recursive: true });+const root = realpathSync(values.root);+const appRoot = resolve(values.app);+for (const needed of ["electron/main.mjs", "dist/index.html", "dist-server/desktop-entry.mjs"]) {+ if (!existsSync(join(appRoot, needed))) throw new Error(`${appRoot} has no ${needed}; run pnpm build && pnpm build:server there`);+}+const BENCH_PORTS = [38799, 48799, 58799];+const paths = {+ home: join(root, "home"), tmp: join(root, "tmp"), data: join(root, "data"), userData: join(root, values.dev ? "user-data-dev" : "user-data"), stage: join(root, `stage-${values.label}`),+ egress: join(root, "egress.log"), seed: join(root, "seed.json"), results: join(root, "results"),+};+for (const dir of [paths.home, paths.tmp, paths.userData, paths.results]) mkdirSync(dir, { recursive: true });++function stage() {+ rmSync(paths.stage, { recursive: true, force: true });+ const appDir = join(paths.stage, "app"), resources = join(paths.stage, "resources");+ cpSync(join(appRoot, "electron"), join(appDir, "electron"), { recursive: true, filter: (source) => !/\.test\.|node-test\.|[\\/]node_modules([\\/]|$)/.test(source) });+ mkdirSync(join(appDir, "src", "locales"), { recursive: true });+ for (const file of readdirSync(join(appRoot, "src", "locales"))) if (file.endsWith(".json") && file !== "source-hashes.json") cpSync(join(appRoot, "src", "locales", file), join(appDir, "src", "locales", file));+ const manifest = JSON.parse(readFileSync(join(appRoot, "package.json"), "utf8"));+ writeFileSync(join(appDir, "package.json"), JSON.stringify({ name: "openmausbot-bench-launch", productName: "OpenMausBot Bench", version: manifest.version, type: "module", main: "bench-launch-entry.mjs" }));+ cpSync(join(HERE, "testing", "bench-launch-entry.mjs"), join(appDir, "bench-launch-entry.mjs"));+ // The installed app owns the real ports; a measured launch never knocks on them.+ const portsFile = join(appDir, "electron", "desktop-ports.mjs");+ const ports = readFileSync(portsFile, "utf8");+ if (!ports.includes("[8799, 18799, 28799]")) throw new Error("electron/desktop-ports.mjs no longer lists the ports this bench replaces");+ writeFileSync(portsFile, ports.replace("[8799, 18799, 28799]", JSON.stringify(BENCH_PORTS)));+ mkdirSync(resources, { recursive: true });+ for (const [name, from] of [["ui", "dist"], ["server", "dist-server"], ["skills", "skills"]]) symlinkSync(join(appRoot, from), join(resources, name));+ const blocker = join(paths.stage, "bench-launch-block.cjs");+ cpSync(join(HERE, "testing", "bench-launch-block.cjs"), blocker);+ let entry = appDir;+ if (!values["no-asar"] && !values.dev) {+ const store = join(ROOT, "node_modules", ".pnpm");+ const packed = readdirSync(store).find((name) => name.startsWith("@electron+asar@"));+ if (!packed) throw new Error("@electron/asar is not installed; pass --no-asar");+ const asar = join(paths.stage, "app.asar");+ execFileSync(process.execPath, ["-e", `require(${JSON.stringify(join(store, packed, "node_modules", "@electron", "asar"))}).createPackage(${JSON.stringify(appDir)}, ${JSON.stringify(asar)}).then(() => process.exit(0), (error) => { console.error(error); process.exit(1); })`], { stdio: "inherit" });+ entry = asar;+ }+ return { entry, resources, blocker };+}++function seed() {+ if (existsSync(paths.seed)) return JSON.parse(readFileSync(paths.seed, "utf8"));+ const [bots, threads, messages] = values.seed.split(",");+ mkdirSync(join(paths.data, "tmp"), { recursive: true });+ const out = execFileSync(process.execPath, ["--experimental-strip-types", join(appRoot, "scripts", "testing", "bench-desktop-seed.ts"), bots, threads, messages], {+ cwd: appRoot, encoding: "utf8", maxBuffer: 16 * 1024 * 1024,+ env: { PATH: dirname(process.execPath), HOME: paths.data, OMB_DATA_DIR: paths.data, TMPDIR: join(paths.data, "tmp") },+ });+ const seeded = JSON.parse(out.trim().split("\n").at(-1));+ writeFileSync(join(paths.data, "config.json"), JSON.stringify({+ features: { smartSetupChoices: false },+ instances: { claude: { driver: "claudeAgent", config: { cli: join(appRoot, "server", "testing", "fake-claude-cli.ts") } } },+ }));+ writeFileSync(paths.seed, JSON.stringify(seeded));+ return seeded;+}++const STORAGE = { "omb-analytics-opt-out": "1", "omb-email-gate": "skipped", "omb-simple-mode-prompt": "1", "grok-move-2026-11": "1", "teams-2026-11b": "1", "modelgo-offer-2026-11": "1", "omb-advanced-mode": "0" };+const electron = require("electron");+const DEV_PAGE_PORT = BENCH_PORTS[0] - 3600;+const fixtureEnv = () => ({+ PATH: dirname(process.execPath), HOME: paths.home, CFFIXED_USER_HOME: paths.home, TMPDIR: paths.tmp, LANG: process.env.LANG ?? "en_US.UTF-8",+ OMB_DATA_DIR: paths.data, OMB_WEBHOOK_PORT: String(BENCH_PORTS[0] + 1), OMB_TEST_SEALED_PATH: "1", OMB_DISABLE_ANNOUNCEMENTS: "1", FAKE_CLAUDE_MODE: "happy",+ OMB_BENCH_EGRESS_LOG: paths.egress,+});+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 = [];+async function startDevServers() {+ const env = { ...fixtureEnv(), OMB_PORT: String(BENCH_PORTS[0]), OMB_UI_PORT: String(DEV_PAGE_PORT) };+ devChildren.push(spawn(process.execPath, ["--require", staged.blocker, "--experimental-strip-types", join(appRoot, "server", "dev-server.ts")], { cwd: appRoot, env, stdio: "ignore" }));+ devChildren.push(spawn(process.execPath, [join(appRoot, "node_modules", "vite", "bin", "vite.js"), "--strictPort"], { cwd: appRoot, env, stdio: "ignore" }));+ for (const url of [`http://127.0.0.1:${BENCH_PORTS[0]}/api/health`, `http://127.0.0.1:${DEV_PAGE_PORT}/`]) {+ const deadline = Date.now() + 60_000;+ while (!(await answers(url))) { if (Date.now() > deadline) throw new Error(`${url} did not answer`); await new Promise((r) => setTimeout(r, 200)); }+ }+}+const stopDevServers = () => { for (const child of devChildren) child.kill("SIGTERM"); };+const staged = stage();+if (!existsSync(join(paths.userData, "desktop-prefs.json"))) writeFileSync(join(paths.userData, "desktop-prefs.json"), JSON.stringify({ seen: [], analytics: false }));+const seeded = seed();++let logRead = 0;+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,+ 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`) } : {}),+ };+ const env = {+ ...fixtureEnv(), OMB_BENCH_LAUNCH: JSON.stringify(config), NODE_OPTIONS: `--require ${staged.blocker}`,+ ...(values.dev ? { ELECTRON_START_URL: `http://127.0.0.1:${DEV_PAGE_PORT}` } : {}),+ };+ const args = [staged.entry, "--use-mock-keychain", "--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1 , EXCLUDE localhost", `--user-data-dir=${paths.userData}`];+ return new Promise((done) => {+ const spawnedAt = Date.now();+ const child = spawn(electron, args, { env, cwd: paths.tmp, stdio: ["ignore", "pipe", "pipe"] });+ let output = "";+ child.stdout.on("data", (chunk) => { output += chunk; });+ child.stderr.on("data", (chunk) => { output += chunk; });+ const timer = setTimeout(() => child.kill("SIGKILL"), 120_000);+ child.once("exit", (code, signal) => {+ clearTimeout(timer);+ if (!existsSync(out)) { done({ failed: true, code, signal, output: output.slice(-3000) }); return; }+ const run = JSON.parse(readFileSync(out, "utf8"));+ const logFile = join(run.derived.logs, "server.log");+ const whole = existsSync(logFile) ? readFileSync(logFile, "utf8") : "";+ const serverLog = whole.slice(logRead);+ logRead = whole.length;+ done({ ...run, spawnedAt, code, serverLog, output: output.slice(-1500) });+ });+ });+}++const round = (value) => (Number.isFinite(value) ? Math.round(value) : null);+const median = (samples) => { const sorted = samples.filter(Number.isFinite).sort((a, b) => a - b); return sorted.length ? sorted[Math.floor(sorted.length / 2)] : null; };+function phases(run) {+ const zero = run.processStart;+ const first = (name, test = () => true) => run.marks.find((entry) => entry.name === name && test(entry))?.t;+ const local = (entry) => /^http:\/\/127\.0\.0\.1:\d+\/?(\?|#|$)/.test(entry.url ?? "");+ const mainNav = run.marks.find((entry) => entry.name === "nav-start" && local(entry));+ const windowIds = run.marks.filter((entry) => entry.name === "window-created").map((entry) => entry.id);+ const shows = run.marks.filter((entry) => entry.name === "window-show");+ const page = run.page ?? {};+ const at = (ms) => (Number.isFinite(ms) ? page.timeOrigin + ms : undefined);+ const logAt = (pattern) => { const line = run.serverLog.split("\n").find((entry) => pattern.test(entry)); const stamp = line && /^\[([^\]]+)\]/.exec(line)?.[1]; return stamp ? Date.parse(stamp) : undefined; };+ const longEnd = (page.longtasks ?? []).reduce((latest, [start, duration]) => Math.max(latest, start + duration), 0);+ const relative = {+ spawnToProcess: zero - run.spawnedAt,+ entry: first("entry"), mainImported: first("main-import:end"), ready: first("ready"),+ splashCreated: first("window-created", (entry) => entry.id === windowIds[0]), splashShown: shows[0]?.t,+ credentialsRead: first("credentials-decrypt:end"), proxyRead: first("resolveProxy:end"),+ fork: first("fork"), forkSpawned: first("fork-spawned"), serverListening: logAt(/\[out\].*openmausbot server on /),+ mainWindowCreated: first("window-created", (entry) => entry.id === windowIds[1]), pageNavStart: mainNav?.t,+ pageResponse: at(page.nav?.responseStart), domContentLoaded: at(page.nav?.dcl), rootFilled: page.seen?.root,+ mainWindowShown: shows.find((entry) => entry.id === windowIds[1])?.t, firstContentfulPaint: at(page.paints?.["first-contentful-paint"]),+ sidebarFirstRow: page.seen?.sidebarRow, sidebarRows: page.seen?.sidebarRows, sidebarPainted: page.painted?.sidebarRows,+ firstMessage: page.seen?.anyMessage, lastMessage: page.seen?.lastMessage, lastMessagePainted: page.painted?.lastMessage,+ lastLongTaskEnd: longEnd ? at(longEnd) : undefined,+ };+ const result = Object.fromEntries(Object.entries(relative).map(([name, t]) => [name, name === "spawnToProcess" ? round(t) : round(t - zero)]));+ result.mainImportMs = round(first("main-import:end") - first("main-import:start"));+ const resources = page.resources ?? [];+ const scripts = resources.filter((entry) => /\.js(\?|$)/.test(entry.url));+ const api = resources.filter((entry) => entry.url.startsWith("/api/"));+ const beforeMessages = (entry) => page.seen?.lastMessage === undefined || page.timeOrigin + entry.start <= page.seen.lastMessage;+ result.counts = {+ scripts: scripts.length, scriptKb: round(scripts.reduce((sum, entry) => sum + entry.decoded, 0) / 1024), scriptTransferKb: round(scripts.reduce((sum, entry) => sum + entry.transfer, 0) / 1024),+ apiCalls: api.length, apiBeforeMessages: api.filter(beforeMessages).length, apiKb: round(api.reduce((sum, entry) => sum + entry.decoded, 0) / 1024),+ slowestApi: api.map((entry) => ({ url: entry.url.slice(0, 60), ms: round(entry.end - entry.start), startMs: round(entry.start) })).sort((a, b) => b.ms - a.ms).slice(0, 5),+ longTasks: (page.longtasks ?? []).length, longTaskMs: round((page.longtasks ?? []).reduce((sum, [, duration]) => sum + duration, 0)),+ syncFsBeforeFork: run.syncAt?.fork ?? null, syncFsBeforeMainShown: run.syncAt?.mainShown ?? null, syncFsDuringImport: run.syncAt?.importEnd && { calls: run.syncAt.importEnd.calls - run.syncAt.importStart.calls, ms: round(run.syncAt.importEnd.ms - run.syncAt.importStart.ms) },+ spawns: run.spawns.map((entry) => `${entry.fn} ${entry.command}${entry.ms === undefined ? "" : ` (${round(entry.ms)} ms)`} @${round(entry.t - zero)}`),+ egressRefused: run.egress.length, rows: page.rows, messages: page.messages, windows: windowIds.length,+ };+ return result;+}++function wipeCaches() {+ for (const name of ["Cache", "Code Cache", "GPUCache", "DawnGraphiteCache", "DawnWebGPUCache", "server-compile-cache", "Shared Dictionary"]) rmSync(join(paths.userData, name), { recursive: true, force: true });+}++const runs = [];+const failures = [];+if (values.dev) await startDevServers();+process.on("exit", stopDevServers);+const primedFile = join(root, values.dev ? "primed-dev" : "primed");+const primed = existsSync(primedFile);+if (!primed) {+ for (const name of ["prime-1", "prime-2"]) {+ log(`${name}: sets the page's kept choices and opens the long chat`);+ const run = await launch(name, { prime: name === "prime-1", screenshot: true });+ if (run.failed) { console.error(JSON.stringify(run, null, 1)); stopDevServers(); process.exit(1); }+ log(`${name}: rows=${run.page?.rows} messages=${run.page?.messages} steps=${JSON.stringify(run.steps)} egress=${run.egress.length}`);+ }+ writeFileSync(primedFile, new Date().toISOString());+}+const count = Number(values.runs);+if (!values.cold && count > 0) await launch("warmup");+for (let index = 0; index < count; index += 1) {+ if (values.cold) wipeCaches();+ const run = await launch(`${values.cold ? "cold" : "warm"}-${index + 1}`);+ if (run.failed || run.timedOut || !run.page?.seen?.lastMessage) { failures.push({ index, failed: run.failed ?? false, timedOut: run.timedOut ?? false, output: run.output, text: run.page?.text }); log(`run ${index + 1} did not reach the chat`); continue; }+ const measured = phases(run);+ runs.push(measured);+ log(`run ${index + 1}: ready ${measured.ready} · fork ${measured.fork} · listening ${measured.serverListening} · nav ${measured.pageNavStart} · shown ${measured.mainWindowShown} · sidebar ${measured.sidebarRows} · messages ${measured.lastMessage} · quiet ${measured.lastLongTaskEnd} (load ${loadavg()[0].toFixed(1)})`);+}+const names = runs[0] ? Object.keys(runs[0]).filter((name) => name !== "counts") : [];+const result = {+ label: values.label, app: appRoot, mode: `${values.dev ? "dev, " : ""}${values.cold ? "cold caches" : "warm"}`, runs: runs.length, failures,+ medianMs: Object.fromEntries(names.map((name) => [name, median(runs.map((run) => run[name]))])),+ minMs: Object.fromEntries(names.map((name) => [name, Math.min(...runs.map((run) => run[name]).filter(Number.isFinite))])),+ counts: runs.at(-1)?.counts ?? null, loadAverage: loadavg().map((value) => Math.round(value * 10) / 10),+ egressLog: existsSync(paths.egress) ? readFileSync(paths.egress, "utf8").split("\n").filter((line) => line.includes("blocked")).slice(-20) : [],+ perRun: runs.map(({ counts: _counts, ...rest }) => rest),+};+const text = JSON.stringify(result, null, 1);+if (values.out) writeFileSync(values.out, text);+process.stdout.write(`${text}\n`);+stopDevServers();diff --git a/scripts/testing/bench-launch-block.cjs b/scripts/testing/bench-launch-block.cjsnew file mode 100644index 0000000000..b02fa3df2f--- /dev/null+++ b/scripts/testing/bench-launch-block.cjs@@ -0,0 +1,26 @@+// scripts/bench-launch.mjs loads this into the bench's Electron main process and, through NODE_OPTIONS, its server+// child: a Node socket to anything but this computer is refused and written down, so a measured launch never calls out.+const fs = require("node:fs");+const net = require("node:net");++const LOADED = Symbol.for("omb.bench-launch.block");+if (!globalThis[LOADED]) {+ globalThis[LOADED] = true;+ const file = process.env.OMB_BENCH_EGRESS_LOG;+ const note = (line) => {+ if (!file) return;+ try { fs.appendFileSync(file, `${Date.now()} pid=${process.pid} ${line}\n`); } catch {}+ };+ note(`loaded type=${process.type ?? "node"}`);+ const LOCAL = new Set(["127.0.0.1", "localhost", "::1", "[::1]", "0.0.0.0", "::"]);+ const connect = net.Socket.prototype.connect;+ net.Socket.prototype.connect = function (...args) {+ const first = Array.isArray(args[0]) ? args[0][0] : args[0];+ const options = first && typeof first === "object" ? first : { port: first, host: typeof args[1] === "string" ? args[1] : undefined };+ 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`)));+ return this;+ };+}diff --git a/scripts/testing/bench-launch-entry.mjs b/scripts/testing/bench-launch-entry.mjsnew file mode 100644index 0000000000..7404ee0260--- /dev/null+++ b/scripts/testing/bench-launch-entry.mjs@@ -0,0 +1,228 @@+// The Electron entry scripts/bench-launch.mjs stages beside a copy of electron/: it points the app at the bench's own+// temporary folders, refuses anything that would reach outside them (the network, the keychain, link and login-item+// registration, global shortcuts), stamps each launch phase on one clock, then loads the app's real main module.+import { app, globalShortcut, safeStorage, session, utilityProcess } from "electron";+import childProcess from "node:child_process";+import fs from "node:fs";+import { createRequire, syncBuiltinESMExports } from "node:module";+import path from "node:path";++const config = JSON.parse(process.env.OMB_BENCH_LAUNCH ?? "null");+if (!config) { console.error("bench-launch-entry runs only under scripts/bench-launch.mjs"); app.exit(64); await new Promise(() => {}); }+const require = createRequire(import.meta.url);+require(config.blocker);++const now = () => performance.timeOrigin + performance.now();+const marks = [];+const mark = (name, extra = {}) => { marks.push({ name, t: now(), ...extra }); };+mark("entry");+globalThis.__ombBenchMark = mark;++// Security: every folder the app derives must sit inside the bench root, checked before the app's code runs.+const real = (target) => {+ let known = path.resolve(target);+ const rest = [];+ while (!fs.existsSync(known) && path.dirname(known) !== known) { rest.unshift(path.basename(known)); known = path.dirname(known); }+ return path.join(fs.realpathSync(known), ...rest);+};+const inside = (target) => { const full = real(target); return full === config.root || full.startsWith(config.root + path.sep); };+const derived = {+ home: app.getPath("home"), appData: app.getPath("appData"), userData: app.getPath("userData"), logs: app.getPath("logs"),+ downloads: app.getPath("downloads"), dataDir: process.env.OMB_DATA_DIR ?? "", profiles: `${process.env.OMB_DATA_DIR ?? ""}-profiles`,+ envHome: process.env.HOME ?? "",+};+const outside = Object.entries(derived).filter(([, value]) => !value || !inside(value));+if (outside.length || !app.commandLine.hasSwitch("use-mock-keychain") || !app.commandLine.hasSwitch("host-resolver-rules")) {+ console.error(`bench-launch-entry: refusing to start: ${JSON.stringify({ outside, derived })}`);+ app.exit(65);+ await new Promise(() => {});+}++if (!config.dev) {+ Object.defineProperty(app, "isPackaged", { value: true, configurable: true });+ Object.defineProperty(process, "resourcesPath", { value: config.resources, configurable: true, enumerable: true });+}+const refused = {};+const refuse = (target, name, result) => { target[name] = (...args) => { refused[name] = (refused[name] ?? 0) + 1; return typeof result === "function" ? result(...args) : result; }; };+refuse(app, "setAsDefaultProtocolClient", true);+refuse(app, "setLoginItemSettings", undefined);+refuse(globalShortcut, "register", false);+refuse(globalShortcut, "registerAll", undefined);++// Synchronous file calls and child processes started on the main thread, by name.+const sync = { calls: 0, ms: 0, byName: {} };+for (const name of Object.keys(fs).filter((key) => key.endsWith("Sync") && typeof fs[key] === "function")) {+ const original = fs[name];+ fs[name] = Object.assign(function (...args) {+ const at = performance.now();+ try { return original.apply(this, args); } finally {+ const took = performance.now() - at;+ sync.calls += 1; sync.ms += took;+ const entry = (sync.byName[name] ??= { calls: 0, ms: 0 });+ entry.calls += 1; entry.ms += took;+ }+ }, original);+}+const spawns = [];+const command = (args) => [args[0], ...(Array.isArray(args[1]) ? args[1].slice(0, 2) : [])].map((part) => path.basename(String(part))).join(" ").slice(0, 120);+for (const name of ["spawn", "execFile", "exec", "fork", "spawnSync", "execFileSync", "execSync"]) {+ const original = childProcess[name];+ childProcess[name] = function (...args) {+ const at = now();+ try { return original.apply(this, args); } finally { spawns.push({ fn: name, command: command(args), t: at, ms: name.endsWith("Sync") ? now() - at : undefined }); }+ };+}+syncBuiltinESMExports();+const syncAt = {};+const snapshot = (name) => { syncAt[name] = { calls: sync.calls, ms: Math.round(sync.ms * 10) / 10 }; };++const timed = (target, name, label) => {+ const original = target[name];+ if (typeof original !== "function") return;+ target[name] = function (...args) {+ mark(`${label}:start`);+ const result = original.apply(this, args);+ Promise.resolve(result).then(() => mark(`${label}:end`), () => mark(`${label}:end`, { failed: true }));+ return result;+ };+};+timed(safeStorage, "decryptStringAsync", "credentials-decrypt");+timed(safeStorage, "encryptStringAsync", "credentials-encrypt");++const fork = utilityProcess.fork;+utilityProcess.fork = function (entry, ...rest) {+ const label = path.basename(String(entry));+ mark("fork", { entry: label }); snapshot("fork");+ const child = fork.call(this, entry, ...rest);+ child.once("spawn", () => mark("fork-spawned", { entry: label }));+ let listening = false;+ child.stdout?.on("data", (chunk) => { if (!listening && String(chunk).includes("openmausbot server on ")) { listening = true; mark("server-first-listen-line"); } });+ return child;+};++const COLLECT = (target) => `(() => {+ if (window.__ombLaunch) return;+ const L = window.__ombLaunch = { seen: {}, painted: {}, longtasks: [], paints: {} };+ const abs = () => performance.timeOrigin + performance.now();+ const checks = {+ root: () => (document.getElementById("root")?.childElementCount ?? 0) > 0,+ sidebarRow: () => Boolean(document.querySelector("[data-sidebar-bot-row]")),+ sidebarRows: () => document.querySelectorAll("[data-sidebar-bot-row]").length >= ${Number(target.rows) || 1},+ anyMessage: () => Boolean(document.querySelector("[data-mid]")),+ lastMessage: () => Boolean(document.querySelector(${JSON.stringify(`[data-mid="${target.lastMessageId ?? "-"}"]`)})),+ };+ const check = () => {+ for (const [name, test] of Object.entries(checks)) {+ if (L.seen[name] || !test()) continue;+ L.seen[name] = abs();+ requestAnimationFrame(() => requestAnimationFrame(() => { L.painted[name] = abs(); }));+ }+ };+ new MutationObserver(check).observe(document, { childList: true, subtree: true });+ check();+ try { new PerformanceObserver((list) => { for (const entry of list.getEntries()) L.longtasks.push([entry.startTime, entry.duration]); }).observe({ type: "longtask", buffered: true }); } catch {}+ try { new PerformanceObserver((list) => { for (const entry of list.getEntries()) L.paints[entry.name] = entry.startTime; }).observe({ type: "paint", buffered: true }); } catch {}+})()`;+const REPORT = `(() => {+ const L = window.__ombLaunch ?? { seen: {}, painted: {}, longtasks: [], paints: {} };+ const nav = performance.getEntriesByType("navigation")[0];+ return {+ timeOrigin: performance.timeOrigin, now: performance.now(), seen: L.seen, painted: L.painted, longtasks: L.longtasks, paints: L.paints,+ visibility: document.visibilityState, rows: document.querySelectorAll("[data-sidebar-bot-row]").length, messages: document.querySelectorAll("[data-mid]").length,+ title: document.title, text: (document.body?.innerText ?? "").slice(0, 400),+ nav: nav ? { responseStart: nav.responseStart, responseEnd: nav.responseEnd, domInteractive: nav.domInteractive, dcl: nav.domContentLoadedEventEnd, load: nav.loadEventEnd, bytes: nav.transferSize } : null,+ resources: performance.getEntriesByType("resource").map((entry) => ({ url: entry.name.replace(location.origin, ""), kind: entry.initiatorType, start: entry.startTime, end: entry.responseEnd, wait: entry.responseStart - entry.requestStart, transfer: entry.transferSize, encoded: entry.encodedBodySize, decoded: entry.decodedBodySize })),+ };+})()`;++let main = null;+let windows = 0;+const local = (url) => /^http:\/\/127\.0\.0\.1:\d+\/?(\?|#|$)/.test(url);+app.on("browser-window-created", (_event, win) => {+ const id = (windows += 1);+ mark("window-created", { id });+ win.once("ready-to-show", () => mark("window-ready-to-show", { id }));+ for (const name of ["show", "showInactive"]) {+ const original = win[name];+ win[name] = function (...args) { mark("window-show", { id }); if (win.webContents === main) snapshot("mainShown"); return original.apply(this, args); };+ }+});+app.on("web-contents-created", (_event, contents) => {+ const id = contents.id;+ mark("contents-created", { id, type: contents.getType() });+ contents.on("did-start-navigation", (details) => { if (details.isMainFrame && !details.isSameDocument) mark("nav-start", { id, url: details.url.slice(0, 48) }); });+ contents.on("dom-ready", () => {+ const url = contents.getURL();+ mark("dom-ready", { id, url: url.slice(0, 48) });+ if (!local(url) || (main && main !== contents)) return;+ main = contents;+ void contents.executeJavaScript(COLLECT(config.target ?? {})).catch(() => {});+ });+ contents.on("did-finish-load", () => mark("did-finish-load", { id }));+ contents.on("did-fail-load", (_e, code, _d, url, isMainFrame) => { if (isMainFrame) mark("did-fail-load", { id, code, url: String(url).slice(0, 48) }); });+});++const egress = [];+app.once("ready", () => {+ mark("ready"); snapshot("ready");+ for (const name of ["clearCache", "resolveProxy"]) timed(session.defaultSession, name, name);+ session.defaultSession.webRequest.onBeforeRequest((details, callback) => {+ let host = "";+ try { host = new URL(details.url).hostname; } catch {}+ const allowed = /^(data|blob|file|devtools|chrome|about):/.test(details.url) || host === "127.0.0.1" || host === "localhost";+ if (!allowed) egress.push({ t: now(), url: details.url.slice(0, 80) });+ callback({ cancel: !allowed });+ });+});++const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+async function finish() {+ const deadline = Date.now() + (config.timeoutMs ?? 45_000);+ let page = null;+ const want = config.prime ? "root" : "lastMessage";+ while (Date.now() < deadline) {+ await sleep(250);+ if (!main || main.isDestroyed()) continue;+ page = await main.executeJavaScript(REPORT).catch(() => null);+ if (!page?.seen?.[want]) continue;+ const lastLong = page.longtasks.reduce((latest, [start, duration]) => Math.max(latest, start + duration), 0);+ if (page.now - Math.max(lastLong, page.seen[want] - page.timeOrigin) >= (config.quietMs ?? 1500)) break;+ }+ const steps = [];+ if (config.prime && main && !main.isDestroyed()) {+ steps.push(await main.executeJavaScript(`(async () => {+ for (const [key, value] of Object.entries(${JSON.stringify(config.prime.storage ?? {})})) localStorage.setItem(key, value);+ const until = async (test, ms) => { const end = performance.now() + ms; while (performance.now() < end) { if (test()) return true; await new Promise((r) => setTimeout(r, 50)); } return false; };+ const row = () => document.querySelector(${JSON.stringify(`[data-sidebar-bot-row="${config.prime.botId}"]`)});+ const hasRow = await until(() => Boolean(row()), 15000);+ if (hasRow) row().click();+ const drawn = await until(() => Boolean(document.querySelector(${JSON.stringify(`[data-mid="${config.target?.lastMessageId}"]`)})), 15000);+ return { hasRow, drawn, keys: Object.keys(localStorage) };+ })()`).catch((error) => ({ error: String(error) })));+ await sleep(2500);+ page = await main.executeJavaScript(REPORT).catch(() => page);+ }+ if (config.screenshot && main && !main.isDestroyed()) {+ try { fs.writeFileSync(config.screenshot, (await main.capturePage()).toPNG()); } catch (error) { steps.push({ screenshot: String(error) }); }+ }+ let metrics = [];+ try { metrics = app.getAppMetrics().map((entry) => ({ type: entry.type, name: entry.name ?? entry.serviceName, rssMb: Math.round((entry.memory?.workingSetSize ?? 0) / 1024) })); } catch {}+ fs.writeFileSync(config.out, JSON.stringify({+ processStart: process.getCreationTime(), marks, sync, syncAt, spawns, refused, egress, page, steps, metrics, derived,+ timedOut: Date.now() >= deadline, versions: { electron: process.versions.electron, node: process.versions.node, app: app.getVersion() },+ }));+ const hardStop = setTimeout(() => app.exit(0), 10_000);+ hardStop.unref();+ app.quit();+}+void app.whenReady().then(finish);++mark("main-import:start"); snapshot("importStart");+try {+ await import(new URL("./electron/main.mjs", import.meta.url).href);+} catch (error) {+ console.error(`bench-launch-entry: the app's main module did not load: ${error?.stack ?? error}`);+ app.exit(66);+ await new Promise(() => {});+}+mark("main-import:end"); snapshot("importEnd");