Repository navigation
fix(codex): gate codex launches on state-DB backfill and pre-warm the session index (fixes #11828) - #11981
fix(codex): gate codex launches on state-DB backfill and pre-warm the session index (fixes #11828)#11981danshapiro wants to merge 45 commits into
Conversation
…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]>
Co-authored-by: Orca <[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]>
… pane (stablyai#11828) 🤖 Generated with [Amplifier](https://github.com/microsoft/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.
…n gate (stablyai#11828) 🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier) Co-Authored-By: Amplifier <[email protected]>
…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]>
…ill is pending (stablyai#11828) 🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier) Co-Authored-By: Amplifier <[email protected]>
…ablyai#11828) 🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier) Co-Authored-By: Amplifier <[email protected]>
…fill (stablyai#11828) 🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier) Co-Authored-By: Amplifier <[email protected]>
…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.
… while the backfill runs (stablyai#11828)
…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).
|
Too many files changed for review. ( Bypass the limit by tagging |
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (240)
💤 Files with no reviewable changes (17)
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (2 passed)
✨ Finishing Touches 💡 1⚔️ Resolve merge conflicts 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
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 winRestore
completed_aton the dispatch failure update.This update sets
statustofailedorcircuit_brokenbut leavescompleted_atNULL. Every other terminal path in this file records it:failWorkerStart(Line 4034),reconcileMissingWorkerTerminal(Line 4228),settleWorkerStop(Line 5141), andsettleWorkerReportInTransaction(Line 5614).The NULL value is also read as an open-ended lifetime.
backfillLegacyQuestionThreadsbounds legacy question inference withAND (completed_at IS NULL OR completed_at >= ?)(Line 998). A dispatch failed throughfailDispatchtherefore 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 winBound or prune
mutation_receiptsafter completion.Completed mutation receipts are never deleted;
completeMutationReceiptonly marks the rowcompleted, andresetAllretains 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 winCase-sensitive failure detection can silently misclassify failed legacy workers as succeeded.
inferLegacyWorkerOutcomeonly 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 legacyworker_donemessage 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 winSpecify the fenced-code language.
Line 146 starts a shell-code fence without a language. Add
shto satisfy markdownlint MD040.Source: Linters/SAST tools
src/cli/bundled-skill-guides.ts-12-12 (1)
12-12: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winSynchronize the bundled
orca-cliguide.
ORCA_CLI_MARKDOWNstill says that--agentreveals the new worktree.skill-guides/orca-cli.mdLines 150-151 now state that--agentalone 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 winWrap the
restoredserver intry/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 usestry/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 winMatch before truncating the buffer.
Line 32 truncates
normalizedto the lastDETECTOR_BUFFER_MAX_CHARScharacters, 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. Searchnormalizedfirst, 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 winIgnore the initial pull after a push arrives.
paneHoldStatusresolves asynchronously. If main broadcastsphase: 'launched'before that promise settles, the push clears the overlay first, and the stale pulledindexingsnapshot 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 winCache the Codex-launch check before the backfill observer.
dataCallbackruns on every incoming chunk, butresolveExpectedLaunchTuiAgent()readsuseAppStore.getState()and scanstabsByWorktree[...]on each call even though the expected launch agent is set from the stable spawn/startup context. ResolveisExpectedCodexLaunchonce, 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 winCheck that
getDefaultWslDistroresolves the actualwsl.exedefault distro.
listWslDistros()useswsl.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 bywsl.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 winClear the Codex indexing entry when a pane closes.
codexIndexingStatesByPaneIdis keyed by numericpaneId, and only the indexing callback removes entries.onPaneClosedinuse-terminal-pane-lifecycle.tsclears the sibling map throughonPtyRecoveryStateRef?.current?.(paneId, null)at line 1188, but it never callsonCodexIndexingStateRef. 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 winReject waiters when the rolled-back surface handle is removed.
invalidateLeafHandlerejects pending waiters withterminal_handle_stale. This rollback path deletes the same maps without that step. Waiters registered throughwaitForTerminalon the removed handle can no longer be satisfied, so they block until their timeout, up toTUI_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 winRoute
emulator.*diagnostics through both dispatch paths.
dispatch()logs emulator RPC requests, but non-streaming methods handled bydispatchStreaming()can also beemulator.*calls. AddemulatorProbebefore the non-streaming handler andemulatorProbeErroraround 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 winUse 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 winUse provider-neutral review-link wording in both Linear strings.
The shared Linear skill copy uses GitHub-specific
PRorpull requestterminology. Replace it withreview linkorpull/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: UpdateattachPr,attachPrSummary, andattachPrPrompt.src/renderer/src/i18n/locales/ja.json#L9498-L9498: UpdatehowToUseDescription.Source: Coding guidelines
src/renderer/src/i18n/locales/zh.json-3781-3781 (1)
3781-3781: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUse 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 winImport the legacy run id for this assertion.
src/main/runtime/rpc/methods/orchestration.tscompares againstORCHESTRATION_LEGACY_RUN_IDfrom../../../../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 winAdd the new
SmartWorkspaceNameFieldplaceholder translationsThese 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 valueRemove the redundant overload declarations.
The implementation signature at Line 57 already assigns a default value to
options. This alone makesoptionsoptional 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 valueCompute
owneronce and apply onetabIdrule.
parsePaneKey(toPaneKey)runs three times at lines 1436, 1450, and 1466 and always returns the same value. The two authority blocks also treattabIddifferently: line 1457 keeps the previoustabIdwhen the new one is absent, and line 1473 overwrites it withundefined.toPaneKeypassedisValidPaneKeyat line 1423, soowner?.tabIdis always present today and the behavior matches. Unify the rule so a future change toisValidPaneKeycannot make the two paths diverge.src/renderer/src/components/mobile/MobilePage.test.tsx (1)
84-96: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the manual-address retention path.
MobilePage.tsxnow tracksaddressIsManualand 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 fromlistNetworkInterfaces, selects a manual address throughbeforeCustomAddressChangeplushandleAddressChange, then triggersloadNetworkInterfacesagain 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 winDecouple the refresh effect from
loadNetworkInterfacesidentity.
loadNetworkInterfacessetsselectedAddressandaddressIsManual, and both values are in itsuseCallbackdependency 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 redundantlistNetworkInterfacesIPC call after the first resolution and after eachhandleAddressChange. 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 winDerive 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
stampWslOrchestrationCompatibilityHostwrites. 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 valueUse newlines for the PowerShell script encoding.
-EncodedCommandsupports 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 valueStale line-number citations in the duplicated
pending-indexrationale. 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: replaceinstallRetryAfterMs (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-270andindex.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 winMemoize the pending Codex backfill probe.
ensureRealHomeCodexHookStateruns in sync launch prep each time the system-default real home is selected. Inpending-indexorremovedstates before retry, the gate still callsisCodexBackfillIndexPending(), which opens the Codexstate_*.sqliteDB and walks~/.codex/sessionsfor.jsonlfiles. Keep the lane deferred but cache the pending result untilretryRealHomeCodexHookAfterIndex()clears it.src/main/runtime/relay/relay-revoke-outbox.test.ts (1)
50-67: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd an assertion that proves the failed enqueue left no in-memory item.
The current assertions pass in both implementations. After the failed
enqueue, the secondenqueuemints a new item because the in-memory list is empty, so disk holds one item. If the implementation retained the failed item, the secondenqueuewould return that same item through the dedupe branch and persist it, so disk would again hold exactly one item matchingpersisted. 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 = falsesrc/main/runtime/rpc/orchestration-legacy-coordinator-authority.ts (1)
129-144: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winDo not cast a possibly missing handle to
string.
identity.terminalHandle ?? (identity.terminal_handle as string)yieldsundefinedtyped asstringwhen both fields are absent. The candidate then carriesundefinedat 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 winRestore 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.tsLines 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 thatsetPortForwardsandsetDetectedPortsare not called.I can draft that test if you want.
src/renderer/src/hooks/useIpcEvents.ts (1)
2660-2676: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winBound 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
listPortForwardsorlistDetectedPortsdoes 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 winCondense 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 winReuse the freshest inventory instead of refetching per candidate.
Each candidate performs two extra
listProcessesround trips (preAdoptionInventoryhere,finalInventoryat Line 4252). With the shared inventory at Line 4066 the cost is1 + 2Nserial RPCs per provider, each bounded byPTY_CONTROLLER_LIST_TIMEOUT_MS. On the SSH relay-ready path this delays recovery of every later candidate.The post-adoption
finalInventoryis 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 valueExtract the private-field cast into one helper.
The same cast to reach the private
dbfield 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 winReset
dbandtempDirinafterEach.This hook closes
dband removestempDirbut keeps both references. The sibling suites reset them: seeorchestration-legacy-coordinator-authority-db.test.tsLines 14-21 andorchestration-legacy-storage-db.test.tsLines 19-26.Without the reset, a test that fails before it assigns
dbleaves the previous instance in the variable.afterEachthen callsclose()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 winClose the database handles if seeding throws.
firstandraware closed only on the success path. If any seeding call between Line 30 and Line 184 throws, the handle stays open andtempDirkeeps a locked SQLite file. On Windows the caller'srmSyncthen fails and reports a cleanup error instead of the real seeding failure.Wrap each phase in
try/finallysoclose()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/finallyaround therawhandle at Lines 160-186.src/main/runtime/orchestration/orchestration-version-skew-migration.test.ts (1)
183-191: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThis test does not yet prove that the database is left unrepaired.
Line 187 exercises the pure resolver, which is useful. Line 188 cannot fail:
resolveOrchestrationMigrationStartVersiononly readsuser_version, so no code between Lines 187 and 188 can change it.The test name promises the repair is skipped. To cover that, construct
OrchestrationDbagainst a database whose stored version exceedsSCHEMA_VERSION, then assert the legacy rows keep their originalrun_idand that nolegacy_adoptionsrow appears. That exercises the early return inmigrate().Also note the literal
19no longer matches the declaredSCHEMA_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 winUse 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.tsreads that key throughORCA_BACKFILL_GATED_COMMAND_ENV, imported fromsrc/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
fallbackCommandand 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 winAssert the adopted run exists before you read its
id.The
!on.find(...)producesCannot 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.tsLine 1114. Consider matching onlegacy = 0plus 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!.idsrc/main/runtime/orchestration/orchestration-schema-version-skew.ts (1)
58-73: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winImport
ORCHESTRATION_LEGACY_RUN_IDinstead of hardcoding'run_legacy_local'.
db.tsaliasesLEGACY_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, returnstrue, and skips repair. Import it from'../../../shared/orchestration-rpc-contract'soLEGACY_RUN_IDstays available elsewhere.Also move the
legacy_adoptionsquery below thesourceGraphearly 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 winReuse the declared handle and pane constants.
These
bindRuncalls repeat the literals'term_current_coord'and'tab_current:55555555-5555-4555-8555-555555555555'. The file already declaresCURRENT_COORDINATOR_HANDLEandCURRENT_COORDINATOR_PANEfor those values, and the mockedverifyOrchestrationCompatibilityCallerkeys 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 winAnnounce 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.tsxusesrole="status"witharia-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 valueThe
Date.nowstub couples this test to the exact number of clock reads.clockReads === 1 ? 0 : clockReads === 2 ? 1 : 120_001returns the expired value for every read after the second. Any newDate.now()call on the check path (for example athread_${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 usevi.useFakeTimers()withvi.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 winTwo 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 transportinvoke, 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: importcreateHarness,evidence,request,invoke, the pane and handle constants, andcleanupLegacyCompatibilityDispatcherHarnessesfrom./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 twoverifyOrchestrationCompatibilityCallermocks so one implementation serves both suites. The race copy also requireslaunchToken === 'coordinator-token'or'worker-token', while the fixture accepts any non-emptylaunchToken. Adopt the stricter token check, or expose it as a fixture option, and letrequestaccept 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 valueReuse
informationalinshowDaemonRestart.!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 winDerive the codex notice match from
CODEX_BACKFILL_INDEXING_NOTICE.TerminalErrorToast.tsxduplicates the first line ofcodex-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 winAdd a case for a backslash home combined with
toShellViewPath.buildCodexBackfillGateWrapperpicks the path separator fromparams.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 passtoShellViewPath. 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 valueReuse
noopUnsubscribefor 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 winKeep horizontal overflow control on the tab strip.
The custom
w-full justify-start gap-4 px-0overrides can removeoverflow-x-auto, and the fixed-width dialog withflex-nonetabs 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
📒 Files selected for processing (240)
config/reliability-gates.jsoncconfig/scripts/orchestration-skill-guidance.test.mjsdocs/plans/2026-07-31-codex-backfill-prewarm.mddocs/plans/2026-08-01-codex-backfill-prewarm.mddocs/reference/plans/2026-07-28-orchestration-seamless-update-migration.mdnative/windows-cli-launcher/OrcaCliLauncher.cspackage.jsonrenderer-worktree-freeze-incident-2026-07-29.mdskill-guides/orca-cli.mdskill-guides/orchestration.mdsrc/cli/bundled-skill-guides.tssrc/cli/handlers/orchestration-check-identity.test.tssrc/cli/handlers/orchestration-legacy-read-only.test.tssrc/cli/handlers/orchestration-migration.test.tssrc/cli/handlers/orchestration-run-cli.test.tssrc/cli/handlers/orchestration-timeout-cli.test.tssrc/cli/handlers/orchestration-timeout.test.tssrc/cli/handlers/orchestration-windows-ask-cli.test.tssrc/cli/handlers/orchestration.test.tssrc/cli/handlers/orchestration.tssrc/cli/handlers/worktree.tssrc/cli/index.test.tssrc/cli/runtime-client.test.tssrc/cli/runtime/client.tssrc/cli/runtime/orchestration-compatibility-envelope.tssrc/cli/runtime/runtime-request-timeout.tssrc/cli/runtime/transport.tssrc/cli/runtime/types.test.tssrc/cli/runtime/types.tssrc/cli/specs/orchestration.tssrc/main/agent-hooks/server-authority-evidence.test.tssrc/main/agent-hooks/server.test.tssrc/main/agent-hooks/server.tssrc/main/cli/windows-launcher-asset.test.tssrc/main/codex/codex-backfill-spawn-hold.test.tssrc/main/codex/codex-backfill-spawn-hold.tssrc/main/codex/codex-managed-hook-slot-reconciliation.tssrc/main/codex/codex-real-home-hook-install.test.tssrc/main/codex/codex-real-home-hook-install.tssrc/main/codex/codex-session-migration-scheduler.test.tssrc/main/codex/codex-session-migration-scheduler.tssrc/main/codex/codex-state-db-prewarm.test.tssrc/main/codex/codex-state-db-prewarm.tssrc/main/codex/codex-state-db.test.tssrc/main/codex/codex-state-db.tssrc/main/daemon/daemon-history-handoff.tssrc/main/daemon/daemon-pty-router-history-handoff.test.tssrc/main/daemon/daemon-pty-router.test.tssrc/main/daemon/daemon-pty-router.tssrc/main/daemon/headless-emulator.tssrc/main/daemon/terminal-host-wsl-context.test.tssrc/main/daemon/wsl-session-context.tssrc/main/index.tssrc/main/ipc/codex-backfill-status.test.tssrc/main/ipc/codex-backfill-status.tssrc/main/ipc/mobile.test.tssrc/main/ipc/mobile.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/ipc/register-core-handlers.test.tssrc/main/ipc/register-core-handlers.tssrc/main/persistence.test.tssrc/main/persistence.tssrc/main/providers/local-pty-provider.test.tssrc/main/providers/local-pty-provider.tssrc/main/pty/wsl-orca-env.test.tssrc/main/pty/wsl-orca-env.tssrc/main/rate-limits/codex-fetcher.test.tssrc/main/rate-limits/codex-fetcher.tssrc/main/runtime/device-registry.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/orchestration-compatibility-authority.test.tssrc/main/runtime/orchestration/db.test.tssrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/formatter.test.tssrc/main/runtime/orchestration/formatter.tssrc/main/runtime/orchestration/orchestration-legacy-coordinator-authority-db.test.tssrc/main/runtime/orchestration/orchestration-legacy-question-migration-db.test.tssrc/main/runtime/orchestration/orchestration-legacy-storage-db.test.tssrc/main/runtime/orchestration/orchestration-legacy-storage-test-fixture.tssrc/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.tssrc/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.tssrc/main/runtime/orchestration/orchestration-schema-version-skew.tssrc/main/runtime/orchestration/orchestration-version-skew-migration.test.tssrc/main/runtime/orchestration/orchestration-worker-dispatch-db.test.tssrc/main/runtime/orchestration/types.tssrc/main/runtime/relay/relay-revoke-outbox.test.tssrc/main/runtime/relay/relay-revoke-outbox.tssrc/main/runtime/rpc/core.tssrc/main/runtime/rpc/dispatcher-error-response.tssrc/main/runtime/rpc/dispatcher-feature-interactions.test.tssrc/main/runtime/rpc/dispatcher-stream-options.tssrc/main/runtime/rpc/dispatcher.tssrc/main/runtime/rpc/errors.tssrc/main/runtime/rpc/methods/orchestration-federation-control-mail.test.tssrc/main/runtime/rpc/methods/orchestration-federation.test.tssrc/main/runtime/rpc/methods/orchestration-federation.tssrc/main/runtime/rpc/methods/orchestration-gates.tssrc/main/runtime/rpc/methods/orchestration-runs.tssrc/main/runtime/rpc/methods/orchestration-worker-topology.tssrc/main/runtime/rpc/methods/orchestration-workers-new-worktree.test.tssrc/main/runtime/rpc/methods/orchestration-workers.tssrc/main/runtime/rpc/methods/orchestration.test.tssrc/main/runtime/rpc/methods/orchestration.tssrc/main/runtime/rpc/orchestration-legacy-authority.tssrc/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher-test-fixture.tssrc/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher.test.tssrc/main/runtime/rpc/orchestration-legacy-compatibility.tssrc/main/runtime/rpc/orchestration-legacy-coordinator-authority.tssrc/main/runtime/rpc/orchestration-legacy-coordinator-race.test.tssrc/main/runtime/rpc/orchestration-legacy-lifecycle.tssrc/main/runtime/rpc/orchestration-legacy-mail.tssrc/main/runtime/rpc/orchestration-legacy-operation.tssrc/main/runtime/rpc/orchestration-legacy-process-identity.tssrc/main/runtime/rpc/orchestration-legacy-question-takeover.test.tssrc/main/runtime/rpc/orchestration-legacy-question.tssrc/main/runtime/rpc/orchestration-legacy-takeover-dispatcher.test.tssrc/main/runtime/rpc/orchestration-mutation-executor.tssrc/main/runtime/rpc/orchestration-mutation-ledger.test.tssrc/main/runtime/rpc/runtime-feature-interaction.tssrc/main/runtime/runtime-rpc.test.tssrc/main/runtime/runtime-rpc.tssrc/main/ssh/ssh-relay-session-reconnect-incarnation.test.tssrc/main/ssh/ssh-relay-session.tssrc/main/ssh/ssh-remote-cli-host-passthrough.test.tssrc/main/ssh/ssh-remote-cli-host-passthrough.tssrc/main/ssh/ssh-remote-cli-in-process-result.tssrc/main/ssh/ssh-remote-orca-cli.test.tssrc/main/ssh/ssh-remote-orca-cli.tssrc/main/ssh/ssh-remote-orchestration-ask-output.tssrc/main/ssh/ssh-remote-orchestration-check-output.tssrc/main/ssh/ssh-remote-orchestration-compatibility.test.tssrc/main/ssh/ssh-remote-orchestration-post-output.tssrc/main/startup/desktop-startup-ordering.test.tssrc/main/startup/legacy-worker-renderer-recovery.test.tssrc/main/startup/legacy-worker-renderer-recovery.tssrc/main/window/attach-main-window-services.test.tssrc/main/window/attach-main-window-services.tssrc/preload/api-types.tssrc/preload/index.tssrc/relay/relay.tssrc/relay/remote-cli-env.test.tssrc/relay/remote-cli-env.tssrc/renderer/src/App.tsxsrc/renderer/src/app-startup-routing.test.tssrc/renderer/src/assets/mobile-page.csssrc/renderer/src/components/mobile/MobileHero.test.tsxsrc/renderer/src/components/mobile/MobileHero.tsxsrc/renderer/src/components/mobile/MobileHeroPairingStep.tsxsrc/renderer/src/components/mobile/MobilePage.test.tsxsrc/renderer/src/components/mobile/MobilePage.tsxsrc/renderer/src/components/mobile/MobilePageContent.tsxsrc/renderer/src/components/mobile/mobile-relay-mint-failure-notice.tsxsrc/renderer/src/components/mobile/use-mobile-pairing-generation.tssrc/renderer/src/components/mobile/use-mobile-pairing-qr-invalidation.tssrc/renderer/src/components/new-workspace/ProjectCombobox.tsxsrc/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsxsrc/renderer/src/components/new-workspace/smart-workspace-command-value.test.tssrc/renderer/src/components/new-workspace/smart-workspace-source-results.test.tssrc/renderer/src/components/settings/MobilePairingConnectionOptions.test.tsxsrc/renderer/src/components/settings/MobilePairingConnectionOptions.tsxsrc/renderer/src/components/settings/MobilePairingQrSection.test.tsxsrc/renderer/src/components/settings/MobilePairingQrSection.tsxsrc/renderer/src/components/settings/MobilePairingSetupSection.test.tsxsrc/renderer/src/components/settings/MobilePairingSetupSection.tsxsrc/renderer/src/components/settings/MobilePane.test.tsxsrc/renderer/src/components/settings/MobilePane.tsxsrc/renderer/src/components/sidebar/Sidebar.test.tsxsrc/renderer/src/components/sidebar/index.tsxsrc/renderer/src/components/sidebar/single-flight-coalescer.test.tssrc/renderer/src/components/sidebar/single-flight-coalescer.tssrc/renderer/src/components/terminal-pane/CodexIndexingOverlay.test.tsxsrc/renderer/src/components/terminal-pane/CodexIndexingOverlay.tsxsrc/renderer/src/components/terminal-pane/TerminalErrorToast.test.tssrc/renderer/src/components/terminal-pane/TerminalErrorToast.tsxsrc/renderer/src/components/terminal-pane/TerminalPane.tsxsrc/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.tssrc/renderer/src/components/terminal-pane/codex-backfill-error-detector.tssrc/renderer/src/components/terminal-pane/codex-backfill-pane-hold.test.tssrc/renderer/src/components/terminal-pane/codex-backfill-pane-hold.tssrc/renderer/src/components/terminal-pane/pty-connection-types.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/terminal-linkifier-click-priming.test.tssrc/renderer/src/components/terminal-pane/terminal-linkifier-click-priming.tssrc/renderer/src/components/terminal-pane/terminal-url-link-click.test.tssrc/renderer/src/components/terminal-pane/terminal-url-link-hit-testing.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.tssrc/renderer/src/constants/terminal.tssrc/renderer/src/hooks/ipc-events-test-harness.tssrc/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.tssrc/renderer/src/hooks/legacy-worker-terminal-recovery-event.tssrc/renderer/src/hooks/useIpcEvents.test.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/renderer/src/lib/launch-ai-vault-session.test.tssrc/renderer/src/lib/launch-ai-vault-session.tssrc/renderer/src/lib/pane-manager/pane-manager-types.tssrc/renderer/src/lib/pane-manager/pane-manager.tssrc/renderer/src/lib/pane-manager/pane-split-close.tssrc/renderer/src/lib/resume-sleeping-agent-session-legacy-worker.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.tssrc/renderer/src/lib/terminal-reveal-identity.test.tssrc/renderer/src/lib/terminal-reveal-identity.tssrc/renderer/src/store/slices/agent-pane-authority.test.tssrc/renderer/src/store/slices/agent-status-provider-session.test.tssrc/renderer/src/store/slices/agent-status.tssrc/renderer/src/web/web-preload-api.tssrc/shared/agent-session-resume.tssrc/shared/codex-backfill-gate-wrapper.test.tssrc/shared/codex-backfill-gate-wrapper.tssrc/shared/codex-backfill-status-types.tssrc/shared/crash-reporting.test.tssrc/shared/crash-reporting.tssrc/shared/mobile-relay-mint-failure.test.tssrc/shared/mobile-relay-mint-failure.tssrc/shared/new-workspace/smart-workspace-command-value.tssrc/shared/new-workspace/smart-workspace-source-results.tssrc/shared/orchestration-check-output.test.tssrc/shared/orchestration-check-output.tssrc/shared/orchestration-compatibility-evidence.test.tssrc/shared/orchestration-compatibility-evidence.tssrc/shared/orchestration-message-wait-timeout.tssrc/shared/remote-runtime-client.tssrc/shared/runtime-rpc-envelope.tssrc/shared/runtime-types.tssrc/shared/setup-agent-sequencing.test.tssrc/shared/setup-agent-sequencing.tssrc/shared/terminal-reveal-identity.tssrc/shared/workspace-session-sleeping-agents.tstests/e2e/global-setup.tstests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.tstests/e2e/orchestration-legacy-worker-restart-recovery.spec.tstests/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
| 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)) | ||
| } | ||
| }) |
There was a problem hiding this comment.
🎯 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.
| 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) | ||
| }) | ||
| }) | ||
| } |
There was a problem hiding this comment.
🎯 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.
| 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) | |
| } | |
| } |
| } 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) | ||
| }) | ||
| } |
There was a problem hiding this comment.
🎯 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.
| 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) |
There was a problem hiding this comment.
🗄️ 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.
| 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) |
| 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 | ||
| } |
There was a problem hiding this comment.
🩺 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" srcRepository: 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.
| onCommandFinished: (exitCode: number | null) => { | ||
| this.retirePtyAgentLaunchAuthority(ptyId) | ||
| this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode }) | ||
| }, |
There was a problem hiding this comment.
🎯 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/mainRepository: 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.tsRepository: 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.
| export type MessageRow = { | ||
| id: string | ||
| run_id: string | ||
| delivery_contract?: MessageDeliveryContract |
There was a problem hiding this comment.
🗄️ 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.
| export type MessageRow = { | |
| id: string | |
| run_id: string | |
| delivery_contract?: MessageDeliveryContract | |
| export type MessageRow = { | |
| id: string | |
| run_id: string | |
| delivery_contract: MessageDeliveryContract |
| 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 |
There was a problem hiding this comment.
🔒 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.
| } 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 | ||
| }) |
There was a problem hiding this comment.
🗄️ 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.')
}There was a problem hiding this comment.
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 240Repository: 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)) })) } JSRepository: stablyai/orca
Length of output: 4261
Reorder stale-PTY error handling so identity mismatches are checked first.
isSshPtyIdentityMismatchErrormatches a separateSSH_PTY_IDENTITY_MISMATCH/identity-mismatch message, whileisSshPtyNotFoundErrorrequiresPTY "..." not found. Sinceattachthrows identity mismatches as their own error rather than a not-found error, theif (!isSshPtyNotFoundError(err))check rethrows it and aborts the whole reattach loop. CheckisSshPtyIdentityMismatchError(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.
reconcileSshAuthorityreceiveswatermarkfrom Line 2798 assshStateWatermarkByTargetId.get(targetId) ?? 0. The map gains an entry only inhandleSshStateChangedEvent(Line 2841). For a target that has not yet produced a push event, the caller passes0whilesshStateWatermarkByTargetId.get(targetId)returnsundefined. The new strict comparison then evaluatesundefined !== 0as true and returns early, so initial-hydration reconciliation never applies the fetchedproviderEpochandconnectionGeneration. Normalize the absent entry to0on 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) !== watermarksrc/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 || trueRepository: 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 || trueRepository: 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 || trueRepository: 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) PYRepository: stablyai/orca
Length of output: 1431
Keep the provider session when a resumable agent reaches
done.payload.state !== 'done'makesproviderSessionundefined for aworking→doneupdate that omitsmetadata.providerSession, soretainsResumableRecoveryIdentitybecomesfalse,liveRecoveryWorktreeIdbecomesnull, 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.tsRepository: 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 2Repository: 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 2Repository: stablyai/orca
Length of output: 32539
Keep
disconnectfrom clearing stored web pairing state.
disconnectEnvironmentdocumentsdisconnectas non-destructive and can be followed byconnectEnvironment, soruntimeEnvironments.disconnect()on web should only clear active clients/status, notactiveEnvironmentand the stored environment.removeis the operation that deletes the saved server.
|
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 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 |
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_stateis notcomplete, Orca supervises a headless codex that runs the index to completion. It also adopts/resumes a stalerunninglease 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_statecheck. If the index is incomplete, trust-grant is deferred using a newpending-indexlane state instead of latching the laneunavailable.Previously, that
unavailablestate 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'sunavailablesemantics.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
e058429e1(GPU startup flags, WSL pty routing, and hook transport budget—environment-specific on the reporter's WSL2 machine).HOMEwith 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.Reviewer notes
5c638031bis a mechanical i18n catalog parity sync (es/ja/ko/zh, produced by the repo's ownsync:localization-catalog) repairing a pre-existing parity failure that blocks the lint gate. Values are English fallbacks, not translations—drop it ifmainfixes parity separately.codexBackfill:status) currently has no consumer beyond the overlay wiring and is a candidate for removal.Generated with Amplifier