Repository navigation
perf(usage): run the Claude/Codex/OpenCode usage scans on a worker thread - #21114
Conversation
Codex rollout files are append-only and grow all day, but any append changed both mtime and size, so `canReuse` discarded the cached entry and the scanner re-read the whole file from byte 0 on the Electron main process. On one real corpus that was 6.59 GB re-read per cycle across 26.63 GB / 21,110 files. Each parsed file now persists a resume point: the offset just past the last newline-terminated line, the parse context at that offset (session id, cwd, model, running totals), a sha256 of the 4 KiB before it, and the file's dev:ino. A grown file resumes there and merges the appended rollup into the cached one; anything unproven falls back to a full reparse — truncation, an in-place rewrite, rotation, a counted tail with no trailing newline, a legacy copied-session suffix offset, or a file that must reclaim deferred fork claims. Resume never depends on mtime equality, so a coarse-mtime filesystem cannot hide an append. Fixture: a 75,737-byte rollout with a 758-byte append re-read 76,495 bytes before and 8,950 after (the append plus two bounded 4 KiB boundary windows). Also bounds the automation-attribution force predicate for both Codex and Claude: it keyed on `lastScanError`, so a persistently failing scan forced a fresh full rescan on every single lookup. It now keys on the most recent scan attempt, which is one forced scan per run regardless of outcome.
…read The three first-party usage scans walk whole rollout and transcript corpora and read OpenCode's SQLite synchronously, all on the Electron main process. They rarely produce a long stall — the JSONL reader streams, so it yields to the loop between chunks — but they pin the main-process event loop at ~95% utilization for the scan's whole duration, which is what every IPC message, timer and window event then queues behind. Move that work to one lazily-spawned, unref'd worker thread shared by all three providers, following the OpenCode SQLite scanner precedent (#8864). Measured on a synthetic 4,000-rollout corpus (25.8 MB cache): a cold scan drops from 2,147 ms of main-thread time to 31 ms, and a steady-state incremental scan from 165 ms to 64 ms. The worker is stateless and the cache crosses the boundary both ways. That costs ~64 ms of structured clone at this corpus size, against 2,147 ms saved on the cold path, and it keeps the persisted cache the single source of truth — a worker-owned copy would need an invalidation protocol and a second resident copy of the same multi-MB array. Failure is closed, never a silent empty result: a worker that cannot spawn, times out, or crash-loops rejects, and the store records the scan error and keeps the previous projection. Two clients already carried the same FIFO/timeout/crash-cap machinery, so extract it once as WorkerThreadRequestQueue (with the packaged entry-path resolver as worker-thread-entry-path) and move all three onto it, rather than adding a third copy. Their existing tests pass unchanged. The oracle is event-loop utilization on the calling thread, not a stopwatch: usage-scan-worker-event-loop.test.ts runs the same scan both ways and asserts the worker leg leaves the caller idle while the main-thread leg does not, so CI load moves both legs together (#18788).
There was a problem hiding this comment.
ℹ️ No critical issues — the extraction and worker move check out. One automated-coverage gap worth closing, plus a minor diagnostic-string change.
Reviewed changes
This run read the full 22-file diff at 510c6e4 and the surrounding worker/queue/scanner modules it touches.
- Worker-thread usage scans — the Claude, Codex and OpenCode scanners now run on one shared, lazily-spawned,
unref'd worker. Each provider'sscanpoints at ascan*ViaWorkerwrapper that renamessourceback to the persisted key and fails closed on spawn failure, timeout, or crash-loop. - Shared request queue extracted —
WorkerThreadRequestQueueandworker-thread-entry-path.tsreplace the duplicated FIFO/timeout/crash-cap machinery inPortScanCommandClientandOpenCodeSqliteWorkerClient; both of those clients' unchanged suites still pass. - Build guard —
usage-scan-worker-entryis added as a rollup input and toWORKER_THREAD_ENTRY_NAMES, so the build fails if its chunk graph ever reachesrequire('electron'). - Oracle test — a new suite bundles the real worker entry and compares caller event-loop utilization for the worker leg against the calling-thread leg, with presence preconditions so an empty scan cannot pass the occupancy assertion.
ℹ️ Two of the three new scan routes have no automated coverage
scanClaudeUsageOnWorker and scanOpenCodeUsageOnWorker are never called by any test, and the worker entry's claude / opencode branches are never executed. The only end-to-end worker run is the codex leg in usage-scan-worker-event-loop.test.ts, usage-scan-worker-client.test.ts only drives the codex route, and the Claude/OpenCode store tests mock scan*ViaWorker outright. A copy-paste slip in either untested route — wrong providerId, wrong scanner in the entry's switch, wrong source key — would ship undetected, because the store-level mock replaces the whole path.
Technical details
# Close the route-coverage gap for the non-Codex providers
## Affected sites
- `src/main/usage/usage-scan-worker-client.test.ts:72` — `describe('UsageScanWorkerClient')` only drives `scanCodexUsageOnWorker`.
- `src/main/usage/usage-scan-worker-entry.ts:26` — the `switch (request.providerId)` has three branches; only `case 'codex'` is reached by tests.
- `src/main/claude-usage/store.test.ts:18` and `src/main/opencode-usage/store.test.ts:22` — mock the spawn wrapper, so the route helpers are bypassed.
## Required outcome
- Each of the three provider routes is exercised through the worker protocol at least once, including the `wrongProvider` guard and the `source` → `processedFiles` / `processedDatabases` rename.
- The worker entry's `claude` and `opencode` branches run against a small fixture (or stub) so the mapping between `providerId`, scanner, and returned `source` key is pinned.
## Suggested approach (optional)
Parametrize the existing client test over the three provider ids, and add a worker-entry suite that builds the entry once (as the oracle already does) and asserts one scan per provider.ℹ️ Nitpicks
src/main/ports/port-scan-command-client.ts:81andsrc/main/worker-thread-request-queue.ts:167— the extraction made two port-scan diagnostics less specific: the queue-full error no longer names the dropped command, and the unavailable error message changed fromport scan probe worker spawn failedto the genericworker spawn failed. Both are log-only and no test asserts them, but if those strings are meant to identify the caller, letcreateUnavailableError/ the cap'sdescribeFulltake the context.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
The event-loop oracle claimed to be self-calibrating — its header said "the ratio is self-calibrating, so CI load moves both legs together (#18788) instead of tipping a fixed millisecond threshold." It computed no ratio. Two separate `it()` blocks each asserted an absolute threshold against its own arm, run separately, so load moved them independently. The comment described a test nobody wrote, and the flake it promised was impossible is the one that landed: `activeRatio > 0.8` on the calling-thread arm measured 0.764 on an ubuntu runner. Fixing the comment is not enough, because the fraction is the wrong quantity. CPU contention drags the calling-thread arm's active/wall fraction *down* toward the worker's, since the loop parks waiting on a contended libuv pool. A 4-vCPU Linux container measured that arm at 0.175-0.756 across twenty runs, idle and loaded — never once above 0.8. Active *milliseconds* move the other way: contention stretches the caller's JS time far more than it stretches the worker arm's fixed post-and-deserialize cost, so the gap widens under load. Merge the two arms into one case over one corpus and assert the worker arm costs the caller under a fifth of the inline arm's active milliseconds. Same twenty Linux runs: 10.9x-83.6x, passing throughout. Keep the presence preconditions on both arms — an arm that silently scanned nothing satisfies the comparison trivially — and extend them to the calling-thread arm, which previously checked only file and session counts.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This run re-reviewed the delta at ccc7d26 since the prior pullfrog review at 510c6e4 — a single-file rewrite of the event-loop oracle's assertions.
- Oracle compares the two scan arms directly —
usage-scan-worker-event-loop.test.tsnow runs the identical Codex scan inline and on the worker over one corpus and assertsworker.activeMs < caller.activeMs / 5, replacing the fixed0.5/0.8active-ratio floors that CPU contention could drag across. Presence preconditions on both arms still stop a no-op scan from satisfying the comparison, so the mutation check survives: an inline worker route makes the arms' active milliseconds comparable and fails the fraction bound.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
The shared-queue extraction turned `Port scan command queue is full; dropped
${command}.` into a constant string, because `describeFull` was given no way
to see the request. Pile-up is per-probe, so the name is the only thing in
that log that identifies which of lsof/ps/netstat was shed.
Pass the rejected request to `describeFull` and restore the name. The request
is built before the cap check so it exists to be named; the id it burns is a
correlation token, so a gap costs nothing.
The existing overflow test asserted only the error class, which is why the
regression escaped a 29-test suite. It now dispatches the overflow under a
different command than the accepted ones and asserts the message text, so a
message that names the wrong request fails too.
Also add a direct WorkerThreadRequestQueue test. Three subsystems share the
queue and each client test only sees the parts its own protocol exercises,
with `queueCap` reachable from port-scan alone. Covers one-at-a-time FIFO
dispatch, the deadline starting at dispatch rather than enqueue, the
consecutive-death cap, and both points where that count clears.
And record the child-process hazard at the usage worker entry. `terminate()`
reaps nothing the thread spawned, and OpenCode discovery reaches a fork
today: `wslGated*` forks the WSL transcript sidecar for a `\\wsl$\...` path,
which a Windows `OPENCODE_DB` or `XDG_DATA_HOME` can be. One scan through
that entry with a UNC `OPENCODE_DB` forked a sidecar that outlived
`terminate()`.
…ragment Checked every message string in the two clients the shared-queue extraction rewrote against origin/main. Only the port-scan queue-full one regressed (fixed in the previous commit); the OpenCode SQLite client's four messages render identically, the remaining source diffs being renames — `error.message` to `lastError`, `call.timeoutMs` and `CALL_DEADLINE_MS` to `timeoutMs`. `session-scanner-worker-client.ts` was not touched by the extraction. But its suite could not have caught it either. `/timed out/`, `/exited with code/` and a bare `rejects.toThrow()` all still match a message that has lost its interpolated value, which is the same blind spot that let the port-scan regression through. Assert the rendered text instead: the timeout names its deadline, the exit names its code, and the crash-loop drain still carries the text of the fault that killed the run.
The previous note said `worker.terminate()` leaves a forked sidecar orphaned.
It does not, and the reproduction that appeared to show it used a stub sidecar
missing the `process.on('disconnect', () => process.exit(0))` the real entry
has. With a faithful one: the sidecar lives exactly as long as the thread and
is gone within 2s of `terminate()`, because tearing the thread down closes the
IPC channel it owned. Two worker lifecycles forked two sidecars and leaked
neither, and the pre-worker main-thread path reaps its sidecar the same way,
on host exit.
What is true and worth recording: a fork is reachable from this bundle at all,
which is easy to miss; it survives only as long as the channel does; and the
sidecar is now re-forked per worker lifecycle instead of pooled for the app's
life. State those, and warn that a future child which does not exit on channel
close would not get the same free cleanup.
There was a problem hiding this comment.
ℹ️ No new issues in this delta — the queue-cap diagnostic fix, the new direct queue suite, and the tightened OpenCode assertions all check out. One earlier point is still open: the Claude and OpenCode worker routes remain unexercised by automated tests.
Reviewed changes
This run re-reviewed the two commits pushed since the prior pullfrog review at ccc7d26 — cace056 and 0806621.
- Port-scan queue-full message restored —
WorkerThreadRequestQueue.dispatchnow builds the request before the queue-cap check, sodescribeFull(request)can name the work that was shed;PortScanCommandClientrendersdropped ${command}again, and its overflow test sheds a different command than the accepted ones and asserts the exact string. - Direct
WorkerThreadRequestQueuesuite added — a 240-line test pins one-at-a-time FIFO dispatch, the deadline clock starting at dispatch rather than enqueue, the consecutive-death cap and drain, and both points where the death count clears. - OpenCode SQLite client test asserts rendered text — the timeout names its deadline, the exit names its code, and the crash-loop drain carries the fault text, replacing
/timed out/,/exited with code/, and a barerejects.toThrow(). - Child-process hazard documented — the usage worker entry now records that
worker.terminate()reaps nothing the thread spawned, with OpenCode's\\wsl$sidecar fork as the live example.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
`USAGE_SCAN_TIMEOUT_MS` was a 10-minute deadline on the whole scan. A cold scan of a real history is legitimately minutes — 637 s measured on a 30 GB corpus with 300 worktrees before the per-cwd memo, ~51 s after — so a larger corpus or a slower disk crosses it. Crossing it killed the worker, recorded a scan error and left the cache unadvanced, so the next refresh started cold and died at the same point, forever. The deadline is now a no-progress window. The worker posts a file counter as it walks the corpus (`UsageScanWorkerProgress`, rate-limited to one message a second), and `WorkerThreadRequestQueue` re-arms the active call's timer on each one via the new optional `isProgress`. Clients that do not pass it keep the plain wall-clock deadline. `MAX_CONSECUTIVE_DEATHS` and idle teardown are unchanged.
…er file Claude's scanner walks batches, so a per-file callback made it loop just to bump a counter.
# Conflicts: # src/main/claude-usage/claude-usage-automation-attribution.ts # src/main/codex-usage/codex-automation-run-attribution.ts # src/main/codex-usage/codex-rollout-file-parse.ts # src/main/codex-usage/codex-rollout-resume-state.ts # src/main/codex-usage/scanner-incremental-append.test.ts # src/main/codex-usage/scanner.ts # src/main/codex-usage/store-automation-usage.test.ts # src/main/codex-usage/types.ts
📝 WalkthroughWalkthroughThe change adds a shared FIFO worker-request queue and migrates existing port-scan and OpenCode SQLite clients to it. It adds a worker protocol, bundled worker entry, client, spawn helpers, progress reporting, and worker-based Claude, Codex, and OpenCode scans. Provider stores now use the worker paths. Scanner tests and worker tests cover dispatch, timeouts, crashes, progress, packaging, and event-loop occupancy. Priority: ➖ Normal Merge Risk: 🔵 Low · up to An unusually slow OpenCode database scan can time out despite continuing to parse, leaving the prior usage projection until a later refresh. Add bounded parser-level progress before merge. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This run re-reviewed the delta since the prior pullfrog review at 0806621: commits daccac5331, 7b4a4a21e8, and the cee3881f4c merge of main into the branch.
- The scan deadline became a no-progress window —
USAGE_SCAN_TIMEOUT_MSis renamed toUSAGE_SCAN_NO_PROGRESS_TIMEOUT_MS, andWorkerThreadRequestQueuenow takes an optionalisProgresspredicate that re-arms the active call's timer on every progress message (armDeadline) instead of enforcing one wall clock over the whole scan. Clients that omit it keep the plain deadline. - The worker reports file-count liveness — a new
UsageScanWorkerProgressmessage andisUsageScanWorkerProgressguard; the entry'screateProgressReporteraccumulatesfilesScannedand rate-limits posts to one per second; all three scanners accept an optionalonFilesScanned(count)callback and invoke it per file/batch. - Both halves of the deadline are pinned by tests — the client suite asserts a scan survives repeated no-progress windows while it keeps reporting, and is still killed when it goes silent.
usage-scan-worker-client.test.ts(10) andworker-thread-request-queue.test.ts(6) pass locally, 16/16. - The merge absorbed the stacked base —
cee3881f4cmergesmain(which now contains #21102 and #21130), so the range-diff shows the stacked scanner/resume files dropping out of this PR's diff. The worker-move surface is otherwise unchanged, and the oracle still drives the realUsageScanWorkerClient, so it handles the new progress messages rather than mistaking them for the result.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: a9099d5e-90fd-443c-85ec-78861b73164c
📒 Files selected for processing (28)
config/build-plugins/plain-node-entry-guard.tselectron.vite.config.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-client.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-client.tssrc/main/claude-usage/scanner.tssrc/main/claude-usage/store.test.tssrc/main/claude-usage/store.tssrc/main/codex-usage/codex-usage-provider.tssrc/main/codex-usage/scanner.tssrc/main/codex-usage/store-automation-usage.test.tssrc/main/codex-usage/store-model-pricing.test.tssrc/main/codex-usage/store-orca-scope.test.tssrc/main/codex-usage/store-persistence.test.tssrc/main/codex-usage/store-test-harness.tssrc/main/opencode-usage/opencode-usage-provider.tssrc/main/opencode-usage/scanner.tssrc/main/opencode-usage/store.test.tssrc/main/ports/port-scan-command-client.test.tssrc/main/ports/port-scan-command-client.tssrc/main/usage/usage-scan-worker-client.test.tssrc/main/usage/usage-scan-worker-client.tssrc/main/usage/usage-scan-worker-entry.tssrc/main/usage/usage-scan-worker-event-loop.test.tssrc/main/usage/usage-scan-worker-protocol.tssrc/main/usage/usage-scan-worker-spawn.tssrc/main/worker-thread-entry-path.tssrc/main/worker-thread-request-queue.test.tssrc/main/worker-thread-request-queue.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
…reen and agent-history (step 7) (#21269) * test(mobile): record main's file-preview and markdown-disk-fallback replies Four of this branch's read sites had no malformed-reply coverage, so the reader change would have had nothing to move at them. `familyGoldens` matrixes only the first scenario of each family, and `files.preview-load`'s base is the grant-refresh chain while `session.tab-documents`' is the served markdown tab — which left `files.read` and `files.readPreview` on the worktree preview path, the artifact image read, and the markdown tab's on-disk fallback recorded on their success path only. This commit is the before picture, taken from main's own tree with no product edit in it. Three new families, five scenarios, ten goldens: - `files.preview-worktree-text` / `files.preview-worktree-image` — `files.read` and `files.readPreview` as the preview screen asks them for a worktree file. - `files.preview-artifact-image` — `files.readTerminalArtifactPreview`. - `session.markdown-disk-fallback` — the `files.read` leg a headless host's `renderer_unavailable` sends the markdown tab down. It carries a second scenario that serves `markdown.readTab`, because a matrix site needs a fulfilled reply recorded somewhere in its own family to replay as the `normal` partition. No existing scenario moved to a new family and no adapter changed, so every pre-existing golden keeps its `adapterSha256` and `scenarioSha256`. Recorded in a detached worktree at the manifest's pin (`4b876758d3`) with this manifest copied in; the control is that all 748 pre-existing goldens came back byte-identical to origin/main's, which `git diff c2962a7 -- mobile/rpc-foundation/goldens` confirms as empty. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * refactor(mobile): checked reply readers for files, dictation, host-screen and agent-history Thirty-five unchecked reply readers across seven files become checked zod readers, so a malformed host reply surfaces as one readable error at the operation boundary instead of a downstream TypeError, a rendered `undefined`, or a screen left ready over garbage. Deliberately a behaviour change on malformed replies only: every good reply decodes to the same value it did, which the `normal` partition of every matrix golden holds byte for byte. Nothing on the wire moves — no method, params, options, timeout or acceptance policy changes at any site. The inventory drops from 137 readers over 31 files to 102 over 24. What each domain checks, and what it deliberately does not: - files/preview — one schema for `files.read` and `files.readTerminalArtifact`, one for the two preview methods. `content` is required on the text pair because the markdown disk fallback publishes it into the tab with no guard; the image pair requires nothing, because normalizeImagePreviewResult guards all four members and the host's own "binary I cannot preview" and "not actually an image" arms are good replies the screen renders today. - files/tab-doc — stricter than the preview screen on the same two methods, because a tab publishes what it read into a typed ready document with no guard. `git.diff` reads as two variants, and an arm this build has not heard of takes the binary one rather than refusing the reply. - files/explorer — the directory listing is an array and a row needs the name and the directory flag the tree projection turns on; the legacy capped list needs its rows' paths and the truncation flag its note draws. - files/ownership — the two members that decide *where a write lands* are fatal on a wrong type rather than salvaged, because absence reads as `local` downstream and a salvage would send a mutation to the wrong host. `hostId`'s absent/null/string states stay distinct, and the SSH connection generation passes through at its own type because the mutation echoes it back to the host. - dictation — the setup the sheet renders is checked; the model rows need the `id` the sheet keys and sends back. The five sends whose reply body no call site reads keep an unknown payload, and so does `speech.dictation.finish`, whose transcript is read past a staleness guard that a reader throw would move the failure across. - host-screen — the repo catalog, the SSH labels and the host platform. The four writes read no reply body; `worktree.activate` stays opaque because the session route's second report site awaits it outside any catch. - agent-history — the capability gate and both scan containers. The session rows stay unknown on purpose: `agent` is a vocabulary that grows with every agent CLI Orca learns to scan and that this client echoes back on resume, so narrowing it would refuse a newer host's reply or drop the very sessions it added. Two shared readers were widened to take the strings the reply readers hand them — `getRepoExecutionHostId` and `buildRepoHostIdByRepoId` — because both already answer `local` for a host-id spelling they cannot parse, and closing that spelling in a reply schema would refuse a newer host's own catalog. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin the corpus and re-record the checked reply readers `baseline` moves to this branch's last fenced commit, which is what `--record` refuses without: main's fenced tree drifted past the session domain's pin when #21114 and the dependency bump landed, and the product edit in the commit before this one moves it again. Every body move is confined to a malformed partition of a family this branch touched. No `normal` partition moved, which is the byte-for-byte control on good replies, and no golden outside the seven files' families moved at all. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): stop the dictation reader requiring a mode main rendered without The setup sheet's `normal` partition refused after the reader landed, which is the success control saying the schema was wrong rather than the fixture: `dictationMode` was declared required because the one unguarded consumer pushes it into a `useState<'toggle' | 'hold'>` and cannot invent a value, but main rendered a sheet whose reply omitted it, and requiring a member no consumer crashes on is exactly the version claim Rule 1 of the remote-wire contract warns about. The member is salvaged now and keeps its open arm set, so an unknown mode still degrades to `toggle` rather than to one that matches no segment. The native-chat refresh spells that same `toggle` for an absent mode, which is the value its state already started at, and the route parity pins are refreshed for the one literal and the two callback bodies that moved. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin past the dictation fix and re-record Second repin of the branch: the fix to the setup reader is a fenced-tree change, so `--record` refuses until `baseline` names it. The speech family's `normal` partition is back to main's projection, which is what said the first reader was wrong. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): mutant evidence for the checked reply readers Three mutations applied by hand, run, and reverted, recorded beside the adapter family mutations in the same shape. They are kept in their own file because a reader mutation is not killed by a pilot scenario: a pilot serves a good reply, and a schema that has stopped checking a member reads a good reply exactly as before. What kills them is a matrix golden's malformed partition, the schema's unit pin, or a consumer pin, and each is named against its mutation. Two survived their first run, and both survivals were defects in the gates: - Loosening the file tab's `content` was invisible, because the pin dropped members only in pairs and each pair is refused by the sibling. The pin now drops exactly one member per iteration, and the preview text schema and the legacy file list got the same treatment. - Collapsing the hostId tri-state was invisible, because no golden serves an explicit null host — the local ownership scenario omits the member. The ownership test now captures all three states end to end, which is where a tri-state belongs. `repo-metadata-platform` is re-anchored where this branch moved the read it mutates: the hand-rolled `readHostPlatform` became the reply schema's own projection. The defect it injects is unchanged. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): record main's repo-icon and speech-vocabulary replies The closed enums this branch introduced had no fixture behind them. `provider`, `dictationMode` and `repoIcon` were carried by no scenario at all — the fulfilled repo-metadata golden records `repoIconsByName: []` — so the corpus could not have moved whatever arm set the schemas declared, which is how a reader can pin a vocabulary the host does not speak and still decode to a zero-move delta. Two scenarios, both appended to an existing family so `familyGoldens` adds no matrix golden, recorded from main's own tree at the pin with no product edit in it: - `settings-repo-metadata-icons` — all three `RepoIcon` arms, a github-sourced image with a label, an explicit `badgeColor`, and a mixed-host catalog so the ssh/settings/platform wave runs too. - `speech-setup-sheet-model-vocabulary` — `provider` on both arms, `status` on two, `dictationMode: "hold"`, and null and numeric `sizeBytes`/`progress`. Control: re-recording the whole corpus at the pin reproduces every committed golden body, including this branch's five earlier before-pictures; only `baseline` and the masked `lockfileSha256` move. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): stop the repo icon narrowing a member no consumer reads The image arm of `repoIcon` declared `source` as the four values `RepoIconImageSource` spells today (src/shared/repo-icon.ts:3). MobileRepoIcon reads `type`, `src`, `label`, `emoji` and `name`, and never `source`, so the only thing that enum could do was fail the union arm for a source a later host adds — dropping the whole icon and drawing the Folder default where main drew the image. That is the one arm set on this branch whose degrade was not already main's own behaviour for an unknown value. Dropping the declaration keeps the member: `looseObject` passes it through verbatim, so the decoded object is byte-identical to the one main published, which `settings-repo-metadata-icons` now records. The two type sites that hold an icon move to the decoded type. A host `RepoIcon` still satisfies the rendered union, so the worktree rows that carry one are unaffected. Every other closed enum on this branch was checked against the host's own shared type and left alone: speech `provider`/`status`/`dictationMode` (runtime-worktree-contracts.ts:83/85/86), `groupBy`/`sortBy` (persisted-ui-state-types.ts:41-42), `platform` (Node's own domain; the handler answers `process.platform`). For each, a salvaged member lands on the same branch main's unknown value did: `=== 'openai'` and `=== 'ready'` stay false, a missing `groupBy` and an unmapped one both answer null, and an unknown platform and a null one both label the host "This computer". Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin past the repo-icon fix and re-record Header-only: all 770 goldens move on `baseline` alone, including the two recorded from main's tree two commits back. The icon fix and the two new fixtures decode to the bytes main published. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): keep the repo-metadata readers total the way main's were readSshTargets and readHostPlatform answered [] and null for any payload at all. The checked schemas threw for a non-object, and because the label write runs first in the same sequence that throw also skipped the platform write, so a malformed reply left both decorative labels at their previous values instead of degrading. A .catch on each restores main's answer without giving up the row filter or the checked reader. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): forward the dictation mode instead of substituting a default The reader closed the mode to two arms and the native-chat refresh spelled `?? 'toggle'`, which is a good-reply change no golden covers: main left the state undefined for a reply that omits the mode, and undefined binds no press handler on the terminal input mic. Head gave that mic a working toggle. The member is forwarded as the string the host sent and the refresh is main's line again, so an absent or unknown mode leaves the mic exactly as inert as main's. The route-parity runtime-string pin is main's own sha again. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin past the review fixes and re-record The repo-metadata readers are total again, so both families' `result-absent` and `result-null` checkpoints decode to main's bytes instead of the caught throw, and the two delta rows they cost go away. The dictation mode forwards verbatim, which no recorded reply exercises differently. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin onto the merge and re-record Pins the corpus to the merge commit so main's ten create-terminal goldens and this branch's own are recorded from one tree. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * docs(mobile): correct three reader comments round 2 caught The ownership schema said an explicit null hostId means the host said local; the code refuses it, which is the whole reason mutant (c) exists. The AiVault sessions cast cited a golden whose fixture row carries three members, not the sixteen the cast claims — the full row is in aivault-history-screen-listed — and both the issues cast and the schema doc said the rows are rendered when the only read anywhere is issues.length. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * docs(mobile): correct stale file:line citations in the batch-A reply schemas Resolved every citation in the seven reply-schema modules and the SAFETY notes against the tree and diffed each target line against the claim beside it. Twelve were wrong, two of them past the end of a file that had shrunk, so they read as evidence while pointing at a closing brace. - file-explorer: the entries put is :157 not :160, the relativePath split is file-list-fallback.ts:48 not :42, and the truncated publish is :136 not :141. buildFileExplorerRows is no symbol at all; the sort-and-walk is flattenDirectoryCache (file-tree.ts:58). - file-ownership: the !summary throw is :68 not :64. - file-preview: the markdown disk fallback reads content at :60 not :65. - file-tab-doc: the html body render is :68 not :81 and the file arm is :73-75 not :86-88 (the file has 78 lines); the isImage guard is :58 not :66; the kind !== 'text' branch is :41 not :44; mobileDiffImageDataUri spans :22-33 not :20-31; the unguarded content.length is mobile-diff-lines.ts:35, the function that does it rather than :34. - agent-history: both members land at :133-135; :135 alone is issues. - dictation: the parenthetical read as citing the staleness guard when it named the rpcPayloadMember read. Both are cited now, :237 and :225. Comments only. No schema, type, or runtime behaviour changes. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * docs(mobile): name the unguarded activation report site that pins the opaque schema Handler audit over all 33 interpret sites in the four domains found one site that is structurally unguarded: use-mobile-session-startup.ts:170 reports the activation verdict from inside a fire-and-forget `void (async …)()` whose only `.catch` sits on the request, not on the chain. A throw there would be an unhandled rejection and would also skip the terminal fetch below it. Nothing throws there today, because `worktree.activate` reads hostScreenUnreadReplySchema, which is `z.unknown()`. That totality is load bearing rather than incidental, so the doc now names the line it protects and contrasts it with the first report site at :141, which is chained `.then(…).catch(…)` and would survive a throw. Comments only. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): pin that a bound descriptor's interpret survives being detached bindDeferredRpcOperation builds interpret as a shorthand method closing over the captured operation, never `this`, which is what lets eleven call sites pass it as a bare function reference. Nothing named that invariant. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * chore(mobile): repin the RPC recording baseline to the main merge Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): pin the closed reply enums to the host unions where tsc looks pullfrog: the PR body promised a Record<HostUnion, true> pin for every closed enum in this batch and the code had none. Adding them in the schema tests would have changed nothing: mobile/tsconfig.json excludes *.test.ts, so a coverage record there is never typechecked (a mutation that dropped a key stayed green). hostUnionArms(coverage) in zod-salvage spells the arm list as a Readonly<Record<U, true>> in the schema module itself, called with the host union as the explicit type argument: an arm the host adds is a missing property, one it drops is an excess property. Used for the speech provider and status (RuntimeSpeechModelSummary), the workspace groupBy and sortBy (PersistedUIState) and Node's platform list, which host-screen now imports from mobile-runtime-host-platform instead of duplicating. The repo icon branches satisfy Readonly<Record<RepoIcon['type'], z.ZodType>>. Three mutations (drop `manual`, add `bogus`, drop the image branch) each fail tsc. The tests iterate the exported lists; the platform mutant is re-anchored to the renamed constant. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…read (stablyai#21114) * perf(codex-usage): resume rollout scans at the last parsed byte Codex rollout files are append-only and grow all day, but any append changed both mtime and size, so `canReuse` discarded the cached entry and the scanner re-read the whole file from byte 0 on the Electron main process. On one real corpus that was 6.59 GB re-read per cycle across 26.63 GB / 21,110 files. Each parsed file now persists a resume point: the offset just past the last newline-terminated line, the parse context at that offset (session id, cwd, model, running totals), a sha256 of the 4 KiB before it, and the file's dev:ino. A grown file resumes there and merges the appended rollup into the cached one; anything unproven falls back to a full reparse — truncation, an in-place rewrite, rotation, a counted tail with no trailing newline, a legacy copied-session suffix offset, or a file that must reclaim deferred fork claims. Resume never depends on mtime equality, so a coarse-mtime filesystem cannot hide an append. Fixture: a 75,737-byte rollout with a 758-byte append re-read 76,495 bytes before and 8,950 after (the append plus two bounded 4 KiB boundary windows). Also bounds the automation-attribution force predicate for both Codex and Claude: it keyed on `lastScanError`, so a persistently failing scan forced a fresh full rescan on every single lookup. It now keys on the most recent scan attempt, which is one forced scan per run regardless of outcome. * perf(usage): run the Claude/Codex/OpenCode usage scans on a worker thread The three first-party usage scans walk whole rollout and transcript corpora and read OpenCode's SQLite synchronously, all on the Electron main process. They rarely produce a long stall — the JSONL reader streams, so it yields to the loop between chunks — but they pin the main-process event loop at ~95% utilization for the scan's whole duration, which is what every IPC message, timer and window event then queues behind. Move that work to one lazily-spawned, unref'd worker thread shared by all three providers, following the OpenCode SQLite scanner precedent (stablyai#8864). Measured on a synthetic 4,000-rollout corpus (25.8 MB cache): a cold scan drops from 2,147 ms of main-thread time to 31 ms, and a steady-state incremental scan from 165 ms to 64 ms. The worker is stateless and the cache crosses the boundary both ways. That costs ~64 ms of structured clone at this corpus size, against 2,147 ms saved on the cold path, and it keeps the persisted cache the single source of truth — a worker-owned copy would need an invalidation protocol and a second resident copy of the same multi-MB array. Failure is closed, never a silent empty result: a worker that cannot spawn, times out, or crash-loops rejects, and the store records the scan error and keeps the previous projection. Two clients already carried the same FIFO/timeout/crash-cap machinery, so extract it once as WorkerThreadRequestQueue (with the packaged entry-path resolver as worker-thread-entry-path) and move all three onto it, rather than adding a third copy. Their existing tests pass unchanged. The oracle is event-loop utilization on the calling thread, not a stopwatch: usage-scan-worker-event-loop.test.ts runs the same scan both ways and asserts the worker leg leaves the caller idle while the main-thread leg does not, so CI load moves both legs together (stablyai#18788). * test(usage): compare the two scan arms instead of two fixed thresholds The event-loop oracle claimed to be self-calibrating — its header said "the ratio is self-calibrating, so CI load moves both legs together (stablyai#18788) instead of tipping a fixed millisecond threshold." It computed no ratio. Two separate `it()` blocks each asserted an absolute threshold against its own arm, run separately, so load moved them independently. The comment described a test nobody wrote, and the flake it promised was impossible is the one that landed: `activeRatio > 0.8` on the calling-thread arm measured 0.764 on an ubuntu runner. Fixing the comment is not enough, because the fraction is the wrong quantity. CPU contention drags the calling-thread arm's active/wall fraction *down* toward the worker's, since the loop parks waiting on a contended libuv pool. A 4-vCPU Linux container measured that arm at 0.175-0.756 across twenty runs, idle and loaded — never once above 0.8. Active *milliseconds* move the other way: contention stretches the caller's JS time far more than it stretches the worker arm's fixed post-and-deserialize cost, so the gap widens under load. Merge the two arms into one case over one corpus and assert the worker arm costs the caller under a fifth of the inline arm's active milliseconds. Same twenty Linux runs: 10.9x-83.6x, passing throughout. Keep the presence preconditions on both arms — an arm that silently scanned nothing satisfies the comparison trivially — and extend them to the calling-thread arm, which previously checked only file and session counts. * fix(ports): name the dropped command when the probe queue is full The shared-queue extraction turned `Port scan command queue is full; dropped ${command}.` into a constant string, because `describeFull` was given no way to see the request. Pile-up is per-probe, so the name is the only thing in that log that identifies which of lsof/ps/netstat was shed. Pass the rejected request to `describeFull` and restore the name. The request is built before the cap check so it exists to be named; the id it burns is a correlation token, so a gap costs nothing. The existing overflow test asserted only the error class, which is why the regression escaped a 29-test suite. It now dispatches the overflow under a different command than the accepted ones and asserts the message text, so a message that names the wrong request fails too. Also add a direct WorkerThreadRequestQueue test. Three subsystems share the queue and each client test only sees the parts its own protocol exercises, with `queueCap` reachable from port-scan alone. Covers one-at-a-time FIFO dispatch, the deadline starting at dispatch rather than enqueue, the consecutive-death cap, and both points where that count clears. And record the child-process hazard at the usage worker entry. `terminate()` reaps nothing the thread spawned, and OpenCode discovery reaches a fork today: `wslGated*` forks the WSL transcript sidecar for a `\\wsl$\...` path, which a Windows `OPENCODE_DB` or `XDG_DATA_HOME` can be. One scan through that entry with a UNC `OPENCODE_DB` forked a sidecar that outlived `terminate()`. * test(ai-vault): assert the OpenCode worker messages exactly, not by fragment Checked every message string in the two clients the shared-queue extraction rewrote against origin/main. Only the port-scan queue-full one regressed (fixed in the previous commit); the OpenCode SQLite client's four messages render identically, the remaining source diffs being renames — `error.message` to `lastError`, `call.timeoutMs` and `CALL_DEADLINE_MS` to `timeoutMs`. `session-scanner-worker-client.ts` was not touched by the extraction. But its suite could not have caught it either. `/timed out/`, `/exited with code/` and a bare `rejects.toThrow()` all still match a message that has lost its interpolated value, which is the same blind spot that let the port-scan regression through. Assert the rendered text instead: the timeout names its deadline, the exit names its code, and the crash-loop drain still carries the text of the fault that killed the run. * fix(usage): correct the worker entry's child-process note The previous note said `worker.terminate()` leaves a forked sidecar orphaned. It does not, and the reproduction that appeared to show it used a stub sidecar missing the `process.on('disconnect', () => process.exit(0))` the real entry has. With a faithful one: the sidecar lives exactly as long as the thread and is gone within 2s of `terminate()`, because tearing the thread down closes the IPC channel it owned. Two worker lifecycles forked two sidecars and leaked neither, and the pre-worker main-thread path reaps its sidecar the same way, on host exit. What is true and worth recording: a fork is reachable from this bundle at all, which is easy to miss; it survives only as long as the channel does; and the sidecar is now re-forked per worker lifecycle instead of pooled for the app's life. State those, and warn that a future child which does not exit on channel close would not get the same free cleanup. * fix(usage): kill a wedged scan worker on no progress, not on wall clock `USAGE_SCAN_TIMEOUT_MS` was a 10-minute deadline on the whole scan. A cold scan of a real history is legitimately minutes — 637 s measured on a 30 GB corpus with 300 worktrees before the per-cwd memo, ~51 s after — so a larger corpus or a slower disk crosses it. Crossing it killed the worker, recorded a scan error and left the cache unadvanced, so the next refresh started cold and died at the same point, forever. The deadline is now a no-progress window. The worker posts a file counter as it walks the corpus (`UsageScanWorkerProgress`, rate-limited to one message a second), and `WorkerThreadRequestQueue` re-arms the active call's timer on each one via the new optional `isProgress`. Clients that do not pass it keep the plain wall-clock deadline. `MAX_CONSECUTIVE_DEATHS` and idle teardown are unchanged. * refactor(usage): report scan progress as a file count, not one call per file Claude's scanner walks batches, so a per-file callback made it loop just to bump a counter.
…read (stablyai#21114) * perf(codex-usage): resume rollout scans at the last parsed byte Codex rollout files are append-only and grow all day, but any append changed both mtime and size, so `canReuse` discarded the cached entry and the scanner re-read the whole file from byte 0 on the Electron main process. On one real corpus that was 6.59 GB re-read per cycle across 26.63 GB / 21,110 files. Each parsed file now persists a resume point: the offset just past the last newline-terminated line, the parse context at that offset (session id, cwd, model, running totals), a sha256 of the 4 KiB before it, and the file's dev:ino. A grown file resumes there and merges the appended rollup into the cached one; anything unproven falls back to a full reparse — truncation, an in-place rewrite, rotation, a counted tail with no trailing newline, a legacy copied-session suffix offset, or a file that must reclaim deferred fork claims. Resume never depends on mtime equality, so a coarse-mtime filesystem cannot hide an append. Fixture: a 75,737-byte rollout with a 758-byte append re-read 76,495 bytes before and 8,950 after (the append plus two bounded 4 KiB boundary windows). Also bounds the automation-attribution force predicate for both Codex and Claude: it keyed on `lastScanError`, so a persistently failing scan forced a fresh full rescan on every single lookup. It now keys on the most recent scan attempt, which is one forced scan per run regardless of outcome. * perf(usage): run the Claude/Codex/OpenCode usage scans on a worker thread The three first-party usage scans walk whole rollout and transcript corpora and read OpenCode's SQLite synchronously, all on the Electron main process. They rarely produce a long stall — the JSONL reader streams, so it yields to the loop between chunks — but they pin the main-process event loop at ~95% utilization for the scan's whole duration, which is what every IPC message, timer and window event then queues behind. Move that work to one lazily-spawned, unref'd worker thread shared by all three providers, following the OpenCode SQLite scanner precedent (stablyai#8864). Measured on a synthetic 4,000-rollout corpus (25.8 MB cache): a cold scan drops from 2,147 ms of main-thread time to 31 ms, and a steady-state incremental scan from 165 ms to 64 ms. The worker is stateless and the cache crosses the boundary both ways. That costs ~64 ms of structured clone at this corpus size, against 2,147 ms saved on the cold path, and it keeps the persisted cache the single source of truth — a worker-owned copy would need an invalidation protocol and a second resident copy of the same multi-MB array. Failure is closed, never a silent empty result: a worker that cannot spawn, times out, or crash-loops rejects, and the store records the scan error and keeps the previous projection. Two clients already carried the same FIFO/timeout/crash-cap machinery, so extract it once as WorkerThreadRequestQueue (with the packaged entry-path resolver as worker-thread-entry-path) and move all three onto it, rather than adding a third copy. Their existing tests pass unchanged. The oracle is event-loop utilization on the calling thread, not a stopwatch: usage-scan-worker-event-loop.test.ts runs the same scan both ways and asserts the worker leg leaves the caller idle while the main-thread leg does not, so CI load moves both legs together (stablyai#18788). * test(usage): compare the two scan arms instead of two fixed thresholds The event-loop oracle claimed to be self-calibrating — its header said "the ratio is self-calibrating, so CI load moves both legs together (stablyai#18788) instead of tipping a fixed millisecond threshold." It computed no ratio. Two separate `it()` blocks each asserted an absolute threshold against its own arm, run separately, so load moved them independently. The comment described a test nobody wrote, and the flake it promised was impossible is the one that landed: `activeRatio > 0.8` on the calling-thread arm measured 0.764 on an ubuntu runner. Fixing the comment is not enough, because the fraction is the wrong quantity. CPU contention drags the calling-thread arm's active/wall fraction *down* toward the worker's, since the loop parks waiting on a contended libuv pool. A 4-vCPU Linux container measured that arm at 0.175-0.756 across twenty runs, idle and loaded — never once above 0.8. Active *milliseconds* move the other way: contention stretches the caller's JS time far more than it stretches the worker arm's fixed post-and-deserialize cost, so the gap widens under load. Merge the two arms into one case over one corpus and assert the worker arm costs the caller under a fifth of the inline arm's active milliseconds. Same twenty Linux runs: 10.9x-83.6x, passing throughout. Keep the presence preconditions on both arms — an arm that silently scanned nothing satisfies the comparison trivially — and extend them to the calling-thread arm, which previously checked only file and session counts. * fix(ports): name the dropped command when the probe queue is full The shared-queue extraction turned `Port scan command queue is full; dropped ${command}.` into a constant string, because `describeFull` was given no way to see the request. Pile-up is per-probe, so the name is the only thing in that log that identifies which of lsof/ps/netstat was shed. Pass the rejected request to `describeFull` and restore the name. The request is built before the cap check so it exists to be named; the id it burns is a correlation token, so a gap costs nothing. The existing overflow test asserted only the error class, which is why the regression escaped a 29-test suite. It now dispatches the overflow under a different command than the accepted ones and asserts the message text, so a message that names the wrong request fails too. Also add a direct WorkerThreadRequestQueue test. Three subsystems share the queue and each client test only sees the parts its own protocol exercises, with `queueCap` reachable from port-scan alone. Covers one-at-a-time FIFO dispatch, the deadline starting at dispatch rather than enqueue, the consecutive-death cap, and both points where that count clears. And record the child-process hazard at the usage worker entry. `terminate()` reaps nothing the thread spawned, and OpenCode discovery reaches a fork today: `wslGated*` forks the WSL transcript sidecar for a `\\wsl$\...` path, which a Windows `OPENCODE_DB` or `XDG_DATA_HOME` can be. One scan through that entry with a UNC `OPENCODE_DB` forked a sidecar that outlived `terminate()`. * test(ai-vault): assert the OpenCode worker messages exactly, not by fragment Checked every message string in the two clients the shared-queue extraction rewrote against origin/main. Only the port-scan queue-full one regressed (fixed in the previous commit); the OpenCode SQLite client's four messages render identically, the remaining source diffs being renames — `error.message` to `lastError`, `call.timeoutMs` and `CALL_DEADLINE_MS` to `timeoutMs`. `session-scanner-worker-client.ts` was not touched by the extraction. But its suite could not have caught it either. `/timed out/`, `/exited with code/` and a bare `rejects.toThrow()` all still match a message that has lost its interpolated value, which is the same blind spot that let the port-scan regression through. Assert the rendered text instead: the timeout names its deadline, the exit names its code, and the crash-loop drain still carries the text of the fault that killed the run. * fix(usage): correct the worker entry's child-process note The previous note said `worker.terminate()` leaves a forked sidecar orphaned. It does not, and the reproduction that appeared to show it used a stub sidecar missing the `process.on('disconnect', () => process.exit(0))` the real entry has. With a faithful one: the sidecar lives exactly as long as the thread and is gone within 2s of `terminate()`, because tearing the thread down closes the IPC channel it owned. Two worker lifecycles forked two sidecars and leaked neither, and the pre-worker main-thread path reaps its sidecar the same way, on host exit. What is true and worth recording: a fork is reachable from this bundle at all, which is easy to miss; it survives only as long as the channel does; and the sidecar is now re-forked per worker lifecycle instead of pooled for the app's life. State those, and warn that a future child which does not exit on channel close would not get the same free cleanup. * fix(usage): kill a wedged scan worker on no progress, not on wall clock `USAGE_SCAN_TIMEOUT_MS` was a 10-minute deadline on the whole scan. A cold scan of a real history is legitimately minutes — 637 s measured on a 30 GB corpus with 300 worktrees before the per-cwd memo, ~51 s after — so a larger corpus or a slower disk crosses it. Crossing it killed the worker, recorded a scan error and left the cache unadvanced, so the next refresh started cold and died at the same point, forever. The deadline is now a no-progress window. The worker posts a file counter as it walks the corpus (`UsageScanWorkerProgress`, rate-limited to one message a second), and `WorkerThreadRequestQueue` re-arms the active call's timer on each one via the new optional `isProgress`. Clients that do not pass it keep the plain wall-clock deadline. `MAX_CONSECUTIVE_DEATHS` and idle teardown are unchanged. * refactor(usage): report scan progress as a file count, not one call per file Claude's scanner walks batches, so a per-file callback made it loop just to bump a counter.
…reen and agent-history (step 7) (stablyai#21269) * test(mobile): record main's file-preview and markdown-disk-fallback replies Four of this branch's read sites had no malformed-reply coverage, so the reader change would have had nothing to move at them. `familyGoldens` matrixes only the first scenario of each family, and `files.preview-load`'s base is the grant-refresh chain while `session.tab-documents`' is the served markdown tab — which left `files.read` and `files.readPreview` on the worktree preview path, the artifact image read, and the markdown tab's on-disk fallback recorded on their success path only. This commit is the before picture, taken from main's own tree with no product edit in it. Three new families, five scenarios, ten goldens: - `files.preview-worktree-text` / `files.preview-worktree-image` — `files.read` and `files.readPreview` as the preview screen asks them for a worktree file. - `files.preview-artifact-image` — `files.readTerminalArtifactPreview`. - `session.markdown-disk-fallback` — the `files.read` leg a headless host's `renderer_unavailable` sends the markdown tab down. It carries a second scenario that serves `markdown.readTab`, because a matrix site needs a fulfilled reply recorded somewhere in its own family to replay as the `normal` partition. No existing scenario moved to a new family and no adapter changed, so every pre-existing golden keeps its `adapterSha256` and `scenarioSha256`. Recorded in a detached worktree at the manifest's pin (`4b876758d3`) with this manifest copied in; the control is that all 748 pre-existing goldens came back byte-identical to origin/main's, which `git diff c2962a7 -- mobile/rpc-foundation/goldens` confirms as empty. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * refactor(mobile): checked reply readers for files, dictation, host-screen and agent-history Thirty-five unchecked reply readers across seven files become checked zod readers, so a malformed host reply surfaces as one readable error at the operation boundary instead of a downstream TypeError, a rendered `undefined`, or a screen left ready over garbage. Deliberately a behaviour change on malformed replies only: every good reply decodes to the same value it did, which the `normal` partition of every matrix golden holds byte for byte. Nothing on the wire moves — no method, params, options, timeout or acceptance policy changes at any site. The inventory drops from 137 readers over 31 files to 102 over 24. What each domain checks, and what it deliberately does not: - files/preview — one schema for `files.read` and `files.readTerminalArtifact`, one for the two preview methods. `content` is required on the text pair because the markdown disk fallback publishes it into the tab with no guard; the image pair requires nothing, because normalizeImagePreviewResult guards all four members and the host's own "binary I cannot preview" and "not actually an image" arms are good replies the screen renders today. - files/tab-doc — stricter than the preview screen on the same two methods, because a tab publishes what it read into a typed ready document with no guard. `git.diff` reads as two variants, and an arm this build has not heard of takes the binary one rather than refusing the reply. - files/explorer — the directory listing is an array and a row needs the name and the directory flag the tree projection turns on; the legacy capped list needs its rows' paths and the truncation flag its note draws. - files/ownership — the two members that decide *where a write lands* are fatal on a wrong type rather than salvaged, because absence reads as `local` downstream and a salvage would send a mutation to the wrong host. `hostId`'s absent/null/string states stay distinct, and the SSH connection generation passes through at its own type because the mutation echoes it back to the host. - dictation — the setup the sheet renders is checked; the model rows need the `id` the sheet keys and sends back. The five sends whose reply body no call site reads keep an unknown payload, and so does `speech.dictation.finish`, whose transcript is read past a staleness guard that a reader throw would move the failure across. - host-screen — the repo catalog, the SSH labels and the host platform. The four writes read no reply body; `worktree.activate` stays opaque because the session route's second report site awaits it outside any catch. - agent-history — the capability gate and both scan containers. The session rows stay unknown on purpose: `agent` is a vocabulary that grows with every agent CLI Orca learns to scan and that this client echoes back on resume, so narrowing it would refuse a newer host's reply or drop the very sessions it added. Two shared readers were widened to take the strings the reply readers hand them — `getRepoExecutionHostId` and `buildRepoHostIdByRepoId` — because both already answer `local` for a host-id spelling they cannot parse, and closing that spelling in a reply schema would refuse a newer host's own catalog. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin the corpus and re-record the checked reply readers `baseline` moves to this branch's last fenced commit, which is what `--record` refuses without: main's fenced tree drifted past the session domain's pin when stablyai#21114 and the dependency bump landed, and the product edit in the commit before this one moves it again. Every body move is confined to a malformed partition of a family this branch touched. No `normal` partition moved, which is the byte-for-byte control on good replies, and no golden outside the seven files' families moved at all. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): stop the dictation reader requiring a mode main rendered without The setup sheet's `normal` partition refused after the reader landed, which is the success control saying the schema was wrong rather than the fixture: `dictationMode` was declared required because the one unguarded consumer pushes it into a `useState<'toggle' | 'hold'>` and cannot invent a value, but main rendered a sheet whose reply omitted it, and requiring a member no consumer crashes on is exactly the version claim Rule 1 of the remote-wire contract warns about. The member is salvaged now and keeps its open arm set, so an unknown mode still degrades to `toggle` rather than to one that matches no segment. The native-chat refresh spells that same `toggle` for an absent mode, which is the value its state already started at, and the route parity pins are refreshed for the one literal and the two callback bodies that moved. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin past the dictation fix and re-record Second repin of the branch: the fix to the setup reader is a fenced-tree change, so `--record` refuses until `baseline` names it. The speech family's `normal` partition is back to main's projection, which is what said the first reader was wrong. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): mutant evidence for the checked reply readers Three mutations applied by hand, run, and reverted, recorded beside the adapter family mutations in the same shape. They are kept in their own file because a reader mutation is not killed by a pilot scenario: a pilot serves a good reply, and a schema that has stopped checking a member reads a good reply exactly as before. What kills them is a matrix golden's malformed partition, the schema's unit pin, or a consumer pin, and each is named against its mutation. Two survived their first run, and both survivals were defects in the gates: - Loosening the file tab's `content` was invisible, because the pin dropped members only in pairs and each pair is refused by the sibling. The pin now drops exactly one member per iteration, and the preview text schema and the legacy file list got the same treatment. - Collapsing the hostId tri-state was invisible, because no golden serves an explicit null host — the local ownership scenario omits the member. The ownership test now captures all three states end to end, which is where a tri-state belongs. `repo-metadata-platform` is re-anchored where this branch moved the read it mutates: the hand-rolled `readHostPlatform` became the reply schema's own projection. The defect it injects is unchanged. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): record main's repo-icon and speech-vocabulary replies The closed enums this branch introduced had no fixture behind them. `provider`, `dictationMode` and `repoIcon` were carried by no scenario at all — the fulfilled repo-metadata golden records `repoIconsByName: []` — so the corpus could not have moved whatever arm set the schemas declared, which is how a reader can pin a vocabulary the host does not speak and still decode to a zero-move delta. Two scenarios, both appended to an existing family so `familyGoldens` adds no matrix golden, recorded from main's own tree at the pin with no product edit in it: - `settings-repo-metadata-icons` — all three `RepoIcon` arms, a github-sourced image with a label, an explicit `badgeColor`, and a mixed-host catalog so the ssh/settings/platform wave runs too. - `speech-setup-sheet-model-vocabulary` — `provider` on both arms, `status` on two, `dictationMode: "hold"`, and null and numeric `sizeBytes`/`progress`. Control: re-recording the whole corpus at the pin reproduces every committed golden body, including this branch's five earlier before-pictures; only `baseline` and the masked `lockfileSha256` move. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): stop the repo icon narrowing a member no consumer reads The image arm of `repoIcon` declared `source` as the four values `RepoIconImageSource` spells today (src/shared/repo-icon.ts:3). MobileRepoIcon reads `type`, `src`, `label`, `emoji` and `name`, and never `source`, so the only thing that enum could do was fail the union arm for a source a later host adds — dropping the whole icon and drawing the Folder default where main drew the image. That is the one arm set on this branch whose degrade was not already main's own behaviour for an unknown value. Dropping the declaration keeps the member: `looseObject` passes it through verbatim, so the decoded object is byte-identical to the one main published, which `settings-repo-metadata-icons` now records. The two type sites that hold an icon move to the decoded type. A host `RepoIcon` still satisfies the rendered union, so the worktree rows that carry one are unaffected. Every other closed enum on this branch was checked against the host's own shared type and left alone: speech `provider`/`status`/`dictationMode` (runtime-worktree-contracts.ts:83/85/86), `groupBy`/`sortBy` (persisted-ui-state-types.ts:41-42), `platform` (Node's own domain; the handler answers `process.platform`). For each, a salvaged member lands on the same branch main's unknown value did: `=== 'openai'` and `=== 'ready'` stay false, a missing `groupBy` and an unmapped one both answer null, and an unknown platform and a null one both label the host "This computer". Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin past the repo-icon fix and re-record Header-only: all 770 goldens move on `baseline` alone, including the two recorded from main's tree two commits back. The icon fix and the two new fixtures decode to the bytes main published. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): keep the repo-metadata readers total the way main's were readSshTargets and readHostPlatform answered [] and null for any payload at all. The checked schemas threw for a non-object, and because the label write runs first in the same sequence that throw also skipped the platform write, so a malformed reply left both decorative labels at their previous values instead of degrading. A .catch on each restores main's answer without giving up the row filter or the checked reader. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): forward the dictation mode instead of substituting a default The reader closed the mode to two arms and the native-chat refresh spelled `?? 'toggle'`, which is a good-reply change no golden covers: main left the state undefined for a reply that omits the mode, and undefined binds no press handler on the terminal input mic. Head gave that mic a working toggle. The member is forwarded as the string the host sent and the refresh is main's line again, so an absent or unknown mode leaves the mic exactly as inert as main's. The route-parity runtime-string pin is main's own sha again. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin past the review fixes and re-record The repo-metadata readers are total again, so both families' `result-absent` and `result-null` checkpoints decode to main's bytes instead of the caught throw, and the two delta rows they cost go away. The dictation mode forwards verbatim, which no recorded reply exercises differently. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): repin onto the merge and re-record Pins the corpus to the merge commit so main's ten create-terminal goldens and this branch's own are recorded from one tree. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * docs(mobile): correct three reader comments round 2 caught The ownership schema said an explicit null hostId means the host said local; the code refuses it, which is the whole reason mutant (c) exists. The AiVault sessions cast cited a golden whose fixture row carries three members, not the sixteen the cast claims — the full row is in aivault-history-screen-listed — and both the issues cast and the schema doc said the rows are rendered when the only read anywhere is issues.length. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * docs(mobile): correct stale file:line citations in the batch-A reply schemas Resolved every citation in the seven reply-schema modules and the SAFETY notes against the tree and diffed each target line against the claim beside it. Twelve were wrong, two of them past the end of a file that had shrunk, so they read as evidence while pointing at a closing brace. - file-explorer: the entries put is :157 not :160, the relativePath split is file-list-fallback.ts:48 not :42, and the truncated publish is :136 not :141. buildFileExplorerRows is no symbol at all; the sort-and-walk is flattenDirectoryCache (file-tree.ts:58). - file-ownership: the !summary throw is :68 not :64. - file-preview: the markdown disk fallback reads content at :60 not :65. - file-tab-doc: the html body render is :68 not :81 and the file arm is :73-75 not :86-88 (the file has 78 lines); the isImage guard is :58 not :66; the kind !== 'text' branch is :41 not :44; mobileDiffImageDataUri spans :22-33 not :20-31; the unguarded content.length is mobile-diff-lines.ts:35, the function that does it rather than :34. - agent-history: both members land at :133-135; :135 alone is issues. - dictation: the parenthetical read as citing the staleness guard when it named the rpcPayloadMember read. Both are cited now, :237 and :225. Comments only. No schema, type, or runtime behaviour changes. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * docs(mobile): name the unguarded activation report site that pins the opaque schema Handler audit over all 33 interpret sites in the four domains found one site that is structurally unguarded: use-mobile-session-startup.ts:170 reports the activation verdict from inside a fire-and-forget `void (async …)()` whose only `.catch` sits on the request, not on the chain. A throw there would be an unhandled rejection and would also skip the terminal fetch below it. Nothing throws there today, because `worktree.activate` reads hostScreenUnreadReplySchema, which is `z.unknown()`. That totality is load bearing rather than incidental, so the doc now names the line it protects and contrasts it with the first report site at :141, which is chained `.then(…).catch(…)` and would survive a throw. Comments only. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): pin that a bound descriptor's interpret survives being detached bindDeferredRpcOperation builds interpret as a shorthand method closing over the captured operation, never `this`, which is what lets eleven call sites pass it as a bare function reference. Nothing named that invariant. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * chore(mobile): repin the RPC recording baseline to the main merge Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): pin the closed reply enums to the host unions where tsc looks pullfrog: the PR body promised a Record<HostUnion, true> pin for every closed enum in this batch and the code had none. Adding them in the schema tests would have changed nothing: mobile/tsconfig.json excludes *.test.ts, so a coverage record there is never typechecked (a mutation that dropped a key stayed green). hostUnionArms(coverage) in zod-salvage spells the arm list as a Readonly<Record<U, true>> in the schema module itself, called with the host union as the explicit type argument: an arm the host adds is a missing property, one it drops is an excess property. Used for the speech provider and status (RuntimeSpeechModelSummary), the workspace groupBy and sortBy (PersistedUIState) and Node's platform list, which host-screen now imports from mobile-runtime-host-platform instead of duplicating. The repo icon branches satisfy Readonly<Record<RepoIcon['type'], z.ZodType>>. Three mutations (drop `manual`, add `bogus`, drop the image branch) each fail tsc. The tests iterate the exported lists; the platform mutant is re-anchored to the renamed constant. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

Stacked on #21102 — review that first; this diff is only the worker move.
What this changes
The Claude, Codex and OpenCode usage scans all run through
UsageProviderStoreLifecycle, and all three ran on the Electron main process. They now run on one lazily-spawned,unref'd worker thread shared by all three, following the OpenCode SQLite scanner precedent (#8864).The premise, corrected
The motivating claim was that the scan blocks the main-process event loop for long stretches. Measured, that is not what happens:
yieldToEventLoopis a baresetImmediate, andscanner.tsyields every 10 files. Holds.readJsonlLinesFromOffsetstreams throughcreateReadStream, so thefor awaitloop awaits real file I/O roughly every 64 KB. A single 200k-event / 62 MB rollout parses with a max event-loop delay of 6.1 ms, not one long block.attributeCodexUsageEventisasyncwith no I/O, so awaiting it only drains microtasks. Holds as stated, but the stream read supplies the real yields, so the loop is interleaved.The real cost is occupancy, not latency spikes: the scan holds the main-process event loop at ~95% utilization for its whole duration. Individual blocks stay small; there is simply no spare main-thread capacity while a scan runs.
Measured
Synthetic 4,000-rollout corpus, 25.8 MB cache, main-thread active time (the fraction of wall time the calling thread spent running JS, via
performance.eventLoopUtilization):Design notes
Stateless worker; the cache crosses both ways. At this corpus size the round-trip structured clone costs ~64 ms — against 2,147 ms saved on the cold path. A worker-owned cache would save only the send leg (~32 ms on an incremental scan, nothing on a cold one) in exchange for an invalidation protocol, a respawn re-seed path, and a second resident copy of a multi-MB array that could silently diverge from the persisted one. Not worth it at this size; see Follow-ups for where that flips.
All three providers, not just Codex. The seam is literally the same function shape for each, and all three scanner import graphs are electron-free. OpenCode's is the most blocking of the three — it reads SQLite synchronously.
Wired at the provider, not the lifecycle.
UsageProviderStoreLifecycleis untouched. Each provider'sscannow points at a typed route inusage-scan-worker-spawn.ts, which keeps each provider's exact record types and leavesplugin:providers (which have no worker entry) unaffected. The protocol is a discriminated union on provider id, so the worker entry narrowspreviouswith aswitchand needs no type assertions.Fails closed. A worker that cannot spawn, stops making progress, or crash-loops rejects. The store's existing
catchrecordslastScanErrorand keeps the previous projection. It never publishes an empty result and never falls back to scanning on the main thread.The deadline is a no-progress window, not a wall clock. The first revision gave each scan a flat 10-minute budget. That is not a backstop, it is a cap on corpus size: a cold scan of a real history is legitimately minutes — 637 s measured on a 30 GB corpus with 300 worktrees before #21130, ~51 s after — so a larger corpus or a slower disk crosses it, and crossing it killed the worker, recorded a scan error and left the cache unadvanced. The next refresh then started cold and died at the same point, with no way out. The worker now posts a file counter as it walks the corpus (
UsageScanWorkerProgress, one message a second at most, so a 21k-file corpus does not wake the main thread 21k times), andWorkerThreadRequestQueuere-arms the active call's timer on each one through a new optionalisProgress. The other two clients do not pass it and keep the plain wall-clock deadline.MAX_CONSECUTIVE_DEATHSand idle teardown are unchanged. Two client tests pin both halves: a scan that reports progress survives five deadline windows, and a worker that reports once and then goes silent is still killed.Object identity is lost on every refresh. Pre-PR, an incremental Codex scan handed unchanged files back as the same objects the caller already held (
reusedByPath.set(filePath, previous)). A structured clone cannot preserve that, so every entry now returns as a fresh deep copy and the entire previous cache becomes garbage per refresh — on the main process this change exists to protect. Measured: an incremental scan reuses 600/600 and 3,000/3,000 entries inline and 0/3,000 through the worker; the cache costs ~6.2 KB per rollout serialized and ~9.4 KB per rollout of live heap, so one 3,000-file refresh moves 28 MB and a 21k-rollout history projects to roughly 190 MB allocated and 190 MB made garbage per refresh. This is the same size argument as the round-trip clone in the Follow-ups: at this corpus size it is affordable, and at 21k rollouts it is the second reason worker-owned cache state starts to pay for itself.One request queue, not three.
OpenCodeSqliteWorkerClientandPortScanCommandClientalready carried near-identical FIFO/timeout/crash-cap machinery. Rather than add a third copy, that is extracted asWorkerThreadRequestQueue(and the packaged entry-path resolver asworker-thread-entry-path.ts) and all three now use it. Both existing clients' test suites pass unchanged; they shrink 327 → 202 and 300 → 157 lines.The oracle
usage-scan-worker-event-loop.test.tsmeasures event-loop active milliseconds on the calling thread, not wall-clock and not the active/wall fraction. One case runs the identical scan over one corpus both ways — first inline, then through the worker — and asserts the worker arm costs the caller under a fifth of the inline arm's JS time. Presence preconditions on both arms (600 files, 600 sessions, 36,000 events) keep an arm that silently scanned nothing from satisfying the comparison trivially.The fraction was the wrong quantity, and the first version of this test asserted two fixed thresholds in two separate cases while its header claimed to compute a self-calibrating ratio. It did not, and it flaked on ubuntu at
activeRatio 0.764against a> 0.8floor. CPU contention drags the inline arm's fraction down toward the worker's, because the loop parks waiting on a contended libuv pool; active milliseconds move the other way, since contention stretches the caller's JS time far more than the worker arm's fixed post-and-deserialize cost.Measured in a cpuset-pinned Linux container, twenty runs:
The old
> 0.8fails 20/20 there, idle included. The comparison passes 20/20, worst margin 10.9x against the 5x trip wire.Mutation checks, all confirmed failing:
expected 295.89 to be less than 66.01(ratio 0.90).expected [] to have a length of 600). The skip case is the one that matters: the comparison alone would pass it.codexUsageProvider.scanto the direct scanner →store-persistence.test.tsfails on itstoHaveBeenCalledWithwiring assertion.WorkerThreadRequestQueuealso gets a direct suite, since three subsystems now share it and each client test only sees what its own protocol exercises. It pins one-at-a-time FIFO dispatch, the deadline starting at dispatch rather than enqueue, the consecutive-death cap, and both points where that count clears. Eight mutations of the queue, all killed.For whoever squashes this
The base commit's own message (
510c6e4b80) carries the claim the oracle fix removed — "runs the same scan both ways and asserts the worker leg leaves the caller idle while the main-thread leg does not, so CI load moves both legs together (#18788)." That was not true when written: the test computed no ratio, and the flake it promised was impossible is the one that landed. It is true of the test now, but the reasoning is different, so the squash message should say the new thing rather than inherit the old sentence. History is not being rewritten to fix it. Suggested replacement paragraph:Packaging
usage-scan-worker-entryis a rollup input inelectron.vite.config.tsand is listed inWORKER_THREAD_ENTRY_NAMESinplain-node-entry-guard.ts, so the build fails if anything in its chunk graph reachesrequire('electron'). Verified beyond "the file exists": a fullelectron-vitebuild emitsout/main/usage-scan-worker-entry.js, and spawning that built file as a real worker returns correct scans for all three providers.resolveWorkerThreadEntryPathhandles the packagedresourcesPath/app.asar/out/mainlayout (pinned by test, matching the port-scan worker) and theundefined resourcesPathcase on a non-Electron host.Verification
npx tsc -p config/tsconfig.node.json --noEmit— cleannpx oxlint src/main config— cleancheck-changed-code-quality.mjs— passes, 0 new findings across 36 changed filesusage,codex-usage,claude-usage,opencode-usage,ports,ai-vaultand the entry guard — all passelectron-vitebuild — exit 0Follow-ups (not in this PR)
usage-cache-snapshot-writer.ts:50synchronouslyJSON.stringifys the whole cache on the main thread every scan. Measured on a real 13 MB Claude cache: 29 ms. Real, but an order of magnitude below what the scan used to cost — worth a ticket, not urgent.load()does areadFileSync+JSON.parseof the same multi-MB cache on the main thread at startup (23 ms on that 13 MB file).UsageOverviewPane.tsx:94-97fans the providers out withPromise.all, but they queue behind each other on the single worker, so a wedged Claude scan makes Codex wait out the full 10-minute timeout — ~30 minutes worst case for the last provider. Left as is: strictly better than pre-PR, which had no deadline at all and blocked the main thread instead. A per-provider lane or a shorter first-scan deadline is the fix if it ever bites.wslGated*calls fork the WSL transcript sidecar whenever the path is a\\wsl$\...UNC one, which anOPENCODE_DBorXDG_DATA_HOMEoverride can be — so the bundle can fork, which is easy to miss. It is not an orphan: the sidecar is reaped within 2s ofworker.terminate(), because tearing the thread down closes the IPC channel it owned and the sidecar entry exits ondisconnect. Verified with a faithful stub — alive while the worker lives (1 at +9s, 1 at +15s), 0 immediately afterterminate(); two worker lifecycles forked two sidecars and leaked neither; the pre-worker main-thread path reaps its sidecar the same way on host exit, so this is not a regression. The residual costs are thatterminate()itself reaps nothing (a future child that does not exit on channel close would be orphaned) and that the sidecar is now re-forked per worker lifecycle rather than pooled for the app's life. Recorded in a comment at the entry point.Not verified
path.join-based.