Skip to content

fix(agent-launch): report a launch that failed before spawning as failed, with its cause - #22913

Merged
brennanb2025 merged 5 commits into
mainfrom
brennanb2025/agent-launch-prestart-failures
Sep 27, 2026
Merged

brennanb2025 merged 5 commits into
mainfrom
brennanb2025/agent-launch-prestart-failures

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​251 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​248
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​141 $\color{#cf222e}{\Huge{\mathbf{−}}}$​57 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​84

ELI5

When a client asks the computer to start an agent in an existing workspace and the computer can't even begin — the agent is turned off in settings, or its launch command can't be built — the computer used to answer "I'm not sure whether it started". Nothing had started, so it now says so, with the real reason. The shipped phone only uses this for launches that create a new workspace (which stay "not sure"), so phone users see the benefit once the mobile "+" agent menu change (#22954) moves that menu onto this call.

What Changed

Before: agent.launchReplay rewrote every error raised while building the launch's terminal to agent_session_operation_unknown and recorded the operation as unknown. A launch refused because the agent is disabled, or because the runtime couldn't build a launch command, reached the phone as "couldn't confirm the agent started", and a retry of the same operation was answered "unknown" again.

After: for a launch into an existing workspace, a failure raised before the terminal's spawn request leaves this process settles the operation as failed with its real cause. The caller gets the original error (for example "Could not build launch command for claude." or runtime_unavailable), and a retry of the same operation id is answered from that record without launching again.

Mechanism:

  • createTerminal gains an onPtySpawnDispatched option, called immediately before it hands the spawn to the PTY controller (and at the start of the renderer-owned path, which this process can't see into).
  • Each replay-safe launch owns one tracker that records whether that fired. If the launch's create throws before it, the tracker remembers that exact error as "not started"; the original error object is rethrown untouched, so the caller keeps its code and message.
  • launchFailureWithoutEffectsCode asks that launch's tracker, and treats a "not started" error like the existing typed refusals: existing-workspace launches only, recorded with the error's own code. The decision is made once and carried on the launch's execution error, so the RPC handler reuses it instead of re-deriving it.
  • The verdict belongs to the launch, not the error object. A failed pane spawn hands the same error object both to the create that sent the spawn request and to a concurrent create waiting on that pane before sending its own; marking the object itself would have let the waiting launch's "not started" clear the spawner's, recording as failed a launch whose agent may be running.

Unchanged: any failure after the spawn request left stays unknown, and a launch that created its workspace first stays unknown (the workspace exists).

Why

A failure after the spawn request is sent proves nothing: an SSH or daemon spawn whose reply was lost may still have started an agent, and loss of contact is never evidence that nothing is running. So the line is drawn at the last point this process can see — the request leaving — rather than at "the spawn reported success". The spawn-committed signal was considered and rejected for this reason: it isn't fired when a remote spawn's reply is lost, so "never committed" can't distinguish "never started" from "started, reply lost". Refusals like a remote spawn being rejected therefore stay unknown; only the providers themselves could prove those, and that's out of scope.

Matching error messages ("agent is disabled", "could not build launch command") was rejected too: it would miss the next pre-spawn failure and could misclassify a post-spawn one with similar text.

Linked Issue

No linked issue.

Visual Proof

Android phone ("+" menu from #22954), tapping Claude while the host cannot build Claude's launch command because its CLI arguments have an unbalanced quote:

Before (host on main) After (host on this branch)
Before: Couldn't confirm the agent started After: Could not build launch command for claude.

With valid arguments restored, the same tap still starts Claude (after):

After: a valid launch still starts Claude

Testing

  • agent-launch-prestart-failure.test.ts (through the real RPC dispatcher and operation ledger): a missing launch command before the spawn request → error carries the real message and the row is failed with that code; runtime_unavailable keeps its code; a retry of the same operation id is answered from the record and creates nothing; a failure after the spawn request → agent_session_operation_unknown, row unknown; one error object seen by one launch before its spawn request and by another after → the second stays unknown; a launch that created its workspace → unknown.
  • terminal-spawn-dispatch.spec.ts (real createTerminal): the hook fires before the PTY controller's spawn, still fires when that spawn throws, and does not fire when the create fails before any spawn request.
  • Two existing tests that match createTerminal's options exactly now expect the new option.
  • pnpm tc:node; src/main/runtime/rpc/methods/agent-launch* (including the caller-selection tests from fix(agent-launch): move only the requesting client's view to a launched tab #22914), src/main/agent-launch and created-mobile-session-tab-caller-selection.test.ts — 14 files / 194 tests pass; the orca-runtime.test.ts spawn-dispatch cases pass; oxlint on changed files; audit:anti-slop clean; check:code-quality:changed 0 findings. (An earlier revision also passed the whole src/main/runtime/rpc/methods directory and orca-runtime.test.ts: 216 files / 3,489 tests.)
  • Ablations (each reverted alone):
Removed behaviour Tests that went red
createTerminal never reports the spawn request both "reports the spawn request…" runtime tests
Launch classifier ignores "not started" the three failed-with-real-cause tests
A failure after the spawn request is also marked "not started" stays unknown when the failure came after the spawn request left
Workspace-creating launches not excluded stays unknown for a launch that created its workspace first
"Not started" marked on the error object for the whole process instead of per launch stays unknown when another launch saw the same error before its own spawn request
  • Live host check (isolated dev host built from this branch, its own profile; the scripted client was pinned to that profile and checked every response's runtime id against it before continuing). It sent the phone's exact agent.launchReplay request (existing workspace, prompt, launchSource) with Claude disabled:
    • The refusal carried the real cause: Agent claude is disabled. Choose an enabled agent.
    • The operation's ledger row was failed with that code.
    • After re-enabling Claude, replaying the same operation id was answered from the row with the same refusal; the terminal count stayed 0 before and after, so nothing launched.
    • The client connected as a local trusted caller rather than a paired phone, so the ledger key differs (trusted-local:runtime vs the phone's device id); the handler, classifier and ledger code are the same.
  • Phone QA (iPhone simulator driven only through orca emulator; isolated dev host from this branch with its own profile; phone from mobile PR fix(mobile): start + menu, quick command and diff-note agents through agent.launch #22954, which moves the "+" agent menu onto agent.launch). I opened the "+" menu with Claude enabled, then disabled Claude on the host over a client pinned to that profile, then tapped Claude in the still-open menu:
Phone showing the disabled-agent refusal - Android phone QA (emulator driven only through `orca emulator`; isolated dev hosts, each with its own profile, built from `main` and from this branch; phone JS from #22954). Pre-spawn failure: Claude's CLI arguments set to `--model "unterminated`, so the launch command cannot be built. That failure is still reached after #23043, which only moves the disabled-agent case: - Before: the phone showed `Couldn't confirm the agent started. Check the workspace before trying again.`, and the ledger row was `unknown`. - After: the phone showed `Could not build launch command for claude.`, and the ledger row was `failed` with that code. No terminal was created. - A second tap sends a new operation id, and that tap gets the same honest answer. - After restoring valid arguments, a tap started Claude in a new tab in both builds. - `tests/e2e/cross-version-wire` could not run locally: the harness timed out extracting its v1.4.190 baseline (`tar -xf timed out after 45000ms`). This change touches no wire shape and adds no runtime member an RPC handler calls (only an option on an existing call).

Notes

  • Wire compatibility: no wire change. A client sees a different refusal for the same failure: the real error instead of agent_session_operation_unknown. The mobile client already reads any non-unknown refusal as "not started" with the host's message.
  • SSH: a remote workspace's failure before the spawn request (agent disabled, launch command) is settled as failed like a local one; anything after the request leaves stays unknown.
  • Disabled agents: fix(agent-launch): refuse a disabled agent on the chat route too #23043 refuses a disabled agent before either launch route runs, covering the chat route this PR does not; with it, a disabled agent no longer reaches the terminal build at all. This PR's tests therefore use a missing launch command as their pre-spawn failure.
  • Scope: agent-launch-surfaces.ts changes are limited to taking the launch's tracker, passing the new option and catching the create. The launch failure-code helpers moved unchanged from agent-launch.ts into agent-launch-failure-code.ts, because rebasing onto fix(agent-launch): move only the requesting client's view to a launched tab #22914 took that file past its line limit.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready to merge (head 80eda090d5)

Verdict: ready to merge. Two review loops ran, and the second came back clean. The start and end readiness checklists both pass. CI is green: 30 passing, 11 skipped, 0 failing.

What changed during review

  • Fixed a safety gap (80eda090d5). The "not started" mark was stored on the error object in a module-wide set. When a pane spawn fails, the same error object reaches two places: the create that sent the spawn request, and any concurrent create waiting on that pane. The waiting launch had sent nothing, so it marked the error "not started". The launch that had sent its request then read that shared mark and recorded failed, even though its agent may be running.
  • The mark now belongs to each launch. Each replay-safe launch has its own tracker, which only recognises the exact error its own create threw before sending its spawn request. The decision is made once and carried on the launch's execution error. A new test covers the shared-error case, and it fails against the old version.
  • Fixed the static analysis failure: the new test's launch parameter now has a named type.
  • Rebased onto current main, which also cleared the RPC recording pin failure. That failure came from a temporary state of main, not from this PR.

Checked without changes

  • The spawn-dispatch hook fires as the first statement before ptyController.spawn. None of the steps before it can start an agent: the shell refusal, the disabled-agent check, building the launch command, workspace trust, the agent-teams plan, and stable-pane adoption (which only attaches, with no command).
  • The launch path always creates its terminal in the background, so the early hook on the renderer path can't be reached from a launch.
  • The executor creates at most one terminal per launch. A chat launch refused before it starts falls back to a terminal, and still calls the tracker only once.
  • A plain agent.launch behaves the same. A launch that creates its workspace first still settles as unknown. The ledger row shape is unchanged, so no migration is needed.
  • Performance: one small closure per launch, and nothing on a hot path.

Live check: isolated dev host on a separate Mac, before and after

Each version ran as its own background dev host with its own profile and home directory. The scripted client was pinned to that profile and checked that every reply came from it. A string-literal check of each version's built bundle confirmed which version was running.

Scenario Before (0a876b2f5a) After (80eda090d5)
Claude disabled, agent.launchReplay into an existing workspace agent_session_operation_unknown, row unknown Agent claude is disabled. Choose an enabled agent., row failed with that code
Claude re-enabled, same operation id sent again unknown again Answered from the record with the same refusal. No terminal was created (count 0 before and after).
Claude enabled, new operation id Terminal created, Claude process live Terminal created, Claude process live
Same operation id sent again Same handle, no second terminal Same handle, no second terminal

Before, Claude disabled in Settings:
Before: Claude disabled in Settings

Before, no agent tab after the refused launch:
Before: no agent tab after the refused launch

Before, a normal launch starts Claude:
Before: normal launch starts Claude

After, Claude disabled in Settings:
After: Claude disabled in Settings

After, no agent tab after the refused launch or its replay:
After: no agent tab after the refused launch or its replay

After, a normal launch still starts Claude:
After: normal launch still starts Claude

Gaps

  • Phone QA on Android was blocked. The shared emulator was already in another session, and it was not driven. The iPhone simulator check in the PR description still applies.
  • The phone released today only sends agent.launchReplay when it is creating a workspace, and that case stays unknown here on purpose. Phone users see this change once the "+" menu moves to agent.launch in fix(mobile): start + menu, quick command and diff-note agents through agent.launch #22954.
  • The refusal reaches the client as error.code: runtime_error, with the real sentence in error.message. The ledger stores that sentence as the operation's code, capped at 128 characters, as it already does.

@brennanb2025
brennanb2025 marked this pull request as ready for review September 27, 2026 18:59
@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: f2eee32e-31c7-48fb-b39d-55ac8b5f5150

📥 Commits

Reviewing files that changed from the base of the PR and between 80eda09 and 823ac08.

📒 Files selected for processing (3)
  • src/main/runtime/rpc/methods/agent-launch-failure-code.ts
  • src/main/runtime/rpc/methods/agent-launch-surfaces.ts
  • src/main/runtime/rpc/methods/agent-launch.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The change adds a callback that reports when terminal creation dispatches a PTY spawn request. Agent launch handling tracks that dispatch state and uses it to classify certain failures for replay. Tests cover terminal dispatch timing, failures before and after dispatch, and retry outcomes.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 823ac

Concurrent launches into the same pane can record a failure when an agent may already have started, making a replay unsafe. Resolve this before merging unless the risk is explicitly accepted.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 823ac

A concurrent launch can receive another terminal creation’s failure and record its own request as definitively failed, even though a spawn for the shared pane may have occurred. Access remains gated, and the identified scenario is limited to concurrent work on the same pane.

Retained concerns

  • Medium · reliability · inferred: A waiting launch can persist a definitive failed outcome from another pane creator’s post-dispatch error, although that creator’s spawn outcome remains uncertain. Subsequent retries of the waiting operation replay the failure rather than reassessing the shared pane.
Security review details

Security Blast Radius

  • inferred — The identified interleaving requires concurrent creation for the same connection, worktree and pane; the inspected paths do not establish broader tenant or service reach.

Trust Boundaries and Controls

  • observed — The launch capability gate precedes replay execution, and replay admission uses the paired-device identity or trusted-local caller key. The dispatch tracker does not grant terminal authority.

Resilience and Maintainability Implications

  • inferred — Caller-scoped operation admission prevents same-ID duplicate execution, but it does not establish the provenance of an error inherited from a pane-scoped reservation. That distinction matters to a definitive replay answer.

Hardening Proposals

  • proposed — Bind a propagated reservation failure to its originating spawn, or keep the waiting launch’s result uncertain when that provenance cannot be established, before recording a definitive failed outcome.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 11 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed and covers the change, rationale, testing, visual proof, compatibility, and known limitations. However, it states "No linked issue" even though the template requires a link… Add the required linked issue, or state that the maintainer exception applies. Complete the omitted Review, Agent skill upstream boundary, and Checklist sections.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the main change: reporting pre-spawn agent launch failures with their original cause.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, visual proof, compatibility, and known limitations. However, it states "No linked issue" even though the template requires a linked issue for outside contributors, and it omits the template's Review, Agent skill upstream boundary, and Checklist sections.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@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 classification edge sits on the wrong side of this PR's own safety line: a launch that waits on a concurrent create's already-dispatched spawn for the same reserved pane is settled as failed even though an agent may be running in that pane. Details inline.

Reviewed changes

  • Per-launch spawn-dispatch tracker — new agent-launch-not-started.ts returns a tracker whose rethrow records the exact error only while no spawn request has been dispatched, and whose failedBeforeDispatch matches that object by identity. The verdict is per launch, so a shared error object cannot clear another launch's record.
  • Runtime hook — TerminalCreateOptions.onPtySpawnDispatched fires immediately before this.ptyController.spawn(...) in orca-runtime-create-terminal.ts, and before the renderer-owned createDesktopTerminal (deliberately conservative: the renderer path stays unknown).
  • Terminal surface wiring — agent-launch-surfaces.ts forwards the hook and wraps createTerminal in created.catch(terminalSpawn.rethrow).
  • Replay-safe classification — executeReplaySafeAgentLaunch now settles an existing-workspace launch that throws before dispatch as failed with the error's own code, and carries the decision once on AgentLaunchExecutionError so the handler no longer re-derives it from the error.
  • Tests — agent-launch-prestart-failure.test.ts drives the classifier through the real RPC dispatcher and ledger; terminal-spawn-dispatch.spec.ts exercises the real createTerminal hook.

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

if (error instanceof AgentLaunchSessionAlreadyExistsError && targetKind === 'existing') {
return AGENT_LAUNCH_SESSION_ALREADY_EXISTS_CODE
}
if (terminalSpawn.failedBeforeDispatch(error) && targetKind === 'existing') {

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.

For an existing-workspace launch, a pre-dispatch throw does not always prove nothing spawned. createTerminal runs adoptStablePane at orca-runtime-create-terminal.ts:64 before the new hook at :127, and that call can be blocked on a concurrent create's in-flight spawn for the same reserved pane. When that in-flight spawn fails after dispatch (e.g. a lost SSH/daemon reply), this launch's create rejects with the same error before its own hook, and this branch records it as failed even though an agent may be running in the pane it targeted — the reduction the PR exists to avoid.

Technical details
# A launch joined to another create's dispatched spawn is classified as failed

## Affected sites
- `src/main/runtime/rpc/methods/agent-launch.ts:234` — the new branch accepts the propagated error as "nothing spawned" for any `existing` target.
- `src/main/runtime/orca-runtime-create-terminal.ts:64,127` — `adoptStablePane` runs before `onPtySpawnDispatched`, so a rejection from it is observed as pre-dispatch.
- `src/main/ipc/pty/pane/adopt-stable.ts:24-29` — the waiter `await activePaneSpawn.promise` for the same `ownerKey`, which is the *other* create's spawn reservation.
- `src/main/ipc/pty/runtime/spawn.ts:78-81,105-121` — the reservation is created around dispatch and is rejected with the provider's own error, so the waiter receives a post-dispatch failure.
- `src/main/runtime/rpc/methods/agent-launch-prestart-failure.test.ts:135-151` — asserts the waiting launch becomes `failed`, but simulates it with a plain pre-throw, not the pane-wait path, so the lost-reply interleaving is untested.

## Required outcome
- A launch that failed only because a concurrent spawn for its target pane rejected should settle `unknown`, mirroring the spawner's own launch. Its create is joined to that spawn; treating the join's failure as a definitive "nothing spawned" is what re-opens the duplicate-agent path.

## Suggested approach (optional)
- Signal the tracker when `adoptStablePane`'s active-reservation branch is entered (e.g. pass `onPtySpawnDispatched` into the adopt call and fire it before awaiting), rather than firing the hook unconditionally earlier — a failure before adopt (shell/launch-command refusal) is still provably pre-spawn and should keep classifying as `failed`.

## Open questions for the human (optional)
- Is a second concurrent launch into one reserved pane reachable for `agent.launchReplay` (two distinct operation ids on the same `paneKey`), or is it precluded upstream? If unreachable, a comment saying so would make this classification defensible.

…led, with its cause

A launch into an existing workspace whose terminal create threw before the
spawn request left this process (agent disabled, no launch command, runtime
unavailable) created nothing, yet agent.launchReplay recorded and answered it
as agent_session_operation_unknown. createTerminal now reports when it hands
the spawn to the pty controller; a failure before that point settles the
ledger row as failed and returns the original error. After the request leaves,
the outcome stays unknown: an SSH or daemon spawn whose reply was lost may
still have started.
… command

A disabled agent is moving to a check made before either launch route runs,
so the tests use a failure that stays inside the terminal build.
…e shared error

A failed pane spawn rejects the same error object into the spawner (after its
request left) and into a concurrent create waiting on that pane (before its
own). Marking the error object globally let the waiting launch's verdict clear
the spawner's, recording a launch that may have started an agent as failed.
The launch now owns its dispatch tracker and carries the decision on its
execution error instead of re-deriving it from the error.

Also names the test's launch parameter type for the anti-slop audit.
…wn module

Rebasing onto the caller-selection change took agent-launch.ts past its line
limit; the failure-code helpers are a self-contained concern.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/agent-launch-prestart-failures branch from 80eda09 to 823ac08 Compare September 27, 2026 20:53
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status update: still ready to merge (head 823ac089a3)

Rebased onto main after #22914.

Android phone check (previously blocked; now done).

Host on main (bdaf9a3ed3) Host on this branch (823ac089a3)
Phone after tapping Claude Couldn't confirm the agent started. Check the workspace before trying again. Could not build launch command for claude.
Ledger row unknown failed, code Could not build launch command for claude.
Terminals created 0 0
Tapping again New operation id, unknown again New operation id, same real cause
Tapping after restoring valid arguments Claude starts in a new tab Claude starts in a new tab
Before After After, with valid arguments
Before After After, valid launch

Not caused by this PR. While a phone is in a session, the desktop covers the terminal with "Your phone left this at phone size". This happens on both builds.

@brennanb2025
brennanb2025 merged commit 89cf55d into main Sep 27, 2026
42 checks passed
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.

1 participant