Repository navigation
fix(agent-launch): make a lost launch safe to retry - #21106
Conversation
📝 WalkthroughWalkthroughThe change adds durable replay support for named Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Callerless recovery can settle another caller’s operation when identifiers collide, while some failed or malformed launches replay inconsistently. Resolve these issues before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed and covers the change, rationale, testing, compatibility, and review status. However, the required linked issue is missing because the description states “N/A — no linked issue was provided,” while the template requires one.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 6acb4930-0628-4cc7-b332-5518e4c2149c
📒 Files selected for processing (15)
src/main/runtime/agent-session-claim-key-retention.tssrc/main/runtime/agent-session-record-store.test.tssrc/main/runtime/agent-session-record-store.tssrc/main/runtime/rpc/methods/agent-launch-replay.test.tssrc/main/runtime/rpc/methods/agent-launch-replay.tssrc/main/runtime/rpc/methods/agent-launch-surfaces.tssrc/main/runtime/rpc/methods/agent-launch.test-fixture.tssrc/main/runtime/rpc/methods/agent-launch.test.tssrc/main/runtime/rpc/methods/agent-launch.tssrc/shared/agent-launch-intent.tssrc/shared/agent-launch-operation.tssrc/shared/agent-session-mutation-envelope.tssrc/shared/agent-session-operation-ledger.tssrc/shared/protocol-version.tssrc/shared/rpc-contract/agent-launch-params.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| function agentLaunchFailureCode(error: unknown): string { | ||
| const code = error instanceof Error ? error.message : '' | ||
| return code.length > 0 ? code : 'agent_launch_failed' |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '145,215p' src/main/runtime/rpc/methods/agent-launch.ts
sed -n '1,120p' src/main/native-chat/agent-session-wire/structured-agent-session-replay-outcome.ts
rg -n "agentLaunchFailureCode|admission\.fail|resolveAgentSessionReplayOutcome|AGENT_SESSION_WIRE_REFUSAL_CODES" src/main src/shared
sed -n '240,290p' src/main/runtime/rpc/methods/agent-launch-replay.test.tsRepository: stablyai/orca
Length of output: 10696
🏁 Script executed:
#!/bin/bash
set -e
sed -n '1,150p' src/main/native-chat/agent-session-wire/structured-agent-session-mutation-admission.ts
sed -n '1,130p' src/main/runtime/rpc/methods/agent-launch-replay.ts
cat -n src/shared/agent-session-wire-refusals.ts
sed -n '1,180p' src/shared/agent-session-operation-ledger.ts
rg -n -C 4 "type .*Rpc|class .*Rpc|throw new Error|error\.message|serialize.*error|defineMethod|RpcError|RPC" src/main/runtime/rpc src/shared | head -n 260
rg -n -C 4 "admission\.fail|fail\(.*code|function fail|fail:" src/main src/shared | head -n 220Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
sed -n '1,150p' src/main/native-chat/agent-session-wire/structured-agent-session-mutation-admission.ts
sed -n '1,130p' src/main/runtime/rpc/methods/agent-launch-replay.ts
cat -n src/shared/agent-session-wire-refusals.ts
sed -n '1,180p' src/shared/agent-session-operation-ledger.ts
rg -n -C 3 "admission\\.fail|function fail|fail:" src/main src/shared | head -n 220Repository: stablyai/orca
Length of output: 39672
🏁 Script executed:
sed -n '1,150p' src/main/native-chat/agent-session-wire/structured-agent-session-mutation-admission.ts
sed -n '1,130p' src/main/runtime/rpc/methods/agent-launch-replay.ts
cat -n src/shared/agent-session-wire-refusals.ts
sed -n '1,180p' src/shared/agent-session-operation-ledger.ts
rg -n -C 3 "admission\.fail|function fail|fail:" src/main src/shared | head -n 220Repository: stablyai/orca
Length of output: 40259
🏁 Script executed:
#!/bin/bash
set -e
sed -n '120,280p' src/main/runtime/rpc/methods/agent-launch-replay.ts
sed -n '130,300p' src/main/runtime/rpc/methods/agent-launch.ts
rg -n "function runSettledAgentSessionMutation|runSettledAgentSessionMutation|fail:|settleAgentSessionOperation|message:" src/main/native-chat/agent-session-wire/structured-agent-session-operation-settlement.ts src/main/runtime/agent-session-record-store.ts src/main/runtime/rpc/methods/agent-launch-replay.ts src/main/runtime/rpc/methods/agent-launch.ts
rg -n "class RpcDispatcher|handler\(.*context|catch \(error|error instanceof Error|error\.message|result.*error|JSON.*error" src/main/runtime/rpc/dispatcher.ts src/main/runtime/rpc/core.ts src/main/runtime/rpcRepository: stablyai/orca
Length of output: 25327
🏁 Script executed:
#!/bin/bash
set -e
sed -n '1,190p' src/main/runtime/rpc/dispatcher.ts
sed -n '130,270p' src/main/runtime/rpc/errors.ts
sed -n '1,100p' src/main/runtime/rpc/dispatcher-error-response.ts
sed -n '1,180p' src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts
rg -n -C 5 "function resolveUnlaunchedIntent|resolveUnlaunchedIntent|throw new Error" src/main/runtime/rpc/methods/agent-launch*.ts src/main/runtime | head -n 180
rg -n -C 3 "agent_launch|worktree_not_found|selector_not_found|operation_invalid" src/main/runtime/rpc/methods/agent-launch*.test.ts src/main/runtime/rpc/methods/agent-launch*.tsRepository: stablyai/orca
Length of output: 36476
🏁 Script executed:
#!/bin/bash
set -e
sed -n '1,145p' src/main/runtime/rpc/errors.ts
rg -n -C 3 "RUNTIME_PASSTHROUGH_CODES|agent_session_operation_invalid|agent_session_operation_unknown|worktree_not_found" src/main/runtime/rpc/errors.ts src/main/runtime/rpc/*.test.ts src/main/runtime/rpc/methods/agent-launch*.test.ts
sed -n '1,125p' src/main/runtime/rpc/methods/agent-launch.ts
rg -n -C 5 "function agentLaunchIntent|agentLaunchIntent" src/main shared src/main/runtime | head -n 120Repository: stablyai/orca
Length of output: 16931
🏁 Script executed:
#!/bin/bash
set -e
sed -n '280,345p' src/main/runtime/agent-session-record-store.ts
rg -n -C 5 "AgentSessionOperationOutcome|status.*failed|outcome\.code|recordOperationOutcome|validate.*outcome|parse.*outcome" src/main/runtime/agent-session-record-store.ts src/main/runtime/agent-session-record-store-file.ts src/sharedRepository: stablyai/orca
Length of output: 45139
Normalize pre-execution failure codes before recording and throwing them.
A rejection from resolveUnlaunchedIntent can reach this handler before launch creation. agentLaunchFailureCode copies any non-empty Error.message, and admission.fail persists that value as outcome.code. Outcome validation accepts any string. On replay, resolveAgentSessionReplayOutcome maps codes outside AGENT_SESSION_WIRE_REFUSAL_CODES to agent_session_operation_invalid, while the first attempt rethrows the original error. The same operation can therefore return different RPC error codes across attempts.
Persist an allowed stable code with the original text in outcome.message, and throw the normalized code on the first attempt. Pass both values through admission.fail. The RPC contract derives the error code from Error.message, so do not retain the original text in the thrown error while normalizing only the persisted code.
| (targetKey ? key === targetKey : row.operationId === args.operationId) && | ||
| !supersedesSettledOutcome(row.outcome, args.outcome) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
sed -n '80,170p' src/shared/agent-session-operation-ledger.ts
rg -n "settleAgentSessionOperation|settleOperation|callerKey" src/main src/shared | head -240Repository: stablyai/orca
Length of output: 34067
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- all settlement call sites ---'
rg -n -C 8 'settleAgentSessionOperation\s*\(' src
printf '%s\n' '--- record-store settlement methods ---'
sed -n '270,335p' src/main/runtime/agent-session-record-store.ts
printf '%s\n' '--- acquisition-failure settlement ---'
sed -n '1,150p' src/main/runtime/agent-session-acquisition-failure-settlement.ts
printf '%s\n' '--- operation settlement implementation ---'
sed -n '1,180p' src/main/native-chat/agent-session-wire/structured-agent-session-operation-settlement.ts
printf '%s\n' '--- ledger admission and row shape ---'
sed -n '1,125p' src/shared/agent-session-operation-ledger.ts
sed -n '180,255p' src/shared/agent-session-operation-ledger.tsRepository: stablyai/orca
Length of output: 24581
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- recordOperationOutcome callers and declarations ---'
rg -n -C 10 'recordOperationOutcome|RecordOutcome|operation outcome' src/main src/shared
printf '%s\n' '--- restart reconciliation symbols ---'
rg -n -C 12 'collectAgentSessionRestartProbes|applyAgentSessionRestartProbes|RestartProbe|unreconciled|operationId' src/main/runtime src/shared | head -500
printf '%s\n' '--- lease and restart identity fields ---'
rg -n -C 8 'handoffOperationId|operationId.*caller|callerKey.*operationId|lease.*caller|unreconciled' src/main/runtime src/shared | head -500Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- restart caller ---'
sed -n '1,115p' src/main/native-chat/agent-session-wire/structured-agent-session-handoff-restart.ts
printf '%s\n' '--- restart invocation and dependencies ---'
rg -n -C 12 'restoreStructured|restart.*handoff|reconcile.*handoff|structured-agent-session-handoff-restart|restore\(' src/main/native-chat/agent-session-wire src/main/runtime | head -280
printf '%s\n' '--- operation admission and duplicate-id behavior ---'
sed -n '1,125p' src/main/runtime/agent-session-operation-admission.ts
rg -n -C 8 'same.*operation|operationId.*client|callerKey.*operationId|operation:.*operationId' src/shared src/main/runtime --glob '*.test.ts' | head -240Repository: stablyai/orca
Length of output: 50369
Preserve caller partitioning during callerless settlement.
When callerKey is absent, settleAgentSessionOperation updates every row with the same operationId. Admission keys rows by (callerKey, operationId), so different callers can have the same operation ID.
restoreStructuredAgentSessionHandoff omits callerKey and records a failed or succeeded outcome. A restart for one caller can therefore overwrite another caller's pending row with the wrong terminal outcome. That caller may replay an incorrect result or receive a refusal instead of executing its operation.
Persist the caller identity with the handoff operation and pass it during restart settlement. As a safety boundary, reject callerless settlement when multiple rows match the operation ID.
There was a problem hiding this comment.
Important
One fix needed before merge: the new test file is binary to Git, so none of its content is reviewable and it can never be blamed or line-diffed again. Everything else checks out.
Reviewed changes
Read the full 15-file diff end to end and exercised the new guards locally: the four touched/near test files (99 pass) plus the whole src/main/native-chat/agent-session-wire suite (574 pass), confirming the monotone-settlement change does not break existing settlement callers. No failing check runs on 9ab1a98.
- Optional
operationIdonagent.launch— new top-level param in the shipped${13-digit-ms}-${32-hex}shape the structured ledger already keys on, regex-validated and optional forever. - Host-computed fingerprint over the parsed intent, name excluded and mutable host settings excluded, so a moved default does not conflict an honest retry.
- Admission before live preconditions — the ledger now runs ahead of workspace-selector resolution, so a replay answers from the record instead of being re-decided against today's world.
- Atomic execution claim —
claimAgentSessionOperation(pending → unknown, reportswon/lost/absent) replaces the blind settle; only the winner runs. - Whole launch result persisted on the widened
succeededarm (optionallaunch, emptysessionIdfor a PTY), with read-time validation inisAgentLaunchResult. - Derived child operation id for the inner attach, so the launch row and its attach row cannot collide under one caller key.
- Monotone settlement — a late
unknowncannot clobber a recordedsucceeded/failed. - New
agent.launch.replay.v1host capability, plus the test-fixture extraction and the claim-key-retention split out of the store.
⚠️ The new test file is binary to Git
src/main/runtime/rpc/methods/agent-launch-replay.test.ts embeds two literal NUL bytes — the ledger's key separator — in the template literals at the new Map([[...]]) rows. Git therefore classifies the file i/-text w/-text, and git diff --merge-base origin/main renders it as Binary files differ: the entire 447-line test suite, which is this PR's main evidence for the concurrency guard, is invisible in review and will never appear in a line-level diff or git blame again. This is exactly the shape the repo's own notes call out as a real maintainability defect.
Technical details
# Test file is binary to Git
## Affected sites
- `src/main/runtime/rpc/methods/agent-launch-replay.test.ts:301` and `:322` — the key is built as `\`device-1<NUL>${OPERATION_ID}\``, writing a raw NUL byte into the source.
## Required outcome
- The file reads as plain text to Git (`git ls-files --eol` reports `i/lf w/lf`), so it diffs and blames normally.
## Suggested approach
- Build the key with the exported helper instead of inlining the separator: `agentSessionOperationKey('device-1', OPERATION_ID)` from `src/shared/agent-session-operation-ledger.ts`, or at minimum the `'\u0000'` escape.ℹ️ A retry that arrives while the launch is still running is refused, not joined
The claim moves the row to unknown for the whole duration of the effect, and answerFromRecordedRow treats a persisted unknown as terminal, so a second request with the same id while the first is mid-create gets agent_session_operation_unknown rather than the eventual result. The concurrent-callers test asserts this (exactly one fulfilled, one rejected), so it is deliberate — but it is a behavioral regression relative to the dedupeWorktreeCreate path it replaces, which joined the in-flight promise. Worth confirming in the client-adoption PR that agent_session_operation_unknown is treated as "still running, ask again later" rather than a terminal create failure (mobile/.../worktree-create-retry.ts:127 currently breaks out of the retry loop on anything that is not a name-collision message).
Technical details
# Concurrent replay is refused rather than awaited
## Affected sites
- `src/main/runtime/rpc/methods/agent-launch-replay.ts:131-138` — a `lost` claim whose row is `unknown` returns the refusal.
- `src/main/runtime/rpc/methods/agent-launch-replay.test.ts:124-137` — pins one-winner/one-rejection for two concurrent callers.
- `mobile/src/tasks/worktree-create-retry.ts:127` — retry loop stops on any message that is not a worktree-name collision.
## Required outcome
- Decide explicitly whether an in-flight replay should await the live execution (safe — no second effect) or keep refusing, and make the client-side handling of the refusal explicit when `operationId` is adopted.
## Open questions for the human
- Is the in-flight refusal intended as the long-term contract, or a stopgap until a live-execution join / reconcile-before-decide lands in the deferred recovery PR?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Review pass — fixed on the branch,
|
6256ed0 to
6350a7f
Compare
There was a problem hiding this comment.
ℹ️ No critical issues — one behavior/comment mismatch worth tightening.
Reviewed changes
Re-reviewed the follow-up commit 6256ed05 against prior pullfrog review 5229367084. The delta is the unreadable-payload handling, the verbatim failed replay, the failure-code bound, and the tests/comments around them.
- Launch payload is no longer gated by the row guard —
outcome.launchis typedunknownand dropped fromisAgentSessionOperationRow, so a payload this build cannot read refuses one replay instead of making the whole store unparseable. - Recorded failures replay their real code —
answerFromRecordedRowreturns afailedrow's owncoderather than narrowing it through the closedagentSession.*vocabulary. - Failure codes are bounded on write —
agentLaunchFailureCodesliceserror.messageto 128 chars before persisting. - Tests rebuilt around the guards — the store-level ablation now substitutes the non-atomic claim into the handler's own store and asserts two worktrees; new guards cover the unreadable payload, the verbatim failure replay, and the code bound.
- Comment-only — the caller-key namespace note in
agent-launch-surfaces.ts.
Verified locally this run: agent-launch-replay.test.ts and agent-launch.test.ts both green (47 tests).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
The commits since the last review are a rebase onto newer main: the prompt receipt became an outcome union (journaled / handed-to-terminal / not-delivered), agent.launch.v2 replaced v1, and the PR's isAgentLaunchResult was reconciled to the new shape via isAgentLaunchPromptReceipt. Approval is withheld only because an inline comment from the previous review is still open — not because of anything in this delta.
Reviewed changes
- Prompt-receipt validator reconciled to the outcome union —
isAgentLaunchPromptReceiptvalidates all three disposal arms and requiresmessageIdonly on thejournaledarm. - Replay test expectation updated — the recorded structured draft now asserts
{ delivery: 'draft', outcome: 'not-delivered' }. - Base-branch sync —
agent.launch.v2, the top-level warning shape, andAgentLaunchModeReasonarrived frommain; the legacy create-guard comment moved intorunLegacyAgentLaunch.
Re-ran both touched suites at 6350a7f: 48 pass.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
6350a7f to
7efa515
Compare
There was a problem hiding this comment.
ℹ️ No critical issues — the follow-up is sound; the PR description needs a sync.
Reviewed changes
Re-reviewed the follow-up commit 7efa5156d0 against prior pullfrog review 5229573124. The delta is an in-process join for live retries, a tightening of the replay caller identity, and the tests around both.
- Live retries join in-process — a per-runtime map keyed on
(callerKey, operationId)hands a second identical request the in-flight promise, so a retry that lands mid-execution gets the eventual result instead ofagent_session_operation_unknown; a same-key request with a different fingerprint is refusedagent_session_operation_conflictbefore admission. - Replay identity tightened to a stable subject —
agentLaunchOperationCallerKeyrequires a paired-device id for remote callers (refusingagent_session_identity_requiredwhen absent) and usestrusted-local:runtimeonly for in-process callers; the rotatingclientIdfallback is gone. - The inner attach shares the launch's caller key —
runAgentLaunchpassesadmission.callerKeyinto the surface factory, so a replay-safe launch's nestedagentSession.attachreserves in the same partition as the launch, with the derived child id keeping the two rows distinct. - The binary-file defect is fixed — the test's ledger keys are built with
agentSessionOperationKey(...), sogit ls-files --eolnow reportsi/lf w/lfand the file diffs and blames normally. - New coverage — join and in-process conflict, replay across a rotated bearer credential, the unpaired-identity refusal with zero side effects, and the
agent_session_operation_unknowncode survivingRpcDispatcher.
agent-launch-replay.test.ts + agent-launch.test.ts: 50 pass; typecheck:node clean.
ℹ️ The PR description no longer matches the identity model
Item 7 of "What changed" still documents caller identity as pairedDeviceId ?? clientId ?? 'local' with the rotating bearer credential as a documented fallback, but agentLaunchOperationCallerKey now refuses a remote caller with no paired device rather than falling back to clientId. The "Tests" section also still describes a handler-level ablation that 7efa5156d0 removed: the deleted test substituted the non-atomic claim into the handler and asserted two worktrees, while what remains is a store-level test asserting one winner from two claimOperation calls. Worth updating both before the client-adoption work reads this description as the contract.
Technical details
# PR description drift after the retry-join commit
## Affected sites
- PR body "What changed" item 7 — states `pairedDeviceId ?? clientId ?? 'local'`; `src/main/runtime/rpc/methods/agent-launch-replay.ts:31-42` now throws `agent_session_identity_required` for a remote caller without a paired device.
- PR body "Tests" concurrency bullet — describes a handler-level ablation removed in `7efa5156d0`.
## Required outcome
- The description states the identity rule the code enforces, so client adoption gates on pairing instead of discovering the refusal at runtime.
- The concurrency bullet describes the tests that actually exist.
## Open questions for the human
- Should `agent.launch.replay.v1` stay advertised unconditionally in `RUNTIME_CAPABILITIES` now that only a paired-device caller can use it, or is "capability plus paired identity" the intended contract?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Hidden Electron QA — replay-safe
|
| Check | Result |
|---|---|
| Overlapping identical retry | Same worktreeId and terminal handle term_98981131-d7bd-48ee-9ec6-2a2cfac91ae9; create ran once |
| Changed-intent reuse | agent_session_operation_conflict |
| Post-settlement replay | Exact recorded result (sameAsFirst: true) |
| Ledger | 1 succeeded row with full launch payload; 1 unknown row after kill |
| After restart retry of claimed-unsettled id | agent_session_operation_unknown; still 2 worktrees (fixture main + replay-qa-one) |
| Host capabilities | agent.launch.v2 and agent.launch.replay.v1 advertised |
Remaining gaps
- No shipped desktop/mobile UI mints
operationIdonagent.launch, so this could not be driven from a user control. - Isolated profile defaulted to a terminal Claude surface (
user_default), not structured native chat. - Folder-workspace target was not separately launched (git worktree create was the stronger retry path).
- Did not wait through Claude's trust prompt to a later turn; the launch effect is the workspace + one agent terminal.
Screenshot paths (untracked): /tmp/orca-pr21106-validation/screenshots/replay-qa-one-workspace.png, /tmp/orca-pr21106-validation/screenshots/replay-qa-one-after-restart.png.
`agent.launch` could not be retried safely. Only a create-worktree target carrying a clientMutationId got any idempotency at all, and that was a 60s in-memory cache with no caller partition that dies with the process; an existing-workspace launch got none. Mobile retries a lost create by design, so the retry is the ordinary case — and a retry past that cache meant a second worktree and a second agent. A caller may now name its launch with an optional `operationId` and get one execution, the recorded answer on every replay, and a truthful refusal when the outcome is unknown. Admission runs before the worktree selector is resolved, so a replay answers from the record rather than re-deciding against today's world. The core is an atomic claim. Admission alone cannot decide who runs: two replays both read `pending`, and settling `unknown` replaces the outcome blind, so two serialized writes are not a compare-and-swap and both callers execute. A conditional current-state swap now reports which caller won, and settlement is monotone so a late `unknown` cannot erase a recorded success. Also here: a host-computed fingerprint over the launch intent that excludes mutable settings, the full launch result persisted so a replay returns the receipt and warning that cannot be recomputed once settings move, and a derived child operation id for the inner attach — the ledger key carries no method, so forwarding the launch id would make the attach conflict with its own launch. Safety, not recovery. Nothing here probes for a surface a dead attempt left behind, adopts one, or finishes an interrupted publication. Callers that send no `operationId` keep today's behaviour exactly, which is why the field is optional and the host advertises `agent.launch.replay.v1`: an older host strips an unknown param and launches anyway, so a client may only treat a retry as safe once the host has said it enforces the ledger.
… store Review follow-ups on the replay-safety ledger. A recorded `launch` payload must not gate row validity. `isAgentLaunchResult` is a hand-maintained mirror of a result type later work will edit, and `isAgentSessionOperationRow` is consulted by the store loader, where one rejected row makes the whole file unparseable — a primary and backup that both fail to parse raise `agent_session_store_corrupt` and the profile loses every lease. That is the same argument the row already makes for keeping `sessionId` required, applied to the field this PR added. The payload is now typed `unknown`, left out of the row guard, and narrowed where it is read, so a payload this build cannot read refuses exactly one replay. A recorded failure now replays as the code the launch raised. Narrowing it through the closed `agentSession.*` refusal list answered `worktree_not_found` with `agent_session_operation_invalid` — the ledger's "your id is malformed" signal, which invites a client to mint a fresh id when the truthful answer is that this launch definitively did not run and the same id is safe to retry. The persisted failure code is bounded on the way in. A code is an identifier, but `error.message` is free text: an errno sentence carrying an absolute path arrived here as one and was written into a file re-serialized whole on every later operation. Bounded on write only — a length check in the row validator would reject rows this same build wrote, which is the hazard above. Comments: the caller key does not give one client a single namespace across surfaces, because the structured attach this launch performs partitions under `structuredCallerFor`; the two coincide only for a bearer-identity caller with no paired device, which is exactly when the derived child id is load-bearing. Recorded as a known limit that a `lost` claim cannot tell a sibling executing now from one a restart abandoned; telling them apart needs execution-generation tagging, which is recovery. Tests: the store-level ablation was inert — it defined a local stand-in and passed identically with and without the guard. It now substitutes the non-atomic composition into the handler's own store and watches one tap create two workspaces. Each of the four new guards was watched failing against the unfixed code: `agent_session_store_corrupt` on reopen, `expected false to be true` on the row guard, `agent_session_operation_invalid` in place of `worktree_not_found`, and a 6042-character code where 128 is the bound.
7efa515 to
47b6314
Compare
Review complete — ready to land as host-side groundworkMerge conflicts are resolved, the branch is rebased on the current The opening readiness audit, two implementation review loops, an independent architecture/precedent challenge, and the closing readiness audit are complete. The closing audit found no remaining P0, P1, or P2 issues. Meaningful fixes made during review:
Architecture judgment: pass for this host-side safety layer. A stable caller/operation identity owns a durable record, an intent fingerprint prevents conflicting reuse, the durable claim moves to Functional, compatibility, security, and performance review: pass with the limits below. The replay records are bounded and expiring, live entries are removed in Validation is green:
Remaining limits:
Status: ready to land as host-side groundwork. |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: c0f9c7ba-e927-4567-8ee9-630fe9006208
📥 Commits
Reviewing files that changed from the base of the PR and between 6256ed05d71bd551e3cd296306a1b7f58ac9d328 and d60ff2d.
📒 Files selected for processing (16)
src/main/runtime/agent-session-claim-key-retention.tssrc/main/runtime/agent-session-record-store.test.tssrc/main/runtime/agent-session-record-store.tssrc/main/runtime/rpc/methods/agent-launch-replay.test.tssrc/main/runtime/rpc/methods/agent-launch-replay.tssrc/main/runtime/rpc/methods/agent-launch-surfaces.tssrc/main/runtime/rpc/methods/agent-launch.test-fixture.tssrc/main/runtime/rpc/methods/agent-launch.test.tssrc/main/runtime/rpc/methods/agent-launch.tssrc/shared/agent-launch-intent.tssrc/shared/agent-launch-operation.tssrc/shared/agent-session-host-authority.tssrc/shared/agent-session-mutation-envelope.tssrc/shared/agent-session-operation-ledger.tssrc/shared/protocol-version.tssrc/shared/rpc-contract/agent-launch-params.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/runtime/agent-session-record-store.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| await settleQuietly(admission.fail(agentLaunchFailureCode(error))) | ||
| throw error |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '150,235p' src/main/runtime/rpc/methods/agent-launch.ts
sed -n '75,125p' src/main/runtime/rpc/methods/agent-launch-replay.ts
rg -n "RpcError|error\.message|throw new Error|serialize.*error|dispatch" src/main/runtime/rpc src/shared | head -240Repository: stablyai/orca
Length of output: 34569
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- dispatcher candidates ---'
fd -i 'dispatcher|error' src/main/runtime/rpc -t f | head -80
printf '%s\n' '--- dispatcher outline ---'
ast-grep outline src/main/runtime/rpc/dispatcher.ts
printf '%s\n' '--- dispatcher error handling ---'
rg -n -C 8 'catch|error:|message|serialize|RpcError|instanceof Error|dispatch' src/main/runtime/rpc/dispatcher.ts src/main/runtime/rpc/core.ts src/main/runtime/rpc/errors.ts 2>/dev/null | head -260
printf '%s\n' '--- replay and operation contracts ---'
rg -n -C 6 'answerFromRecordedRow|admission\.fail|refusal|operation.*failed|status.*failed|message' src/main/runtime/rpc/methods src/shared | head -300Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
set -eu
sed -n '1,280p' src/main/runtime/rpc/dispatcher.ts
printf '\n--- RPC error helpers ---\n'
fd -i 'error' src/main/runtime/rpc -t f | head -40
rg -n -C 8 'serialize|serializeError|instanceof Error|catch \(error|error\.message|response\.error|RpcError' src/main/runtime/rpc --glob '*.ts' | head -320
printf '\n--- replay refusal definitions ---\n'
rg -n -C 12 'answerFromRecordedRow|admission\.fail|refusal:|status: .failed.|outcome\.code|outcome\.message' src/main/runtime/rpc/methods src/shared --glob '*.ts' | head -320Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
set -eu
printf '%s\n' '--- dispatcher error mapping ---'
cat -n src/main/runtime/rpc/dispatcher-error-response.ts
printf '%s\n' '--- relevant error mapping tests ---'
rg -n -C 12 'non-Error|plain|unknown|throw.*string|mapDispatcherError|runtime_error|message' src/main/runtime/rpc/*test.ts | head -260
printf '%s\n' '--- package target and Error cause usage ---'
rg -n -C 3 '"target"|"lib"|Error\(.*cause|cause:' package.json tsconfig*.json src/main/runtime/rpc src/shared --glob '*.ts' | head -180Repository: stablyai/orca
Length of output: 30717
🏁 Script executed:
set -eu
cat -n src/main/runtime/rpc/dispatcher-error-response.ts
printf '\n--- direct mapper references and tests ---\n'
rg -n -C 10 'mapDispatcherError|mapRuntimeError|non-Error|String\(error\)|error\.message|runtime_error' \
src/main/runtime/rpc/dispatcher-error-response.ts \
src/main/runtime/rpc/errors.ts \
src/main/runtime/rpc/*test.ts | head -320Repository: stablyai/orca
Length of output: 30487
Throw the recorded failure code.
For an Error message longer than 128 characters, line 216 records the truncated code, but mapRuntimeError serializes the original message for the first request. The replay path throws the recorded code, so the client-visible RPC messages differ. A non-Error throw can also serialize differently from the recorded agent_launch_failed code.
Compute the code once. Record and throw that code.
Proposed fix
} catch (error) {
- await settleQuietly(admission.fail(agentLaunchFailureCode(error)))
- throw error
+ const code = agentLaunchFailureCode(error)
+ await settleQuietly(admission.fail(code))
+ throw new Error(code, { cause: error })
}| return ( | ||
| (receipt.mode === 'structured' || receipt.mode === 'terminal') && | ||
| (receipt.preferred === 'structured' || receipt.preferred === 'terminal') && | ||
| typeof receipt.reason === 'string' && |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '108,206p' src/shared/agent-launch-intent.ts
rg -n -C 3 '\bAgentLaunchModeReason\b' src/shared src/mainRepository: stablyai/orca
Length of output: 11077
Validate the persisted launch-mode reason.
AgentLaunchModeReason is a closed union of ten string literals, but isAgentLaunchModeReceipt accepts every string. An unsupported persisted value can therefore pass isAgentLaunchResult as a valid AgentLaunchResult. Replace the string check with an explicit check for all allowed reason values.
|
@brennanb2025 Your explicit separation of live joining, settled replay and post-claim uncertainty was useful for our agent-runtime experiments. At d60ff2d we ran the original durable store and admission code against real temporary files: saved synthetic outcomes replayed after reopening the store, changed intent conflicted, and a claimed-but-unsettled operation remained unknown. Eight concurrent admissions produced one execute and seven unknown refusals at that lower boundary; we did not run the full handler, launch a real agent, or repeat your Electron kill/restart QA. The experiment helped us separate "do not duplicate the action" from "help the operator establish what happened." I saw that you already name both client adoption and reconciliation as follow-up scope. When a client does adopt this, would exposing a read-only receipt containing the stable caller/operation identity and any known resource references be a useful first step for investigating unknown outcomes, even before adoption/recovery exists? The question is about giving the operator evidence without encouraging a fresh launch ID, not adding recovery to this PR. |
* feat(agent-launch): make a lost launch safe to retry `agent.launch` could not be retried safely. Only a create-worktree target carrying a clientMutationId got any idempotency at all, and that was a 60s in-memory cache with no caller partition that dies with the process; an existing-workspace launch got none. Mobile retries a lost create by design, so the retry is the ordinary case — and a retry past that cache meant a second worktree and a second agent. A caller may now name its launch with an optional `operationId` and get one execution, the recorded answer on every replay, and a truthful refusal when the outcome is unknown. Admission runs before the worktree selector is resolved, so a replay answers from the record rather than re-deciding against today's world. The core is an atomic claim. Admission alone cannot decide who runs: two replays both read `pending`, and settling `unknown` replaces the outcome blind, so two serialized writes are not a compare-and-swap and both callers execute. A conditional current-state swap now reports which caller won, and settlement is monotone so a late `unknown` cannot erase a recorded success. Also here: a host-computed fingerprint over the launch intent that excludes mutable settings, the full launch result persisted so a replay returns the receipt and warning that cannot be recomputed once settings move, and a derived child operation id for the inner attach — the ledger key carries no method, so forwarding the launch id would make the attach conflict with its own launch. Safety, not recovery. Nothing here probes for a surface a dead attempt left behind, adopts one, or finishes an interrupted publication. Callers that send no `operationId` keep today's behaviour exactly, which is why the field is optional and the host advertises `agent.launch.replay.v1`: an older host strips an unknown param and launches anyway, so a client may only treat a retry as safe once the host has said it enforces the ledger. * fix(agent-launch): keep an unreadable launch payload from costing the store Review follow-ups on the replay-safety ledger. A recorded `launch` payload must not gate row validity. `isAgentLaunchResult` is a hand-maintained mirror of a result type later work will edit, and `isAgentSessionOperationRow` is consulted by the store loader, where one rejected row makes the whole file unparseable — a primary and backup that both fail to parse raise `agent_session_store_corrupt` and the profile loses every lease. That is the same argument the row already makes for keeping `sessionId` required, applied to the field this PR added. The payload is now typed `unknown`, left out of the row guard, and narrowed where it is read, so a payload this build cannot read refuses exactly one replay. A recorded failure now replays as the code the launch raised. Narrowing it through the closed `agentSession.*` refusal list answered `worktree_not_found` with `agent_session_operation_invalid` — the ledger's "your id is malformed" signal, which invites a client to mint a fresh id when the truthful answer is that this launch definitively did not run and the same id is safe to retry. The persisted failure code is bounded on the way in. A code is an identifier, but `error.message` is free text: an errno sentence carrying an absolute path arrived here as one and was written into a file re-serialized whole on every later operation. Bounded on write only — a length check in the row validator would reject rows this same build wrote, which is the hazard above. Comments: the caller key does not give one client a single namespace across surfaces, because the structured attach this launch performs partitions under `structuredCallerFor`; the two coincide only for a bearer-identity caller with no paired device, which is exactly when the derived child id is load-bearing. Recorded as a known limit that a `lost` claim cannot tell a sibling executing now from one a restart abandoned; telling them apart needs execution-generation tagging, which is recovery. Tests: the store-level ablation was inert — it defined a local stand-in and passed identically with and without the guard. It now substitutes the non-atomic composition into the handler's own store and watches one tap create two workspaces. Each of the four new guards was watched failing against the unfixed code: `agent_session_store_corrupt` on reopen, `expected false to be true` on the row guard, `agent_session_operation_invalid` in place of `worktree_not_found`, and a 6042-character code where 128 is the bound. * fix(agent-launch): keep live retries in one execution * docs(agent-launch): clarify failed replay guidance



ELI5
If a client loses the reply to an agent launch, retrying used to risk creating a second workspace or agent. A caller can now give the launch a stable operation ID: identical retries share the live launch or receive its recorded result, while changed or uncertain retries are refused before another launch can run.
What Changed
operationIdtoagent.launchand a host capability that tells clients when replay protection is available.agent_session_operation_conflict.agent_session_operation_unknown; the host refuses to guess and does not create a second surface. Recovery or adoption of a partial surface is outside this safety change.operationIdkeep the existing behavior. No shipped client currently sends the outer ID, so this PR is the host-side prerequisite for client adoption rather than an end-to-end mobile rollout.Why
The previous 60-second in-memory worktree cache expired, disappeared on restart, covered only one target shape, and was not a durable execution owner. The new receipt and claim make the host authoritative for a named launch. The live join preserves normal retry behavior without weakening the conservative restart boundary.
Linked Issue
N/A — no linked issue was provided.
Visual Proof
The change has no new UI control. Hidden Electron QA and screenshots show one
replay-qa-oneworkspace and terminal after an overlapping retry, and the same single workspace after a forced host restart.Testing
After the final rebase: 95 focused tests,
pnpm tc, the changed-code quality gate, andgit diff --checkpass. Independent review passes also ran broader focused sets of 143 and 113 tests.Hidden macOS Electron QA exercised the real local runtime: matching live and settled retries returned the same worktree and terminal handle, changed intent returned
agent_session_operation_conflict, and a retry after an interrupted claim returnedagent_session_operation_unknown. CI covers the full test matrix, cross-version wire compatibility, macOS packaging, and Windows packaging.Mobile device QA was not run because this PR changes no mobile UI and the current mobile caller does not opt into the new operation ID. SSH was not exercised because execution-host routing is unchanged; local and folder-workspace resolution continue through the existing host-owned paths.
AI Disclosure
Review
Two independent review loops completed. The first fixed live-retry joining, stable caller identity, RPC error propagation, shared operation-ID validation, and a binary test-source defect. The second found no further material defect.
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)