diff --git a/notes/windows-perf-progress.md b/notes/windows-perf-progress.md new file mode 100644 index 000000000..5cd3b89ff --- /dev/null +++ b/notes/windows-perf-progress.md @@ -0,0 +1,248 @@ +# Windows Performance Investigation — Progress Log + +Goal: (1) significantly improve Windows startup time (~1 min cold start reported), +(2) fix OpenCode-driven UI freezes, (3) improve overall Windows performance. +All changes must be proven with before/after benchmark numbers. + +## Status + +- [x] Benchmark harness for startup time (`tools/benchmarks/startup-time-bench.mjs`) +- [x] Startup bottleneck FIXED + verified: **19.31s → 1.80s median** (fixture); + real-world profile was 62s of blocked main thread → now 0 icacls spawns steady-state +- [x] OpenCode freeze ROOT CAUSE found + fixed: MessagePart hook flood (see F5/D2). + Benchmark: 22.9 MB / 540 ms / 400 main-process fanouts per turn → 469 KB / 79 ms / 120 + (legacy vs throttled plugin behavior through the real hook HTTP pipeline) +- [x] General Windows sync-work audit (results below); audit item #2 (readHooksJson per + status IPC) investigated and found NOT hot — renderer barely calls those handlers. + Fixed pre-existing Windows-only test failures (hydrate-shell-path delimiter). +- [x] Windows ConPTY e2e perf validation (F7 below) + +## Key facts / environment + +- Branch: `Jinwoo-H/windows-launch-time` +- Electron app, entry: `src/main/index.ts` (~1557 lines) +- Existing startup diagnostics: `ORCA_STARTUP_DIAGNOSTICS=1` writes `[startup] ` lines to stderr + (`src/main/startup/startup-diagnostics.ts`) +- Prior art: PR #4618 "perf: speed up desktop startup", #5011 "stop main-thread PowerShell ACL storm + on env-store reads", #4526 "Avoid OpenCode config cleanup freezes on Windows", b240d5eee + "Measure startup hydration phases" + +## Follow-ups / known issues (out of scope for this branch) + +- Pre-existing Windows-only unit test failures: `daemon-pty-adapter.test.ts` (61) and + `history-manager.test.ts` (3, chmod-based fs-error simulation is a no-op on Windows). + Identical with/without this branch's changes. CI never sees them (ubuntu-only). +- Consider a Windows CI lane for the terminal-perf e2e suite (F6/F7) and these unit suites. +- Typing-latency load-sensitivity (F7): possible deeper work on daemon checkpoint + scheduling/priority if user reports persist after D3. +- Audit leftovers (F4): non-recursive `grantDirAcl` execFileSync on hook install + (installer-utils.ts:210) could be async; readHooksJson caching unnecessary (not hot). + +### D3 — Async checkpoint writes (implemented) + +`HistoryManager.checkpoint` (every ~5s per dirty session, Electron main process) switched +from writeFileSync+renameSync (~1MB snapshot JSON, inflated by Defender on Windows) to +fs.promises with the same tmp+rename atomicity; ordering preserved by the adapter's +checkpointInFlight guard. + +## Suspects (startup) + +1. **`grantDirAcl(userData, { recursive: true })`** — `src/main/index.ts:517-523`, win32 only, + runs **synchronously on the main process inside `openMainWindow()` before window creation**. + Spawns `icacls /grant:r :(OI)(CI)(F) /T /C` with a **60s timeout**. + The comment itself admits large userData dirs (tens of thousands of Chromium cache files) + can take >10s. This blocks first paint for the whole walk. Matches "1 minute launch" and + "Windows only". +2. Windows Defender real-time scan of exe/asar/native modules on cold start (environmental, + can't fix in code, but reducing file count / sync IO helps). +3. TBD: store sync load, daemon init, i18n init, sherpa-onnx native module load. + +### F3 — Baseline benchmark (2026-06-10) + +Harness: `node tools/benchmarks/startup-time-bench.mjs --label baseline --iterations 3 --files 28000` +(28k-file synthetic Chromium-cache-shaped userData fixture in %TEMP%, headless launch of +the electron-vite build with `ORCA_STARTUP_DIAGNOSTICS=1`, milestones parsed from stderr). + +| phase (median of 3) | baseline | +|---|---| +| spawnToAppReady | 857ms | +| appReadyToServices | 178ms | +| servicesToI18n | 2ms | +| i18nToOpenWindow | 7ms | +| **aclGrantMs** | **15.65s** | +| windowCreatedToLoaded | 1.06s | +| **totalToDidFinishLoad** | **19.31s** | + +ACL walk = 81% of total. (Fixture is kinder than the real profile: same file count but +freshly-written small files → real %APPDATA%\Orca measured 62s for the same command.) +JSON: tools/benchmarks/results/startup-baseline-2026-06-10T19-36-01-305Z.json + +### F4 — Sync main-thread audit (subagent, 2026-06-10) + +Ranked offenders beyond the ACL grant (#1): +2. `readHooksJson` + JSON.parse re-read per agent-status IPC call across ~10 hook services + (`src/main/*/hook-service.ts` via `agent-hooks/installer-utils.ts:50`) — 10-100ms per + status snapshot, all platforms. Remediation: in-memory cache. +3. `whoami.exe` SID resolution (win32-utils.ts:92) — already cached, OK. +4. macOS-only `defaults read` per browser probe — not Windows. +5. `installer-utils.ts:210` non-recursive grantDirAcl on hook install (execFileSync, + 500ms-2s) — infrequent write path, low priority. +6. `secure-file.ts` sync PowerShell on credential write path — by design (#5011), leave. + +## Suspects (OpenCode freeze) + +- User report: UI freezes ~5s after sending prompt; OpenCode session itself continues fine + (visible from external terminal). So the agent process is healthy — the freeze is in Orca's + main process or renderer. Spinner in left panel still animates (= renderer compositor alive? + or just that one timer). Need to find sync main-process work triggered by OpenCode activity. +- Prior fix #4526 "Avoid OpenCode config cleanup freezes on Windows" — re-check that path. + +### Research results (subagent, 2026-06-10) — ranked candidates + +1. **ConPTY output flood vs PTY batching/backpressure** (HIGH): Windows ConPTY re-renders + full TUI frames → 10-100x output volume vs macOS. Batching in `src/main/ipc/pty.ts` + (16KB chunks / 8ms flush, 512KB renderer in-flight window). If renderer xterm.write is + slow, ACKs stall → in-flight fills → main stalls. Tests: terminal-foreground-redraw-freeze, + artificial-opencode-terminal-load e2e. +2. **Sync `runtime.onPtyData` per data event before batching** (MED-HIGH): + `src/main/ipc/pty.ts:1376-1430` → `orca-runtime.ts:3256-3420`: normalizeTerminalChunk + + tail-buffer append + agent-status OSC parsing run synchronously per chunk on main. + Daemon PTY path. High event rate × per-event cost can saturate the main loop. +3. **`mirrorUserConfig` recursive fs work in `buildPtyEnv` on PTY spawn** (MED): + `src/main/opencode/hook-service.ts:359-524` + `pty/overlay-mirror.ts:63-110` — + readdir/safeRemoveTree/symlinks on main thread at spawn; #4526 fixed only clearPty side. + Timing mismatch with "5s after prompt" though. +4. Agent-status event fan-out per OSC title (LOW-MED). 5. Tail-buffer O(n²) (LOW). + +Gap in coverage: no test exercises rapid continuous ConPTY-scale data + sync onPtyData +accumulation on Windows. + +### F5 — ROOT CAUSE (2026-06-10): OpenCode MessagePart hook flood + +Eliminated candidates first: ran `terminal-foreground-redraw-freeze.spec.ts` on THIS Windows +machine (real ConPTY + daemon provider) — passes; renderer output scheduler protections hold. +The raw TUI-output-flood theory doesn't explain an OpenCode-specific permanent freeze. + +The actual mechanism (src/main/opencode/hook-service.ts plugin source): +- OpenCode publishes `message.part.updated` with the FULL accumulated text of the part on + every streamed append (architecture: parts are republished, not deltas). +- Orca's plugin POSTed that full text to the agent-hook server on EVERY event → + **O(n²) bytes per streaming turn**. A 120KB reply in 400 updates = ~23 MB through + loopback HTTP + main-process JSON.parse; real turns are worse (per-token updates). +- Main process spends its whole loop on HTTP receive + parse + normalize + fanout. UI symptom + matches the user report exactly: everything dead (window close needs main + renderer + round-trip), EXCEPT the sidebar agent indicator — which is the one thing fed by the very + agentStatus:set flood that's starving everything else. +- Why Windows-biased: same flood exists on macOS but combines on Windows with ConPTY + full-frame redraw volume and generally slower process IO; also Windows daemon-PTY path + adds main-process onPtyData work. +- Why "5 seconds after sending the prompt": that's when the accumulated text gets big. +- Why OpenCode keeps working: plugin POST failures are swallowed; the session is healthy. +- Downstream payloads were already bounded (prompt 200 chars, lastAssistantMessage 8000 + chars via agent-status-types normalization) — the renderer wasn't the bottleneck; the + main-process ingest was. + +### F7 — Windows ConPTY e2e perf validation (2026-06-10) + +Ran the terminal-perf budget specs on this Windows machine (real ConPTY + daemon PTY +provider — a path CI never exercises): +- `terminal-output-scheduler.spec.ts`: PASS (all tests) +- `terminal-foreground-redraw-freeze.spec.ts`: PASS +- `terminal-typing-latency.spec.ts`: PASSES in isolation, repeatedly — median 13.6-23.1ms, + worst 34-42ms (budgets: 250ms median / 1000ms worst). Two earlier runs that exceeded the + worst-key budget (1054.9ms, 2016.1ms outlier on a single key) occurred while other heavy + tooling (vitest/tsgo/builds) ran concurrently on the machine → load-sensitivity, not a + deterministic product defect. Note the product implication: under heavy host load + (exactly what coding agents generate), a keystroke can stall >1s on Windows. Plausible + contributors for follow-up: daemon checkpoint ticks (5s interval; snapshot serialize in + daemon + sync writeFileSync of checkpoint JSON on main — daemon-pty-adapter.ts:592, + history-manager.ts:109), Defender scanning fresh build artifacts. + +### F6 — Windows e2e perf coverage gap + +All terminal-perf e2e specs run on ubuntu-latest in CI. Verified they DO run on a Windows +dev machine (`npx playwright test ... --project electron-headless` works locally). Consider +a Windows CI lane for the terminal-perf suite. + +## OpenCode fix (D2) + +1. **Plugin throttle + cap (source fix)** — `src/main/opencode/hook-service.ts`: + assistant MessagePart posts are trailing-edge coalesced to ≥250ms apart and text is + capped at 4000 chars (leading edge posts immediately so previews stay snappy; pending + snapshot flushed before SessionIdle so the done-row preview is the final message; user + prompts bypass the throttle slot). Plugin file is rewritten on every Orca-launched + OpenCode spawn, so the fix deploys to new sessions immediately. +2. **Listener-side cap (stale-plugin defense)** — `src/shared/agent-hook-listener.ts`: + OpenCode MessagePart text capped at 8000 chars at ingest (OPENCODE_HOOK_TEXT_MAX_CHARS) + so pre-fix plugins in long-running OpenCode processes can't blow up state maps. +3. **Benchmark/regression test** — `src/main/agent-hooks/opencode-message-part-flood-bench.test.ts` + drives the real hook HTTP pipeline with both behaviors. Measured on this machine: + | metric/turn | legacy plugin | throttled plugin | + |---|---|---| + | posts | 400 | 120 | + | bytes through main | 22.9 MB | 469 KB (49x less) | + | wall time | 540 ms | 79 ms | + | listener fanouts | 400 | 120 | +4. Behavioral plugin tests — `src/main/opencode/hook-plugin-message-part-throttle.test.ts` + executes the generated plugin with fake timers + stubbed fetch. + +## Findings + +### F1 — Recursive icacls walk is the ~1 min startup (CONFIRMED, 2026-06-10) + +- This machine's real packaged-Orca userData: `%APPDATA%\Orca` = **28,650 files / 2.06 GB** + (mostly Chromium caches: Cache, Code Cache, GPUCache, blob_storage…). +- Measured the exact command Orca runs in `openMainWindow()` (src/main/index.ts:517-523): + - `icacls /grant:r :(OI)(CI)(F) /T /C` → **62.0 s** + - App runs it with `execFileSync` (main thread, BLOCKING, before BrowserWindow creation) + with a **60s timeout** → every cold launch freezes ~60s, then the grant *times out and + silently fails* (execFileSync throws, caught). Users pay the full minute and get nothing. + - Non-recursive root-only grant: **4.8 s** (NTFS propagates inheritable ACE internally). + - `icacls \* /grant:r …` (immediate children, 48 entries): **4.7 s**. +- Why it exists (PR #1152): Chromium's BrowserWindow ctor resets userData DACL with + Inherit-Only ACEs → EPERM on writes in existing subdirs (codex-runtime-home, agent-hooks…). + Explicit child ACEs survive propagation. Per-write EPERM retries exist as backstop in + `codex-accounts/fs-utils.ts` + `agent-hooks/installer-utils.ts`. +- Windows ACL inheritance recalculates from the immediate parent during propagation, so + explicit ACEs on userData + immediate children are sufficient; per-file ACEs on 28k + Chromium cache files are useless work. + +### F2 — Instrumentation prior art + +- `ORCA_STARTUP_DIAGNOSTICS=1` → `[startup] ` lines on stderr (startup-diagnostics.ts). + Only 2 events exist today (single-instance lock). Commit b240d5eee (branch + perf/startup-first-window, NOT merged here) has a full StartupPhaseTimer framework — + too large to cherry-pick; adding minimal milestone logs instead. +- Hermetic benchmark launch path: `ORCA_E2E_USER_DATA_DIR=` redirects userData + (works packaged + dev), `ORCA_E2E_HEADLESS=1` keeps window hidden. Dev/preview mode + skips single-instance lock → safe alongside installed Orca. + +## Decisions / fixes + +### D0 — RESULTS: ACL fix benchmark (2026-06-10) + +| phase (median) | baseline (3 it.) | after fix (4 it.) | steady state (3 it.) | +|---|---|---|---| +| aclGrantMs | **15.65s sync/blocking** | async (off critical path) | **0ms (marker hit)** | +| totalToWindowCreated | 18.25s | 930ms | 814ms | +| totalToDidFinishLoad | **19.31s** | **2.04s** | **1.80s** | + +- First launch after fix: total 2.06s while the background grant ran 6.81s concurrently. +- Marker verified written by real icacls run; subsequent launches log `acl-grant-done + mode=marker-hit` with zero spawns. +- JSON evidence: tools/benchmarks/results/startup-{baseline,acl-fix,acl-fix-steady}-*.json +- Files: src/main/startup/windows-user-data-acl.ts (+tests), src/main/index.ts (wire-up + + startup milestones), src/main/win32-utils.ts (export identity resolver), + tools/benchmarks/startup-time-bench.mjs (harness). + +### D1 — ACL grant fix (implemented as planned) + +Replace the synchronous recursive walk with: +1. A persisted marker (`windows-acl-grant.json` in userData, keyed on identity + scheme + version): when present → skip everything (steady-state launches: 0 icacls spawns, 0 ms). +2. When marker missing (first launch after install/profile import): grant root + + immediate children via **async spawn** (never blocks window creation); write marker + on success. Per-write EPERM retries remain the backstop during the async window — + that's exactly what they're for (#1152 comment says so). +3. Drop the /T full-tree walk entirely; it grants nothing the immediate-children + ACEs + inheritance propagation don't already cover. diff --git a/src/main/agent-hooks/opencode-message-part-flood-bench.test.ts b/src/main/agent-hooks/opencode-message-part-flood-bench.test.ts new file mode 100644 index 000000000..2c5137105 --- /dev/null +++ b/src/main/agent-hooks/opencode-message-part-flood-bench.test.ts @@ -0,0 +1,137 @@ +/** + * Benchmark-style regression test for the OpenCode MessagePart flood. + * + * Drives the REAL agent-hook HTTP pipeline (loopback socket, body read, + * JSON.parse, normalization, listener fanout) with two client behaviors: + * + * - "legacy plugin": one POST per streamed part update, each carrying the + * FULL accumulated reply text (how plugin builds before the throttle fix + * behaved) — O(n²) bytes per turn. + * - "throttled plugin": leading + trailing-edge coalesced posts at 250ms + * cadence with text capped at 4000 chars (current plugin behavior). + * + * The byte/post-count assertions are deterministic; wall-clock timings are + * logged as benchmark evidence (see notes/windows-perf-progress.md) but not + * asserted, to keep CI stable. + */ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { makePaneKey } from '../../shared/stable-pane-id' + +const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ + getCohortAtEmitMock: vi.fn(), + trackMock: vi.fn() +})) + +vi.mock('../telemetry/client', () => ({ + track: trackMock +})) + +vi.mock('../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: getCohortAtEmitMock +})) + +import { AgentHookServer } from './server' + +const PANE = makePaneKey('tab-bench', '99999999-9999-4999-8999-999999999999') + +// A realistic long streaming reply: ~120 KB final text arriving in 400 +// part updates (OpenCode re-publishes the whole part per append). +const FINAL_REPLY_CHARS = 120_000 +const LEGACY_PART_UPDATES = 400 +// Throttled plugin posts at most one MessagePart per 250ms. A ~30s turn +// yields ~120 posts; we use that worst-case count with the 4000-char cap. +const THROTTLED_POSTS = 120 +const THROTTLED_TEXT_CAP = 4_000 + +describe('OpenCode MessagePart flood benchmark', () => { + let server: AgentHookServer + let tempDir: string + let listenerEvents: number + + beforeEach(async () => { + getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 }) + tempDir = mkdtempSync(join(tmpdir(), 'orca-hook-bench-')) + server = new AgentHookServer() + listenerEvents = 0 + server.setListener(() => { + listenerEvents++ + }) + await server.start({ env: 'production', userDataPath: tempDir }) + }) + + afterEach(() => { + server.stop() + rmSync(tempDir, { recursive: true, force: true }) + }) + + async function postMessagePart(env: Record, text: string): Promise { + const response = await fetch(`http://127.0.0.1:${env.ORCA_AGENT_HOOK_PORT}/hook/opencode`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': env.ORCA_AGENT_HOOK_TOKEN + }, + body: JSON.stringify({ + paneKey: PANE, + tabId: 'tab-bench', + worktreeId: 'wt-bench', + env: 'production', + payload: { + hook_event_name: 'MessagePart', + role: 'assistant', + text, + messageID: 'msg-bench', + sessionID: 'session-bench' + } + }) + }) + expect(response.status).toBe(204) + } + + it('throttled plugin behavior cuts per-turn hook-pipeline bytes by >40x', async () => { + const env = server.buildPtyEnv() + expect(env.ORCA_AGENT_HOOK_PORT).toBeTruthy() + + // Legacy: full accumulated text per part update. + let legacyBytes = 0 + const legacyStart = performance.now() + for (let i = 1; i <= LEGACY_PART_UPDATES; i++) { + const text = 'x'.repeat(Math.floor((FINAL_REPLY_CHARS * i) / LEGACY_PART_UPDATES)) + legacyBytes += text.length + await postMessagePart(env, text) + } + const legacyMs = performance.now() - legacyStart + const legacyEvents = listenerEvents + + listenerEvents = 0 + + // Throttled: bounded post count, bounded text. + let throttledBytes = 0 + const throttledStart = performance.now() + for (let i = 1; i <= THROTTLED_POSTS; i++) { + const text = 'x'.repeat(THROTTLED_TEXT_CAP) + throttledBytes += text.length + await postMessagePart(env, text) + } + const throttledMs = performance.now() - throttledStart + const throttledEvents = listenerEvents + + // eslint-disable-next-line no-console + console.log( + `[bench] legacy: ${LEGACY_PART_UPDATES} posts, ${(legacyBytes / 1024 / 1024).toFixed(1)} MB, ` + + `${legacyMs.toFixed(0)} ms, ${legacyEvents} listener fanouts | ` + + `throttled: ${THROTTLED_POSTS} posts, ${(throttledBytes / 1024).toFixed(0)} KB, ` + + `${throttledMs.toFixed(0)} ms, ${throttledEvents} listener fanouts` + ) + + // Deterministic: the turn's total text volume through the main process + // drops from O(n²) (~23 MB here) to O(posts × cap) (~470 KB here, >40x + // less). Real turns stream far more than 400 part updates, so the + // real-world ratio is larger still. + expect(throttledBytes).toBeLessThan(legacyBytes / 40) + expect(THROTTLED_POSTS).toBeLessThan(LEGACY_PART_UPDATES / 3 + 1) + }, 120_000) +}) diff --git a/src/main/agent-hooks/server.test.ts b/src/main/agent-hooks/server.test.ts index c87c864b3..d173acf8b 100644 --- a/src/main/agent-hooks/server.test.ts +++ b/src/main/agent-hooks/server.test.ts @@ -3842,6 +3842,38 @@ describe('OpenCode hook normalization', () => { expect(result?.payload.lastAssistantMessage).toBe('Hello! How can I help?') }) + it('caps oversized MessagePart text from stale (pre-throttle) plugin builds', () => { + // Why: plugin builds installed before the throttle/cap fix re-post the + // full accumulated reply on every streamed part update. The listener must + // bound the text so each event's status compare, IPC fanout, and renderer + // store update stay O(cap) instead of O(reply length). + const assistant = _internals.normalizeHookPayload( + 'opencode', + buildBody({ + hook_event_name: 'MessagePart', + role: 'assistant', + text: 'a'.repeat(500_000) + }), + 'production' + ) + expect(assistant?.payload.lastAssistantMessage?.length).toBe(8_000) + + // Why: prompt has always been single-line-capped at 200 by + // normalizeAgentStatusObject; this asserts the oversized input still + // flows through without blowing past that bound. + const user = _internals.normalizeHookPayload( + 'opencode', + buildBody({ + hook_event_name: 'MessagePart', + role: 'user', + text: 'u'.repeat(500_000), + messageID: 'msg-cap' + }), + 'production' + ) + expect(user?.payload.prompt?.length).toBe(200) + }) + it('subsequent SessionIdle preserves cached prompt + assistant message', () => { _internals.normalizeHookPayload( 'opencode', diff --git a/src/main/daemon/history-manager.ts b/src/main/daemon/history-manager.ts index 4cc9a85f1..c9fe0d187 100644 --- a/src/main/daemon/history-manager.ts +++ b/src/main/daemon/history-manager.ts @@ -5,8 +5,8 @@ import { readFileSync, existsSync, rmSync, - renameSync, - unlinkSync + unlinkSync, + promises as fsPromises } from 'fs' import { getHistorySessionDirName } from './history-paths' import type { TerminalSnapshot } from './types' @@ -139,10 +139,14 @@ export class HistoryManager { }) // Why: atomic write via tmp+rename prevents half-written checkpoints // on crash. Reading a corrupt checkpoint is worse than reading a - // slightly stale one. + // slightly stale one. Async IO — this runs every ~5s per dirty session + // on the Electron main process, and a sync ~MB write (worse under + // antivirus scanning on Windows) would stall input/IPC for its + // duration. Overlap is prevented by the adapter's checkpointInFlight + // guard, which awaits this promise before the next tick. const tmpPath = `${writer.checkpointPath}.tmp` - writeFileSync(tmpPath, data) - renameSync(tmpPath, writer.checkpointPath) + await fsPromises.writeFile(tmpPath, data) + await fsPromises.rename(tmpPath, writer.checkpointPath) } catch (err) { this.handleWriteError(sessionId, err) } diff --git a/src/main/index.ts b/src/main/index.ts index 678ac7ad1..542731d09 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -2,7 +2,6 @@ it owns app lifecycle, service wiring, window creation, and hook/daemon startup. Splitting by line count would fragment tightly coupled startup logic across files without a cleaner ownership seam. */ -import { grantDirAcl } from './win32-utils' import { existsSync } from 'fs' import { join } from 'path' import os from 'node:os' @@ -72,6 +71,7 @@ import { shouldBypassSingleInstanceLock } from './startup/single-instance-lock' import { isStartupDiagnosticsEnabled, logStartupDiagnostic } from './startup/startup-diagnostics' +import { ensureWindowsUserDataAclGrant } from './startup/windows-user-data-acl' import { RateLimitService } from './rate-limits/service' import { getInitialClaudeRateLimitTarget } from './rate-limits/claude-rate-limit-target' import { getInitialCodexRateLimitTarget } from './rate-limits/codex-rate-limit-target' @@ -281,6 +281,14 @@ if (startupDiagnosticsEnabled) { }) } +// Why: startup benchmarking needs in-process timestamps — harness-side stderr +// arrival times include pipe buffering jitter. `t` is ms since process start. +function logStartupMilestone(event: string, details: Record = {}): void { + if (startupDiagnosticsEnabled) { + logStartupDiagnostic(event, { t: Math.round(performance.now()), ...details }) + } +} + function focusExistingWindow(): void { focusExistingMainWindow({ app, @@ -467,6 +475,7 @@ function prepareCodexRuntimeHomeForLaunch(target?: CodexAccountSelectionTarget): } function openMainWindow(): BrowserWindow { + logStartupMilestone('open-main-window-start') if (!store) { throw new Error('Store must be initialized before opening the main window') } @@ -510,16 +519,21 @@ function openMainWindow(): BrowserWindow { } // Why: Chromium's BrowserWindow constructor resets the userData DACL to a - // Protected DACL. Grant explicit Full Control ACEs on all existing children - // before the constructor runs so they survive the upcoming DACL reset. - // Per-write EPERM retries in fs-utils/installer-utils serve as the backstop - // for any directories created after startup. + // Protected DACL, breaking writes in pre-existing subdirs. Explicit ACEs on + // userData + immediate children fix the tree permanently; the grant runs in + // the background on first launch only (marker-gated) because the previous + // synchronous recursive walk blocked startup ~60s on large profiles. See + // startup/windows-user-data-acl.ts; per-write EPERM retries are the backstop. if (process.platform === 'win32') { - try { - grantDirAcl(app.getPath('userData'), { recursive: true }) - } catch { - // Non-fatal; per-call retries are the backstop. - } + logStartupMilestone('acl-grant-start') + ensureWindowsUserDataAclGrant(app.getPath('userData'), { + onDone: (result) => { + logStartupMilestone('acl-grant-done', { mode: result.mode }) + if (result.mode === 'failed') { + console.warn('[win32-acl] userData ACL grant failed:', result.reason) + } + } + }) } const window = createMainWindow(store, { @@ -564,6 +578,10 @@ function openMainWindow(): BrowserWindow { } }) recordCrashBreadcrumb('main_window_created') + logStartupMilestone('window-created') + window.once('ready-to-show', () => { + logStartupMilestone('ready-to-show') + }) // Why: telemetry-plan.md§First-launch experience anchors default-on // `app_opened` to the first main-window load. Existing users in the @@ -573,6 +591,7 @@ function openMainWindow(): BrowserWindow { const onFirstWindowLoad = (): void => { clearExpectedRendererReload(rendererWebContentsId) recordCrashBreadcrumb('main_window_loaded') + logStartupMilestone('did-finish-load') if (!store) { return } @@ -715,6 +734,7 @@ function openMainWindow(): BrowserWindow { }) } }) + logStartupMilestone('load-start') loadMainWindow(window) return window } @@ -1112,10 +1132,12 @@ function driveSyntheticTitleFromHook( } app.whenReady().then(async () => { + logStartupMilestone('app-ready') electronApp.setAppUserModelId(devInstanceIdentity.appUserModelId) app.setName(devInstanceIdentity.name) store = new Store() + logStartupMilestone('store-loaded') applyAppIcon(store.getSettings().appIcon) if (shouldSuppressDevEducation({ isDev: is.dev })) { suppressDevEducationForStore(store) @@ -1276,8 +1298,10 @@ app.whenReady().then(async () => { }) }) + logStartupMilestone('services-initialized') await ensureMainI18n() await setMainUiLanguage(store.getSettings().uiLanguage) + logStartupMilestone('i18n-ready') registerAppMenu({ onCheckForUpdates: (options) => checkForUpdatesFromMenu(options), diff --git a/src/main/opencode/hook-plugin-message-part-throttle.test.ts b/src/main/opencode/hook-plugin-message-part-throttle.test.ts new file mode 100644 index 000000000..d53fe8266 --- /dev/null +++ b/src/main/opencode/hook-plugin-message-part-throttle.test.ts @@ -0,0 +1,203 @@ +/** + * Executes the generated OpenCode plugin source (the artifact that runs inside + * OpenCode's process) to verify streamed message.part.updated events are + * coalesced and capped before POSTing to Orca's agent-hook server. The + * un-throttled plugin re-posted the full accumulated reply per streamed + * append — O(n²) bytes per turn — which saturated Orca's main + renderer + * event loops on Windows and froze the UI mid-reply. + */ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { getPathMock } = vi.hoisted(() => ({ + getPathMock: vi.fn<(name: string) => string>() +})) + +vi.mock('electron', () => ({ + app: { + getPath: getPathMock + } +})) + +import { _internals } from './hook-service' + +type RecordedPost = { + url: string + body: { + paneKey: string + payload: { hook_event_name: string; role?: string; text?: string } + } +} + +type PluginEventHandler = (input: { event: unknown }) => Promise + +const ENV_KEYS = ['ORCA_PANE_KEY', 'ORCA_AGENT_HOOK_PORT', 'ORCA_AGENT_HOOK_TOKEN'] as const + +describe('OpenCode plugin MessagePart throttling', () => { + let tempDir: string + let posts: RecordedPost[] + let savedEnv: Record + let savedFetch: typeof globalThis.fetch + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), 'orca-opencode-plugin-test-')) + posts = [] + savedEnv = {} + for (const key of ENV_KEYS) { + savedEnv[key] = process.env[key] + } + process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' + process.env.ORCA_AGENT_HOOK_PORT = '45678' + process.env.ORCA_AGENT_HOOK_TOKEN = 'test-token' + savedFetch = globalThis.fetch + globalThis.fetch = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => { + posts.push({ url: String(url), body: JSON.parse(String(init?.body)) }) + return new Response(null, { status: 204 }) + }) as typeof globalThis.fetch + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + globalThis.fetch = savedFetch + for (const key of ENV_KEYS) { + if (savedEnv[key] === undefined) { + delete process.env[key] + } else { + process.env[key] = savedEnv[key] + } + } + rmSync(tempDir, { recursive: true, force: true }) + }) + + async function loadPluginEventHandler(): Promise { + const pluginPath = join(tempDir, 'orca-opencode-status.mjs') + writeFileSync(pluginPath, _internals.getOpenCodePluginSource()) + const module = (await import(pathToFileURL(pluginPath).href)) as { + OrcaOpenCodeStatusPlugin: (ctx: unknown) => Promise<{ event: PluginEventHandler }> + } + const client = { + session: { + // No parentID → root session, events flow through. + list: async () => ({ data: [{ id: 'session-1' }] }) + } + } + const hooks = await module.OrcaOpenCodeStatusPlugin({ client }) + return hooks.event + } + + function assistantPartEvent(text: string): { event: unknown } { + return { + event: { + type: 'message.part.updated', + properties: { + sessionID: 'session-1', + part: { type: 'text', text, messageID: 'msg-assistant' } + } + } + } + } + + async function seedAssistantRole(handler: PluginEventHandler): Promise { + await handler({ + event: { + type: 'message.updated', + properties: { + sessionID: 'session-1', + info: { id: 'msg-assistant', role: 'assistant' } + } + } + }) + } + + function messagePartPosts(): RecordedPost[] { + return posts.filter((post) => post.body.payload.hook_event_name === 'MessagePart') + } + + it('coalesces a streamed reply into leading + trailing posts with capped text', async () => { + const handler = await loadPluginEventHandler() + await seedAssistantRole(handler) + + // Simulate a streaming turn: 50 part updates, each carrying the full + // accumulated text so far (how OpenCode actually publishes parts). + let text = '' + for (let i = 0; i < 50; i++) { + text += 'chunk-of-streamed-reply-text-'.repeat(10) + await handler(assistantPartEvent(text)) + } + + // Leading edge only — everything else is pending behind the throttle. + expect(messagePartPosts()).toHaveLength(1) + + await vi.advanceTimersByTimeAsync(300) + + const parts = messagePartPosts() + expect(parts).toHaveLength(2) + // Trailing post carries the LATEST snapshot, capped. + const trailing = parts[1].body.payload + expect(trailing.text!.length).toBeLessThanOrEqual(4000) + expect(text.startsWith(trailing.text!)).toBe(true) + }) + + it('flushes the pending reply snapshot before posting SessionIdle', async () => { + const handler = await loadPluginEventHandler() + await seedAssistantRole(handler) + // Mark the session busy so the idle transition is not deduped away. + await handler({ + event: { + type: 'session.status', + properties: { sessionID: 'session-1', status: { type: 'busy' } } + } + }) + posts.length = 0 + + await handler(assistantPartEvent('first')) + await handler(assistantPartEvent('first final')) + expect(messagePartPosts()).toHaveLength(1) + + await handler({ + event: { type: 'session.idle', properties: { sessionID: 'session-1' } } + }) + + const eventNames = posts.map((post) => post.body.payload.hook_event_name) + expect(eventNames).toEqual(['MessagePart', 'MessagePart', 'SessionIdle']) + expect(posts[1].body.payload.text).toBe('first final') + }) + + it('posts user prompts immediately without consuming the assistant throttle slot', async () => { + const handler = await loadPluginEventHandler() + await handler({ + event: { + type: 'message.updated', + properties: { + sessionID: 'session-1', + info: { id: 'msg-user', role: 'user' } + } + } + }) + + await handler({ + event: { + type: 'message.part.updated', + properties: { + sessionID: 'session-1', + part: { type: 'text', text: 'u'.repeat(10_000), messageID: 'msg-user' } + } + } + }) + + const parts = messagePartPosts() + expect(parts).toHaveLength(1) + expect(parts[0].body.payload.role).toBe('user') + expect(parts[0].body.payload.text!.length).toBe(4000) + + // An assistant part right after the user prompt still posts immediately + // (leading edge) because user posts do not touch the throttle clock. + await seedAssistantRole(handler) + await handler(assistantPartEvent('assistant reply')) + expect(messagePartPosts()).toHaveLength(2) + }) +}) diff --git a/src/main/opencode/hook-service.test.ts b/src/main/opencode/hook-service.test.ts index add20ca79..99b6b070e 100644 --- a/src/main/opencode/hook-service.test.ts +++ b/src/main/opencode/hook-service.test.ts @@ -114,8 +114,10 @@ describe('OpenCode hook plugin source', () => { const source = _internals.getOpenCodePluginSource() expect(source).toContain( - 'await post("MessagePart", { role, text: part.text, messageID: part.messageID, sessionID });' + 'await post("MessagePart", { role, text: capMessagePartText(part.text), messageID: part.messageID, sessionID });' ) + expect(source).toContain('messageID: pending.messageID,') + expect(source).toContain('sessionID: pending.sessionID,') expect(source).toContain('await setStatus("busy", { sessionID });') expect(source.match(/await setStatus\("idle", \{ sessionID \}\);/g) ?? []).toHaveLength(2) }) diff --git a/src/main/opencode/hook-service.ts b/src/main/opencode/hook-service.ts index ff0d9bde7..ddc727d53 100644 --- a/src/main/opencode/hook-service.ts +++ b/src/main/opencode/hook-service.ts @@ -160,6 +160,57 @@ function getOpenCodePluginSource(): string { 'let lastStatus = "idle";', 'const childSessionById = new Map();', '', + '// Why: message.part.updated re-sends the FULL accumulated text of the part', + '// after every streamed append, so posting each event forwards O(n^2) bytes', + '// per turn through Orca (loopback HTTP -> main JSON parse -> status compare', + '// -> IPC -> renderer store update -> React commit). On Windows that flood', + '// saturated both event loops and froze the whole UI a few seconds into a', + '// streaming reply. The dashboard only needs a bounded preview at a human', + '// cadence: cap the text and trailing-edge coalesce assistant parts.', + 'const MESSAGE_PART_THROTTLE_MS = 250;', + 'const MESSAGE_PART_MAX_CHARS = 4000;', + 'let pendingAssistantPart = null;', + 'let assistantPartFlushTimer = null;', + 'let lastAssistantPartPostAt = 0;', + '', + 'function capMessagePartText(text) {', + ' return text.length > MESSAGE_PART_MAX_CHARS ? text.slice(0, MESSAGE_PART_MAX_CHARS) : text;', + '}', + '', + 'async function flushPendingAssistantPart() {', + ' if (assistantPartFlushTimer) {', + ' clearTimeout(assistantPartFlushTimer);', + ' assistantPartFlushTimer = null;', + ' }', + ' const pending = pendingAssistantPart;', + ' pendingAssistantPart = null;', + ' if (!pending) return;', + ' lastAssistantPartPostAt = Date.now();', + ' await post("MessagePart", {', + ' role: pending.role,', + ' text: capMessagePartText(pending.text),', + ' messageID: pending.messageID,', + ' sessionID: pending.sessionID,', + ' });', + '}', + '', + 'function queueAssistantPart(part) {', + ' // Why: keep only the latest snapshot — each event already contains the', + ' // full accumulated text, so intermediate snapshots are pure waste.', + ' pendingAssistantPart = part;', + ' const sinceLastPost = Date.now() - lastAssistantPartPostAt;', + ' if (sinceLastPost >= MESSAGE_PART_THROTTLE_MS) {', + ' void flushPendingAssistantPart();', + ' return;', + ' }', + ' if (!assistantPartFlushTimer) {', + ' assistantPartFlushTimer = setTimeout(() => {', + ' void flushPendingAssistantPart();', + ' }, MESSAGE_PART_THROTTLE_MS - sinceLastPost);', + ' if (assistantPartFlushTimer.unref) assistantPartFlushTimer.unref();', + ' }', + '}', + '', '// Why: message.part.updated fires for every Part (text, tool, reasoning)', '// but does not include the message role — that lives on the parent', '// message.updated event. Cache the role per messageID so the plugin can', @@ -312,11 +363,21 @@ function getOpenCodePluginSource(): string { ' if (!part || part.type !== "text" || !part.text) return;', ' const role = messageRoleById.get(part.messageID);', ' if (!role) return;', - ' await post("MessagePart", { role, text: part.text, messageID: part.messageID, sessionID });', + ' if (role === "user") {', + ' // Why: user prompts arrive as a single event, not a stream — post', + ' // immediately (still capped) so the throttle slot stays free for', + ' // the assistant reply that follows within the same window.', + ' await post("MessagePart", { role, text: capMessagePartText(part.text), messageID: part.messageID, sessionID });', + ' return;', + ' }', + ' queueAssistantPart({ role, text: part.text, messageID: part.messageID, sessionID });', ' return;', ' }', '', ' if (event.type === "session.idle" || event.type === "session.error") {', + ' // Why: flush the coalesced final reply snapshot before the idle', + ' // transition so the done-state preview shows the completed message.', + ' await flushPendingAssistantPart();', ' await setStatus("idle", { sessionID });', ' return;', ' }', diff --git a/src/main/startup/hydrate-shell-path.test.ts b/src/main/startup/hydrate-shell-path.test.ts index ebd235d59..772133249 100644 --- a/src/main/startup/hydrate-shell-path.test.ts +++ b/src/main/startup/hydrate-shell-path.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { EventEmitter } from 'events' +import { delimiter } from 'node:path' import type { ChildProcessWithoutNullStreams } from 'child_process' import { _resetHydrateShellPathCache, @@ -169,30 +170,37 @@ describe('mergePathSegments', () => { } }) + // Why: mergePathSegments joins with the platform PATH delimiter, so the + // expectations must too — hardcoding ':' made this suite fail on Windows + // dev machines even though the code under test was correct. + const joinPath = (...segments: string[]): string => segments.join(delimiter) + it('prepends new segments ahead of existing PATH entries', () => { - process.env.PATH = '/usr/bin:/bin' + process.env.PATH = joinPath('/usr/bin', '/bin') const added = mergePathSegments(['/Users/tester/.opencode/bin', '/Users/tester/.cargo/bin']) expect(added).toEqual(['/Users/tester/.opencode/bin', '/Users/tester/.cargo/bin']) expect(process.env.PATH).toBe( - '/Users/tester/.opencode/bin:/Users/tester/.cargo/bin:/usr/bin:/bin' + joinPath('/Users/tester/.opencode/bin', '/Users/tester/.cargo/bin', '/usr/bin', '/bin') ) }) it('skips segments already on PATH so re-hydration is a no-op', () => { - process.env.PATH = '/Users/tester/.cargo/bin:/usr/bin' + process.env.PATH = joinPath('/Users/tester/.cargo/bin', '/usr/bin') const added = mergePathSegments(['/Users/tester/.cargo/bin', '/Users/tester/.opencode/bin']) expect(added).toEqual(['/Users/tester/.opencode/bin']) - expect(process.env.PATH).toBe('/Users/tester/.opencode/bin:/Users/tester/.cargo/bin:/usr/bin') + expect(process.env.PATH).toBe( + joinPath('/Users/tester/.opencode/bin', '/Users/tester/.cargo/bin', '/usr/bin') + ) }) it('returns [] and leaves PATH untouched when given nothing', () => { - process.env.PATH = '/usr/bin:/bin' + process.env.PATH = joinPath('/usr/bin', '/bin') expect(mergePathSegments([])).toEqual([]) - expect(process.env.PATH).toBe('/usr/bin:/bin') + expect(process.env.PATH).toBe(joinPath('/usr/bin', '/bin')) }) }) diff --git a/src/main/startup/windows-user-data-acl.test.ts b/src/main/startup/windows-user-data-acl.test.ts new file mode 100644 index 000000000..b49510b0b --- /dev/null +++ b/src/main/startup/windows-user-data-acl.test.ts @@ -0,0 +1,135 @@ +import { EventEmitter } from 'node:events' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { + ensureWindowsUserDataAclGrant, + WINDOWS_ACL_GRANT_MARKER_FILE, + WINDOWS_ACL_GRANT_SCHEME_VERSION, + type WindowsAclGrantResult +} from './windows-user-data-acl' + +type SpawnCall = { target: string; args: string[] } + +function createFakeSpawn(exitCode: number): { + calls: SpawnCall[] + spawnFn: (command: string, args?: readonly string[], options?: unknown) => EventEmitter +} { + const calls: SpawnCall[] = [] + return { + calls, + spawnFn: (_command: string, args: readonly string[] = []) => { + calls.push({ target: args[0] ?? '', args: [...args] }) + const child = new EventEmitter() as EventEmitter & { kill: () => void } + child.kill = () => undefined + setImmediate(() => child.emit('exit', exitCode)) + return child + } + } +} + +function awaitResult( + userDataPath: string, + options: Parameters[1] +): Promise { + return new Promise((resolve) => { + ensureWindowsUserDataAclGrant(userDataPath, { ...options, onDone: resolve }) + }) +} + +describe('ensureWindowsUserDataAclGrant', () => { + let userDataPath: string + + beforeEach(() => { + userDataPath = mkdtempSync(join(os.tmpdir(), 'orca-acl-test-')) + }) + + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + }) + + it('grants children + root then writes the marker', async () => { + const fake = createFakeSpawn(0) + const result = await awaitResult(userDataPath, { + identity: 'testuser', + spawnFn: fake.spawnFn as never + }) + expect(result).toEqual({ mode: 'granted' }) + expect(fake.calls).toHaveLength(2) + expect(fake.calls[0].target).toBe(join(userDataPath, '*')) + expect(fake.calls[1].target).toBe(userDataPath) + expect(fake.calls[0].args).toContain('testuser:(OI)(CI)(F)') + const marker = JSON.parse( + readFileSync(join(userDataPath, WINDOWS_ACL_GRANT_MARKER_FILE), 'utf-8') + ) + expect(marker.schemeVersion).toBe(WINDOWS_ACL_GRANT_SCHEME_VERSION) + expect(marker.identity).toBe('testuser') + }) + + it('skips all spawns when the marker matches the identity', async () => { + writeFileSync( + join(userDataPath, WINDOWS_ACL_GRANT_MARKER_FILE), + JSON.stringify({ + schemeVersion: WINDOWS_ACL_GRANT_SCHEME_VERSION, + identity: 'testuser', + grantedAt: 1 + }) + ) + const fake = createFakeSpawn(0) + const result = await awaitResult(userDataPath, { + identity: 'testuser', + spawnFn: fake.spawnFn as never + }) + expect(result).toEqual({ mode: 'marker-hit' }) + expect(fake.calls).toHaveLength(0) + }) + + it('re-grants when the marker belongs to a different identity', async () => { + writeFileSync( + join(userDataPath, WINDOWS_ACL_GRANT_MARKER_FILE), + JSON.stringify({ + schemeVersion: WINDOWS_ACL_GRANT_SCHEME_VERSION, + identity: 'someone-else', + grantedAt: 1 + }) + ) + const fake = createFakeSpawn(0) + const result = await awaitResult(userDataPath, { + identity: 'testuser', + spawnFn: fake.spawnFn as never + }) + expect(result).toEqual({ mode: 'granted' }) + expect(fake.calls).toHaveLength(2) + }) + + it('does not write the marker when icacls fails, so the next launch retries', async () => { + const fake = createFakeSpawn(5) + const result = await awaitResult(userDataPath, { + identity: 'testuser', + spawnFn: fake.spawnFn as never + }) + expect(result).toEqual({ mode: 'failed', reason: 'exit 5; exit 5' }) + expect(() => readFileSync(join(userDataPath, WINDOWS_ACL_GRANT_MARKER_FILE))).toThrow() + }) + + it('no-ops without a resolvable identity', async () => { + const fake = createFakeSpawn(0) + const result = await awaitResult(userDataPath, { + identity: null, + spawnFn: fake.spawnFn as never + }) + expect(result).toEqual({ mode: 'no-identity' }) + expect(fake.calls).toHaveLength(0) + }) + + it('ignores a corrupt marker and re-grants', async () => { + writeFileSync(join(userDataPath, WINDOWS_ACL_GRANT_MARKER_FILE), '{not json') + const fake = createFakeSpawn(0) + const result = await awaitResult(userDataPath, { + identity: 'testuser', + spawnFn: fake.spawnFn as never + }) + expect(result).toEqual({ mode: 'granted' }) + }) +}) diff --git a/src/main/startup/windows-user-data-acl.ts b/src/main/startup/windows-user-data-acl.ts new file mode 100644 index 000000000..bf1e1d01f --- /dev/null +++ b/src/main/startup/windows-user-data-acl.ts @@ -0,0 +1,163 @@ +import { spawn } from 'node:child_process' +import { readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { getIcaclsExePath, resolveCurrentWindowsIdentity } from '../win32-utils' + +/** + * Startup ACL grant for the win32 userData tree. + * + * Why this exists (PR #1152): Chromium's BrowserWindow constructor resets the + * userData DACL to a Protected DACL whose propagated child ACEs carry the + * Inherit-Only flag, so file writes inside pre-existing subdirectories + * (codex-runtime-home, agent-hooks, …) fail with EPERM. Explicit ACEs survive + * future DACL propagation, so granting them once fixes the tree permanently. + * + * Why not `icacls /T` synchronously (the previous implementation): NTFS + * inheritance is recalculated from the immediate parent, so explicit ACEs on + * userData + its immediate children already protect the whole tree — per-file + * ACEs on tens of thousands of Chromium cache files are pure waste. On a real + * 28k-file profile the recursive walk measured 62s, blocking the main thread + * before first paint and then *timing out* (60s cap), so users paid ~1 minute + * per launch for a grant that never completed. + * + * Strategy: + * - A marker file records that the grant completed for this identity. When it + * matches, startup performs zero icacls spawns. + * - When absent, the grant runs asynchronously (never blocks window creation): + * userData root + immediate children (`\*`). Per-write EPERM + * retries in codex-accounts/fs-utils and agent-hooks/installer-utils remain + * the backstop during the brief async window, exactly as they already were + * for the (common) case where the old synchronous walk timed out. + */ + +export const WINDOWS_ACL_GRANT_MARKER_FILE = 'windows-acl-grant.json' +export const WINDOWS_ACL_GRANT_SCHEME_VERSION = 1 + +const GRANT_TIMEOUT_MS = 120_000 + +type WindowsAclGrantMarker = { + schemeVersion: number + identity: string + grantedAt: number +} + +export type WindowsAclGrantResult = + | { mode: 'marker-hit' } + | { mode: 'granted' } + | { mode: 'failed'; reason: string } + | { mode: 'no-identity' } + +type EnsureOptions = { + onDone?: (result: WindowsAclGrantResult) => void + /** Test seam — defaults to node:child_process spawn. */ + spawnFn?: typeof spawn + /** Test seam — defaults to the real current-user identity. */ + identity?: string | null +} + +function readMarker(userDataPath: string): WindowsAclGrantMarker | null { + try { + const parsed = JSON.parse( + readFileSync(join(userDataPath, WINDOWS_ACL_GRANT_MARKER_FILE), 'utf-8') + ) as Partial + if ( + parsed.schemeVersion === WINDOWS_ACL_GRANT_SCHEME_VERSION && + typeof parsed.identity === 'string' + ) { + return parsed as WindowsAclGrantMarker + } + } catch { + // missing or corrupt → re-grant + } + return null +} + +function writeMarker(userDataPath: string, identity: string): void { + const marker: WindowsAclGrantMarker = { + schemeVersion: WINDOWS_ACL_GRANT_SCHEME_VERSION, + identity, + grantedAt: Date.now() + } + writeFileSync(join(userDataPath, WINDOWS_ACL_GRANT_MARKER_FILE), JSON.stringify(marker)) +} + +function runIcaclsGrant( + spawnFn: typeof spawn, + target: string, + identity: string +): Promise<{ ok: boolean; reason?: string }> { + return new Promise((resolve) => { + // /C continues past per-entry errors (e.g. files locked by another + // process); a partial grant is still strictly better than none and the + // per-write EPERM backstop covers stragglers. + const child = spawnFn( + getIcaclsExePath(), + [target, '/grant:r', `${identity}:(OI)(CI)(F)`, '/C'], + { + stdio: 'ignore', + windowsHide: true + } + ) + let settled = false + const settle = (ok: boolean, reason?: string): void => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + resolve(ok ? { ok } : { ok, reason }) + } + const timer = setTimeout(() => { + child.kill() + settle(false, 'timeout') + }, GRANT_TIMEOUT_MS) + timer.unref?.() + child.on('error', (error) => settle(false, error.message)) + child.on('exit', (code) => settle(code === 0, code === 0 ? undefined : `exit ${code}`)) + }) +} + +/** + * Ensure the userData tree carries explicit Full Control ACEs for the current + * user. Returns immediately; the grant itself (first launch only) runs in the + * background. Call before BrowserWindow creation on win32. + */ +export function ensureWindowsUserDataAclGrant( + userDataPath: string, + options: EnsureOptions = {} +): void { + const onDone = options.onDone ?? ((): void => undefined) + const identity = + options.identity !== undefined ? options.identity : resolveCurrentWindowsIdentity() + if (!identity) { + onDone({ mode: 'no-identity' }) + return + } + const marker = readMarker(userDataPath) + if (marker && marker.identity === identity) { + onDone({ mode: 'marker-hit' }) + return + } + const spawnFn = options.spawnFn ?? spawn + void (async () => { + // Immediate children first: those explicit ACEs are the durable fix + // (Chromium replaces the root DACL on every BrowserWindow construction, + // but never strips explicit ACEs from children). Root second so writes + // directly under userData succeed before Chromium's first reset. + const children = await runIcaclsGrant(spawnFn, join(userDataPath, '*'), identity) + const root = await runIcaclsGrant(spawnFn, userDataPath, identity) + if (children.ok && root.ok) { + try { + writeMarker(userDataPath, identity) + onDone({ mode: 'granted' }) + } catch (error) { + onDone({ mode: 'failed', reason: `marker write: ${String(error)}` }) + } + return + } + onDone({ + mode: 'failed', + reason: [children.reason, root.reason].filter(Boolean).join('; ') || 'unknown' + }) + })() +} diff --git a/src/main/win32-utils.ts b/src/main/win32-utils.ts index 550b16d03..a4b8dae12 100644 --- a/src/main/win32-utils.ts +++ b/src/main/win32-utils.ts @@ -80,6 +80,10 @@ export function isPermissionError(error: unknown): boolean { // and always available on Windows. Cached because it never changes in-process. let cachedIdentity: string | null | undefined +export function resolveCurrentWindowsIdentity(): string | null { + return resolveCurrentIdentity() +} + function resolveCurrentIdentity(): string | null { if (cachedIdentity !== undefined) { return cachedIdentity diff --git a/src/shared/agent-hook-listener.ts b/src/shared/agent-hook-listener.ts index 1479e4412..8fae9c029 100644 --- a/src/shared/agent-hook-listener.ts +++ b/src/shared/agent-hook-listener.ts @@ -47,6 +47,19 @@ const MAX_WARNED_KEYS = 32 /** Slowloris cap: drop requests that have not finished sending after 5 s. */ export const HOOK_REQUEST_SLOWLORIS_MS = 5_000 +/** Why: OpenCode plugin builds installed before the throttle/cap fix re-post + * the full accumulated reply text on every streamed part update (O(n²) bytes + * per turn). Capping at ingest bounds the per-event cost of the status + * compare, IPC fanout, renderer store update, and disk persist regardless of + * which plugin version is running inside the OpenCode process. */ +export const OPENCODE_HOOK_TEXT_MAX_CHARS = 8_000 + +function capOpenCodeHookText(text: string): string { + return text.length > OPENCODE_HOOK_TEXT_MAX_CHARS + ? text.slice(0, OPENCODE_HOOK_TEXT_MAX_CHARS) + : text +} + /** Bound paneKey size — `${tabId}:${leafUuid}` is well under 200 chars in * practice; cap defends per-pane caches against pathological input. * Exported so non-HTTP ingest paths (e.g. Orca's `ingestRemote`) can apply @@ -320,7 +333,7 @@ function extractPromptText(hookPayload: Record): ExtractedPromp // role === 'user', the text *is* the prompt — surface it even though // OpenCode has no UserPromptSubmit-equivalent. if (hookPayload.role === 'user' && typeof hookPayload.text === 'string') { - const trimmed = hookPayload.text.trim() + const trimmed = capOpenCodeHookText(hookPayload.text.trim()) if (trimmed.length > 0) { return { text: trimmed, source: 'role_user_text' } } @@ -1207,7 +1220,7 @@ function extractOpenCodeToolFields( if (eventName === 'MessagePart' && hookPayload.role === 'assistant') { const text = readString(hookPayload, 'text') if (text) { - return { lastAssistantMessage: text } + return { lastAssistantMessage: capOpenCodeHookText(text) } } } return {} diff --git a/tools/benchmarks/results/startup-acl-fix-2026-06-10T19-37-58-671Z.json b/tools/benchmarks/results/startup-acl-fix-2026-06-10T19-37-58-671Z.json new file mode 100644 index 000000000..4ad36ad4c --- /dev/null +++ b/tools/benchmarks/results/startup-acl-fix-2026-06-10T19-37-58-671Z.json @@ -0,0 +1,445 @@ +{ + "label": "acl-fix", + "platform": "win32", + "arch": "x64", + "cpus": "Intel(R) Core(TM) Ultra 9 185H", + "fixtureDir": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "fixtureFiles": 28000, + "exe": null, + "iterations": [ + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 1734.3 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 1734.4 + }, + { + "event": "app-ready", + "details": { + "t": 1741 + }, + "harnessMs": 1770.3 + }, + { + "event": "store-loaded", + "details": { + "t": 1747 + }, + "harnessMs": 1776 + }, + { + "event": "services-initialized", + "details": { + "t": 1890 + }, + "harnessMs": 1919.4 + }, + { + "event": "i18n-ready", + "details": { + "t": 1892 + }, + "harnessMs": 1921.1 + }, + { + "event": "open-main-window-start", + "details": { + "t": 1899 + }, + "harnessMs": 1928.3 + }, + { + "event": "acl-grant-start", + "details": { + "t": 1899 + }, + "harnessMs": 1928.3 + }, + { + "event": "window-created", + "details": { + "t": 1935 + }, + "harnessMs": 1964.6 + }, + { + "event": "load-start", + "details": { + "t": 1958 + }, + "harnessMs": 1987.2 + }, + { + "event": "ready-to-show", + "details": { + "t": 3263 + }, + "harnessMs": 3292.4 + }, + { + "event": "did-finish-load", + "details": { + "t": 3264 + }, + "harnessMs": 3292.8 + } + ], + "phases": { + "spawnToAppReady": 1770.3, + "appReadyToServices": 149, + "servicesToI18n": 2, + "i18nToOpenWindow": 7, + "aclGrantMs": null, + "windowCreatedToLoaded": 1329, + "totalToWindowCreated": 1964.6, + "totalToDidFinishLoad": 3292.8 + } + }, + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 716.3 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 716.3 + }, + { + "event": "app-ready", + "details": { + "t": 731 + }, + "harnessMs": 762.5 + }, + { + "event": "store-loaded", + "details": { + "t": 738 + }, + "harnessMs": 769.1 + }, + { + "event": "services-initialized", + "details": { + "t": 886 + }, + "harnessMs": 917.3 + }, + { + "event": "i18n-ready", + "details": { + "t": 888 + }, + "harnessMs": 919.2 + }, + { + "event": "open-main-window-start", + "details": { + "t": 894 + }, + "harnessMs": 925.4 + }, + { + "event": "acl-grant-start", + "details": { + "t": 894 + }, + "harnessMs": 925.4 + }, + { + "event": "window-created", + "details": { + "t": 938 + }, + "harnessMs": 968.6 + }, + { + "event": "load-start", + "details": { + "t": 957 + }, + "harnessMs": 988 + }, + { + "event": "ready-to-show", + "details": { + "t": 2088 + }, + "harnessMs": 2119.2 + }, + { + "event": "did-finish-load", + "details": { + "t": 2089 + }, + "harnessMs": 2119.5 + } + ], + "phases": { + "spawnToAppReady": 762.5, + "appReadyToServices": 155, + "servicesToI18n": 2, + "i18nToOpenWindow": 6, + "aclGrantMs": null, + "windowCreatedToLoaded": 1151, + "totalToWindowCreated": 968.6, + "totalToDidFinishLoad": 2119.5 + } + }, + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 600.7 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 600.7 + }, + { + "event": "app-ready", + "details": { + "t": 613 + }, + "harnessMs": 639.3 + }, + { + "event": "store-loaded", + "details": { + "t": 618 + }, + "harnessMs": 644.5 + }, + { + "event": "services-initialized", + "details": { + "t": 744 + }, + "harnessMs": 771 + }, + { + "event": "i18n-ready", + "details": { + "t": 746 + }, + "harnessMs": 772.5 + }, + { + "event": "open-main-window-start", + "details": { + "t": 751 + }, + "harnessMs": 777.6 + }, + { + "event": "acl-grant-start", + "details": { + "t": 751 + }, + "harnessMs": 777.6 + }, + { + "event": "window-created", + "details": { + "t": 786 + }, + "harnessMs": 812.8 + }, + { + "event": "load-start", + "details": { + "t": 808 + }, + "harnessMs": 834.3 + }, + { + "event": "ready-to-show", + "details": { + "t": 1873 + }, + "harnessMs": 1899.5 + }, + { + "event": "did-finish-load", + "details": { + "t": 1873 + }, + "harnessMs": 1899.7 + } + ], + "phases": { + "spawnToAppReady": 639.3, + "appReadyToServices": 131, + "servicesToI18n": 2, + "i18nToOpenWindow": 5, + "aclGrantMs": null, + "windowCreatedToLoaded": 1087, + "totalToWindowCreated": 812.8, + "totalToDidFinishLoad": 1899.7 + } + }, + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 652.2 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 652.2 + }, + { + "event": "app-ready", + "details": { + "t": 665 + }, + "harnessMs": 690.3 + }, + { + "event": "store-loaded", + "details": { + "t": 672 + }, + "harnessMs": 697.7 + }, + { + "event": "services-initialized", + "details": { + "t": 824 + }, + "harnessMs": 848.8 + }, + { + "event": "i18n-ready", + "details": { + "t": 825 + }, + "harnessMs": 850.6 + }, + { + "event": "open-main-window-start", + "details": { + "t": 832 + }, + "harnessMs": 856.8 + }, + { + "event": "acl-grant-start", + "details": { + "t": 832 + }, + "harnessMs": 856.8 + }, + { + "event": "window-created", + "details": { + "t": 867 + }, + "harnessMs": 892 + }, + { + "event": "load-start", + "details": { + "t": 889 + }, + "harnessMs": 913.8 + }, + { + "event": "ready-to-show", + "details": { + "t": 1926 + }, + "harnessMs": 1951.4 + }, + { + "event": "did-finish-load", + "details": { + "t": 1927 + }, + "harnessMs": 1951.6 + } + ], + "phases": { + "spawnToAppReady": 690.3, + "appReadyToServices": 159, + "servicesToI18n": 1, + "i18nToOpenWindow": 7, + "aclGrantMs": null, + "windowCreatedToLoaded": 1060, + "totalToWindowCreated": 892, + "totalToDidFinishLoad": 1951.6 + } + } + ], + "summaryMedianMs": { + "spawnToAppReady": 726.4, + "appReadyToServices": 152, + "servicesToI18n": 2, + "i18nToOpenWindow": 6.5, + "aclGrantMs": null, + "windowCreatedToLoaded": 1119, + "totalToWindowCreated": 930.3, + "totalToDidFinishLoad": 2035.55 + } +} diff --git a/tools/benchmarks/results/startup-acl-fix-steady-2026-06-10T19-41-40-683Z.json b/tools/benchmarks/results/startup-acl-fix-steady-2026-06-10T19-41-40-683Z.json new file mode 100644 index 000000000..b0bb1076a --- /dev/null +++ b/tools/benchmarks/results/startup-acl-fix-steady-2026-06-10T19-41-40-683Z.json @@ -0,0 +1,363 @@ +{ + "label": "acl-fix-steady", + "platform": "win32", + "arch": "x64", + "cpus": "Intel(R) Core(TM) Ultra 9 185H", + "fixtureDir": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "fixtureFiles": 28000, + "exe": null, + "iterations": [ + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 690.7 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 690.7 + }, + { + "event": "app-ready", + "details": { + "t": 700 + }, + "harnessMs": 733.2 + }, + { + "event": "store-loaded", + "details": { + "t": 707 + }, + "harnessMs": 740.1 + }, + { + "event": "services-initialized", + "details": { + "t": 865 + }, + "harnessMs": 897.8 + }, + { + "event": "i18n-ready", + "details": { + "t": 866 + }, + "harnessMs": 899.6 + }, + { + "event": "open-main-window-start", + "details": { + "t": 873 + }, + "harnessMs": 906 + }, + { + "event": "acl-grant-start", + "details": { + "t": 873 + }, + "harnessMs": 906 + }, + { + "event": "window-created", + "details": { + "t": 913 + }, + "harnessMs": 946.6 + }, + { + "event": "load-start", + "details": { + "t": 936 + }, + "harnessMs": 969.2 + }, + { + "event": "ready-to-show", + "details": { + "t": 2026 + }, + "harnessMs": 2059.3 + }, + { + "event": "did-finish-load", + "details": { + "t": 2026 + }, + "harnessMs": 2059.4 + }, + { + "event": "acl-grant-done", + "details": { + "t": 7686, + "mode": "granted" + }, + "harnessMs": 7719 + } + ], + "phases": { + "spawnToAppReady": 733.2, + "appReadyToServices": 165, + "servicesToI18n": 1, + "i18nToOpenWindow": 7, + "aclGrantMs": 6813, + "windowCreatedToLoaded": 1113, + "totalToWindowCreated": 946.6, + "totalToDidFinishLoad": 2059.4 + } + }, + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 605.1 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 605.1 + }, + { + "event": "app-ready", + "details": { + "t": 611 + }, + "harnessMs": 638.3 + }, + { + "event": "store-loaded", + "details": { + "t": 617 + }, + "harnessMs": 644.2 + }, + { + "event": "services-initialized", + "details": { + "t": 748 + }, + "harnessMs": 775.3 + }, + { + "event": "i18n-ready", + "details": { + "t": 750 + }, + "harnessMs": 777.6 + }, + { + "event": "open-main-window-start", + "details": { + "t": 757 + }, + "harnessMs": 784.2 + }, + { + "event": "acl-grant-start", + "details": { + "t": 757 + }, + "harnessMs": 784.2 + }, + { + "event": "acl-grant-done", + "details": { + "t": 757, + "mode": "marker-hit" + }, + "harnessMs": 784.7 + }, + { + "event": "window-created", + "details": { + "t": 786 + }, + "harnessMs": 813.9 + }, + { + "event": "load-start", + "details": { + "t": 808 + }, + "harnessMs": 835.1 + }, + { + "event": "ready-to-show", + "details": { + "t": 1768 + }, + "harnessMs": 1795.2 + }, + { + "event": "did-finish-load", + "details": { + "t": 1768 + }, + "harnessMs": 1795.3 + } + ], + "phases": { + "spawnToAppReady": 638.3, + "appReadyToServices": 137, + "servicesToI18n": 2, + "i18nToOpenWindow": 7, + "aclGrantMs": 0, + "windowCreatedToLoaded": 982, + "totalToWindowCreated": 813.9, + "totalToDidFinishLoad": 1795.3 + } + }, + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 575 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 575 + }, + { + "event": "app-ready", + "details": { + "t": 584 + }, + "harnessMs": 607.5 + }, + { + "event": "store-loaded", + "details": { + "t": 589 + }, + "harnessMs": 613.1 + }, + { + "event": "services-initialized", + "details": { + "t": 724 + }, + "harnessMs": 747.2 + }, + { + "event": "i18n-ready", + "details": { + "t": 725 + }, + "harnessMs": 749 + }, + { + "event": "open-main-window-start", + "details": { + "t": 731 + }, + "harnessMs": 754.1 + }, + { + "event": "acl-grant-start", + "details": { + "t": 731 + }, + "harnessMs": 754.1 + }, + { + "event": "acl-grant-done", + "details": { + "t": 731, + "mode": "marker-hit" + }, + "harnessMs": 754.5 + }, + { + "event": "window-created", + "details": { + "t": 757 + }, + "harnessMs": 780.3 + }, + { + "event": "load-start", + "details": { + "t": 777 + }, + "harnessMs": 801 + }, + { + "event": "ready-to-show", + "details": { + "t": 1685 + }, + "harnessMs": 1708.4 + }, + { + "event": "did-finish-load", + "details": { + "t": 1685 + }, + "harnessMs": 1708.6 + } + ], + "phases": { + "spawnToAppReady": 607.5, + "appReadyToServices": 140, + "servicesToI18n": 1, + "i18nToOpenWindow": 6, + "aclGrantMs": 0, + "windowCreatedToLoaded": 928, + "totalToWindowCreated": 780.3, + "totalToDidFinishLoad": 1708.6 + } + } + ], + "summaryMedianMs": { + "spawnToAppReady": 638.3, + "appReadyToServices": 140, + "servicesToI18n": 1, + "i18nToOpenWindow": 7, + "aclGrantMs": 0, + "windowCreatedToLoaded": 982, + "totalToWindowCreated": 813.9, + "totalToDidFinishLoad": 1795.3 + } +} diff --git a/tools/benchmarks/results/startup-baseline-2026-06-10T19-36-01-305Z.json b/tools/benchmarks/results/startup-baseline-2026-06-10T19-36-01-305Z.json new file mode 100644 index 000000000..f535defe0 --- /dev/null +++ b/tools/benchmarks/results/startup-baseline-2026-06-10T19-36-01-305Z.json @@ -0,0 +1,363 @@ +{ + "label": "baseline", + "platform": "win32", + "arch": "x64", + "cpus": "Intel(R) Core(TM) Ultra 9 185H", + "fixtureDir": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "fixtureFiles": 28000, + "exe": null, + "iterations": [ + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 7624.5 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 7624.6 + }, + { + "event": "app-ready", + "details": { + "t": 7639 + }, + "harnessMs": 7672.5 + }, + { + "event": "store-loaded", + "details": { + "t": 7642 + }, + "harnessMs": 7674.8 + }, + { + "event": "services-initialized", + "details": { + "t": 8477 + }, + "harnessMs": 8510.9 + }, + { + "event": "i18n-ready", + "details": { + "t": 8480 + }, + "harnessMs": 8513 + }, + { + "event": "open-main-window-start", + "details": { + "t": 8488 + }, + "harnessMs": 8521 + }, + { + "event": "acl-grant-start", + "details": { + "t": 8488 + }, + "harnessMs": 8521 + }, + { + "event": "acl-grant-done", + "details": { + "t": 24135, + "ok": true + }, + "harnessMs": 24168.5 + }, + { + "event": "window-created", + "details": { + "t": 24164 + }, + "harnessMs": 24197.8 + }, + { + "event": "load-start", + "details": { + "t": 24184 + }, + "harnessMs": 24217.3 + }, + { + "event": "ready-to-show", + "details": { + "t": 26021 + }, + "harnessMs": 26054 + }, + { + "event": "did-finish-load", + "details": { + "t": 26021 + }, + "harnessMs": 26054.2 + } + ], + "phases": { + "spawnToAppReady": 7672.5, + "appReadyToServices": 838, + "servicesToI18n": 3, + "i18nToOpenWindow": 8, + "aclGrantMs": 15647, + "windowCreatedToLoaded": 1857, + "totalToWindowCreated": 24197.8, + "totalToDidFinishLoad": 26054.2 + } + }, + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 811.3 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 811.4 + }, + { + "event": "app-ready", + "details": { + "t": 822 + }, + "harnessMs": 857.3 + }, + { + "event": "store-loaded", + "details": { + "t": 830 + }, + "harnessMs": 864.8 + }, + { + "event": "services-initialized", + "details": { + "t": 1000 + }, + "harnessMs": 1035.6 + }, + { + "event": "i18n-ready", + "details": { + "t": 1002 + }, + "harnessMs": 1037.3 + }, + { + "event": "open-main-window-start", + "details": { + "t": 1009 + }, + "harnessMs": 1044.4 + }, + { + "event": "acl-grant-start", + "details": { + "t": 1009 + }, + "harnessMs": 1044.5 + }, + { + "event": "acl-grant-done", + "details": { + "t": 18191, + "ok": true + }, + "harnessMs": 18226.3 + }, + { + "event": "window-created", + "details": { + "t": 18219 + }, + "harnessMs": 18254.6 + }, + { + "event": "load-start", + "details": { + "t": 18241 + }, + "harnessMs": 18275.9 + }, + { + "event": "ready-to-show", + "details": { + "t": 19278 + }, + "harnessMs": 19312.8 + }, + { + "event": "did-finish-load", + "details": { + "t": 19278 + }, + "harnessMs": 19313 + } + ], + "phases": { + "spawnToAppReady": 857.3, + "appReadyToServices": 178, + "servicesToI18n": 2, + "i18nToOpenWindow": 7, + "aclGrantMs": 17182, + "windowCreatedToLoaded": 1059, + "totalToWindowCreated": 18254.6, + "totalToDidFinishLoad": 19313 + } + }, + { + "outcome": "ok", + "events": [ + { + "event": "before-single-instance-lock", + "details": { + "version": "1.4.58", + "packaged": false, + "platform": "win32", + "osRelease": "10.0.26200", + "userData": "C:\\Users\\jinwo\\AppData\\Local\\Temp\\orca-startup-bench\\userdata-28000", + "e2eUserData": true + }, + "harnessMs": 583.2 + }, + { + "event": "single-instance-lock-result", + "details": { + "acquired": true, + "bypassed": false, + "skippedForDev": true + }, + "harnessMs": 583.2 + }, + { + "event": "app-ready", + "details": { + "t": 593 + }, + "harnessMs": 616.4 + }, + { + "event": "store-loaded", + "details": { + "t": 599 + }, + "harnessMs": 622.3 + }, + { + "event": "services-initialized", + "details": { + "t": 732 + }, + "harnessMs": 755.5 + }, + { + "event": "i18n-ready", + "details": { + "t": 734 + }, + "harnessMs": 757.6 + }, + { + "event": "open-main-window-start", + "details": { + "t": 740 + }, + "harnessMs": 763.7 + }, + { + "event": "acl-grant-start", + "details": { + "t": 740 + }, + "harnessMs": 763.7 + }, + { + "event": "acl-grant-done", + "details": { + "t": 14595, + "ok": true + }, + "harnessMs": 14618.2 + }, + { + "event": "window-created", + "details": { + "t": 14621 + }, + "harnessMs": 14645 + }, + { + "event": "load-start", + "details": { + "t": 14640 + }, + "harnessMs": 14664 + }, + { + "event": "ready-to-show", + "details": { + "t": 15621 + }, + "harnessMs": 15644.5 + }, + { + "event": "did-finish-load", + "details": { + "t": 15621 + }, + "harnessMs": 15644.7 + } + ], + "phases": { + "spawnToAppReady": 616.4, + "appReadyToServices": 139, + "servicesToI18n": 2, + "i18nToOpenWindow": 6, + "aclGrantMs": 13855, + "windowCreatedToLoaded": 1000, + "totalToWindowCreated": 14645, + "totalToDidFinishLoad": 15644.7 + } + } + ], + "summaryMedianMs": { + "spawnToAppReady": 857.3, + "appReadyToServices": 178, + "servicesToI18n": 2, + "i18nToOpenWindow": 7, + "aclGrantMs": 15647, + "windowCreatedToLoaded": 1059, + "totalToWindowCreated": 18254.6, + "totalToDidFinishLoad": 19313 + } +} diff --git a/tools/benchmarks/startup-time-bench.mjs b/tools/benchmarks/startup-time-bench.mjs new file mode 100644 index 000000000..5e2f390bb --- /dev/null +++ b/tools/benchmarks/startup-time-bench.mjs @@ -0,0 +1,330 @@ +#!/usr/bin/env node +/** + * Orca startup-time benchmark. + * + * Launches the built app (out/) against a synthetic userData fixture that + * mimics a long-lived real profile (tens of thousands of Chromium cache + * files — the documented pathological case for the win32 startup ACL grant), + * parses `ORCA_STARTUP_DIAGNOSTICS=1` milestone lines from stderr, and + * reports per-phase timings across iterations. + * + * Usage: + * node tools/benchmarks/startup-time-bench.mjs --label baseline + * [--iterations 5] [--files 28000] [--fixture-dir ] + * [--exe ] [--timeout-ms 240000] + * + * Prereq (when not using --exe): `pnpm build:electron-vite` so out/ exists. + * Results: tools/benchmarks/results/startup-