Skip to content

fix(agent-launch): make a lost launch safe to retry - #21106

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/agent-launch-replay-safety
Sep 17, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/agent-launch-replay-safety

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​612 $\color{#cf222e}{\Huge{\mathbf{−}}}$​100 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​512
Prod 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​825 $\color{#cf222e}{\Huge{\mathbf{−}}}$​50 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​775

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

  • Added an optional operationId to agent.launch and a host capability that tells clients when replay protection is available.
  • Added durable, caller-scoped admission before workspace lookup or launch effects. The host fingerprints the parsed request, atomically claims one executor, records the full result, and replays it after settlement or restart.
  • Added an in-process join for matching retries that overlap the original launch. A changed request using the same ID returns agent_session_operation_conflict.
  • Remote replay requires a stable paired-device identity, so bearer-token rotation cannot open a second ledger partition. Trusted local calls use one stable local namespace.
  • A crash after the claim but before settlement remains 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.
  • Callers that omit operationId keep 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-one workspace and terminal after an overlapping retry, and the same single workspace after a forced host restart.

Single workspace after overlapping retry

Same workspace after restart

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

After the final rebase: 95 focused tests, pnpm tc, the changed-code quality gate, and git diff --check pass. 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 returned agent_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

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security: no credentials or prompts are added to the durable operation record.
  • Compatibility: the wire field is optional and replay use is capability-gated; older callers keep the legacy path.
  • Performance: existing callers do not open the replay store or allocate live-operation entries. Opt-in rows and live entries are bounded and cleaned; opt-in terminal launches may cold-initialize the structured host, which remains an unmeasured latency cost.
  • Recovery: an interrupted claimed launch is safely refused after restart. Re-deriving or adopting a partial surface remains future work.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change adds durable replay support for named agent.launch operations. It validates operation IDs, fingerprints launch parameters, claims ledger rows atomically, records outcomes, and replays persisted results. It derives a separate child operation ID for structured-session attachment. It preserves existing behavior when callers omit operationId. It also adds capability and result validation, claim-key retention helpers, shared test fixtures, and replay-safety tests.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to d60ff

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 i… Add the issue reference that this pull request fixes, for example by replacing “Fixes #” or the current N/A text with a valid issue link or issue number.
Docstring Coverage ⚠️ Warning Docstring coverage is 40.48% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 42 functions across 16 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: making failed or lost agent.launch responses safe to retry.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 6acb4930-0628-4cc7-b332-5518e4c2149c

📥 Commits

Reviewing files that changed from the base of the PR and between 9add08b and 9ab1a98.

📒 Files selected for processing (15)
  • src/main/runtime/agent-session-claim-key-retention.ts
  • src/main/runtime/agent-session-record-store.test.ts
  • src/main/runtime/agent-session-record-store.ts
  • src/main/runtime/rpc/methods/agent-launch-replay.test.ts
  • src/main/runtime/rpc/methods/agent-launch-replay.ts
  • src/main/runtime/rpc/methods/agent-launch-surfaces.ts
  • src/main/runtime/rpc/methods/agent-launch.test-fixture.ts
  • src/main/runtime/rpc/methods/agent-launch.test.ts
  • src/main/runtime/rpc/methods/agent-launch.ts
  • src/shared/agent-launch-intent.ts
  • src/shared/agent-launch-operation.ts
  • src/shared/agent-session-mutation-envelope.ts
  • src/shared/agent-session-operation-ledger.ts
  • src/shared/protocol-version.ts
  • src/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.

Comment on lines +160 to +162
function agentLaunchFailureCode(error: unknown): string {
const code = error instanceof Error ? error.message : ''
return code.length > 0 ? code : 'agent_launch_failed'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

🔎 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.ts

Repository: 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 220

Repository: 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 220

Repository: 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 220

Repository: 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/rpc

Repository: 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*.ts

Repository: 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 120

Repository: 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/shared

Repository: 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.

Comment on lines +98 to +99
(targetKey ? key === targetKey : row.operationId === args.operationId) &&
!supersedesSettledOutcome(row.outcome, args.outcome)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

🔎 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 -240

Repository: 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.ts

Repository: 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 -500

Repository: 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 -240

Repository: 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 operationId on agent.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, reports won/lost/absent) replaces the blind settle; only the winner runs.
  • Whole launch result persisted on the widened succeeded arm (optional launch, empty sessionId for a PTY), with read-time validation in isAgentLaunchResult.
  • 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 unknown cannot clobber a recorded succeeded/failed.
  • New agent.launch.replay.v1 host 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?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review pass — fixed on the branch, 6256ed05d7

Reviewed against the requested outcome, not just the diff. The core mechanism holds; four things did not, and are fixed here. Each fix was watched failing against the unfixed code before it was kept.

The core: verified, independently

claimAgentSessionOperation is genuinely atomic as composed at the call site, not merely as a pure function. transact serializes in-process and takes a proper-lockfile on the store path across processes, and claimAgentSessionOperation does its read and its conditional write inside one apply(). Two concurrent replays both admit, both reach the claim, exactly one wins.

I reproduced the RED arm rather than taking it on the PR's word. Substituting the genuinely non-atomic composition — the status read in one transact, the unconditional unknown write in a second — makes createManagedWorktree go 1 → 2 and claims won go 1 → 2. The concurrency is real (Promise.allSettled starts both before either awaits), not await a; await b.

Fixed

1. An unreadable launch payload could cost the whole store. isAgentSessionOperationRow gated row validity on isAgentLaunchResult, and that guard is what the store loader consults: one rejected row makes the file unparseable, and a primary and backup that both fail to parse raise agent_session_store_corrupt — the profile loses every lease. Proven, not argued: corrupting only the launch payload of one row made AgentSessionRecordStore.open throw agent_session_store_corrupt at agent-session-record-store-file.ts:304.

This is the same argument the row already makes for keeping sessionId required, not applied to the field the PR added. And isAgentLaunchResult is a hand-maintained mirror of a result type later work will edit, so the realistic trigger is a field tightened there rejecting rows this same build wrote. The payload is now typed unknown, left out of the row guard, and narrowed where it is read — so a payload we cannot read refuses exactly one replay.

2. A recorded failure replayed under the wrong code. The first attempt threw worktree_not_found; the replay threw agent_session_operation_invalid, because the recorded code was narrowed through the closed agentSession.* refusal list and none of this method's codes is on it. That is the ledger's "your id is malformed" signal — it invites a client to mint a fresh id, when the truthful answer is that the launch definitively did not run and the same id is safe to reuse. It also silently undercut the pre-execution/execution split's entire purpose. agent.launch answers with its own thrown codes now.

3. The persisted failure code was unbounded free text. agentLaunchFailureCode put error.message verbatim into the row; a 6042-character ENOENT sentence carrying an absolute path landed in a file that is re-serialized whole on every later ledger write. Bounded to 128 on the way in only — a length check in the row validator would reject rows this build wrote, which is finding 1 again.

4. Two comments claimed more than the code does.

  • The caller key does not give one client a single namespace across surfaces. The structured attach this launch performs partitions under structuredCallerFor (clientId or trusted-local:<kind>), so the two coincide only for a bearer-identity caller with no paired device — which is precisely when the derived child id is load-bearing. Corrected in both files.
  • The lost branch now records that unknown cannot tell a sibling executing right now from one a restart abandoned.

5. The store-level ablation test was inert. It defined a local stand-in for the old composition and passed identically with and without the guard, while its comment claimed "with this substituted into the handler, the test above creates two worktrees for one tap" — a substitution the suite never performed. It now substitutes the non-atomic composition into the handler's own store and asserts the two worktrees. The second ABLATION: test was renamed; it demonstrates a mechanism honestly but never ablated anything.

Confirmed as written

  • Schema decision. Correct, and load-bearing. main's validator ignores the unknown launch key; the loader stores the parsed object whole (state.operations.set(key, value)) and the writer is Object.fromEntries, so a downgrade preserves rather than drops it. schemaVersion < CURRENT returns null, so a bump really would drop every lease. sessionId: '' is accepted by both validators, and no reader breaks on it.
  • Capability negotiation. operationId is optional, host-to-client negotiation is the right direction given how params degrade, and the capability is genuinely advertised (the status filter excludes only browser and E2E kills). A client sending none gets today's behaviour with zero ledger rows, pinned by test. Nothing re-mints an id after an ambiguous launch.
  • Child operation id. Deterministic, stable across replays, ages out with its parent, and does not bypass the attach's ownership checks — the attach still runs its own admission and fingerprint.
  • Omitting the in-flight join. Right for this PR. But name the gap honestly: refusing an in-flight duplicate is defensible, and the mechanisms that refuse elsewhere first re-derive whether the operation is live in this process or merely in doubt after a restart, and refuse only the second. Collapsing both into one unknown is the deviation, not the refusal. Recorded in the code.
  • Pre-execution/execution split. Correct and does not weaken the guarantee. resolveUnlaunchedIntent creates nothing, and everything past it is genuinely uncertain. Fix 2 above is what makes the split actually buy the retryability it was added for.
  • Caller-key divergence. Safe to leave. The attach row is never read back — the launch's own row answers every replay — so divergence only parks a row in another partition to age out. Its one real cost is the global 4096 budget; not reachable at realistic launch rates.
  • No "never the bearer credential" claim exists. The comment already says websocket dispatch sets clientId to the token and that it rotates. Nothing to fix.

Deliberately left

  • The durable ledger is reachable only by installing the structured session host, so a terminal-only launch that names an operation installs it even with structured chat off. Real coupling, but not introduced here: aiVault.listSessions already calls ensureStructuredAgentSessionHost() unconditionally, and terminal.send and session.tabs.createTerminal do on a content match. Decoupling means the runtime owning the store and the host consuming it — a second store instance is not an option, since each open re-marks every lease unreconciled. That is a separate change, and doing it inside a safety PR is the wrong risk.
  • No recovery crept in. I looked for it. Nothing probes, adopts, or reconciles.
  • An in-doubt row's only exit is the 24h TTL. Named, not built — a probe or an explicit abandon is recovery.
  • agent_session_operation_capacity / _unknown have no user-facing rendering. No client sends operationId yet; it belongs with the client that adopts it.

Validation

pnpm tc clean · oxlint clean · changed-code quality gate 0 findings across 15 files · src/shared + src/main/runtime 16,471 passed · src/main/native-chat 1,196 passed · the three launch/store suites 92 passed · both lockfiles byte-identical to main.

No device or emulator QA. No client invokes the new path — mobile sends no outer operationId — so an end-to-end QA run here could not fail and would be evidence of nothing. Saying that explicitly rather than producing a green screenshot.

Wrong in the brief

The brief said the pre-execution/execution split made "a bad selector retryable rather than permanently refused." It did not, quite: a failed row is still refused on replay, never re-run. What the split actually buys is the information that nothing happened, so the caller knows a retry is safe — and finding 2 was destroying exactly that signal on the wire.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/agent-launch-replay-safety branch from 6256ed0 to 6350a7f Compare September 16, 2026 23:46

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ 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.launch is typed unknown and dropped from isAgentSessionOperationRow, so a payload this build cannot read refuses one replay instead of making the whole store unparseable.
  • Recorded failures replay their real code — answerFromRecordedRow returns a failed row's own code rather than narrowing it through the closed agentSession.* vocabulary.
  • Failure codes are bounded on write — agentLaunchFailureCode slices error.message to 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).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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 — isAgentLaunchPromptReceipt validates all three disposal arms and requires messageId only on the journaled arm.
  • 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, and AgentLaunchModeReason arrived from main; the legacy create-guard comment moved into runLegacyAgentLaunch.

Re-ran both touched suites at 6350a7f: 48 pass.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 force-pushed the brennanb2025/agent-launch-replay-safety branch from 6350a7f to 7efa515 Compare September 17, 2026 00:09

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ 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 of agent_session_operation_unknown; a same-key request with a different fingerprint is refused agent_session_operation_conflict before admission.
  • Replay identity tightened to a stable subject — agentLaunchOperationCallerKey requires a paired-device id for remote callers (refusing agent_session_identity_required when absent) and uses trusted-local:runtime only for in-process callers; the rotating clientId fallback is gone.
  • The inner attach shares the launch's caller key — runAgentLaunch passes admission.callerKey into the surface factory, so a replay-safe launch's nested agentSession.attach reserves 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(...), so git ls-files --eol now reports i/lf w/lf and 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_unknown code surviving RpcDispatcher.

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?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Hidden Electron QA — replay-safe agent.launch (HEAD 7efa5156d027d52014797f10de1eab054edb6cec)

QA only. No production code, commits, or pushes. Isolated hidden Electron profile, CDP attach, ORCA_BACKGROUND_LAUNCH=1.

Limit: no shipped UI client sends operationId

Desktop renderer IPC (window.api.runtime.call) does not advertise agent.launch.v2, so that path refuses agent.launch with agent_launch_unsupported. Mobile's create still sends agent.launch without an outer operationId. This run used the real local runtime RPC behind the built Electron app (Unix-socket dispatcher, same process as the hidden window), not a new UI control.

Scenario exercised

  1. Opted-in agent.launch with a stable ${13-digit-ms}-${32-hex} operationId, create-worktree target, Claude, draft prompt.
  2. Identical retry in flight (three parallel RPCs).
  3. Same id with a changed agent (codex) while the first was live.
  4. Same id again after settlement (ledger replay, not the in-process join).
  5. Second operation claimed then host SIGKILL before settle; restart same profile; retry.

Visible evidence

One workspace replay-qa-one under replay-qa-repo. One Terminal 1 Claude trust prompt. Resource manager shows 1 terminal. After restart, still only that workspace — the interrupted second launch did not create replay-qa-unknown.

One launch effect: active replay-qa-one workspace with a single Claude terminal

Same workspace after host restart; no second worktree from the unsettled retry

Backing-state evidence

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 operationId on agent.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.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/agent-launch-replay-safety branch from 7efa515 to 47b6314 Compare September 17, 2026 00:42
@brennanb2025 brennanb2025 changed the title feat(agent-launch): make a lost launch safe to retry fix(agent-launch): make a lost launch safe to retry Sep 17, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review complete — ready to land as host-side groundwork

Merge conflicts are resolved, the branch is rebased on the current origin/main, and the reviewed head is d60ff2db02bf2b6c6ac4fd39c179c9854409d2a4.

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:

  • Preserved the stable agent_session_operation_unknown RPC error through dispatch.
  • Replaced literal NUL bytes in the replay test source with valid escaped fixtures.
  • Removed rotating client identity from replay ownership: paired callers use the paired device ID and local callers use a stable trusted-local namespace.
  • Joined overlapping identical retries across the full launch handler, while rejecting reuse of an operation ID for changed intent.
  • Reused the shared operation timestamp parser.
  • Corrected the failure-replay comment so it matches the implemented contract.

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 unknown before the external launch effect, overlapping identical calls join one live promise, and settled retries replay the stored result. This prevents the reviewed double-launch class without adding work to callers that do not opt in.

Functional, compatibility, security, and performance review: pass with the limits below. The replay records are bounded and expiring, live entries are removed in finally, remote identity is stable, and the wire change is additive. No platform-specific execution behavior changed.

Validation is green:

  • Local focused suites: 95/95 tests passed after the final rebase; earlier review rounds also passed 143 and 113 focused tests.
  • pnpm tc, changed-code quality checks, formatting, lint, and git diff --check passed.
  • Final CI passed static analysis, typecheck, cross-version wire compatibility, all 8 test shards, mobile verification, Pullfrog, and macOS/Windows packaging.
  • Hidden Electron/CDP QA proved identical concurrent join, changed-intent conflict, settled replay, and fail-closed unknown behavior after a forced host restart. Screenshots and detailed evidence are attached here. That run used the functionally identical patch before the final mechanical rebase and comment-only correction.

Remaining limits:

  • This is host-side groundwork. Current shipped callers, including the mobile caller, do not yet provide operationId, so they do not receive replay protection until they adopt it.
  • A restart after the durable claim but before settlement remains unknown and is refused. Recovery or adoption would require a stable external resource identity and reconciliation.
  • Opt-in cold initialization and store latency were not benchmarked.
  • SSH, folder-workspace, mobile-device, and structured-launch paths were not separately exercised live; the applicable unit, wire, mobile, and packaging checks are green.

Status: ready to land as host-side groundwork.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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.ts
  • src/main/runtime/agent-session-record-store.test.ts
  • src/main/runtime/agent-session-record-store.ts
  • src/main/runtime/rpc/methods/agent-launch-replay.test.ts
  • src/main/runtime/rpc/methods/agent-launch-replay.ts
  • src/main/runtime/rpc/methods/agent-launch-surfaces.ts
  • src/main/runtime/rpc/methods/agent-launch.test-fixture.ts
  • src/main/runtime/rpc/methods/agent-launch.test.ts
  • src/main/runtime/rpc/methods/agent-launch.ts
  • src/shared/agent-launch-intent.ts
  • src/shared/agent-launch-operation.ts
  • src/shared/agent-session-host-authority.ts
  • src/shared/agent-session-mutation-envelope.ts
  • src/shared/agent-session-operation-ledger.ts
  • src/shared/protocol-version.ts
  • src/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.

Comment on lines +216 to +217
await settleQuietly(admission.fail(agentLaunchFailureCode(error)))
throw error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 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 -240

Repository: 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 -300

Repository: 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 -320

Repository: 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 -180

Repository: 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 -320

Repository: 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' &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 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/main

Repository: 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
brennanb2025 merged commit 0bf815a into main Sep 17, 2026
29 checks passed
@joinwell52-AI

Copy link
Copy Markdown

@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.

Bounded original-code probe and all 11 observations.

ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants