Skip to content

fix(codex): gate codex launches on state-DB backfill and pre-warm the session index (fixes #11828) - #11981

Closed
danshapiro wants to merge 45 commits into
stablyai:mainfrom
danshapiro:codex-backfill-prewarm
Closed

danshapiro wants to merge 45 commits into
stablyai:mainfrom
danshapiro:codex-backfill-prewarm

Conversation

@danshapiro

Copy link
Copy Markdown

Fixes #11828

Problem

For users with a large Codex session history (reporter: 4,829 rollout files / ~14 GB), every Codex pane deterministically failed at launch with Codex's misleading "local database appears to be damaged" error: Codex 0.146 rebuilds its state-DB index from scratch over the session history Orca populated into the managed CODEX_HOME, and codex-cli's internal startup wait is only ~30s. A pane's codex therefore dies, and since each retry only advances the index in 30s slices, it effectively never completes.

Solution

The fix comprises three cooperating parts:

1. State-DB prewarm

When a home's backfill_state is not complete, Orca supervises a headless codex that runs the index to completion. It also adopts/resumes a stale running lease left by a killed codex. This is hooked into the codex-session-migration scheduler.

2. State-first startup ordering

Before spawning any short-budget startup codex (the real-home hook trust-grant app-server, with a 10s budget), Orca performs a cheap read-only backfill_state check. If the index is incomplete, trust-grant is deferred using a new pending-index lane state instead of latching the lane unavailable.

Previously, that unavailable state disabled the scheduler, so the fix could never run in exactly the scenario it targets, and the killed trust-grant codex left a stale running lease. Trust-grant now re-runs after prewarm completes; genuine non-backfill failures retain today's unavailable semantics.

3. Main-process codex launch gate and indexing UI

Codex pane launches are held at the single main-process spawn choke point. This covers both renderer-initiated panes and main-initiated worktree-creation panes via a wait-for-go wrapper. While held, panes show an "Indexing Codex session history…" overlay, then auto-launch codex the moment the index completes.

The gate is fail-open by design: any error reading state launches codex normally, and every hold has a hard 15-minute ceiling. The backfill-error detector and toast remain as a fallback net. SSH/remote panes and Windows-host↔WSL homes are explicitly out of scope because the state DB is not reliably readable there; they retain today's behavior.

Verification

  • Full gates pass: lint, typecheck, and build; 40,210 tests pass. All branch-owned tests, including the new gate/hold/wrapper/prewarm/scheduler/detector suites, pass 100%. The handful of remaining local test failures were proven pre-existing at merge base e058429e1 (GPU startup flags, WSL pty routing, and hook transport budget—environment-specific on the reporter's WSL2 machine).
  • End-to-end verified on the reporter's actual machine (WSL2 Ubuntu 24.04) in a sandboxed HOME with a real 15 GB copy of the session history: trust-grant deferral was observed, prewarm ran the index to completion, trust-grant then succeeded, and a worktree-creation codex pane was held with the indexing overlay and auto-launched codex successfully once complete—the exact reporter flow that previously hard-failed.
  • Two independent cross-model reviews (plan and whole-branch delta) passed; final whole-branch verdict: "ready to merge."

Reviewer notes

  • Commit 5c638031b is a mechanical i18n catalog parity sync (es/ja/ko/zh, produced by the repo's own sync:localization-catalog) repairing a pre-existing parity failure that blocks the lint gate. Values are English fallbacks, not translations—drop it if main fixes parity separately.
  • The Windows wrapper variant is unit-tested but was not exercised end-to-end (work was done on Linux/WSL2); worst case, it fails open to today's behavior.
  • A per-pane hold status API (codexBackfill:status) currently has no consumer beyond the overlay wiring and is a candidate for removal.
  • Codex's 30s wait and "damaged database" wording are arguably an upstream codex-cli issue too, but Orca owns the first-run experience that makes the failure deterministic.
  • Companion issue [Bug]: Interrupted Codex state-DB index leaves managed CODEX_HOME wedged — every Codex pane fails after a 30s hang with nothing surfaced to the user #11830 (the interrupted-index failure mode) is related but out of scope.

Generated with Amplifier

OrcaWin and others added 30 commits July 29, 2026 20:25
…11271)

* fix(orchestration): preserve active workers across updates

* test(ssh): model absent legacy adoption

* test(orchestration): align compatibility contracts

* fix(windows): escape updater PowerShell booleans

* fix(windows): restore stock uninstall process check

* fix(orchestration): keep recovery off renderer startup barrier

* fix(orchestration): harden legacy recovery migration

* fix(orchestration): close recovery review gaps

* fix(orchestration): complete legacy worker cutover recovery

* fix(orchestration): preserve legacy workers across updates

---------

Co-authored-by: OrcaWin <[email protected]>
…blyai#11436)

* fix(new-workspace): stop UI flashing when typing ahead of search

Hold branch results while queries settle, show the spinner only on
initial load, use stable cmdk values, and guard selections against
stale rows. This prevents the highlight from jumping around when
typing faster than the debounced search settles.

* fix(new-workspace): keep dropdown visible while typing within settled qu

Hold the last search results while the user extends or trims the query,
only hiding them when the query diverges completely. This prevents the
dropdown from flashing empty between debounced keystrokes and removes the
guard that made provider rows unselectable during typing.

* fix(new-workspace): align held provider results with live typing

Cap prefix hold by length delta, hide GitHub/GitLab/Linear rows when the
field is cleared ahead of debounce, and re-sync the cmdk arm when search
settles so the highlight cannot lag the resolved selection.
…#11405)

* fix(windows): separate updater from orchestration migration

* fix(terminal): attest adopted reveal identity

---------

Co-authored-by: OrcaWin <[email protected]>
…ai#11521)

Match Run on field layout so short provider details like stablyai/orca
sit on the far right of the committed Project field instead of next to the name.
…idebar (stablyai#11530)

* fix(sidebar): stop background workspace creation from scrolling the sidebar

Creating a workspace in the background still spawns its terminals, and the
renderer treated "no presentation stated" as "point the user at this
terminal" -- revealing (scrolling to) the owning workspace.

Split adoption from surfacing with an explicit surfaceOwner flag: background
worktree creates and worker dispatch adopt their tabs silently, while
`orca terminal create` keeps its discoverability reveal.

* fix(sidebar): keep split-mode setup panes silent, tighten surfaceOwner

Review catch: with setupScriptLaunchMode split-vertical/horizontal the Setup
terminal goes through splitTerminal, whose reveal payload had no surfaceOwner,
so a background create still scrolled the sidebar in that configuration.

Also narrow surfaceOwner to `false` so "surface it" can only be expressed by
omitting the key, and fold the repeated conditional spreads into ownerSurfacing.
…i#11528)

* fix(relay): refuse silent fallback when pairing invite fails

When Orca Relay pairing fails, don't silently degrade to a LAN-only QR under the Relay label. Instead, surface structured failure information so the UI can clearly inform the user and offer recovery options.

* fix issues
… findings

Stage-2 validation (live codex 0.146.0 runs, openai/codex rust-v0.146.0
source, orca repo inspection): 8 assumptions verified, 6 falsified.
Plan updated accordingly:

- Prewarm now targets BOTH the system home and the managed home (A10:
  gate-true fresh panes run on the real ~/.codex, not the managed home)
- Respawn budget counts fast failures only; ~30s claim-blocked exits are
  expected (A2/A3: codex backfill lease election, 900s stale-lease window)
- Termination: stdin-EOF first, tree-kill on Windows, quit-stop wiring
  (A11: bare child.kill() orphans codex.exe behind .cmd wrappers)
- Toast text made honest for lanes without a prewarm (A10/AD-3)
- Detector scope documented: visible Orca-launched panes (A13)
- Task 7 E2E uses cp -a copies instead of cp -al hardlinks (A14: codex
  has a rollout compression/replace path)

Full evidence ledger: .the-usual-logs/codex-backfill-prewarm/load-bearing-ledger.md
… in prewarm plan

Fresh-eyes review (iteration 1) found three blocking defects in the plan's
verbatim code blocks:

1. Task 2 test/impl timing contradiction: tests used fake timers while the
   implementation's defaultDeps captured the native Date.now at module load,
   which vi.useFakeTimers() does not replace - making the respawn-budget
   tests unpassable either way. Fix: createDeps now injects call-time
   now()/sleep() wrappers that read the faked clock.

2. Fast-failure budget measured child lifetime at poll detection (quantized
   to 5s multiples), misclassifying genuine 5-10s crashes as expected
   claim-blocked exits and respawning until the 60-min deadline. Fix: record
   exitedAt inside the exit/error listeners and measure lifetime from the
   event itself; comment contradiction (30s vs 10s constant) reworded; new
   implementation note pins the deps.now()/deps.sleep()/exitedAt discipline.

3. Task 3 stop-propagation gate was vacuous (vi.waitFor on a negative
   assertion resolves before the chain settles) and Step 2's expected
   failure claimed a TS error vitest cannot produce. Fix: stopped-case test
   now uses the file's deferred-release pattern plus a settlement barrier
   (the scheduler's stopped-result rerun proves the first chain settled via
   .finally before asserting heal/prewarm were not called); Step 2's red
   expectation rewritten to match actual vitest/esbuild behavior.
…ations are satisfiable

Fresh-eyes review (iteration 2) found the plan's capstone verification gate
unexecutable: Task 7 Step 3's five observations were jointly unsatisfiable
under the home-lane model. On the real-home lane (the scheduler's eligibility
gate) fresh codex panes read the real ~/.codex - which Step 2 already proved
complete - so the pane failure/toast observation could never occur while the
prewarm observation could; on the managed lane the scheduler never runs.
Additionally, ORCA_USER_DATA_PATH is overwritten at startup
(configure-process.ts:182-185), so the step's sandbox never redirected
userData at all.

Redesign: use the repo's E2E isolation lane (ORCA_E2E_USER_DATA_DIR +
ORCA_E2E_HOME_DIR + matching HOME) so the 'real' ~/.codex is itself the
disposable sandbox seeded with the copied 15 GB session history and
credentials. The prewarm's system-home leg and every fresh codex pane then
target the same incomplete home, making all five observations achievable in
one run; the empty sandbox twin leg is an asserted not-needed no-op.
Observation checks now discriminate the prewarm child by exact CODEX_HOME
value (the rate-limits fetcher spawns an identical command line), and the
HALT rule names the likeliest sandbox failure (hook trust-grant lane going
'unavailable').
🤖 Generated with Amplifier

Co-Authored-By: Amplifier <[email protected]>
…n index

Step 1 smoke verification (temp home, 2026-07-31):
sleep 60 | CODEX_HOME=$SMOKE_HOME codex -s read-only -a untrusted app-server
created state_5.sqlite in the temp home within 15s and
'select status from backfill_state' printed: complete.
PREWARM_CODEX_ARGS keeps the '-s read-only -a untrusted app-server' variant.

killCodexAppServerProcessTree was already exported from
codex-app-server-session.ts, so no extraction was needed.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <[email protected]>
…eal (stablyai#11828)

Quit-path verification: before-quit (src/main/index.ts) sets isQuitting=true,
and the app.exit(0) relaunch path runs onBeforeRelaunch first, which also sets
isQuitting=true — the scheduler's shouldStop() is already covered on both
paths, so no extra stop call was needed.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <[email protected]>
🤖 Generated with Amplifier

Co-Authored-By: Amplifier <[email protected]>
oxlint reads eslint-disable-next-line against the literal next line; the
prettier-wrapped declaration left the regex two lines below the comment,
so the lint gate failed.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <[email protected]>
Pre-existing on main (e058429): en.json gained 26 mobile-pairing keys
without locale parity, failing verify:localization-catalog. Repaired with
the repo's own `pnpm run sync:localization-catalog` so the lint gate can
run; drop this commit if main fixes parity independently.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <[email protected]>
…stablyai#11828)

Six falsified assumptions planned around: prewarm not-tracked gate aligned
with the pending predicate (deadlock fix); gate fail-open max wait + grant
retry bypasses the pending re-check (no forever-parked pane or lane);
rate-limit fetcher skips while backfill pending (second doomed spawner /
lease thief); gate predicate excludes SSH (connectionId axis); pane-scoped
agent signal (split-pane false positive); gate clause moved into the
fresh-spawn arm (compound reattach paths). Recorded acceptable risks and
E2E criterion scope notes.
…ests and fetcher-skip snippet

- Task 5: replace vi.runOnlyPendingTimersAsync() (fires the 15-min fail-open
  timer, breaking four of six gate tests and making the re-poll test pass for
  the wrong reason) with vi.advanceTimersByTimeAsync(0); pin the timer
  discipline in a load-bearing comment.
- Task 2 Step 7: add required provider: 'codex' field to the rate-limit skip
  snippet so Step 8's pnpm typecheck gate can pass as written; reword the
  adjacent note to state the field is required by ProviderRateLimits.
…defects in prewarm plan

Fresh-eyes review (iteration 5) found four blocking executable-plan defects:

- Task 5 Step 5: the synchronous fail-open path of waitForCodexBackfillGate
  left codexBackfillGateDispose permanently non-null (the returned noop was
  stored after onClear ran), muting input-undeliverable recovery for the
  pane's lifetime. The integration clause now arms the dispose only while
  actually parked.
- Task 2 Step 3: the trust-grant deferral could rewrite a genuinely latched
  'unavailable' lane to 'pending-index', un-latching
  isRealHomeCodexHookLaneUsable() and bypassing the retry cooldown
  (including the permanent unsupported-binary latch). Added a
  currentLane !== 'unavailable' conjunct plus a regression-pin test.
- Task 5 Step 4: red/green expectations were unachievable - only one of the
  new tests can red-fail (expectation rewritten honestly); the reattach test
  now sets restoredLeafId + restoredPtyIdByLeafId + the store tab ptyId and
  asserts the sessionId reattach signature; the SSH test now wires the
  store-driven connectionId fixture.
- WSL third axis: the gate predicate now excludes WSL panes via
  projectRuntime (both remote-axis fields are null on WSL panes), with a new
  fail-open test; the rate-limit fetcher skip excludes WSL UNC homes
  (local prewarm cannot cure them; no sync sqlite/readdir over UNC), with a
  regression-pin test. Global Constraints and ledger A6 updated to the
  three-axis model.
…nding (stablyai#11828)

Extracts reconcileManagedHookDefinition into
codex-managed-hook-slot-reconciliation.ts verbatim: the deferral pushed
codex-real-home-hook-install.ts past the 300-code-line lint ceiling.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <[email protected]>
danshapiro and others added 15 commits August 1, 2026 01:16
…elivery (stablyai#11828)

Load-bearing validation (run 3) falsified five plan assumptions:
- raw deferred pty writes are lossy/garbled (live-pty experiment) -> delivery
  now rides a release-sentinel gate wrapper mirroring setup-agent-sequencing
- ensure/daemon adoption can resolve spawns without creating a pty -> hold
  begins only for created dispositions
- per-registration hold registry strands holds on window recreate -> module
  scope with broadcast rebind
- launchAiVaultSessionInNewTab can omit launchAgent -> unconditional queue fix
- web-attached serve panes hold without an overlay -> documented residual

Also: UNC WSL homes fail open (AD-A10), WAL-contention and pre-DB startup
window validated with tests added, daemon-provider assertion added to the E2E.
…fects in prewarm plan (stablyai#11828)

- Task 1/2: gate-wrapper shell flavor now follows the PANE's shell, never
  process.platform alone - new resolveCodexBackfillGateShellPlatform helper
  (with a deterministic truth-table test) picks posix for win32-host WSL
  panes and the integration snippet passes toShellViewPath: toLinuxPath so
  the distro bash can poll the sentinel through /mnt (hooks.ts:493-495
  precedent); adaptation note rewritten to match the snippet
- Task 5: test locator no longer greps for identifiers that only match the
  deleted spawn-gate test file - it now names pty-connection.test.ts's
  describe('codex backfill spawn gate (stablyai#11828)') block (~:23614) with a
  content-based grep, spells out which of its 6 tests to delete vs keep,
  and Steps 3/5 run concrete file paths instead of placeholders
…ller-arm tests (stablyai#11828)

The plan's Task 3 test snippets passed leafId literals ('leaf-wt', 'l')
that fail isTerminalLeafId's strict UUID check, so the controller path
never minted a paneKey: the worktree-hold test could never pass, the
SSH passthrough pin passed vacuously, and Step 3's guidance misdirected
implementers toward a phantom pty.ts placement bug.

- Use real UUID leafId literals in both concrete spawn fixtures; keep
  valid tabIds (tab-wt / tab-remote per the existing SSH fixture).
- SSH passthrough test now documents that paneKey minting ignores
  connectionId, so exclusion is attributable to the connectionId arm
  alone (non-vacuous).
- Post-snippet note adds two hard requirements: UUID leafId + valid
  tabId on every spawn, and widening the ~:3102 harness's local
  RuntimeSpawnController type (that test passes no tabId/leafId).
- Step 3 failure triage now checks for a missing paneKey (test bug)
  before touching pty.ts placement.
…il-open structural (stablyai#11828)

The ~40-line gate integration block was duplicated near-verbatim at both
provider.spawn dispatch paths in pty.ts (controller dispatch and the
renderer pty:spawn handler), differing only in the env object used for
the lane lookup. Neither copy was try/caught, so a throw from
resolveCodexBackfillGateHome or buildCodexBackfillGateWrapper would
reject the spawn and brick the pane.

- Extract one module-scope maybeGateCodexSpawnOnBackfill() beside the
  existing gate helpers; the whole body is try/caught so ANY gate error
  leaves the spawn options untouched and the launch proceeds ungated
  (fail-open now structural, not incidental). Both call sites are thin
  calls; hold-begin guards (isReattach !== true, ensure-arm
  disposition === 'created') stay at their sites unchanged.
- Correct stale comments on the retained global codexBackfill:status /
  onStatusChanged surface (preload, api-types, web stub, prewarm
  broadcast in main/index.ts): main-side per-pane hold broadcasts now
  drive pane gating/overlay; the global surface is retained for
  backward-compat pending a follow-up removal review. Comments only.
- Test hygiene: rmSync the mkdtemp'd home (and its 100 session files)
  in a try/finally in codex-backfill-spawn-hold.test.ts.

Verified: pty.test.ts 408/408 (unmodified), spawn-hold test 20/20,
pnpm typecheck exit 0, pnpm lint exit 0.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <[email protected]>
… non-bash pane shells parse it (stablyai#11828)

The posix gate wrapper was a bare bash poll loop typed into the pane's own
interactive shell. On fish/nushell (both supported by
shell-process-detection.ts) that line is a parse error, so neither the
sentinel poll nor the eval of ORCA_BACKFILL_GATED_COMMAND ever ran: codex
never launched and both fail-open ceilings (main's 15-min sentinel touch and
the wrapper's 20-min deadline) were structurally dead — a fail-closed
regression on the gated launch path. On dash/POSIX sh it degraded to a
silent gate no-op via the unset SECONDS arithmetic.

Wrap the unchanged script as a single quoted `bash -lc '<script>'` command
word — the buildPosixSetupCommand precedent in setup-agent-sequencing, which
ships on the identical interactive-shell delivery path — so every supported
shell parses the outer line identically and the bash-isms (including the
fail-open eval and the SECONDS deadline) only ever execute inside bash. The
quotePosixArg helper is mirrored locally to avoid an import cycle with
setup-agent-sequencing, which consumes this module's env names.

Tests: pin the bash -lc single-quoted-word envelope in the wrapper unit
test (existing substring assertions unchanged), and add a pty spawn-hold
test that launches a gated codex pane with SHELL=/usr/bin/fish and asserts
the line typed into the shell is the quoted bash -lc envelope carrying the
eval, never the withheld codex command.

Raised by fresh-eyes review iteration 1 (major, blocking).
@greptile-apps

greptile-apps Bot commented Aug 1, 2026

Copy link
Copy Markdown

Too many files changed for review. (240 files found, 100 file limit)

Bypass the limit by tagging @greptile-apps to review.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 384ffa42-266d-4db8-a6f4-b9ab89c933bc

📥 Commits

Reviewing files that changed from the base of the PR and between 16c5526 and 08302d8.

📒 Files selected for processing (240)
  • config/reliability-gates.jsonc
  • config/scripts/orchestration-skill-guidance.test.mjs
  • docs/plans/2026-07-31-codex-backfill-prewarm.md
  • docs/plans/2026-08-01-codex-backfill-prewarm.md
  • docs/reference/plans/2026-07-28-orchestration-seamless-update-migration.md
  • native/windows-cli-launcher/OrcaCliLauncher.cs
  • package.json
  • renderer-worktree-freeze-incident-2026-07-29.md
  • skill-guides/orca-cli.md
  • skill-guides/orchestration.md
  • src/cli/bundled-skill-guides.ts
  • src/cli/handlers/orchestration-check-identity.test.ts
  • src/cli/handlers/orchestration-legacy-read-only.test.ts
  • src/cli/handlers/orchestration-migration.test.ts
  • src/cli/handlers/orchestration-run-cli.test.ts
  • src/cli/handlers/orchestration-timeout-cli.test.ts
  • src/cli/handlers/orchestration-timeout.test.ts
  • src/cli/handlers/orchestration-windows-ask-cli.test.ts
  • src/cli/handlers/orchestration.test.ts
  • src/cli/handlers/orchestration.ts
  • src/cli/handlers/worktree.ts
  • src/cli/index.test.ts
  • src/cli/runtime-client.test.ts
  • src/cli/runtime/client.ts
  • src/cli/runtime/orchestration-compatibility-envelope.ts
  • src/cli/runtime/runtime-request-timeout.ts
  • src/cli/runtime/transport.ts
  • src/cli/runtime/types.test.ts
  • src/cli/runtime/types.ts
  • src/cli/specs/orchestration.ts
  • src/main/agent-hooks/server-authority-evidence.test.ts
  • src/main/agent-hooks/server.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/cli/windows-launcher-asset.test.ts
  • src/main/codex/codex-backfill-spawn-hold.test.ts
  • src/main/codex/codex-backfill-spawn-hold.ts
  • src/main/codex/codex-managed-hook-slot-reconciliation.ts
  • src/main/codex/codex-real-home-hook-install.test.ts
  • src/main/codex/codex-real-home-hook-install.ts
  • src/main/codex/codex-session-migration-scheduler.test.ts
  • src/main/codex/codex-session-migration-scheduler.ts
  • src/main/codex/codex-state-db-prewarm.test.ts
  • src/main/codex/codex-state-db-prewarm.ts
  • src/main/codex/codex-state-db.test.ts
  • src/main/codex/codex-state-db.ts
  • src/main/daemon/daemon-history-handoff.ts
  • src/main/daemon/daemon-pty-router-history-handoff.test.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/headless-emulator.ts
  • src/main/daemon/terminal-host-wsl-context.test.ts
  • src/main/daemon/wsl-session-context.ts
  • src/main/index.ts
  • src/main/ipc/codex-backfill-status.test.ts
  • src/main/ipc/codex-backfill-status.ts
  • src/main/ipc/mobile.test.ts
  • src/main/ipc/mobile.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/register-core-handlers.test.ts
  • src/main/ipc/register-core-handlers.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/pty/wsl-orca-env.test.ts
  • src/main/pty/wsl-orca-env.ts
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/runtime/device-registry.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration-compatibility-authority.test.ts
  • src/main/runtime/orchestration/db.test.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/formatter.test.ts
  • src/main/runtime/orchestration/formatter.ts
  • src/main/runtime/orchestration/orchestration-legacy-coordinator-authority-db.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-question-migration-db.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-storage-db.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-storage-test-fixture.ts
  • src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.ts
  • src/main/runtime/orchestration/orchestration-schema-version-skew.ts
  • src/main/runtime/orchestration/orchestration-version-skew-migration.test.ts
  • src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts
  • src/main/runtime/orchestration/types.ts
  • src/main/runtime/relay/relay-revoke-outbox.test.ts
  • src/main/runtime/relay/relay-revoke-outbox.ts
  • src/main/runtime/rpc/core.ts
  • src/main/runtime/rpc/dispatcher-error-response.ts
  • src/main/runtime/rpc/dispatcher-feature-interactions.test.ts
  • src/main/runtime/rpc/dispatcher-stream-options.ts
  • src/main/runtime/rpc/dispatcher.ts
  • src/main/runtime/rpc/errors.ts
  • src/main/runtime/rpc/methods/orchestration-federation-control-mail.test.ts
  • src/main/runtime/rpc/methods/orchestration-federation.test.ts
  • src/main/runtime/rpc/methods/orchestration-federation.ts
  • src/main/runtime/rpc/methods/orchestration-gates.ts
  • src/main/runtime/rpc/methods/orchestration-runs.ts
  • src/main/runtime/rpc/methods/orchestration-worker-topology.ts
  • src/main/runtime/rpc/methods/orchestration-workers-new-worktree.test.ts
  • src/main/runtime/rpc/methods/orchestration-workers.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts
  • src/main/runtime/rpc/methods/orchestration.ts
  • src/main/runtime/rpc/orchestration-legacy-authority.ts
  • src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher-test-fixture.ts
  • src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher.test.ts
  • src/main/runtime/rpc/orchestration-legacy-compatibility.ts
  • src/main/runtime/rpc/orchestration-legacy-coordinator-authority.ts
  • src/main/runtime/rpc/orchestration-legacy-coordinator-race.test.ts
  • src/main/runtime/rpc/orchestration-legacy-lifecycle.ts
  • src/main/runtime/rpc/orchestration-legacy-mail.ts
  • src/main/runtime/rpc/orchestration-legacy-operation.ts
  • src/main/runtime/rpc/orchestration-legacy-process-identity.ts
  • src/main/runtime/rpc/orchestration-legacy-question-takeover.test.ts
  • src/main/runtime/rpc/orchestration-legacy-question.ts
  • src/main/runtime/rpc/orchestration-legacy-takeover-dispatcher.test.ts
  • src/main/runtime/rpc/orchestration-mutation-executor.ts
  • src/main/runtime/rpc/orchestration-mutation-ledger.test.ts
  • src/main/runtime/rpc/runtime-feature-interaction.ts
  • src/main/runtime/runtime-rpc.test.ts
  • src/main/runtime/runtime-rpc.ts
  • src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/main/ssh/ssh-remote-cli-host-passthrough.test.ts
  • src/main/ssh/ssh-remote-cli-host-passthrough.ts
  • src/main/ssh/ssh-remote-cli-in-process-result.ts
  • src/main/ssh/ssh-remote-orca-cli.test.ts
  • src/main/ssh/ssh-remote-orca-cli.ts
  • src/main/ssh/ssh-remote-orchestration-ask-output.ts
  • src/main/ssh/ssh-remote-orchestration-check-output.ts
  • src/main/ssh/ssh-remote-orchestration-compatibility.test.ts
  • src/main/ssh/ssh-remote-orchestration-post-output.ts
  • src/main/startup/desktop-startup-ordering.test.ts
  • src/main/startup/legacy-worker-renderer-recovery.test.ts
  • src/main/startup/legacy-worker-renderer-recovery.ts
  • src/main/window/attach-main-window-services.test.ts
  • src/main/window/attach-main-window-services.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/relay/relay.ts
  • src/relay/remote-cli-env.test.ts
  • src/relay/remote-cli-env.ts
  • src/renderer/src/App.tsx
  • src/renderer/src/app-startup-routing.test.ts
  • src/renderer/src/assets/mobile-page.css
  • src/renderer/src/components/mobile/MobileHero.test.tsx
  • src/renderer/src/components/mobile/MobileHero.tsx
  • src/renderer/src/components/mobile/MobileHeroPairingStep.tsx
  • src/renderer/src/components/mobile/MobilePage.test.tsx
  • src/renderer/src/components/mobile/MobilePage.tsx
  • src/renderer/src/components/mobile/MobilePageContent.tsx
  • src/renderer/src/components/mobile/mobile-relay-mint-failure-notice.tsx
  • src/renderer/src/components/mobile/use-mobile-pairing-generation.ts
  • src/renderer/src/components/mobile/use-mobile-pairing-qr-invalidation.ts
  • src/renderer/src/components/new-workspace/ProjectCombobox.tsx
  • src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx
  • src/renderer/src/components/new-workspace/smart-workspace-command-value.test.ts
  • src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts
  • src/renderer/src/components/settings/MobilePairingConnectionOptions.test.tsx
  • src/renderer/src/components/settings/MobilePairingConnectionOptions.tsx
  • src/renderer/src/components/settings/MobilePairingQrSection.test.tsx
  • src/renderer/src/components/settings/MobilePairingQrSection.tsx
  • src/renderer/src/components/settings/MobilePairingSetupSection.test.tsx
  • src/renderer/src/components/settings/MobilePairingSetupSection.tsx
  • src/renderer/src/components/settings/MobilePane.test.tsx
  • src/renderer/src/components/settings/MobilePane.tsx
  • src/renderer/src/components/sidebar/Sidebar.test.tsx
  • src/renderer/src/components/sidebar/index.tsx
  • src/renderer/src/components/sidebar/single-flight-coalescer.test.ts
  • src/renderer/src/components/sidebar/single-flight-coalescer.ts
  • src/renderer/src/components/terminal-pane/CodexIndexingOverlay.test.tsx
  • src/renderer/src/components/terminal-pane/CodexIndexingOverlay.tsx
  • src/renderer/src/components/terminal-pane/TerminalErrorToast.test.ts
  • src/renderer/src/components/terminal-pane/TerminalErrorToast.tsx
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-pane-hold.test.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-pane-hold.ts
  • src/renderer/src/components/terminal-pane/pty-connection-types.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-linkifier-click-priming.test.ts
  • src/renderer/src/components/terminal-pane/terminal-linkifier-click-priming.ts
  • src/renderer/src/components/terminal-pane/terminal-url-link-click.test.ts
  • src/renderer/src/components/terminal-pane/terminal-url-link-hit-testing.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/constants/terminal.ts
  • src/renderer/src/hooks/ipc-events-test-harness.ts
  • src/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.ts
  • src/renderer/src/hooks/legacy-worker-terminal-recovery-event.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/lib/launch-ai-vault-session.test.ts
  • src/renderer/src/lib/launch-ai-vault-session.ts
  • src/renderer/src/lib/pane-manager/pane-manager-types.ts
  • src/renderer/src/lib/pane-manager/pane-manager.ts
  • src/renderer/src/lib/pane-manager/pane-split-close.ts
  • src/renderer/src/lib/resume-sleeping-agent-session-legacy-worker.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.ts
  • src/renderer/src/lib/terminal-reveal-identity.test.ts
  • src/renderer/src/lib/terminal-reveal-identity.ts
  • src/renderer/src/store/slices/agent-pane-authority.test.ts
  • src/renderer/src/store/slices/agent-status-provider-session.test.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/agent-session-resume.ts
  • src/shared/codex-backfill-gate-wrapper.test.ts
  • src/shared/codex-backfill-gate-wrapper.ts
  • src/shared/codex-backfill-status-types.ts
  • src/shared/crash-reporting.test.ts
  • src/shared/crash-reporting.ts
  • src/shared/mobile-relay-mint-failure.test.ts
  • src/shared/mobile-relay-mint-failure.ts
  • src/shared/new-workspace/smart-workspace-command-value.ts
  • src/shared/new-workspace/smart-workspace-source-results.ts
  • src/shared/orchestration-check-output.test.ts
  • src/shared/orchestration-check-output.ts
  • src/shared/orchestration-compatibility-evidence.test.ts
  • src/shared/orchestration-compatibility-evidence.ts
  • src/shared/orchestration-message-wait-timeout.ts
  • src/shared/remote-runtime-client.ts
  • src/shared/runtime-rpc-envelope.ts
  • src/shared/runtime-types.ts
  • src/shared/setup-agent-sequencing.test.ts
  • src/shared/setup-agent-sequencing.ts
  • src/shared/terminal-reveal-identity.ts
  • src/shared/workspace-session-sleeping-agents.ts
  • tests/e2e/global-setup.ts
  • tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts
  • tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts
  • tests/e2e/orchestration-worker-terminal-visibility.spec.ts
💤 Files with no reviewable changes (17)
  • src/renderer/src/components/mobile/MobileHero.test.tsx
  • src/renderer/src/store/slices/agent-status-provider-session.test.ts
  • src/renderer/src/components/mobile/MobileHero.tsx
  • src/renderer/src/components/sidebar/Sidebar.test.tsx
  • src/renderer/src/components/mobile/MobileHeroPairingStep.tsx
  • src/renderer/src/components/settings/MobilePairingSetupSection.tsx
  • src/main/ssh/ssh-remote-orca-cli.test.ts
  • src/main/startup/desktop-startup-ordering.test.ts
  • src/main/runtime/runtime-rpc.test.ts
  • src/renderer/src/components/new-workspace/smart-workspace-command-value.test.ts
  • src/renderer/src/components/settings/MobilePane.test.tsx
  • src/renderer/src/app-startup-routing.test.ts
  • src/renderer/src/lib/pane-manager/pane-manager-types.ts
  • src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts
  • src/shared/runtime-types.ts
  • src/renderer/src/App.tsx
  • src/renderer/src/components/mobile/MobilePageContent.tsx

📝 Walkthrough

Walkthrough

The change set adds legacy orchestration adoption, authority attestation, takeover fencing, worker-terminal recovery, and retained terminal history handling. It adds Codex session-index detection, prewarming, main-process spawn holds, IPC status reporting, renderer overlays, and fail-open platform handling. It updates runtime, preload, relay, SSH, WSL, mobile pairing, workspace source, localization, and persistence behavior. It also updates tests, reliability gates, implementation plans, incident documentation, CLI behavior, and the package version.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, solution, verification, and risks, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add all required template sections, including a screenshot statement, explicit cross-platform AI review findings, security audit, and platform-specific notes.
Out of Scope Changes check ⚠️ Warning The pull request includes unrelated orchestration migration, Jira and mobile pairing removal, relay, updater, SSH, and broad runtime API changes beyond [#11828]. Remove unrelated changes or link and document the additional objectives, keeping this pull request focused on Codex state-DB backfill and launch gating.
Docstring Coverage ⚠️ Warning Docstring coverage is 25.58% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the Codex launch gating and state-DB prewarming changes addressed by the pull request.
Linked Issues check ✅ Passed For [#11828], the changes prewarm incomplete indexes, defer launches during indexing, show progress, fail open, and preserve fallback handling for the reported Codex failure.
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch codex-backfill-prewarm

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 13

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main/runtime/orchestration/db.ts (2)

5693-5700: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Restore completed_at on the dispatch failure update.

This update sets status to failed or circuit_broken but leaves completed_at NULL. Every other terminal path in this file records it: failWorkerStart (Line 4034), reconcileMissingWorkerTerminal (Line 4228), settleWorkerStop (Line 5141), and settleWorkerReportInTransaction (Line 5614).

The NULL value is also read as an open-ended lifetime. backfillLegacyQuestionThreads bounds legacy question inference with AND (completed_at IS NULL OR completed_at >= ?) (Line 998). A dispatch failed through failDispatch therefore stays a candidate for every later legacy question, which can attach a question to the wrong dispatch.

🐛 Proposed fix to record the completion timestamp
       `UPDATE dispatch_contexts
          SET status = ?, failure_count = ?, last_failure = ?,
+             completed_at = COALESCE(completed_at, datetime('now')),
              capability_revoked_at = COALESCE(capability_revoked_at, datetime('now'))
          WHERE id = ?`

1248-1284: 🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Bound or prune mutation_receipts after completion.

Completed mutation receipts are never deleted; completeMutationReceipt only marks the row completed, and resetAll retains the ledger. Add a retention/pruning strategy or restore a bounded capacity so long-running sessions cannot accumulate permanent rows.

🟡 Minor comments (16)
src/main/runtime/rpc/orchestration-legacy-operation.ts-178-181 (1)

178-181: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Case-sensitive failure detection can silently misclassify failed legacy workers as succeeded.

inferLegacyWorkerOutcome only recognizes an exact 'Failed' or a 'Failed:' prefix. Any other casing or phrasing ('failed', 'FAILED: timeout', 'Task failed') falls through to 'succeeded'. Since this function is the sole outcome source when a legacy worker_done message omits --outcome, a failed legacy worker can get recorded as succeeded in orchestration state.

♻️ Proposed broader match
 export function inferLegacyWorkerOutcome(subject: string): 'succeeded' | 'failed' {
   const normalized = subject.trim()
-  return normalized === 'Failed' || normalized.startsWith('Failed:') ? 'failed' : 'succeeded'
+  return /^failed\b/i.test(normalized) ? 'failed' : 'succeeded'
 }
docs/plans/2026-08-01-codex-backfill-prewarm.md-146-148 (1)

146-148: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Specify the fenced-code language.

Line 146 starts a shell-code fence without a language. Add sh to satisfy markdownlint MD040.

Source: Linters/SAST tools

src/cli/bundled-skill-guides.ts-12-12 (1)

12-12: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Synchronize the bundled orca-cli guide.

ORCA_CLI_MARKDOWN still says that --agent reveals the new worktree. skill-guides/orca-cli.md Lines 150-151 now state that --agent alone leaves it in the background. Update the embedded paragraph and its parity test so bundled guidance gives the same launch behavior.

src/main/agent-hooks/server.test.ts-6389-6401 (1)

6389-6401: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Wrap the restored server in try/finally.

The assertion at lines 6391-6398 can throw. If it throws, restored.stop() at line 6401 never runs. The HTTP listener and its timers then leak into the remaining tests of this file. The final block at lines 6403-6416 already uses try/finally; apply the same pattern here.

🧹 Proposed cleanup
     const restored = new AgentHookServer()
     await restored.start({ env: 'production', userDataPath })
-    expect(
-      restored.attestCompatibilityAuthority({
-        paneKey: PANE,
-        launchTokenHash,
-        connectionId: 'ssh-target',
-        terminalProvenance: 'restored'
-      })
-    ).toEqual({ paneKey: PANE, source: 'hydrated_commitment' })
-    restored.retirePaneAuthority(PANE)
-    restored.flushStatusPersistSync()
-    restored.stop()
+    try {
+      expect(
+        restored.attestCompatibilityAuthority({
+          paneKey: PANE,
+          launchTokenHash,
+          connectionId: 'ssh-target',
+          terminalProvenance: 'restored'
+        })
+      ).toEqual({ paneKey: PANE, source: 'hydrated_commitment' })
+      restored.retirePaneAuthority(PANE)
+      restored.flushStatusPersistSync()
+    } finally {
+      restored.stop()
+    }
src/renderer/src/components/terminal-pane/codex-backfill-error-detector.ts-31-35 (1)

31-35: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Match before truncating the buffer.

Line 32 truncates normalized to the last DETECTOR_BUFFER_MAX_CHARS characters, and Line 33 searches only that tail. If a single chunk is larger than 4096 characters and carries the signature before its last 4096 characters, the detector drops the match. Terminal chunks can exceed that size during replay or a redraw burst. Search normalized first, then keep the tail for the next chunk.

🐛 Proposed fix
       const normalized = (tail + chunk).replace(ANSI_ESCAPE_PATTERN, '').replace(/\r/g, '')
-      tail = normalized.slice(-DETECTOR_BUFFER_MAX_CHARS)
-      if (!tail.includes(CODEX_BACKFILL_TIMEOUT_SIGNATURE)) {
+      const matched = normalized.includes(CODEX_BACKFILL_TIMEOUT_SIGNATURE)
+      tail = normalized.slice(-DETECTOR_BUFFER_MAX_CHARS)
+      if (!matched) {
         return null
       }
src/renderer/src/components/terminal-pane/codex-backfill-pane-hold.ts-22-34 (1)

22-34: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Ignore the initial pull after a push arrives.

paneHoldStatus resolves asynchronously. If main broadcasts phase: 'launched' before that promise settles, the push clears the overlay first, and the stale pulled indexing snapshot then restores it. No further push follows, because main drops the hold after release, so the overlay stays until the pane relaunches. Track whether a push was delivered and skip the pull result in that case.

🐛 Proposed fix
   let disposed = false
+  let sawPush = false
   void api
     .paneHoldStatus(paneKey)
     .then((state) => {
-      if (!disposed && state && state.paneKey === paneKey) {
+      if (!disposed && !sawPush && state && state.paneKey === paneKey) {
         onState(toIndexingState(state))
       }
     })
     .catch(() => {})
   const unsubscribe = api.onPaneHoldChanged((state) => {
     if (!disposed && state.paneKey === paneKey) {
+      sawPush = true
       onState(toIndexingState(state))
     }
   })
src/renderer/src/components/terminal-pane/pty-connection.ts-3553-3553 (1)

3553-3553: 🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Cache the Codex-launch check before the backfill observer.

dataCallback runs on every incoming chunk, but resolveExpectedLaunchTuiAgent() reads useAppStore.getState() and scans tabsByWorktree[...] on each call even though the expected launch agent is set from the stable spawn/startup context. Resolve isExpectedCodexLaunch once, disable the detector for non-Codex connections, and adjust the invariant comment/synchronization if hidden bytes can reach this path.

Also address: 7313-7322

src/main/daemon/wsl-session-context.ts-44-45 (1)

44-45: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Check that getDefaultWslDistro resolves the actual wsl.exe default distro.

listWslDistros() uses wsl.exe --list --quiet, but the quiet list output does not include the default-distro marker. This fallback can bind when no distro was configured or when the first configured distro is not the default. Use the default configured by wsl.exe --set-default/registry semantics instead of relying on list order.

src/renderer/src/components/terminal-pane/TerminalPane.tsx-591-606 (1)

591-606: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clear the Codex indexing entry when a pane closes.

codexIndexingStatesByPaneId is keyed by numeric paneId, and only the indexing callback removes entries. onPaneClosed in use-terminal-pane-lifecycle.ts clears the sibling map through onPtyRecoveryStateRef?.current?.(paneId, null) at line 1188, but it never calls onCodexIndexingStateRef. A pane that closes while indexing is pending leaves its entry behind.

Pane IDs come from PaneManager, and the manager is recreated inside the lifecycle effect keyed on [tabId, cwd] while this component stays mounted. A new manager can therefore reissue an ID that a retained entry still holds, and the overlay renders on an unrelated pane. Add the same null call for Codex indexing state next to the existing recovery-state cleanup.

🐛 Proposed cleanup in `src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts`
       onPaneClosed: (paneId, closedPane) => {
         onPtyRecoveryStateRef?.current?.(paneId, null)
+        onCodexIndexingStateRef?.current?.(paneId, null)
src/main/runtime/orca-runtime.ts-3900-3916 (1)

3900-3916: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Reject waiters when the rolled-back surface handle is removed.

invalidateLeafHandle rejects pending waiters with terminal_handle_stale. This rollback path deletes the same maps without that step. Waiters registered through waitForTerminal on the removed handle can no longer be satisfied, so they block until their timeout, up to TUI_IDLE_DEFAULT_TIMEOUT_MS (5 minutes).

🐛 Proposed fix
       if (
         surfaceHandle &&
         handleRecord?.tabId === candidate.tabId &&
         handleRecord.leafId === candidate.leafId &&
         handleRecord.ptyId === candidate.ptyId
       ) {
         this.handles.delete(surfaceHandle)
+        this.rejectWaitersForHandle(surfaceHandle, 'terminal_handle_stale')
       }
src/main/runtime/rpc/dispatcher.ts-75-129 (1)

75-129: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Route emulator.* diagnostics through both dispatch paths.

dispatch() logs emulator RPC requests, but non-streaming methods handled by dispatchStreaming() can also be emulator.* calls. Add emulatorProbe before the non-streaming handler and emulatorProbeError around its catch block, or extract the shared invocation wrapper.

src/renderer/src/i18n/locales/ja.json-9343-9343 (1)

9343-9343: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use the existing technical term for cleanup.

"cleanup": "掃除" conflicts with the adjacent クリーンアップ strings and reads as household cleaning. Use クリーンアップ or the catalog-approved technical term.

src/renderer/src/i18n/locales/ja.json-603-612 (1)

603-612: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use provider-neutral review-link wording in both Linear strings.

The shared Linear skill copy uses GitHub-specific PR or pull request terminology. Replace it with review link or pull/merge request.

As per coding guidelines, source-control and review changes must support GitLab and other supported providers.

  • src/renderer/src/i18n/locales/ja.json#L603-L612: Update attachPr, attachPrSummary, and attachPrPrompt.
  • src/renderer/src/i18n/locales/ja.json#L9498-L9498: Update howToUseDescription.

Source: Coding guidelines

src/renderer/src/i18n/locales/zh.json-3781-3781 (1)

3781-3781: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use context-accurate Chinese terms for these labels.

当地的 describes a geographic locality. Use 本地 for the local-skill label on Line 3781.

恩典 and 优雅 do not describe an automation grace period. Use 宽限 or 宽限期 on Lines 13359-13362, or keep the synchronized English fallback until translation review.

Also applies to: 13359-13362

Source: Learnings

src/main/runtime/rpc/orchestration-legacy-coordinator-race.test.ts-228-230 (1)

228-230: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Import the legacy run id for this assertion. src/main/runtime/rpc/methods/orchestration.ts compares against ORCHESTRATION_LEGACY_RUN_ID from ../../../../shared/orchestration-rpc-contract; using that imported value keeps the run id in this guard in sync with the guard implementation.

src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx-1314-1330 (1)

1314-1330: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add the new SmartWorkspaceNameField placeholder translations

These placeholder keys are referenced by SmartWorkspaceNameField, but none are present in the locale JSON bundles, so the UI shows the inline English defaults.

🧹 Nitpick comments (30)
src/main/runtime/orchestration/formatter.ts (1)

53-58: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the redundant overload declarations.

The implementation signature at Line 57 already assigns a default value to options. This alone makes options optional for external callers, without needing the two overload declarations at Lines 53-54.

Keep a single exported signature with the default parameter.

♻️ Proposed simplification
-export function formatMessageBanner(msg: MessageRow, options: MessageFormattingOptions): string
-export function formatMessageBanner(msg: MessageRow): string
 export function formatMessageBanner(
   msg: MessageRow,
   options: MessageFormattingOptions = {}
 ): string {
src/main/agent-hooks/server.ts (1)

1436-1476: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Compute owner once and apply one tabId rule.

parsePaneKey(toPaneKey) runs three times at lines 1436, 1450, and 1466 and always returns the same value. The two authority blocks also treat tabId differently: line 1457 keeps the previous tabId when the new one is absent, and line 1473 overwrites it with undefined. toPaneKey passed isValidPaneKey at line 1423, so owner?.tabId is always present today and the behavior matches. Unify the rule so a future change to isValidPaneKey cannot make the two paths diverge.

src/renderer/src/components/mobile/MobilePage.test.tsx (1)

84-96: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the manual-address retention path.

MobilePage.tsx now tracks addressIsManual and reminits the pairing QR when a network refresh changes the resolved address. The mock at Line 123 always returns an empty interface list, so no test exercises these branches. Add a test that returns interfaces from listNetworkInterfaces, selects a manual address through beforeCustomAddressChange plus handleAddressChange, then triggers loadNetworkInterfaces again and asserts the manual address survives and the QR reminits only on a real change.

Also applies to: 123-123

src/renderer/src/components/mobile/MobilePage.tsx (1)

149-206: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Decouple the refresh effect from loadNetworkInterfaces identity.

loadNetworkInterfaces sets selectedAddress and addressIsManual, and both values are in its useCallback dependency list (Line 184). The effect at Lines 186-191 depends on that callback, so every address update produces a new callback identity and re-runs the effect. This issues a redundant listNetworkInterfaces IPC call after the first resolution and after each handleAddressChange. It also makes the loop count depend on OS interface stability.

Keep the refresh in a ref (or depend only on stage) so the effect runs once per flow entry.

Also, the manual detection at Lines 164-167 duplicates the check at Line 199. Extract one helper that takes the address and the interface list.

src/main/pty/wsl-orca-env.ts (1)

80-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the WSLENV entries from the imported constants.

Lines 80-82 hardcode the same variable names that lines 3-5 already import as constants and that stampWslOrchestrationCompatibilityHost writes. A rename of a constant leaves these literals stale, and the WSL guest then loses the compatibility host metadata without a compile error.

♻️ Proposed change
-    'ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND/u',
-    'ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID/u',
-    'ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION/u',
+    `${ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV}/u`,
+    `${ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV}/u`,
+    `${ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV}/u`,
src/shared/codex-backfill-gate-wrapper.ts (1)

77-95: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Use newlines for the PowerShell script encoding.

-EncodedCommand supports multiline decoded scripts, while '; ' inserts extra statement separators into the PowerShell block. Keep the wrapped script on natural lines.

♻️ Proposed change
     'if (-not $?) { exit 1 }',
     'exit 0'
-  ].join('; ')
+  ].join('\n')
src/main/codex/codex-real-home-hook-install.ts (2)

107-115: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stale line-number citations in the duplicated pending-index rationale. The same rationale text was copied into the source file and the test file, and both copies cite absolute line numbers that break after any edit above them. Reference symbols instead of line numbers.

  • src/main/codex/codex-real-home-hook-install.ts#L107-L115: replace installRetryAfterMs (permanent for unsupported binaries, :266-270) with a reference to the retry-delay helper by name.
  • src/main/codex/codex-real-home-hook-install.test.ts#L605-L611: remove :266-270 and index.ts:847/:973, and shorten the comment to the non-obvious claim that a genuine failure must stay latched.

As per coding guidelines: "Comments must be concise, limited to non-obvious information, and preferably one line".

Source: Coding guidelines


116-130: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Memoize the pending Codex backfill probe.

ensureRealHomeCodexHookState runs in sync launch prep each time the system-default real home is selected. In pending-index or removed states before retry, the gate still calls isCodexBackfillIndexPending(), which opens the Codex state_*.sqlite DB and walks ~/.codex/sessions for .jsonl files. Keep the lane deferred but cache the pending result until retryRealHomeCodexHookAfterIndex() clears it.

src/main/runtime/relay/relay-revoke-outbox.test.ts (1)

50-67: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add an assertion that proves the failed enqueue left no in-memory item.

The current assertions pass in both implementations. After the failed enqueue, the second enqueue mints a new item because the in-memory list is empty, so disk holds one item. If the implementation retained the failed item, the second enqueue would return that same item through the dedupe branch and persist it, so disk would again hold exactly one item matching persisted. Assert the in-memory state directly after the failure to make the test discriminating.

💚 Proposed assertion
     secureFileMocks.failWrites = true
     expect(() => outbox.enqueue(binding)).toThrow('disk full')
+    expect(outbox.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([])
 
     secureFileMocks.failWrites = false
src/main/runtime/rpc/orchestration-legacy-coordinator-authority.ts (1)

129-144: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Do not cast a possibly missing handle to string.

identity.terminalHandle ?? (identity.terminal_handle as string) yields undefined typed as string when both fields are absent. The candidate then carries undefined at an authority boundary. The current downstream checks fail closed, so the request becomes read-only, but the type lies and a future comparison change could turn this into a silent match. Make the fields explicit and reject a candidate without both values.

♻️ Proposed typing fix
   ): LegacyPrincipalCandidate {
+    const terminalHandle = identity.terminalHandle ?? identity.terminal_handle
+    const paneKey = identity.paneKey ?? identity.pane_key
+    if (!terminalHandle || !paneKey) {
+      throw legacyCoordinatorReadOnly()
+    }
     return {
       runId,
       role: 'coordinator',
-      terminalHandle: identity.terminalHandle ?? (identity.terminal_handle as string),
-      paneKey: identity.paneKey ?? (identity.pane_key as string)
+      terminalHandle,
+      paneKey
     }
   }
src/renderer/src/hooks/useIpcEvents.test.ts (1)

4918-4919: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Restore coverage for the SSH port hydration authority guard.

This change set deletes the SSH port snapshot hydration test that covered stale snapshots and superseded authority. src/renderer/src/hooks/useIpcEvents.ts Lines 2660-2676 add a new initial-hydration path that fetches forwarded and detected ports and then applies them only while the SSH authority is unchanged. That guard prevents a dead session's ports from reappearing in the Ports panel, and it now has no test. Add a test that resolves the port snapshot after the authority changes and asserts that setPortForwards and setDetectedPorts are not called.

I can draft that test if you want.

src/renderer/src/hooks/useIpcEvents.ts (1)

2660-2676: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Bound the new port-snapshot round trips.

The hydration loop at Line 2647 awaits each target in sequence. This block adds two more IPC calls per connected target inside that loop. If listPortForwards or listDetectedPorts does not settle, hydration stalls for every remaining target, so SSH connect state stops updating on launch. Apply an explicit timeout to both calls, or move the port fetch out of the sequential loop so a slow target cannot block the others. The authority re-check at Lines 2668-2672 is correct and should stay.

Based on learnings: avoid unbounded renderer IPC calls and apply a shared timeout wrapper so hangs cannot block the UI indefinitely.

Source: Learnings

src/main/index.ts (1)

2094-2113: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the new startup comments.

Lines 2095-2105 add three multi-line comments that describe direct control flow. Keep concise comments only for non-obvious constraints.

Suggested comment reduction
-    // Why: `#11828` — finish Codex's one-time session index in the background so panes
-    // don't die in 30s slices against a large managed-home history.
-    // Why: `#11828` — a trust grant deferred behind the session index must run as
-    // soon as the prewarm finishes, not wait minutes for the next pane launch.
+    // Prewarm large managed histories before Codex pane launch.
     startStateDbPrewarm: (options, override) =>
       startCodexStateDbPrewarmInBackground(options, override).then((summaries) => {
+        // Retry a trust grant deferred until indexing completes.
         retryRealHomeCodexHookAfterIndex({
@@
-        // Why: main-side per-pane hold broadcasts now drive pane gating/overlay; this global broadcast is retained for backward-compat pending a follow-up removal review.
+        // Keep this compatibility broadcast until its removal review.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines

src/main/runtime/orca-runtime.ts (1)

4101-4110: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Reuse the freshest inventory instead of refetching per candidate.

Each candidate performs two extra listProcesses round trips (preAdoptionInventory here, finalInventory at Line 4252). With the shared inventory at Line 4066 the cost is 1 + 2N serial RPCs per provider, each bounded by PTY_CONTROLLER_LIST_TIMEOUT_MS. On the SSH relay-ready path this delays recovery of every later candidate.

The post-adoption finalInventory is needed for fencing. The pre-adoption refetch is redundant when no state-changing operation ran since the last inventory read. Track the last inventory and reuse it while it is still unmutated.

src/main/runtime/rpc/orchestration-legacy-question-takeover.test.ts (1)

178-178: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the private-field cast into one helper.

The same cast to reach the private db field appears in three tests. One local helper keeps the cast in a single place and simplifies later schema-access changes.

♻️ Proposed helper
+function rawSqlite(db: OrchestrationDb): Database.Database {
+  return (db as unknown as { db: Database.Database }).db
+}

Then replace each occurrence:

-    const sqlite = (harness.db as unknown as { db: Database.Database }).db
+    const sqlite = rawSqlite(harness.db)

Also applies to: 229-229, 335-335

src/main/runtime/orchestration/orchestration-legacy-question-migration-db.test.ts (1)

11-16: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reset db and tempDir in afterEach.

This hook closes db and removes tempDir but keeps both references. The sibling suites reset them: see orchestration-legacy-coordinator-authority-db.test.ts Lines 14-21 and orchestration-legacy-storage-db.test.ts Lines 19-26.

Without the reset, a test that fails before it assigns db leaves the previous instance in the variable. afterEach then calls close() on an already-closed handle, and that error can mask the original failure.

♻️ Proposed cleanup reset
   afterEach(() => {
     db?.close()
+    db = undefined
     if (tempDir) {
       rmSync(tempDir, { recursive: true, force: true })
+      tempDir = undefined
     }
   })
src/main/runtime/orchestration/orchestration-legacy-storage-test-fixture.ts (1)

29-186: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Close the database handles if seeding throws.

first and raw are closed only on the success path. If any seeding call between Line 30 and Line 184 throws, the handle stays open and tempDir keeps a locked SQLite file. On Windows the caller's rmSync then fails and reports a cleanup error instead of the real seeding failure.

Wrap each phase in try/finally so close() always runs.

♻️ Proposed structure
   const first = new OrchestrationDb(dbPath)
-  const currentRun = first.createRun({
+  try {
+    // ... existing seeding through the malformedRejections array ...
+  } finally {
+    first.close()
+  }

Apply the same try/finally around the raw handle at Lines 160-186.

src/main/runtime/orchestration/orchestration-version-skew-migration.test.ts (1)

183-191: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

This test does not yet prove that the database is left unrepaired.

Line 187 exercises the pure resolver, which is useful. Line 188 cannot fail: resolveOrchestrationMigrationStartVersion only reads user_version, so no code between Lines 187 and 188 can change it.

The test name promises the repair is skipped. To cover that, construct OrchestrationDb against a database whose stored version exceeds SCHEMA_VERSION, then assert the legacy rows keep their original run_id and that no legacy_adoptions row appears. That exercises the early return in migrate().

Also note the literal 19 no longer matches the declared SCHEMA_VERSION, which is now 21. Derive the values from the exported constant so the scenario stays a genuine future version.

src/shared/setup-agent-sequencing.test.ts (1)

53-73: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the exported constant for the gate env key.

Line 65 uses SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV, but Lines 56, 64, and 71 hardcode 'ORCA_BACKFILL_GATED_COMMAND'. src/shared/setup-agent-sequencing.ts reads that key through ORCA_BACKFILL_GATED_COMMAND_ENV, imported from src/shared/codex-backfill-gate-wrapper.ts.

If the constant's value changes, these three cases stop populating the key the resolver reads. The first two assertions would then fall through to fallbackCommand and fail with a confusing message, and the third would pass for the wrong reason.

♻️ Proposed key reference
+import { ORCA_BACKFILL_GATED_COMMAND_ENV } from './codex-backfill-gate-wrapper'
       resolveSetupAgentSequenceLaunchCommand(
-        { ORCA_BACKFILL_GATED_COMMAND: 'codex --resume' },
+        { [ORCA_BACKFILL_GATED_COMMAND_ENV]: 'codex --resume' },
         'gate wrapper'
       )

Apply the same change at Lines 64 and 71.

tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts (1)

625-632: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the adopted run exists before you read its id.

The ! on .find(...) produces Cannot read properties of undefined (reading 'id') when no run matches. In a 300-second serial Electron test that message hides the cause. Add an explicit expectation first.

The match also depends on the exact objective string, which is duplicated from src/main/runtime/orchestration/db.ts Line 1114. Consider matching on legacy = 0 plus the adoption record instead, or export the objective as a constant.

♻️ Proposed diagnostic assertion
         }>('orchestration.runList')
-        assignmentRunId = runs.result.runs.find(
+        const adopted = runs.result.runs.find(
           (candidate) =>
             candidate.objective === 'Recovered orchestration work from a contract update'
-        )!.id
+        )
+        expect(adopted, 'Expected an adopted legacy Run in orchestration.runList').toBeTruthy()
+        assignmentRunId = adopted!.id
src/main/runtime/orchestration/orchestration-schema-version-skew.ts (1)

58-73: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Import ORCHESTRATION_LEGACY_RUN_ID instead of hardcoding 'run_legacy_local'.

db.ts aliases LEGACY_RUN_ID = ORCHESTRATION_LEGACY_RUN_ID, but this file stores its own copy. If the contract run ID changes, this query misses legacy rows and adoption rows, returns true, and skips repair. Import it from '../../../shared/orchestration-rpc-contract' so LEGACY_RUN_ID stays available elsewhere.

Also move the legacy_adoptions query below the sourceGraph early return so the adoption row is read only when needed.

src/main/runtime/rpc/orchestration-legacy-takeover-dispatcher.test.ts (1)

222-227: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse the declared handle and pane constants.

These bindRun calls repeat the literals 'term_current_coord' and 'tab_current:55555555-5555-4555-8555-555555555555'. The file already declares CURRENT_COORDINATOR_HANDLE and CURRENT_COORDINATOR_PANE for those values, and the mocked verifyOrchestrationCompatibilityCaller keys off those constants. If a constant changes, these literals will drift and the tests will fence unexpectedly.

♻️ Proposed change (apply to each occurrence)
     harness.db.bindRun({
       runId: harness.adoptedRunId,
-      coordinatorHandle: 'term_current_coord',
-      coordinatorPaneKey: 'tab_current:55555555-5555-4555-8555-555555555555',
+      coordinatorHandle: CURRENT_COORDINATOR_HANDLE,
+      coordinatorPaneKey: CURRENT_COORDINATOR_PANE,
       takeoverLegacy: true
     })

Also applies to: 249-254, 314-319

src/renderer/src/components/terminal-pane/CodexIndexingOverlay.tsx (1)

19-22: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Announce the wait state to assistive technology.

The overlay reports a blocking wait and its text changes as indexing advances. Screen readers will not announce it without a live region. MobilePane.tsx uses role="status" with aria-live="polite" for the analogous pairing-ready message.

♿ Proposed change
-    <div className="absolute inset-x-3 bottom-3 z-50 flex items-center gap-2 rounded-md border border-border bg-muted px-3 py-2 text-xs text-muted-foreground">
+    <div
+      role="status"
+      aria-live="polite"
+      className="absolute inset-x-3 bottom-3 z-50 flex items-center gap-2 rounded-md border border-border bg-muted px-3 py-2 text-xs text-muted-foreground"
+    >
src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher.test.ts (1)

346-375: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The Date.now stub couples this test to the exact number of clock reads. clockReads === 1 ? 0 : clockReads === 2 ? 1 : 120_001 returns the expired value for every read after the second. Any new Date.now() call on the check path (for example a thread_${Date.now()} id or a timing log) shifts the sequence and can flip the asserted wait budget. Consider driving the clock from an explicit array of expected values, or use vi.useFakeTimers() with vi.setSystemTime() so the intent is order-independent.

♻️ Suggested value-driven clock stub
-    let clockReads = 0
-    const now = vi.spyOn(Date, 'now').mockImplementation(() => {
-      clockReads += 1
-      return clockReads === 1 ? 0 : clockReads === 2 ? 1 : 120_001
-    })
+    // Why: the check path reads the clock at start, at wait entry, then after the wait.
+    const clockReadings = [0, 1, 120_001]
+    const now = vi
+      .spyOn(Date, 'now')
+      .mockImplementation(() => clockReadings.shift() ?? 120_001)
src/main/runtime/rpc/orchestration-legacy-coordinator-race.test.ts (1)

15-179: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Two new files carry the same legacy-orchestration harness. This change adds a shared fixture and, in parallel, an independent local copy of the same setup: the constants, the SQLite user_version-18 downgrade, createHarness, evidence, request, the transport invoke, and the row-count helper. The single root cause is that the extraction covered only one of the two consumers, so the downgrade SQL and the caller-verification mock must now be maintained twice.

  • src/main/runtime/rpc/orchestration-legacy-coordinator-race.test.ts#L15-L179: import createHarness, evidence, request, invoke, the pane and handle constants, and cleanupLegacyCompatibilityDispatcherHarnesses from ./orchestration-legacy-compatibility-dispatcher-test-fixture, then delete the local copies. Keep only the race-specific helpers (installTakeoverDuringMutationPreflight, settleLegacyWorkerAndTakeOver, mutationReceiptCount, messageCount).
  • src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher-test-fixture.ts#L15-L176: reconcile the two verifyOrchestrationCompatibilityCaller mocks so one implementation serves both suites. The race copy also requires launchToken === 'coordinator-token' or 'worker-token', while the fixture accepts any non-empty launchToken. Adopt the stricter token check, or expose it as a fixture option, and let request accept the caller evidence as an optional argument so both call styles work.
src/renderer/src/components/terminal-pane/TerminalErrorToast.tsx (2)

56-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse informational in showDaemonRestart. !ssh && !isCodexBackfillIndexingNotice(error) is exactly !informational, so the classifier runs twice on the same string.

♻️ Proposed simplification
-  const showDaemonRestart =
-    !ssh &&
-    !isCodexBackfillIndexingNotice(error) &&
-    onRestartDaemon &&
-    shouldOfferDaemonRestart(error)
+  const showDaemonRestart = !informational && onRestartDaemon && shouldOfferDaemonRestart(error)

33-36: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the codex notice match from CODEX_BACKFILL_INDEXING_NOTICE. TerminalErrorToast.tsx duplicates the first line of codex-backfill-error-detector.ts’s exported notice; use that constant so the toast stays aligned with the detector and preserves the red failure/daemon-restart UX if the wording is reworded or localized.

src/shared/codex-backfill-gate-wrapper.test.ts (1)

43-62: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case for a backslash home combined with toShellViewPath. buildCodexBackfillGateWrapper picks the path separator from params.codexHomePath.includes('\\'), so a Windows or WSL UNC home takes a different code path than the POSIX fixture. The current tests exercise the separator choice only through the win32 test, which does not pass toShellViewPath. One combined case pins both the separator and the translated env value.

♻️ Proposed added test
   it('applies toShellViewPath to the env value but keeps the host view in releaseFilePath', () => {
  it('keeps a backslash home separator while translating the env value', () => {
    const wrapper = buildCodexBackfillGateWrapper({
      ...baseParams,
      codexHomePath: '\\\\wsl.localhost\\Ubuntu\\home\\user\\.codex',
      toShellViewPath: () => '/home/user/.codex/.orca/backfill-release-test'
    })

    expect(wrapper.releaseFilePath).toContain('\\.orca\\backfill-release-')
    expect(wrapper.env[ORCA_BACKFILL_RELEASE_FILE_ENV]).toBe(
      '/home/user/.codex/.orca/backfill-release-test'
    )
  })
src/renderer/src/web/web-preload-api.ts (1)

815-822: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse noopUnsubscribe for the two subscription stubs.

Every other subscription stub in this file returns the shared noopUnsubscribe. The inline () => () => {} closures allocate a new function per call and break that pattern.

♻️ Proposed change
     codexBackfill: {
       status: () => Promise.resolve({ pending: false, lastWatermark: null }),
-      onStatusChanged: () => () => {},
+      onStatusChanged: () => noopUnsubscribe,
       // Why: hold state rides Electron IPC only; web-served panes (incl. orca-serve attaches on the serve host's
       // local runtime) render no overlay — accepted residual AD-A9, bounded by the gate's fail-open ceilings.
       paneHoldStatus: () => Promise.resolve(null),
-      onPaneHoldChanged: () => () => {}
+      onPaneHoldChanged: () => noopUnsubscribe
     },
src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx (1)

1414-1417: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep horizontal overflow control on the tab strip.

The custom w-full justify-start gap-4 px-0 overrides can remove overflow-x-auto, and the fixed-width dialog with flex-none tabs can make the strip overflow when multiple modes are available. Restore the horizontal overflow class or an explicit overflow handling class.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 384ffa42-266d-4db8-a6f4-b9ab89c933bc

📥 Commits

Reviewing files that changed from the base of the PR and between 16c5526 and 08302d8.

📒 Files selected for processing (240)
  • config/reliability-gates.jsonc
  • config/scripts/orchestration-skill-guidance.test.mjs
  • docs/plans/2026-07-31-codex-backfill-prewarm.md
  • docs/plans/2026-08-01-codex-backfill-prewarm.md
  • docs/reference/plans/2026-07-28-orchestration-seamless-update-migration.md
  • native/windows-cli-launcher/OrcaCliLauncher.cs
  • package.json
  • renderer-worktree-freeze-incident-2026-07-29.md
  • skill-guides/orca-cli.md
  • skill-guides/orchestration.md
  • src/cli/bundled-skill-guides.ts
  • src/cli/handlers/orchestration-check-identity.test.ts
  • src/cli/handlers/orchestration-legacy-read-only.test.ts
  • src/cli/handlers/orchestration-migration.test.ts
  • src/cli/handlers/orchestration-run-cli.test.ts
  • src/cli/handlers/orchestration-timeout-cli.test.ts
  • src/cli/handlers/orchestration-timeout.test.ts
  • src/cli/handlers/orchestration-windows-ask-cli.test.ts
  • src/cli/handlers/orchestration.test.ts
  • src/cli/handlers/orchestration.ts
  • src/cli/handlers/worktree.ts
  • src/cli/index.test.ts
  • src/cli/runtime-client.test.ts
  • src/cli/runtime/client.ts
  • src/cli/runtime/orchestration-compatibility-envelope.ts
  • src/cli/runtime/runtime-request-timeout.ts
  • src/cli/runtime/transport.ts
  • src/cli/runtime/types.test.ts
  • src/cli/runtime/types.ts
  • src/cli/specs/orchestration.ts
  • src/main/agent-hooks/server-authority-evidence.test.ts
  • src/main/agent-hooks/server.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/cli/windows-launcher-asset.test.ts
  • src/main/codex/codex-backfill-spawn-hold.test.ts
  • src/main/codex/codex-backfill-spawn-hold.ts
  • src/main/codex/codex-managed-hook-slot-reconciliation.ts
  • src/main/codex/codex-real-home-hook-install.test.ts
  • src/main/codex/codex-real-home-hook-install.ts
  • src/main/codex/codex-session-migration-scheduler.test.ts
  • src/main/codex/codex-session-migration-scheduler.ts
  • src/main/codex/codex-state-db-prewarm.test.ts
  • src/main/codex/codex-state-db-prewarm.ts
  • src/main/codex/codex-state-db.test.ts
  • src/main/codex/codex-state-db.ts
  • src/main/daemon/daemon-history-handoff.ts
  • src/main/daemon/daemon-pty-router-history-handoff.test.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/headless-emulator.ts
  • src/main/daemon/terminal-host-wsl-context.test.ts
  • src/main/daemon/wsl-session-context.ts
  • src/main/index.ts
  • src/main/ipc/codex-backfill-status.test.ts
  • src/main/ipc/codex-backfill-status.ts
  • src/main/ipc/mobile.test.ts
  • src/main/ipc/mobile.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/register-core-handlers.test.ts
  • src/main/ipc/register-core-handlers.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/pty/wsl-orca-env.test.ts
  • src/main/pty/wsl-orca-env.ts
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/runtime/device-registry.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration-compatibility-authority.test.ts
  • src/main/runtime/orchestration/db.test.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/formatter.test.ts
  • src/main/runtime/orchestration/formatter.ts
  • src/main/runtime/orchestration/orchestration-legacy-coordinator-authority-db.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-question-migration-db.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-storage-db.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-storage-test-fixture.ts
  • src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.ts
  • src/main/runtime/orchestration/orchestration-schema-version-skew.ts
  • src/main/runtime/orchestration/orchestration-version-skew-migration.test.ts
  • src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts
  • src/main/runtime/orchestration/types.ts
  • src/main/runtime/relay/relay-revoke-outbox.test.ts
  • src/main/runtime/relay/relay-revoke-outbox.ts
  • src/main/runtime/rpc/core.ts
  • src/main/runtime/rpc/dispatcher-error-response.ts
  • src/main/runtime/rpc/dispatcher-feature-interactions.test.ts
  • src/main/runtime/rpc/dispatcher-stream-options.ts
  • src/main/runtime/rpc/dispatcher.ts
  • src/main/runtime/rpc/errors.ts
  • src/main/runtime/rpc/methods/orchestration-federation-control-mail.test.ts
  • src/main/runtime/rpc/methods/orchestration-federation.test.ts
  • src/main/runtime/rpc/methods/orchestration-federation.ts
  • src/main/runtime/rpc/methods/orchestration-gates.ts
  • src/main/runtime/rpc/methods/orchestration-runs.ts
  • src/main/runtime/rpc/methods/orchestration-worker-topology.ts
  • src/main/runtime/rpc/methods/orchestration-workers-new-worktree.test.ts
  • src/main/runtime/rpc/methods/orchestration-workers.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts
  • src/main/runtime/rpc/methods/orchestration.ts
  • src/main/runtime/rpc/orchestration-legacy-authority.ts
  • src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher-test-fixture.ts
  • src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher.test.ts
  • src/main/runtime/rpc/orchestration-legacy-compatibility.ts
  • src/main/runtime/rpc/orchestration-legacy-coordinator-authority.ts
  • src/main/runtime/rpc/orchestration-legacy-coordinator-race.test.ts
  • src/main/runtime/rpc/orchestration-legacy-lifecycle.ts
  • src/main/runtime/rpc/orchestration-legacy-mail.ts
  • src/main/runtime/rpc/orchestration-legacy-operation.ts
  • src/main/runtime/rpc/orchestration-legacy-process-identity.ts
  • src/main/runtime/rpc/orchestration-legacy-question-takeover.test.ts
  • src/main/runtime/rpc/orchestration-legacy-question.ts
  • src/main/runtime/rpc/orchestration-legacy-takeover-dispatcher.test.ts
  • src/main/runtime/rpc/orchestration-mutation-executor.ts
  • src/main/runtime/rpc/orchestration-mutation-ledger.test.ts
  • src/main/runtime/rpc/runtime-feature-interaction.ts
  • src/main/runtime/runtime-rpc.test.ts
  • src/main/runtime/runtime-rpc.ts
  • src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/main/ssh/ssh-remote-cli-host-passthrough.test.ts
  • src/main/ssh/ssh-remote-cli-host-passthrough.ts
  • src/main/ssh/ssh-remote-cli-in-process-result.ts
  • src/main/ssh/ssh-remote-orca-cli.test.ts
  • src/main/ssh/ssh-remote-orca-cli.ts
  • src/main/ssh/ssh-remote-orchestration-ask-output.ts
  • src/main/ssh/ssh-remote-orchestration-check-output.ts
  • src/main/ssh/ssh-remote-orchestration-compatibility.test.ts
  • src/main/ssh/ssh-remote-orchestration-post-output.ts
  • src/main/startup/desktop-startup-ordering.test.ts
  • src/main/startup/legacy-worker-renderer-recovery.test.ts
  • src/main/startup/legacy-worker-renderer-recovery.ts
  • src/main/window/attach-main-window-services.test.ts
  • src/main/window/attach-main-window-services.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/relay/relay.ts
  • src/relay/remote-cli-env.test.ts
  • src/relay/remote-cli-env.ts
  • src/renderer/src/App.tsx
  • src/renderer/src/app-startup-routing.test.ts
  • src/renderer/src/assets/mobile-page.css
  • src/renderer/src/components/mobile/MobileHero.test.tsx
  • src/renderer/src/components/mobile/MobileHero.tsx
  • src/renderer/src/components/mobile/MobileHeroPairingStep.tsx
  • src/renderer/src/components/mobile/MobilePage.test.tsx
  • src/renderer/src/components/mobile/MobilePage.tsx
  • src/renderer/src/components/mobile/MobilePageContent.tsx
  • src/renderer/src/components/mobile/mobile-relay-mint-failure-notice.tsx
  • src/renderer/src/components/mobile/use-mobile-pairing-generation.ts
  • src/renderer/src/components/mobile/use-mobile-pairing-qr-invalidation.ts
  • src/renderer/src/components/new-workspace/ProjectCombobox.tsx
  • src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx
  • src/renderer/src/components/new-workspace/smart-workspace-command-value.test.ts
  • src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts
  • src/renderer/src/components/settings/MobilePairingConnectionOptions.test.tsx
  • src/renderer/src/components/settings/MobilePairingConnectionOptions.tsx
  • src/renderer/src/components/settings/MobilePairingQrSection.test.tsx
  • src/renderer/src/components/settings/MobilePairingQrSection.tsx
  • src/renderer/src/components/settings/MobilePairingSetupSection.test.tsx
  • src/renderer/src/components/settings/MobilePairingSetupSection.tsx
  • src/renderer/src/components/settings/MobilePane.test.tsx
  • src/renderer/src/components/settings/MobilePane.tsx
  • src/renderer/src/components/sidebar/Sidebar.test.tsx
  • src/renderer/src/components/sidebar/index.tsx
  • src/renderer/src/components/sidebar/single-flight-coalescer.test.ts
  • src/renderer/src/components/sidebar/single-flight-coalescer.ts
  • src/renderer/src/components/terminal-pane/CodexIndexingOverlay.test.tsx
  • src/renderer/src/components/terminal-pane/CodexIndexingOverlay.tsx
  • src/renderer/src/components/terminal-pane/TerminalErrorToast.test.ts
  • src/renderer/src/components/terminal-pane/TerminalErrorToast.tsx
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-pane-hold.test.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-pane-hold.ts
  • src/renderer/src/components/terminal-pane/pty-connection-types.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-linkifier-click-priming.test.ts
  • src/renderer/src/components/terminal-pane/terminal-linkifier-click-priming.ts
  • src/renderer/src/components/terminal-pane/terminal-url-link-click.test.ts
  • src/renderer/src/components/terminal-pane/terminal-url-link-hit-testing.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/constants/terminal.ts
  • src/renderer/src/hooks/ipc-events-test-harness.ts
  • src/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.ts
  • src/renderer/src/hooks/legacy-worker-terminal-recovery-event.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/lib/launch-ai-vault-session.test.ts
  • src/renderer/src/lib/launch-ai-vault-session.ts
  • src/renderer/src/lib/pane-manager/pane-manager-types.ts
  • src/renderer/src/lib/pane-manager/pane-manager.ts
  • src/renderer/src/lib/pane-manager/pane-split-close.ts
  • src/renderer/src/lib/resume-sleeping-agent-session-legacy-worker.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.ts
  • src/renderer/src/lib/terminal-reveal-identity.test.ts
  • src/renderer/src/lib/terminal-reveal-identity.ts
  • src/renderer/src/store/slices/agent-pane-authority.test.ts
  • src/renderer/src/store/slices/agent-status-provider-session.test.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/agent-session-resume.ts
  • src/shared/codex-backfill-gate-wrapper.test.ts
  • src/shared/codex-backfill-gate-wrapper.ts
  • src/shared/codex-backfill-status-types.ts
  • src/shared/crash-reporting.test.ts
  • src/shared/crash-reporting.ts
  • src/shared/mobile-relay-mint-failure.test.ts
  • src/shared/mobile-relay-mint-failure.ts
  • src/shared/new-workspace/smart-workspace-command-value.ts
  • src/shared/new-workspace/smart-workspace-source-results.ts
  • src/shared/orchestration-check-output.test.ts
  • src/shared/orchestration-check-output.ts
  • src/shared/orchestration-compatibility-evidence.test.ts
  • src/shared/orchestration-compatibility-evidence.ts
  • src/shared/orchestration-message-wait-timeout.ts
  • src/shared/remote-runtime-client.ts
  • src/shared/runtime-rpc-envelope.ts
  • src/shared/runtime-types.ts
  • src/shared/setup-agent-sequencing.test.ts
  • src/shared/setup-agent-sequencing.ts
  • src/shared/terminal-reveal-identity.ts
  • src/shared/workspace-session-sleeping-agents.ts
  • tests/e2e/global-setup.ts
  • tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts
  • tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts
  • tests/e2e/orchestration-worker-terminal-visibility.spec.ts
💤 Files with no reviewable changes (17)
  • src/renderer/src/components/mobile/MobileHero.test.tsx
  • src/renderer/src/store/slices/agent-status-provider-session.test.ts
  • src/renderer/src/components/mobile/MobileHero.tsx
  • src/renderer/src/components/sidebar/Sidebar.test.tsx
  • src/renderer/src/components/mobile/MobileHeroPairingStep.tsx
  • src/renderer/src/components/settings/MobilePairingSetupSection.tsx
  • src/main/ssh/ssh-remote-orca-cli.test.ts
  • src/main/startup/desktop-startup-ordering.test.ts
  • src/main/runtime/runtime-rpc.test.ts
  • src/renderer/src/components/new-workspace/smart-workspace-command-value.test.ts
  • src/renderer/src/components/settings/MobilePane.test.tsx
  • src/renderer/src/app-startup-routing.test.ts
  • src/renderer/src/lib/pane-manager/pane-manager-types.ts
  • src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts
  • src/shared/runtime-types.ts
  • src/renderer/src/App.tsx
  • src/renderer/src/components/mobile/MobilePageContent.tsx

Comment on lines +1065 to +1078
let disposed = false
void api
.paneHoldStatus(paneKey)
.then((state) => {
if (!disposed && state && state.paneKey === paneKey) {
onState(toIndexingState(state))
}
})
.catch(() => {})
const unsubscribe = api.onPaneHoldChanged((state) => {
if (!disposed && state.paneKey === paneKey) {
onState(toIndexingState(state))
}
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Prevent a stale initial status from restoring the overlay.

If paneHoldStatus() captures indexing, then paneHoldChanged emits launched before the Promise resolves, the later initial response calls onState() with indexing again. The pane can retain the overlay after Codex starts.

Subscribe before the status request. Ignore the initial response after a same-pane push event. Add a test that resolves a deferred indexing response after a launched event.

Comment on lines +644 to 662
result = {
...result,
result: prepareOrchestrationCheckOutput(result.result, terminal, flags.has('format'))
}
printResult(result, json, (r) => formatOrchestrationCheckText(r, terminal))
const compatibilityAck = result.result.legacyCompatibility?.ackMessageIds
if (compatibilityAck && compatibilityAck.length > 0) {
await flushStdout()
await client.call('orchestration.check', {
terminal,
compatibilityAck: JSON.stringify({
messageIds: compatibilityAck,
types: getOptionalStringFlag(flags, 'types')
?.split(',')
.map((type) => type.trim())
.filter(Boolean)
})
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Wrap the compatibility acknowledgment call so its failure cannot mask an already-successful check.

printResult already delivers the check result to the user at line 648. If the follow-up client.call('orchestration.check', { compatibilityAck: ... }) at lines 651-661 rejects, the exception propagates out of this handler after the successful output was printed. The command then likely reports failure (non-zero exit, error output) for a check that actually succeeded. The acknowledgment is a best-effort legacy-compatibility signal; its failure should not change the reported outcome of an already-delivered check.

🐛 Proposed fix
     const compatibilityAck = result.result.legacyCompatibility?.ackMessageIds
     if (compatibilityAck && compatibilityAck.length > 0) {
       await flushStdout()
-      await client.call('orchestration.check', {
-        terminal,
-        compatibilityAck: JSON.stringify({
-          messageIds: compatibilityAck,
-          types: getOptionalStringFlag(flags, 'types')
-            ?.split(',')
-            .map((type) => type.trim())
-            .filter(Boolean)
-        })
-      })
+      try {
+        await client.call('orchestration.check', {
+          terminal,
+          compatibilityAck: JSON.stringify({
+            messageIds: compatibilityAck,
+            types: getOptionalStringFlag(flags, 'types')
+              ?.split(',')
+              .map((type) => type.trim())
+              .filter(Boolean)
+          })
+        })
+      } catch (error) {
+        // Why: the ack is a best-effort legacy-compatibility signal; its failure
+        // must not turn an already-delivered successful check into a reported failure.
+        console.error('orchestration check: compatibility acknowledgment failed', error)
+      }
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
result = {
...result,
result: prepareOrchestrationCheckOutput(result.result, terminal, flags.has('format'))
}
printResult(result, json, (r) => formatOrchestrationCheckText(r, terminal))
const compatibilityAck = result.result.legacyCompatibility?.ackMessageIds
if (compatibilityAck && compatibilityAck.length > 0) {
await flushStdout()
await client.call('orchestration.check', {
terminal,
compatibilityAck: JSON.stringify({
messageIds: compatibilityAck,
types: getOptionalStringFlag(flags, 'types')
?.split(',')
.map((type) => type.trim())
.filter(Boolean)
})
})
}
result = {
...result,
result: prepareOrchestrationCheckOutput(result.result, terminal, flags.has('format'))
}
printResult(result, json, (r) => formatOrchestrationCheckText(r, terminal))
const compatibilityAck = result.result.legacyCompatibility?.ackMessageIds
if (compatibilityAck && compatibilityAck.length > 0) {
await flushStdout()
try {
await client.call('orchestration.check', {
terminal,
compatibilityAck: JSON.stringify({
messageIds: compatibilityAck,
types: getOptionalStringFlag(flags, 'types')
?.split(',')
.map((type) => type.trim())
.filter(Boolean)
})
})
} catch (error) {
// Why: the ack is a best-effort legacy-compatibility signal; its failure
// must not turn an already-delivered successful check into a reported failure.
console.error('orchestration check: compatibility acknowledgment failed', error)
}
}

Comment on lines +1008 to +1026
} else if (result.result.legacyCompatibility?.resumeRequired) {
console.log(`Question ${result.result.messageId} committed.`)
console.log(`Resume with: ${result.result.legacyCompatibility.resumeCommand}`)
} else if (result.result.answer !== null) {
console.log(result.result.answer)
}
if (result.result.legacyCompatibility?.resumeRequired) {
await flushStdout()
process.exitCode = 75
return
}
const answerAck = result.result.legacyCompatibility?.answerAcknowledgement
if (answerAck && result.result.answer !== null) {
await flushStdout()
await client.call('orchestration.check', {
terminal: from,
compatibilityQuestionAck: JSON.stringify(answerAck)
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Same unhandled-ack-failure gap as the check handler.

This mirrors the orchestration check handler above: console.log(result.result.answer) (or the resume-required output) already delivers the result at lines 1009-1013, but the client.call('orchestration.check', { compatibilityQuestionAck: ... }) call at lines 1022-1025 has no error handling. If it rejects, the already-answered ask command would report failure to the caller.

Comment on lines +1541 to +1552
const shouldClearStablePaneKey =
options?.shouldClearStablePaneKey?.(entry.stablePaneKey) ?? true
const revokedPaneKeys = new Set([legacyPaneKey])
if (shouldClearStablePaneKey) {
revokedPaneKeys.add(entry.stablePaneKey)
}
if (this.revokeHydratedAuthorityForPaneKeys(revokedPaneKeys)) {
statusChanged = true
}
this.legacyPaneKeyAliases.delete(legacyPaneKey)
clearPaneCacheState(this.state, legacyPaneKey)
this.currentAuthorityObservations.delete(legacyPaneKey)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Alias revocation drops the stable pane's persisted authority when the caller asked to keep it.

Line 1547 calls revokeHydratedAuthorityForPaneKeys({ legacyPaneKey }) before line 1550 deletes the alias entry. Inside that method, line 1596 resolves legacyPaneKey through the still-present alias to entry.stablePaneKey. Lines 1598 and 1600 then delete hydratedLaunchTokenHashByPaneKey and persistedAuthorityCommitmentsByPaneKey for the stable pane, even when shouldClearStablePaneKey returns false.

The result is inconsistent state. The frozen commitment object is not marked revoked, because line 1588 checks the unresolved key and line 1589 resolves the stable key to itself. Only the two maps lose the entry. The next runStatusPersist therefore writes a file without an authorityCommitments row for that live pane, and restored attestation fails after the next app start.

The existing test at src/main/agent-hooks/server-authority-evidence.test.ts lines 183-222 does not catch this. It asserts source: 'current_hook', which currentAuthorityObservations satisfies on its own.

Delete the alias entry before revoking so the legacy key no longer resolves to the stable pane. Other callers pass both the physical and the stable key explicitly, so they keep their current behavior.

🐛 Proposed fix
         const shouldClearStablePaneKey =
           options?.shouldClearStablePaneKey?.(entry.stablePaneKey) ?? true
         const revokedPaneKeys = new Set([legacyPaneKey])
         if (shouldClearStablePaneKey) {
           revokedPaneKeys.add(entry.stablePaneKey)
         }
+        // Why: revoke after dropping the alias so a kept stable pane isn't reached by alias resolution.
+        this.legacyPaneKeyAliases.delete(legacyPaneKey)
         if (this.revokeHydratedAuthorityForPaneKeys(revokedPaneKeys)) {
           statusChanged = true
         }
-        this.legacyPaneKeyAliases.delete(legacyPaneKey)
         clearPaneCacheState(this.state, legacyPaneKey)
         this.currentAuthorityObservations.delete(legacyPaneKey)

Add a case to the same test that asserts the persisted commitment for the stable pane survives, then restart the server and assert source: 'hydrated_commitment' still attests.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const shouldClearStablePaneKey =
options?.shouldClearStablePaneKey?.(entry.stablePaneKey) ?? true
const revokedPaneKeys = new Set([legacyPaneKey])
if (shouldClearStablePaneKey) {
revokedPaneKeys.add(entry.stablePaneKey)
}
if (this.revokeHydratedAuthorityForPaneKeys(revokedPaneKeys)) {
statusChanged = true
}
this.legacyPaneKeyAliases.delete(legacyPaneKey)
clearPaneCacheState(this.state, legacyPaneKey)
this.currentAuthorityObservations.delete(legacyPaneKey)
const shouldClearStablePaneKey =
options?.shouldClearStablePaneKey?.(entry.stablePaneKey) ?? true
const revokedPaneKeys = new Set([legacyPaneKey])
if (shouldClearStablePaneKey) {
revokedPaneKeys.add(entry.stablePaneKey)
}
// Why: revoke after dropping the alias so a kept stable pane isn't reached by alias resolution.
this.legacyPaneKeyAliases.delete(legacyPaneKey)
if (this.revokeHydratedAuthorityForPaneKeys(revokedPaneKeys)) {
statusChanged = true
}
clearPaneCacheState(this.state, legacyPaneKey)
this.currentAuthorityObservations.delete(legacyPaneKey)

Comment on lines 4451 to 4466
private getWorkspaceSessionHostIdForWorktree(worktreeId: string): ExecutionHostId {
const repo = this.store?.getRepo?.(getRepoIdFromWorktreeId(worktreeId))
return repo ? getRepoExecutionHostId(repo) : 'local'
const scope = parseWorkspaceKey(worktreeId)
if (scope?.type === 'folder') {
const workspace = this.store
?.getFolderWorkspaces?.()
.find((entry) => entry.id === scope.folderWorkspaceId)
if (!workspace) {
throw new Error('folder_workspace_not_found')
}
const connectionId = this.resolveFolderWorkspaceConnectionId(workspace)
return connectionId ? toSshExecutionHostId(connectionId) : LOCAL_EXECUTION_HOST_ID
}
const resolvedWorktreeId = scope?.type === 'worktree' ? scope.worktreeId : worktreeId
const repo = this.store?.getRepo?.(getRepoIdFromWorktreeId(resolvedWorktreeId))
return repo ? getRepoExecutionHostId(repo) : LOCAL_EXECUTION_HOST_ID
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: List call sites of the workspace-session host resolver and its wrappers.
set -euo pipefail

fd -t f 'orca-runtime.ts' src/main/runtime | while IFS= read -r file; do
  rg -n -C4 \
    'getWorkspaceSessionHostIdForWorktree|getWorkspaceSessionForWorktree|setWorkspaceSessionForWorktree' \
    "$file"
done

# Confirm the two throw sites reachable from the resolver.
rg -n -C3 "folder_workspace_not_found|folder_workspace_connection_ambiguous" src

Repository: stablyai/orca

Length of output: 16398


🏁 Script executed:

#!/bin/bash
# Inspect the relevant callers and terminal-topology entry points that can reach the throw paths.
set -euo pipefail

file="$(fd -t f 'orca-runtime.ts' src/main/runtime | head -n1)"
echo "FILE=$file"

echo
echo "--- getTerminalTopologyRevision ---"
sed -n '14168,14184p' "$file"

echo
echo "--- getTerminalTopologyRevision call sites ---"
rg -n -C6 'getTerminalTopologyRevision\b|adoptTerminalOrphansFromInventory\b|listTerminals\b' "$file"

echo
echo "--- persistWindowlessPtyBindingsForDesktopAttach ---"
sed -n '4850,4882p' "$file"

echo
echo "--- getWorkspaceSessionForWorktree read callers without obvious try/catch ---"
python3 - <<'PY'
from pathlib import Path
import re
p = [x for x in Path('src/main/runtime').glob('*.ts') if x.name == 'orca-runtime.ts'][0]
lines = p.read_text(encoding='utf-8').splitlines()
calls=[]
try_b = {}
except_b = {}
for i,l in enumerate(lines,1):
    if 'try {' in l:
        try_b[i]=1
    if '}' in l:
        except_b[i]=1
    for pat in ['getWorkspaceSessionForWorktree(', 'getWorkspaceSessionHostIdForWorktree(', 'getTerminalTopologyRevision(']:
        if pat in l and pat != 'setWorkspaceSessionForWorktree(' and 'private getWorkspaceSessionForWorktree' not in l and 'private getWorkspaceSessionHostIdForWorktree' not in l:
            start=max(1,i-5); end=min(len(lines),i+5)
            print(f"— line {i} {p}:{pat}")
            for n in range(start,end+1):
                print(f"{n:5d}: {lines[n-1]}")
PY

echo
echo "--- exact throw sites referenced ---"
sed -n '4451,4480p' "$file"
sed -n '25800,25812p' "$file"

Repository: stablyai/orca

Length of output: 24126


Make the workspace-session host resolver non-throwing for stale folder workspaces.

getWorkspaceSessionHostIdForWorktree now throws for missing folder workspaces (folder_workspace_not_found) and ambiguous folder connections (folder_workspace_connection_ambiguous). These throw paths reach unguarded callers such as windowless PTY persistence and terminal-list topology revisions, where a stale folder-workspace record aborts unrelated desktop attach or RPC paths. Return LOCAL_EXECUTION_HOST_ID for unknown folder workspaces/connection ambiguity, or wrap the read paths so stale persistence is treated as unavailable instead of throwing.

Comment on lines +9274 to +9277
onCommandFinished: (exitCode: number | null) => {
this.retirePtyAgentLaunchAuthority(ptyId)
this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode })
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect sequenced setup+agent launch wrapping and command-finished producers.
set -euo pipefail

fd -t f 'setup-agent-sequencing.ts' src/shared --exec cat -n {}
rg -n -C5 "onCommandFinished|command-finished" src/shared src/main

Repository: stablyai/orca

Length of output: 35660


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect retirement behavior and consumers/readers.
fd -t f 'orca-runtime.ts' src/main --exec sh -c '
  echo "===== outline retirement references =="
  ast-grep outline "$1" --match retirePtyAgentLaunchAuthority --view expanded || true
  echo "===== retirement implementation =="
  rg -n -C 8 "retirePtyAgentLaunchAuthority|retireAgentHookCompatibilityAuthorityFn|launchToken" "$1"
  echo "===== consumers around launch token =="
  rg -n -C 6 "getAgentStatusLaunchConfigForPaneKey|getExactWorkerProviderSession|getOrchestrationDispatchAuthority|verifyOrchestrationCompatibilityCaller|launchTokenHash|launchToken" "$1"
' sh {}

echo "===== sequenced launch callers =="
rg -n -C 8 "createSequencedSetupAgentCommands|SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV|resolveSetupAgentSequence|SequencedSetupAgentCommands" src/main src/shared

echo "===== command finished scanner implementation =="
cat -n src/shared/terminal-osc133-command-finished.ts

Repository: stablyai/orca

Length of output: 50370


Gate command-finished launch-authority retirement to the agent exiting.

command-finished is emitted for any foreground command exit, including the setup command in createSequencedSetupAgentCommands. retirePtyAgentLaunchAuthority clears pty.launchToken, deletes the restored receipt, and retires hook compatibility for every pane key, so the setup step can deny authorization for the agent that starts after it. Retire only on a foreground-agent exit or an incarnation/generation-scoped launch exit.

Comment on lines 225 to +228
export type MessageRow = {
id: string
run_id: string
delivery_contract?: MessageDeliveryContract

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make delivery_contract mandatory.

The migration defines messages.delivery_contract as NOT NULL, but this optional field permits projections and constructed MessageRow values to omit it. src/main/runtime/orchestration/formatter.ts then classifies an omitted value as current authority, rather than legacy read-only.

Require delivery_contract on MessageRow and update every row producer and projection to provide an explicit value.

Proposed type change
 export type MessageRow = {
   id: string
   run_id: string
-  delivery_contract?: MessageDeliveryContract
+  delivery_contract: MessageDeliveryContract
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export type MessageRow = {
id: string
run_id: string
delivery_contract?: MessageDeliveryContract
export type MessageRow = {
id: string
run_id: string
delivery_contract: MessageDeliveryContract

Comment on lines +44 to +68
export function verifyAttestedLegacyCandidate(args: {
runtime: OrcaRuntimeService
evidence?: OrchestrationCompatibilityEvidence
candidate: LegacyPrincipalCandidate
}) {
const authority = args.runtime.verifyOrchestrationCompatibilityCaller(args.evidence)
if (
!authority ||
!equivalentLegacyPaneKey(args.candidate.paneKey, authority.paneKey) ||
args.candidate.terminalHandle !== authority.terminalHandle
) {
throw legacyReadOnlyError()
}
if (
args.candidate.role === 'worker' &&
args.candidate.dispatchId &&
!args.runtime.getOrchestrationDb().isDispatchProcessCurrent({
dispatchId: args.candidate.dispatchId,
paneKey: authority.paneKey,
processIncarnation: authority.processIncarnation
})
) {
throw legacyReadOnlyError()
}
return authority

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🔴 Critical | 🏗️ Heavy lift

Compare the caller token with the committed token before reuse.

This check validates the caller token with the runtime, but it never compares authority.launchTokenHash with the immutable LegacyCompatibilityPrincipalRow.launch_token_hash. candidateFromPrincipal() also drops that value. Existing-principal paths can therefore authorize a different launch that reuses the same pane, handle, and process identity.

Carry the committed hash in LegacyPrincipalCandidate. Reject the request when the candidate hash is absent or differs from authority.launchTokenHash. Apply the same fail-closed rule to dispatch-derived candidates.

Comment on lines +50 to +58
} else {
const question = params.question as string
const options = parseLegacyOptions(params.options)
const recipient = params.to as string
const operation = operationIdentity(request, 'ask', {
question: normalizeLegacyText(question),
options: options.map(normalizeLegacyText),
recipient
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate params.question like params.to.

Line 28 rejects a missing --to for non-resume asks. No equivalent check exists for params.question. Line 51 casts it with as string, so an omitted question flows into normalizeLegacyText, into operationIdentity, and into db.commitLegacyAskOperation as undefined. The result is a persisted question row with no body, and the semantic-identity dedupe keys on that empty value. Reject the missing argument next to the existing --to check.

🛡️ Proposed validation
   if (!params.resume) {
+    if (!params.question) {
+      throw new OrchestrationError('invalid_argument', 'Legacy ask requires --question.')
+    }
     if (!params.to) {
       throw new OrchestrationError('invalid_argument', 'Legacy ask requires --to.')
     }

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

🛑 Comments failed to post (4)
src/main/ssh/ssh-relay-session.ts (1)

1167-1178: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Compare the not-found and identity-mismatch SSH PTY error predicates.
set -euo pipefail

rg -n -C 10 'isSshPtyNotFoundError|isSshPtyIdentityMismatchError' src --type=ts -g '!**/*.test.ts'

Repository: stablyai/orca

Length of output: 16787


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "PWD: $(pwd)"
echo "Repository files around target/predicates:"
git ls-files | rg '(^|/)ssh-relay-session\.ts$|(^|/)ssh-pty-errors\.ts$|(^|/)ssh-pty-provider|(^|/)ssh-pty-session-reattach\.ts$|(^|/)pty\.ts$' || true

echo
echo "Predicate definitions:"
cat -n src/main/providers/ssh-pty-errors.ts

echo
echo "Relevant catch block:"
sed -n '1138,1182p' src/main/ssh/ssh-relay-session.ts | nl -ba -v1138

echo
echo "Relevant attach helper around error classification:"
sed -n '56,84p' src/main/providers/ssh-pty-session-reattach.ts | nl -ba -v56

echo
echo "Search for SSH_PTY_IDENTITY_MISMATCH_ERROR and related text usage:"
rg -n -C 5 'SSH_PTY_IDENTITY_MISMATCH_ERROR|identity mismatch|PTY ".*" not found|pty\.attach|attach FAILED' src/main providers src/shared 2>/dev/null | head -n 240

Repository: stablyai/orca

Length of output: 1479


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Relevant catch block:"
sed -n '1138,1190p' src/main/ssh/ssh-relay-session.ts

echo
echo "Relevant attach helper around error classification:"
sed -n '56,85p' src/main/providers/ssh-pty-session-reattach.ts

echo
echo "Behavioral probe for current predicates:"
node - <<'JS'
const SSH_PTY_IDENTITY_MISMATCH_ERROR = 'SSH_PTY_IDENTITY_MISMATCH'
function isSshPtyNotFoundError(error) {
  const message = error instanceof Error ? error.message : String(error)
  return /PTY ".+" not found/i.test(message)
}
function isSshPtyIdentityMismatchError(error) {
  const message = error instanceof Error ? error.message : String(error)
  return message.includes(SSH_PTY_IDENTITY_MISMATCH_ERROR) || /identity mismatch/i.test(message)
}
for (const message of [
  'PTY "abc123" not found',
  'SSH_PTY_IDENTITY_MISMATCH some details',
  'relay identity mismatch details',
]) {
  console.log(JSON.stringify({
    message,
    notFound: isSshPtyNotFoundError(new Error(message)),
    identityMismatch: isSshPtyIdentityMismatchError(new Error(message)),
    wouldBeReorderedToSkipContinuation: isSshPtyIdentityMismatchError(new Error(message)) && isSshPtyNotFoundError(new Error(message))
  }))
}
JS

Repository: stablyai/orca

Length of output: 4261


Reorder stale-PTY error handling so identity mismatches are checked first.

isSshPtyIdentityMismatchError matches a separate SSH_PTY_IDENTITY_MISMATCH/identity-mismatch message, while isSshPtyNotFoundError requires PTY "..." not found. Since attach throws identity mismatches as their own error rather than a not-found error, the if (!isSshPtyNotFoundError(err)) check rethrows it and aborts the whole reattach loop. Check isSshPtyIdentityMismatchError(err) before the not-found guard so stale PTYs can be skipped without tearing down the session.

src/renderer/src/hooks/useIpcEvents.ts (1)

2728-2728: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

The exact watermark match disables reconciliation before the first push event.

reconcileSshAuthority receives watermark from Line 2798 as sshStateWatermarkByTargetId.get(targetId) ?? 0. The map gains an entry only in handleSshStateChangedEvent (Line 2841). For a target that has not yet produced a push event, the caller passes 0 while sshStateWatermarkByTargetId.get(targetId) returns undefined. The new strict comparison then evaluates undefined !== 0 as true and returns early, so initial-hydration reconciliation never applies the fetched providerEpoch and connectionGeneration. Normalize the absent entry to 0 on both sides.

🐛 Proposed fix
-            sshStateWatermarkByTargetId.get(targetId) !== watermark
+            (sshStateWatermarkByTargetId.get(targetId) ?? 0) !== watermark
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

            (sshStateWatermarkByTargetId.get(targetId) ?? 0) !== watermark
src/renderer/src/store/slices/agent-status.ts (1)

1772-1775: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether a test pins provider-session retention across working -> done without metadata.providerSession.
fd -t f 'agent-status-provider-session.test.ts' --exec rg -n -C6 "done" {}
rg -nP --type=ts -C4 'retainsResumableRecoveryIdentity'

Repository: stablyai/orca

Length of output: 1320


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and inspect the relevant slice and any related tests without modifying repository files.
git ls-files '*agent-status*' | sed -n '1,80p'

printf '\n--- agent-status slice relevant sections ---\n'
if [ -f src/renderer/src/store/slices/agent-status.ts ]; then
  wc -l src/renderer/src/store/slices/agent-status.ts
  sed -n '1740,1830p' src/renderer/src/store/slices/agent-status.ts
  sed -n '1920,2010p' src/renderer/src/store/slices/agent-status.ts
fi

printf '\n--- focused rg for session retention variables ---\n'
rg -n --type=ts -C 5 'providerSession|retAINSResumableRecoveryIdentity|liveRecoveryWorktreeId|sleepingAgentSessionsByPaneKey' src/renderer/src/store || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- agent-status slice relevant sections ---\n'
if [ -f src/renderer/src/store/slices/agent-status.ts ]; then
  wc -l src/renderer/src/store/slices/agent-status.ts
  sed -n '1740,1830p' src/renderer/src/store/slices/agent-status.ts
  sed -n '1920,2010p' src/renderer/src/store/slices/agent-status.ts
fi

printf '\n--- focused rg for session retention variables in agent-status ---\n'
rg -n -C 5 'retainsResumableRecoveryIdentity|liveRecoveryWorktreeId|sleepingAgentSessionsByPaneKey|providerSession|canReuseExistingProviderSession' src/renderer/src/store/slices/agent-status.ts src/renderer/src/store/slices/agent-status-*.test.ts || true

printf '\n--- tests around working -> done without metadata.providerSession ---\n'
rg -n -C 8 'working.*done|done.*working|without metadata|metadata providerSession|without metadata' src/renderer/src/store/slices/agent-status-*.test.ts || true

Repository: stablyai/orca

Length of output: 242


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- agent-status slice relevant sections ---'
if [ -f src/renderer/src/store/slices/agent-status.ts ]; then
  wc -l src/renderer/src/store/slices/agent-status.ts
  sed -n '1740,1830p' src/renderer/src/store/slices/agent-status.ts
  sed -n '1920,2010p' src/renderer/src/store/slices/agent-status.ts
fi

printf '%s\n' ''
printf '%s\n' '--- focused rg for session retention variables in agent-status ---'
rg -n -C 5 'retainsResumableRecoveryIdentity|liveRecoveryWorktreeId|sleepingAgentSessionsByPaneKey|providerSession|canReuseExistingProviderSession' src/renderer/src/store/slices/agent-status.ts src/renderer/src/store/slices/agent-status-*.test.ts || true

printf '%s\n' ''
printf '%s\n' '--- tests around working -> done without metadata.providerSession ---'
rg -n -C 8 'working.*done|done.*working|without metadata|metadata providerSession|without metadata' src/renderer/src/store/slices/agent-status-*.test.ts || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import re
from pathlib import Path

slice_path = Path("src/renderer/src/store/slices/agent-status.ts")
src = slice_path.read_text()

m = re.search(r'const providerSession =\n(.*?)\n *const existingProviderSession', src, re.S)
print("--- providerSession resolution ---")
if not m:
    print("missing providerSession block")
else:
    print(m.group(0))

retains = re.search(r'const retainsResumableRecoveryIdentity =\n(.*?)\n *const matchedSleepingLaunchConfig', src, re.S)
print("\n--- retainsResumableRecoveryIdentity ---")
if retains:
    print(retains.group(0))

live = re.search(r'const liveRecoveryWorktreeId =\n(.*?)\n *const liveRecoveryRecord =', src, re.S)
print("\n--- liveRecoveryWorktreeId ---")
if live:
    print(live.group(0))

# Simulate the relevant expression for a working -> done update with no metadata.providerSession.
existing = {"agentType": "codex", "state": "working", "providerSession": {"key": "session_id", "id": "root-session"}}
identity = {"agentType": "codex", "inheritedFromActivePane": False}
payload = {"state": "done", "prompt": "finish the task"}
metadata = {}

def is_resumable_tui_agent(agent_type):
    return agent_type in {"codex", "claude"}

can_reuse_existing_provider_session = (
    existing.get("agentType") == identity["agentType"]
    and existing["state"] != "done"
    and payload["state"] != "done"
)
provider_session = metadata.get("providerSession") or (existing["providerSession"] if can_reuse_existing_provider_session else None)
retains_resumable_recovery_identity = (
    payload["state"] == "done"
    and is_resumable_tui_agent(identity["agentType"])
    and provider_session is not None
)
recovery_wid_cond = "live" if provider_session is not None else None
print("\n--- working -> done without metadata.providerSession under current condition ---")
print("canReuseExistingProviderSession:", can_reuse_existing_provider_session)
print("providerSession:", provider_session)
print("retainsResumableRecoveryIdentity:", retains_resumable_recovery_identity)
print("liveRecoveryWorktreeId:", recovery_wid_cond)

can_reuse_narrow = existing.get("agentType") == identity["agentType"] and existing["state"] != "done"
provider_session_narrow = metadata.get("providerSession") or (existing["providerSession"] if can_reuse_narrow else None)
retains_resumable_recovery_identity_narrow = (
    payload["state"] == "done"
    and is_resumable_tui_agent(identity["agentType"])
    and provider_session_narrow is not None
)
recovery_wid_cond_narrow = "live" if provider_session_narrow is not None else None
print("\n--- working -> done without metadata.providerSession under narrower condition ---")
print("canReuseExistingProviderSession:", can_reuse_narrow)
print("providerSession:", provider_session_narrow)
print("retainsResumableRecoveryIdentity:", retains_resumable_recovery_identity_narrow)
print("liveRecoveryWorktreeId:", recovery_wid_cond_narrow)
PY

Repository: stablyai/orca

Length of output: 1431


Keep the provider session when a resumable agent reaches done. payload.state !== 'done' makes providerSession undefined for a working → done update that omits metadata.providerSession, so retainsResumableRecoveryIdentity becomes false, liveRecoveryWorktreeId becomes null, and the resumed agent loses its persistent session anchor. Only block re-inheritance for an already-done state.

src/renderer/src/web/web-preload-api.ts (1)

1365-1378: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Trace runtimeEnvironments disconnect/connect contract and callers.
set -euo pipefail
rg -n 'runtimeEnvironments' -C 4 src/preload/api-types.ts
rg -n 'runtimeEnvironments\.(disconnect|remove|connect)\b' -C 4 src/renderer src/shared
rg -n 'disconnectActiveRuntimeEnvironment' -C 6 src/renderer/src/web/web-preload-api.ts

Repository: stablyai/orca

Length of output: 6567


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== outline RuntimeEnvironmentsPane =="
ast-grep outline src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx --view compact || true

echo "== relevant RuntimeEnvironmentsPane sections =="
sed -n '400,620p' src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx | cat -n

echo "== SshStatusSegment disconnect section =="
sed -n '230,275p' src/renderer/src/components/status-bar/SshStatusSegment.tsx | cat -n

echo "== preload/types full runtimeEnvironments signature =="
sed -n '3304,3365p' src/preload/api-types.ts | cat -n

echo "== tests mentioning disconnect/remove/list web =="
rg -n 'disconnect|removed|disconnected|activeRuntimeEnvironmentId|clearStoredWebRuntimeEnvironment|runtimeEnvironments' src/renderer/src/web/web-preload-api.test.ts src/renderer/src/web -C 3

echo "== all active runtime environment setters/clearers =="
rg -n '(activeEnvironment|activeEnvironmentId|clearStoredWebRuntimeEnvironment|saveStoredWebRuntimeEnvironment|setStoredWebRuntimeEnvironment|addFromPairingCode|remove|disconnect)' src -C 2

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== RuntimeEnvironmentsPane relevant sections =="
sed -n '500,585p' src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx | cat -n
sed -n '1360,1405p' src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx | cat -n

echo "== SshStatusSegment relevant sections =="
sed -n '220,265p' src/renderer/src/components/status-bar/SshStatusSegment.tsx | cat -n

echo "== web preload api methods around runtimeEnvironments =="
sed -n '1350,1385p' src/renderer/src/web/web-preload-api.ts | cat -n

echo "== web preload tests around runtime environments =="
sed -n '240,290p' src/renderer/src/web/web-preload-api.test.ts | cat -n

echo "== all definitions and usages of clearStoredWebRuntimeEnvironment/addFromPairingCode/connectEnvironment =="
rg -n 'clearStoredWebRuntimeEnvironment|saveStoredWebRuntimeEnvironment|setStoredWebRuntimeEnvironment|addFromPairingCode|connectEnvironment|disconnectRuntimeHost|runtimeEnvironments.addFromPairingCode|runtimeEnvironments.connect' src/preload src/renderer/src -C 2

Repository: stablyai/orca

Length of output: 32539


Keep disconnect from clearing stored web pairing state.

disconnectEnvironment documents disconnect as non-destructive and can be followed by connectEnvironment, so runtimeEnvironments.disconnect() on web should only clear active clients/status, not activeEnvironment and the stored environment. remove is the operation that deletes the saved server.

@danshapiro

Copy link
Copy Markdown
Author

Closing this for now — the PR diff is not what it should be.

The branch was forked from the v1.4.162 release lineage (e058429), which is not an ancestor of this repo's main (16c5526). As a result the PR diff shows 45 commits / 240 files instead of the actual change (34 commits / 50 files): ~11 already-merged commits from the release lineage (e.g. #11271, #11423, #11453, #11472, #11521, #11528, #11530) rode along under different SHAs, dragging ~190 unrelated files into the diff. That's why greptile hit its 100-file limit and why nearly all of CodeRabbit's findings land on files this change never touched.

The fix itself (codex state-DB prewarm + backfill-gated codex launches for #11828) is complete and E2E-verified. We'll reopen (or open a fresh PR) once the 34 commits are rebased onto main proper, with gates re-run against that base.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

5 participants