Skip to content

refactor(agent-launch): redefine the agent.launch contract - #20999

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/agent-launch-contract-pr-a
Sep 16, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/agent-launch-contract-pr-a

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​54 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​51
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​84 $\color{#cf222e}{\Huge{\mathbf{−}}}$​67 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​17

ELI5

agent.launch lets a caller ask the host to start an agent without choosing structured chat or a terminal first. This change makes its response precise about what happened to the prompt and why the host chose a mode. Because the response contract changed, clients must advertise agent.launch.v2 before calling it.

What Changed

  • Replaced the prompt receipt's delivered: boolean with a discriminated outcome: journaled, handed-to-terminal, or not-delivered. The current executor returns not-delivered because prompt delivery remains the caller's responsibility.
  • Consolidated the launch mode, reason, and receipt types in the shared contract. The host decision code now re-exports that precise reason union instead of maintaining a looser duplicate.
  • Removed AgentLaunchCustomization, which was unreachable from the RPC schema and unused by the executor. Settings-level launch-command routing remains unchanged.
  • Bumped the negotiated capability from agent.launch.v1 to agent.launch.v2, fencing the breaking response shape from older clients.
  • Updated the mobile v2 decoder to accept warnings only at the result's top level. Capability negotiation and the existing unsupported-method fallback keep old clients and hosts on worktree.create.
  • Kept the existing optional clientMutationId create guard unchanged and narrowly described. This PR does not claim durable launch replay or introduce a second idempotency mechanism.

Why

The old boolean prompt receipt could not distinguish text committed to a transcript from text handed to a terminal. The mode receipt was also declared twice, with one copy accepting any reason string. These ambiguities made the contract easy to misuse.

main added the mobile agent.launch caller while this PR was open. The resolved version treats top-level warnings as the sole v2 shape and preserves bidirectional compatibility: a v2 mobile client falls back before calling a v1 host, while a v1 client is rejected by a v2 host and falls back after the unsupported response.

Linked Issue

N/A — this focused contract refactor was split from ongoing agent-launch work and has no linked issue.

Visual Proof

Application smoke evidence is attached to the PR. It shows the branch-built hidden Electron renderer in a stable state. The contract and mobile decoder changes do not alter rendered UI.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated

Validation performed on macOS after resolving the merge with current origin/main:

  • Focused host launch, orchestration, and cross-version tests — 5 files, 91 tests passed.
  • Focused mobile launch, retry, workspace creation, capability, and transport tests — 6 files, 97 tests passed.
  • pnpm tc:node — passed.
  • Mobile typecheck — passed.
  • pnpm run check:code-quality:changed — passed with zero findings across all nine changed files.
  • Hidden Electron/CDP smoke run with ORCA_BACKGROUND_LAUNCH=1 — correct worktree renderer reached a stable state with zero console errors and zero page errors.
  • PR CI covers the broader test matrix, cross-version wire compatibility, packaging, and Windows packaging.

Review

Independent review loops were run after re-baselining against current origin/main. The review removed an unimplemented launch-operation ID and replay disposition that had been backed only by a 60-second repo-scoped cache, removed an unused caller-identity helper, restored the existing bounded create guard, and added the v2 capability fence. The merge resolution preserved main's complete-launch deduplication, setup cancellation, and warning behavior, then re-ran the focused host and mobile suites.

The resulting architecture keeps the contract within implemented guarantees. Durable launch replay remains separate work because it requires persisted operation identity, caller scope, a host-computed request fingerprint, and recoverable outcomes; the existing create cache does not provide those properties.

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

Reliability contract:

  • Invariant: a paired caller may invoke the method only after negotiating the exact result version, and the host never reports prompt delivery it did not perform.
  • Failure source: older clients understand the v1 result shape; prompt delivery and warning interpretation changed in v2.
  • Oracle and gate: AGENT_LAUNCH_RUNTIME_CAPABILITY gates the RPC before any work starts; the returned receipt, prompt outcome, and top-level warning are the caller-visible record.
  • Platform coverage: the contract and gate are host-neutral. Mobile uses the negotiated capability and preserves its worktree.create fallback. No shell, path, process, WSL, or SSH routing changed. Windows packaging remains covered by CI.
  • Performance budget: no polling, listeners, subprocesses, timers, caches, scans, or render-path work were added. The change reshapes a small result object and narrows shared types.
  • Diagnostics: capability rejection uses agent_launch_unsupported; successful calls return a typed mode reason, detail, prompt outcome, and optional warning.
  • Residual gap: clientMutationId still provides only bounded create deduplication. Durable retry/replay across disconnects or host restarts is not exposed as a guarantee by this PR.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)

`agent.launch` has no clients yet, so the contract is redefined in place
rather than versioned.

- params require `operation.id`, pinned to the shipped operation-id mint so
  the host can read the embedded timestamp back. No caller-supplied
  fingerprint: the host derives its own.
- the result carries `disposition` ('created' | 'replayed', the same
  vocabulary `RuntimeCreateAgentSessionResult` already uses) and a single
  top-level `warning` instead of one on the terminal arm only.
- the prompt receipt becomes an outcome enum, so a receipt can under-claim
  instead of reporting a bare `delivered: false`.
- the dead `customization` field is deleted, and the mode-reason union and
  receipt are declared once in shared with main re-exporting.
- `clientMutationId` joins the reserved create fields, with a test pinning
  the list to the create schema in both directions.

Contract only; no behaviour change and no ledger wiring.
`clientMutationId` joined AGENT_LAUNCH_RESERVED_CREATE_FIELDS, so three
comments describing the stripped set as agent fields now teach the wrong
model — including a SAFETY rationale, where a reader is trusting it most.
The rationale's claim is unchanged and still sound: deleting keys from a
parsed object leaves the rest the parsed shape.

@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 — minor suggestions inline.

Reviewed changes

  • Required launch operation id — agent.launch params now require operation.id, format-pinned to AGENT_SESSION_OPERATION_ID_PATTERN (newly exported), carried into AgentLaunchIntent.
  • disposition on the result — new 'created' | 'replayed', hardcoded 'created' in every executor path, mirroring RuntimeCreateAgentSessionResult.
  • Prompt receipt becomes an outcome enum — delivered: boolean replaced by 'journaled' | 'handed-to-terminal' | 'not-delivered' plus optional messageId; the executor returns 'not-delivered'.
  • warning hoisted off the terminal outcome arm onto AgentLaunchResult.
  • Reserved create fields — withoutReservedAgentCreateFields → withoutReservedLaunchCreateFields, now also stripping clientMutationId; new two-way parity test against WorktreeCreate.
  • Dead code removed / type de-duplicated — AgentLaunchCustomization and intent.customization deleted; AgentLaunchModeReceipt consolidated into shared with the real reason union and re-exported from agent-launch-mode.
  • rpcCallerKey added — a single caller-identity derivation, currently with no callers.

ℹ️ The required operation.id has no consumer yet

Nothing in the host reads the required id: the handler still gates idempotency on the optional params.target.create.clientMutationId (agent-launch.ts:107), and withoutReservedLaunchCreateFields strips that key out of the create payload. A client that follows the new contract and sends only operation.id therefore gets no retry protection until the follow-up ledger lands — worth stating explicitly in the contract docs so the first caller does not assume otherwise.

Technical details
# `operation.id` is validated and carried but not yet load-bearing

## Affected sites
- `src/main/runtime/rpc/methods/agent-launch-schemas.ts:31` — requires `operation.id` and rejects malformed shapes.
- `src/main/runtime/rpc/methods/agent-launch.ts:107` — the only dedupe gate is `params.target.create.clientMutationId`; `operation.id` is not consulted.
- `src/main/agent-launch/agent-launch-executor.ts` — `intent.operation` is never read.

## Required outcome
- Either document that a caller must keep sending `clientMutationId` for retry safety until the ledger lands, or wire the dedupe to `operation.id` as part of making it required.

## Open questions for the human
- Is requiring `operation.id` before any consumer exists deliberate sequencing (safe, since there are no callers), or should the field stay optional until the follow-up consumes it?

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

Comment thread src/main/runtime/rpc/rpc-caller-key.ts Resolved

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

ℹ️ Incremental review — no new issues; the delta is documentation text only.

Reviewed changes (delta against prior pullfrog review)

  • Comment wording only — "agent fields" reworded to "fields the launch owns" / "reserved keys" in agent-launch-schemas.ts, the AgentLaunchTarget JSDoc, and the agent-launch-worktree-creation.ts SAFETY comment. No code or behavior changed.

The previously raised rpcCallerKey caller-identity question remains open; this commit does not touch that file.

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

@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 0f949c99-4adb-41ba-a951-5cfba36bd493

📥 Commits

Reviewing files that changed from the base of the PR and between 06b0f86 and 9e73d7b.

📒 Files selected for processing (9)
  • mobile/src/tasks/agent-launch-worktree-create.test.ts
  • mobile/src/tasks/agent-launch-worktree-create.ts
  • src/main/agent-launch/agent-launch-executor.test.ts
  • src/main/agent-launch/agent-launch-executor.ts
  • src/main/agent-launch/agent-launch-mode.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/protocol-version.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/rpc/methods/agent-launch.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The shared launch contract now defines prompt disposal outcomes, top-level warnings, typed launch modes, and runtime capability agent.launch.v2. The RPC method no longer forwards client operation IDs and deduplicates eligible worktree creation by clientMutationId. The executor reports not-delivered prompt outcomes. Mobile parsing reads warnings only from the top-level result. Tests cover these contract and capability changes.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 9e73d

The v2 contract changes are consistently fenced by capability negotiation, and prompt delivery is accurately reported as not performed by this launch path. The change is ready to merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 15 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 identifies the main change: redefining the agent.launch contract.
Description check ✅ Passed The description is detailed and covers the required change summary, rationale, testing, compatibility, review notes, and checklist. The Linked Issue section contains N/A despite the template requiring…
  • 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2f055f9a-b7bb-4c10-b08d-a1389096a997

📥 Commits

Reviewing files that changed from the base of the PR and between 170ebce and 5f45441.

📒 Files selected for processing (11)
  • src/main/agent-launch/agent-launch-executor.test.ts
  • src/main/agent-launch/agent-launch-executor.ts
  • src/main/agent-launch/agent-launch-mode.ts
  • src/main/runtime/rpc/methods/agent-launch-reserved-create-fields.test.ts
  • src/main/runtime/rpc/methods/agent-launch-schemas.ts
  • src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts
  • src/main/runtime/rpc/methods/agent-launch.test.ts
  • src/main/runtime/rpc/methods/agent-launch.ts
  • src/main/runtime/rpc/rpc-caller-key.ts
  • src/shared/agent-launch-intent.ts
  • src/shared/agent-session-host-authority.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Comment thread src/shared/agent-launch-intent.ts Resolved
…ency key

Review follow-ups on the contract redefinition.

`operation: { id }` becomes a flat `clientOperationId`, spelled the way
`terminal.createAgentSession` and the structured mutation envelope already
spell the same concept, and admitted by the shipped
`parseAgentSessionOperationTimestamp` rather than a second copy of its
pattern — so `agent-session-host-authority` keeps the regex private.

The handler now dedupes on that id instead of the create payload's
`clientMutationId`. That field is optional, so keying on it left any launch
that omitted one with no idempotency at all, while the required attempt id
did nothing. Reserving `clientMutationId` is still right, but for the reason
the comments now give: `createManagedWorktree` never reads it, so a copy left
in the forwarded payload is inert while still reading as a guarantee. The
previous rationale — that it was a second live dedupe key — was not true.

`messageId` moves onto the prompt receipt's `journaled` arm so a producer
cannot report the text as committed without saying where, and `rpcCallerKey`
picks up the `terminal.create` call site it was lifted from instead of
shipping with no callers.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review pass — clean, with four contract fixes applied

Reviewed against "what would we write from scratch", not against the submitted shape. The PR's structure holds up; four things in it did not, and are fixed in aff8f3ee3a.

Fixed

1. The required attempt id did nothing; the optional one was load-bearing.
operation.id was required on the wire but read by no code, while the handler still keyed dedupeWorktreeCreate on params.target.create.clientMutationId — which is optional, so any launch that omitted it got no idempotency at all. The contract said one thing, the code did another. The handler now dedupes on the attempt id, unconditionally for a create target.

2. The reserved-field rationale was factually wrong.
The type doc and the parity test both claimed leaving clientMutationId in the create payload "would register one launch under two independent dedupe keys". It would not: buildManagedWorktreeCreateArgs builds an explicit arg object and never reads that field, so the copy was already inert. Reserving it is still correct, for the reason now written down — an inert field that still reads as an idempotency guarantee. A test encoding a wrong reason teaches the next reader a wrong model, so the comment was rewritten rather than deleted.

3. operation: { id } → flat clientOperationId, validated by the shipped parser.
The repo already spells this exact concept flat and by that name in three places (RuntimeCreateAgentSessionRequest, CreateAgentSessionParams, MutationEnvelope), so a caller minting one id for a session and a launch now spells it once. Validation reuses parseAgentSessionOperationTimestamp — already exported, and it adds a Number.isSafeInteger guard — instead of exporting that module's private regex to re-pin the same pattern at a second site. src/shared/agent-session-host-authority.ts consequently drops out of the diff entirely.

4. messageId moved onto the journaled arm. It was a loose optional with a prose "set only for journaled". Now structural: a producer cannot report the text as committed and fail to say where.

Also: rpcCallerKey shipped with zero callers while terminal.create already wrote the identical pairedDeviceId ?? clientId ?? 'local' chain inline. It now uses the helper — which makes the helper live, and means its semantics are the shipped ones rather than an untested assertion. terminal.ensureAgentSession / createAgentSession are deliberately left alone: they pass the chain through undefined, and collapsing that onto local would change what their caller context keys on.

Verified, not assumed

  • Zero client callers, with a positive control: the same grep finds 87 worktree.create call sites and no agent.launch invocation in src/renderer, mobile/ or the CLI. This is what makes redefining in place free, so it was checked rather than inherited.
  • Parity test ablation — all four arms ablated individually; each fails only its own assertion with the other three green, then restored and re-run clean.
  • The new assertions ablated too: reverting the dedupe key reddens 3 tests; a constant key reddens 3; breaking the caller key reddens the shipped terminal.create idempotency test.
  • 2584 tests green across src/main/agent-launch + src/main/runtime/rpc. Changed-code quality gate: 0 new findings across 11 files. Generated RPC catalog regenerates byte-identical (agent.launch is in RPC_METHODS_WITHOUT_SHARED_PARAMS, so the rename cannot stale it). Both lockfiles byte-identical to main.
  • tc is red only on NativeChatMessageList.windowing.test.tsx, which is not in this PR and carries the same unused import at origin/main. Pre-existing; not folded in here.
  • dedupeWorktreeCreate self-releases (TTL on success, immediate drop on failure), so making it unconditional adds no unbounded growth.

Deliberately left alone

  • The warning hole on the agent-first terminal path. When the settled mode is terminal and the target is create-worktree, the executor returns early and never reaches the only producer of a warning; AgentLaunchWorkspaceFactory.createWorktree has no warning channel in its return type. Moving warning to the top level neither fixed nor worsened it. The fix belongs in the factory's return type — patching the result type alone would create a second place that can disagree. Confirmed, not re-derived.
  • disposition stays 'created' | 'replayed', matching the shipped RuntimeCreateAgentSessionResult exactly. Worth flagging for the follow-up: once a durable ledger is admitting these, a two-valued disposition cannot express "I cannot tell you" — that is a decision for the PR that introduces the indeterminate case, not this one.
  • No device or emulator QA. This PR has no observable surface change and no client callers; QA here could not fail, so running it would be vacuous evidence rather than weak evidence.

@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 in this delta. The only outstanding item is the earlier rpcCallerKey caller-identity thread, which this commit does not touch.

Reviewed changes (delta against the prior pullfrog review at 5f45441)

  • Attempt id becomes the launch's idempotency key — operation: { id } becomes a flat required clientOperationId, and the handler now dedupes every create-worktree launch on agent.launch:${clientOperationId} instead of the optional create.clientMutationId, which left a launch that omitted it unguarded.
  • Wire validation reuses the shipped parser — the schema refines through parseAgentSessionOperationTimestamp, the same one CreateAgentSessionParams uses, so AGENT_SESSION_OPERATION_ID_PATTERN stops being exported from agent-session-host-authority.
  • Reserved-field rationale corrected — clientMutationId stays reserved, now justified by createManagedWorktree never reading it rather than by a second live dedupe key.
  • Prompt receipt disposal becomes a union — messageId hangs off the journaled arm so a producer cannot claim the text was committed without naming where.
  • rpcCallerKey takes its first call site — terminal.create calls it in place of the identical inline pairedDeviceId ?? clientId ?? 'local', with the derivation's doc updated.
  • Tests — malformed-id shapes plus dedupe-by-attempt-id coverage (concurrent, sequential, distinct id, and a stale clientMutationId); the reserved-field parity test's comment was corrected.

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

@brennanb2025

brennanb2025 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor Author

CI settled — all three reds are one pre-existing import, not this PR

Green: all 8 test shards, package, package (windows), cross-version wire compatibility, pullfrog, test vs non-test LoC, root directory guard, detect code-relevant changes.

Red: static analysis, typecheck, and verify. All three are the same line:

src/renderer/src/components/native-chat/NativeChatMessageList.windowing.test.tsx:12:15
  'NativeChatMessage' is declared but never used.

That file is not in this PR (git diff --name-only origin/main...HEAD — 11 files, none under src/renderer), and origin/main carries the identical unused import at the same line. verify is a pure roll-up: its log reports TEST: success, PACKAGE: success, PACKAGE_WINDOWS: success, CROSS_VERSION_WIRE: success, and fails only with static_analysis: expected success, got failure / typecheck: expected success, got failure.

Main's tip red gets its own maintainer PR rather than being folded in here. This PR is as green as its base allows.

The ledger admits attempts whose outcome was never recorded, and neither
`created` nor `replayed` can say "I cannot tell you" — a caller handed
`created` for an unresolved attempt starts a second agent. Noted at the type
rather than in review, so whoever wires the ledger reads it where they edit.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Two notes for the record

1. The capability is advertised but never invoked — which is not the same as "not advertised".

NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES (protocol-version.ts:262) already includes AGENT_LAUNCH_RUNTIME_CAPABILITY on main, before any of this work. So shipped native remote clients advertise agent.launch.v1 today. Call sites that actually invoke the method in mobile/ + src/renderer + src/preload: 0 (positive control: 10 in src/main).

The consequence, stated exactly: the params change is incompatible, and it is unobservable in both directions only because nothing invokes the method. The capability string is unchanged, so a mixed pair could not negotiate the difference if one ever did. A casual reader would assume "not advertised"; it is advertised, and the protection is the absence of callers rather than the absence of a claim. This property came in with the base commit that made the attempt id required, not with the rename. Closing it is an agent.launch.v2 bump — a decision, not an oversight, and one this PR does not take.

2. disposition is two-valued only while it can be, and that is now recorded at the type.

Pushed in dbc2962b85, on AgentLaunchDisposition itself rather than left in review:

Two-valued deliberately, and only while it can be: every launch here is settled before it returns, so both answers are knowable. Whoever admits launches through the operation ledger owns re-reading this — a durable ledger has a state the host genuinely cannot resolve (an attempt whose outcome was never recorded), and neither word above can say "I cannot tell you". A caller handed created for an unresolved attempt starts a second agent. Add the third member with the ledger, not after it.

In-repo precedent (RuntimeCreateAgentSessionResult) is two-valued and wins at zero clients, so the vocabulary stays as-is here. The references that build a disposition vocabulary at all make it wider precisely because the honest answers include "pending" and "indeterminate" — which is the shape the ledger will need. Noting it where the next editor works, rather than in a thread, is the whole point.

@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 head commit is a coherent walk-back, but the PR description still documents the reverted contract.

Reviewed changes (delta against the prior pullfrog review at aff8f3ee)

  • Reverted the attempt id — clientOperationId is gone from the params schema and AgentLaunchIntent; agent-launch.ts:108 again gates dedupe on the optional create.clientMutationId, with a comment scoping full replay to the follow-up ledger.
  • Reverted disposition — AgentLaunchDisposition and the result member are removed.
  • Reverted the reserved-field rename and its parity test — withoutReservedAgentCreateFields / AGENT_LAUNCH_RESERVED_CREATE_FIELDS are back to main's shape, and clientMutationId is no longer stripped.
  • Deleted rpcCallerKey — the module and its terminal.create call site are gone; terminal.create is back to the inline pairedDeviceId ?? clientId ?? 'local'.
  • Bumped AGENT_LAUNCH_RUNTIME_CAPABILITY to agent.launch.v2 — supportsAgentLaunch exact-matches the constant, and a new test asserts a 'agent.launch.v1' client is refused.
  • Kept the result-shape work — prompt receipt outcome union (not-delivered from the executor), top-level warning via the new CreatedSurface, and the AgentLaunchModeReceipt consolidation into shared.

ℹ️ The PR description documents a contract the head commit reverted

The body still claims a required operation id, a disposition field, the reserved-field rename, and rpcCallerKey, and states "no v2, no deprecation path" — none of which is in the diff at 06b0f86. Update the description so reviewers and the follow-up work read the contract that actually shipped.

Technical details
# PR description no longer matches the diff

## Affected sites
- `src/main/runtime/rpc/methods/agent-launch-schemas.ts:25-49` — no `clientOperationId`; `AgentLaunchIntent` (`src/shared/agent-launch-intent.ts:51-58`) carries only `agent`, `target`, `prompt`, `sessionOptions`, `reuseTerminal`.
- `src/shared/agent-launch-intent.ts:89-99` — `AgentLaunchResult` has no `disposition`; `AgentLaunchDisposition` is gone.
- `src/shared/agent-launch-intent.ts:150` — the function is still `withoutReservedAgentCreateFields`, and `agent-launch-reserved-create-fields.test.ts` is deleted.
- `src/main/runtime/rpc/rpc-caller-key.ts` — deleted, with its `terminal.create` call site reverted.
- `src/shared/protocol-version.ts:253` — `AGENT_LAUNCH_RUNTIME_CAPABILITY` is now `'agent.launch.v2'`.

## Required outcome
- Rewrite the body around what remains: the prompt-receipt outcome union, the top-level `warning`, the `AgentLaunchModeReceipt` consolidation, and the v2 capability bump.

## Open questions for the human
- Is the attempt-id / durable-ledger work dropped from this PR entirely, or deferred to the follow-up named in the body?

ℹ️ The capability is bumped in place and hard-refuses the prior version

AGENT_LAUNCH_RUNTIME_CAPABILITY keeps its symbol but changes value from agent.launch.v1 to agent.launch.v2, and supportsAgentLaunch refuses any client that advertises the old value. The documented pattern for a published shape change is a sibling capability with a downgrade path; this is safe today only because agent.launch never reached a release, so no shipped client can be refused.

Technical details
# capability rename vs the documented evolution pattern

## Affected sites
- `src/shared/protocol-version.ts:253` — same constant symbol, value `agent.launch.v1` → `agent.launch.v2`, and it is advertised through `NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES` / `ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES`.
- `src/main/runtime/rpc/methods/agent-launch.ts:31-38,95` — exact-match gate that throws `agent_launch_unsupported`.
- `docs/reference/remote-wire-compatibility.md` Rule 3 and the `agent-session.turn-item.v1` worked example — the sanctioned mechanism is a new capability name that downgrades incapable clients rather than mutating a shipped value.

## Required outcome
- Nothing to change now. Once a caller ships, prefer a sibling capability with a downgrade over a hard refuse if a later incompatible result change lands.

## Open questions for the human
- Is the hard refusal intended for an eventual client skew, or should a `v1`-advertising caller keep being served the old result shape?

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Application smoke screenshot (hidden Electron renderer)

This is an application smoke screenshot, not a demonstration of agent.launch.

No renderer or current repository client invokes agent.launch, so this branch’s RPC contract change was not exercised through UI.

What was validated: branch-built Orca from worktree /Users/brennanbenson/orca/workspaces/orca/agent-launch-contract-pr-a at 06b0f8614a, launched hidden with ORCA_BACKGROUND_LAUNCH=1 and an isolated profile, attached via CDP to the intended instance, and reached a stable empty-profile rendered state.

  • Renderer identity: Orca: brennanb2025/agent-launch-contract-pr-a (isDev: true, devRepoRoot matches the assigned worktree)
  • CDP: http://127.0.0.1:9334 → page http://127.0.0.1:5174/
  • Console: 0 errors, 3 pre-existing warnings (Radix tooltip controlled/uncontrolled; React Grab outdated). No page errors.
  • Screenshot: uncropped hidden-renderer viewport, 1728×994 PNG

Application smoke screenshot of the hidden renderer

Limitations: this does not cover agent.launch RPC behavior, mixed-version clients, or any rendered caller (none exists). Isolated fresh profile shows the empty “Add a project to get started” state, which is expected.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final review status — land after fixes

The review is complete at 06b0f8614a. The branch is clean, matches the PR head, and GitHub reports it mergeable with a clean merge state.

Meaningful fixes applied

  • Removed the required launch operation ID and created | replayed disposition because the implementation only had a 60-second, repo-scoped create cache and could not provide the durable replay contract those fields implied.
  • Restored the existing optional clientMutationId bounded create guard without presenting it as launch replay.
  • Removed the unused caller-key abstraction and unrelated terminal lifecycle churn.
  • Bumped the breaking result shape to agent.launch.v2, so a v1 client is rejected before launch work begins.
  • Kept the sound contract improvements: discriminated prompt outcomes, top-level warnings, one shared precise mode receipt, and removal of unreachable customization fields.

Review judgments

  • Functional correctness: clean after fixes. Prompt delivery is not over-claimed, warnings survive terminal fallback, and the capability gate protects the new result shape.
  • Architecture: clean for this PR. Durable replay requires persisted operation identity, caller scope, a host-computed request fingerprint, and recoverable outcomes. This PR no longer promises those semantics or adds another partial guard.
  • Performance: clean. No polling, listeners, subprocesses, timers, caches, scans, render work, or hot-path fanout were added.
  • Compatibility: clean. No shell, path, process, WSL, SSH-routing, folder-workspace, or mobile UI behavior changed. Windows packaging passed. Mobile simulator QA has no runnable changed action because no mobile or rendered client invokes agent.launch.
  • Independent review: the first full-diff loop found and fixed the contract/implementation mismatch; the second full-diff loop returned clean. The end readiness audit returned PASS with zero candidate findings, so no severity counsel was required.

Validation

  • Local focused launch/orchestration/cross-version suite: 90 tests passed.
  • Independent final readiness suite: 94 focused tests passed.
  • pnpm tc:node: passed.
  • pnpm run check:code-quality:changed: zero findings across seven changed files.
  • PR CI: all required checks green, including static analysis, full typecheck, eight test shards, cross-version wire compatibility, package, and Windows package.
  • Hidden Electron application smoke evidence: correct branch renderer, stable state, zero console errors, zero page errors. The evidence accurately notes that no current UI invokes the changed RPC.

The remaining durable-retry work is an explicit future capability, not a guarantee of this contract. This PR is ready to land.

brennanb2025 added a commit that referenced this pull request Sep 16, 2026
Six commits. No agent-launch contract moved: agent-launch-intent, the shared
launch params, the executor and the mobile task module are all byte-identical
to the merge base.

protocol-version.ts did change, but not for this work - #20767 adds
BROWSER_IDENTITY_RUNTIME_CAPABILITY ('browser.identity.v1'). Checked rather than
assumed, because that file is one of the ones #20999 moves; agent.launch.v2 is
still absent from main, so nothing here adapts to it.

Twelve goldens conflicted, all on recorderSha256/adapterSha256. Both sides
re-record, so neither side's hashes fit the merged source. Re-recorded, seeded
from theirs so a recorder that failed to run would fail loudly.

Twelve files written by the re-record; the other 705 changed goldens were staged
by the merge and are main's. Behaviour-preserving, by multiset comparison of
added vs removed content lines with pool keys and hash fields normalised out:

  net added:   0
  net removed: 0

Only the 24 source-hash lines moved - a pure recorder-source shift with no
semantic change. Re-validated in normal (non-record) mode: 17 files, 821 passed.
brennanb2025 added a commit that referenced this pull request Sep 16, 2026
…h receipt

main landed `unchecked-rpc-reader-inventory.ts`, a ratchet on RpcOperation
readers that re-type their reply instead of validating it. Its ceiling for
mobile-workspace-create-operations.ts is 4, counted on a tree without this
branch's `agentLaunchRun`, so the merge produced "listed 4, found 5".

The inventory's own header prescribes this case: a merge is the one time a line
goes up without a migration undoing itself, and the instruction is to raise it
and name the PR that brought it. It describes main landing an operation the
branch never saw; here it is the mirror - the branch holds one main had not
seen - so the line is annotated with #19850 rather than left bare.

Not converted to `rpcResultVariant(variant, schema)`, which would lower the line
instead. That is a validation change rather than a migration, which is exactly
what the file's own comment says these five readers deliberately are not; the
agent.launch reply is already guarded at the consumer, where
readAgentLaunchCreateOutcome returns null on a malformed payload and the create
surfaces "Failed to create workspace". Writing a schema now would also target a
reply shape #20999 is actively redefining.

Ablated: with the line back at 4 the ratchet fails "listed 4, found 5"; at 5 it
passes.
brennanb2025 added a commit that referenced this pull request Sep 16, 2026
…agent (#19850)

* refactor(agent-launch): make the launch-mode decision surface-neutral

`decideWorkerStartMode` was the only shared answer to "structured chat session
or terminal agent?", but it lived in an orchestration-named module and spoke
orchestration's vocabulary, so the other launch surfaces could not call it.
Move the decision to `main/agent-launch/agent-launch-mode` unchanged and leave
`orchestration-worker-start-mode` as the adapter that supplies the noun.

A worker is not a special kind of launch; it is the same launch with a dispatch
attached. Naming the receipt's subject is the only thing orchestration actually
contributed, so that is the only thing the adapter keeps: "worker" in both
sentences, plus the `--terminal` wording, which reads as nonsense anywhere a
`--terminal` flag does not exist. Both are pinned, because they are asserted.

No behavior change. The receipts are byte-identical for every reachable case,
proven by running the new pin against both implementations.

Also pins the wording, which nothing was holding. The existing suites assert
`toContain` fragments ('terminal agent', 'cannot create') and the CLI suite
asserts a receipt handed to it by a mock rather than one this code produced;
all six files stayed green against a deliberately corrupted vocabulary. A
dispatch receipt is the only place a structured-to-terminal downgrade explains
itself, so the whole sentence is the contract, not a fragment of it.

* feat(agent-launch): add the launch intent and the one executor that runs it

The sequencing around the launch decision was duplicated per surface, and the
duplicate is where the bug lives. A new worktree was created agent-first, so
its startup terminal WAS the agent and the structured branch below it could
never be reached — every new-worktree launch was a PTY regardless of the user's
default. Orchestration fixed that for itself in #19431; mobile and the CLI
still have it.

`executeAgentLaunch` inverts the order once, for everyone. When the preference
is structured the worktree is created with NO startup agent, the executing host
is then asked whether it can host a session for the workspace that now exists,
and only then is a surface created. The host verdict cannot be hoisted above
creation: `agentSession.createSupport` only answers for a workspace it can
resolve, which is why the decision stays in two halves.

Agent-first creation is deliberately preserved for PTY launches — it is what
sequences the agent's startup command behind the setup runner, so wait-for-setup
comes for free there.

What actually differs per surface is only how a surface is built (an
orchestration worker's session takes a dispatch hold and a mailbox a plain
launch must not take), so that is injected as a factory rather than branched on.

The intent also strips the reserved agent fields from a migrated create payload:
a caller moving off `worktree.create` passes its existing params, and a stale
`startupAgent` in there would re-create the very path this replaces.

Tests assert order and arguments, not just the resulting mode. Reintroducing
agent-first creation reddens 4 of 11.

* feat(agent-launch): expose the launch executor as the agent.launch RPC

Adds `agent.launch` — one host-side method that decides structured-vs-terminal and
creates the surface — wired to the real runtime factories: `createManagedWorktree`
for the workspace, forking on `startupAgent` exactly as the orchestration worker
path does; `createStructuredAgentSessionForWorktree` for a chat session; and
`createTerminal` for a PTY agent. Allowlisted for mobile, which is the surface the
routing gap was reported on.

`worktree.create` is untouched. Its `startupAgent` keeps meaning "spawn a PTY agent"
verbatim, because it answers with `agentTerminalHandle` only on that path: a host
that quietly routed it to a structured session would hand every older client a
response with no handle and no error. All new behaviour sits behind
`agent.launch.v1`, which the host now advertises and a remote client must negotiate,
so a client that does not gets today's behaviour unchanged.

* feat(mobile): route workspace creates through agent.launch

Picking an agent on the mobile create sheet always produced a terminal, even
when the user's default was native chat, because all three create paths put
`startupAgent` on `worktree.create`. That means "create the worktree
agent-first", so its startup terminal IS the agent and the structured branch
below it is unreachable — while the same phone's in-workspace "+" button opened
a chat.

The blank, branch and new-branch creates now send the same payload through
`agent.launch` and let the host settle the surface. `worktree.create` is
untouched, and a host that does not advertise `agent.launch.v1` (read from the
existing `status.get` probe) keeps today's path exactly.

Work-item creates stay on `worktree.create`: they pre-fill the issue/PR URL as
an unsent `startupDraft`, which a structured session cannot hold yet, so routing
them would submit the URL as a first turn.

* fix(agent-launch): drop the deleted draft-prompt blocker from the reason map

main removed the draft-prompt blocker in #19681 (a structured session now holds
an unsent draft), so the exhaustive Record no longer typechecks.

* chore(agent-launch): carry a SAFETY rationale on the agent placement cast

The type-assertion gate landed after this branch's base, so the new file's
copy of the worker-start cast is now a changed-code finding.

* chore(agent-launch): carry agent.launch through main's RPC typing and casting gates

The typed-method contract, the generated params catalog and the
`assertionStyle: never` casting scan all landed after this branch's base.

- AGENT_LAUNCH_METHODS kept an `RpcMethod[]` annotation, which widened its
  method name to `string` and broke assignability; every sibling infers instead.
- `agent.launch` binds a schema under src/main, so it joins the catalog's
  RPC_METHODS_WITHOUT_SHARED_PARAMS and the parity gate's hand-listed twin.
- The now-typed methods make most test casts unnecessary; the few that remain
  carry the line-specific SAFETY rationale the casting gate requires.

* test(mobile): supply the agent-launch fixture the create-submit recording needs

The golden RPC recordings landed upstream while this branch was out, so they
first met agent.launch here. Three things had to happen, and only one of them is
a fixture bump.

1. workspace-settings-mounts.ts mounts useNewWorkspaceCreateSubmit against a
   fixture model that throws on any member it was not given. This PR added a
   required getAgentLaunchSupport, so the submit aborted with "Missing model
   fixture" before it ever issued the create, and three cleanup checkpoints
   vanished. That read like a product regression and was not one. Supplying the
   member restores the recording byte-for-byte; it is pinned false for the same
   reason the cutover probe is, so the baseline stays on worktree.create.

2. Editing that adapter moves adapterSha256 for the twelve settings goldens it
   mounts. Their recordings are unchanged - header only, by design: the digest
   is per-golden so editing a module fails exactly the goldens that mounted it.

3. Five goldens changed behaviourally, and both changes are this PR's:
   the capability probe now reports agentLaunch, and a create whose reply
   carries no worktree returns "Failed to create workspace" instead of throwing
   a TypeError off an unguarded result.worktree read. The launch route needs
   that guard, since a receipt can arrive without a worktreeId.

* refactor(mobile): decode the launch receipt instead of asserting its shape

The changed-code quality gate refuses type assertions, and the eight it flagged
were worth removing rather than suppressing.

The production one was the point. readAgentLaunchCreateOutcome asserted the RPC
payload into Partial<AgentLaunchResult> and then runtime-checked it anyway, so
the assertion bought nothing and claimed a contract the host had not proven. It
now narrows with `in` and validates each hop, which is the same nullability
question readCreateResult already answers on the sibling path - a launch receipt
can legitimately arrive without a worktreeId. AgentLaunchCreateOutcome ties
worktreeId to the shared contract so a change there fails this reader's
typecheck rather than passing a differently-typed field through.

The test fakes claimed a whole RpcClient via `as unknown as RpcClient` while
implementing one member. They now build a typed literal, matching the pattern in
use-mobile-structured-agent-options.test.ts. The read sites cast params and then
read one field; they now assert the payload with toMatchObject, which removes
the cast and pins more of the shape than the cast did.

Also pins the warning passthrough, which nothing covered: a terminal launch that
seats the workspace but cannot start the pty reports why, and the absent, blank,
non-string and structured-surface cases report nothing. Writing that test caught
a real drop I had introduced in the reader.

* ci(mobile): re-run Mobile Checks when a shared capability changes

Mobile Checks is path-filtered to mobile/**, but mobile imports the negotiated
capability names straight from src/shared/protocol-version.ts and records the
whole capability read verbatim in its goldens. So a capability added desktop-side
rewrites a mobile fixture while never triggering the suite that would catch it.

That is what happened here: #19849 introduced agent.launch.v1 and Mobile Checks
never ran on it. Verified at the run level rather than by check name - the
window-free check-runs API on 3837ae8 returns 49 check-runs across six runs
(PR Checks x2, PR test LoC x2, Track Community PRs, Review) and no Mobile Checks
among them. The breakage surfaced only in this PR, which happens to touch mobile/**.

The workflow already concedes this pattern for terminal-file-link-conformance.ts;
protocol-version.ts has the stronger claim, since mobile records its output.

Also corrects the mount adapter's SAFETY comment. It claimed the recorder supplies
only the members the hook reads, which was false the moment the hook gained a
required getAgentLaunchSupport - and the assertion it annotates is exactly what
stopped the compiler from saying so. The twelve goldens are adapterSha256 churn
from that comment: every body is byte-identical, which is the digest doing its job.

* docs(agent-launch): stop the receipt-wording comment claiming a migration

The decision was never moved out of orchestration-worker-start-mode; this PR
adds a second copy beside it. Say so, and name the unenforced agreement.

* docs(agent-launch): stop the executor comment claiming a migration that has not happened

The header asserted two things the tree does not support: that every launch
surface routes through the executor, and that the mode decision "already lived"
in `agent-launch-mode`. `agent.launch` is the executor's only consumer, and
`orchestration-worker-start-mode.ts` is byte-identical (blob 92dc5c6, 217
lines) at the merge base and all three stack heads, still used by workers.ts.
Describe the two live copies and leave the cutover to later stack work.

* fix(agent-launch): preserve setup and refusal fallbacks

* refactor(mobile): parse the launch outcome into a named type at its boundary

anti-slop/no-object-parameters flagged terminalLaunchWarning's `result: object`.
The rule is pointing at a real seam rather than a style nit: the helper advertised
a loose object and did the narrowing inside itself, so every caller handed it
unparsed wire data and nothing downstream held a real type.

Parsed at the boundary instead. parseTerminalLaunchOutcome takes `unknown` and
returns TerminalLaunchOutcome | null, so the narrowing happens once, where the
untrusted payload enters, and the consumer works with a named type.

The type is taken from the shared contract rather than restated - a Pick over the
terminal member of AgentLaunchOutcome - so a change to that union fails here
instead of flowing through. `handle` is deliberately excluded: nothing reads it,
and requiring it would drop the warning off a reply that omitted one, which is a
behaviour change smuggled in under a typing change.

No assertion and no config exemption: reintroducing `as Partial<AgentLaunchResult>`
would trade this finding for the defect removed earlier in this branch, and the
rule is correct here.

The rule arrived with the merge-forward (#20781, newer than this branch's
merge-base), and anti-slop is not one of the changed-code gate's six scans - it
runs only repo-wide - which is why a clean local gate did not predict it.

Behaviour is unchanged across all five warning cases, and the positive case was
re-ablated on the new parser: dropping the warning reddens exactly it,
1 failed | 18 passed, restored byte-identical to 19 passed.

* fix(agent-launch): dedupe complete launch and cancel setup wait

* fix(agent-launch): memoize the whole launch so a replay cannot mint a second session

A replayed agent.launch could create a second structured session in the same
worktree, with activate: true.

dedupeWorktreeCreate wrapped only the worktree half, inside the workspace
factory. On a replay the create was reused, and the executor then continued to
createSurface and built another surface inside it. The terminal route hid this:
its cached create carries a startup terminal handle, so the executor returns on
early. A structured create has no handle by construction - that is the whole
point of the structured fork - so it fell through every time. Mobile replays
this method deliberately on a delivery-ambiguous response, up to five attempts,
so the path is reachable by design rather than in theory.

The handler now wraps the entire launch in the same dedupe, on the same
(repo, clientMutationId) identity, exactly as worktree.create wraps its own
body. A replay returns the original AgentLaunchResult instead of re-running
createSurface, which makes the two routes replay-identical.

The inner dedupe is removed rather than kept. Wrapping both levels on one key
deadlocks: dedupeWorktreeCreate stores the in-flight promise before the inner
call runs, so the inner call would be handed the outer's promise, which is
waiting on it. The launch-level memo subsumes the worktree-level one.

Failures are still dropped rather than cached, so an unknown outcome stays
unknown instead of replaying as a fabricated success.

The guard replays a STRUCTURED launch: the terminal route cannot reproduce this
and a test there would pass either way. Ablated against the pre-fix files -
1 failed | 22 passed, "expected vi.fn() to be called 1 times, but got 2 times",
which is the duplicate session - then restored to 23 passed. The stub's dedupe
had to be made faithful for that to be observable; the shared one passes through
so other tests can see raw calls.

* Revert "fix(agent-launch): memoize the whole launch so a replay cannot mint a second session"

This reverts commit 59bc5e9.

The same defect was already fixed upstream on this stack's base branch by
539e283, which landed while this was being written. That change is broader
(it also cancels the setup wait) and namespaces the dedupe key, so it supersedes
this one. Reverting rather than hand-merging keeps a single implementation
instead of a hybrid nobody chose.

The behavioural guard from this commit is ported back on top of the upstream
implementation separately: it asserts exactly one structured session survives a
replay, where the upstream tests assert the dedupe wiring.

* ci(mobile): close the round-1 signal gaps around agent.launch

Three review findings, all narrow.

Mobile Checks is path-filtered, and this branch made mobile's types depend on the
shared RPC contract: rpc-params-contract.ts is a type-only re-export of the
generated params catalog, and mobile/tsconfig.json includes **/*.ts. So a
desktop-only edit under src/shared/rpc-contract/ could break mobile's typecheck
with no mobile signal at all - the same blind spot the protocol-version.ts entry
closed, one directory over. Added src/shared/rpc-contract/** to the paths filter.

agent.launch had no cross-version trigger. Added the three prefixes a paired peer
actually exchanges: the intent contract, the wire schema, and the RPC method.
src/main/agent-launch/ is deliberately NOT listed - the executor shapes behaviour
but is not itself wire, and AgentLaunchResult's shape is already covered by
agent-launch-intent. Extending the cross-version SUITE to cover a negotiated
handshake is separate work, not this.

The break branch that answers an accepted-but-empty reply with "Failed to create
workspace" had no unit coverage; the golden that used to discriminate it
collapsed five partitions into one shared error when the null guard replaced the
unchecked read. Covered on BOTH routes - worktree.create with no worktree.id and
agent.launch with no worktreeId - since the branch serves both. Ablated by
bypassing the guard: 2 failed | 11 passed, the two new cases returning a
fabricated worktree instead of the error, restored to 13 passed.

* fix(agent-launch): give a launch one place to say the workspace is incomplete

createManagedWorktree reports an unspawned startup terminal or an uncopied
working tree as a top-level `warning`, and worktree.create hands it straight to
mobile. The launch path narrowed that result down to
{worktreeId, startupTerminalHandle} and dropped it, so every agent.launch create
lost a warning the old method surfaces - on both arms.

The channel was also asymmetric by accident rather than design: a terminal
outcome could carry `warning`, a structured one had nowhere to put it, so the
arm this PR exists to enable was the arm that could not report an incomplete
create at all.

Now there is exactly one place a launch warning lives: AgentLaunchResult.warning,
at the top level. It is about the create as often as the surface, it applies to a
structured session and a terminal alike, and a reader should not branch on
outcome.kind to discover the workspace it just opened is missing something. The
terminal arm's own `warning?` is removed rather than left beside it - two homes
for one fact is how they drift. Every producer folds in: the create, the surface,
and the refusal downgrade.

Consumer census before removing it: one production reader (mobile's
readAgentLaunchCreateOutcome) and no others - the renderer and mobile launch
call sites never read it. The mobile reader now reads the top-level field, which
also lets its outcome parser go away entirely.

Guard ablated by restoring the pre-fix narrowing: 2 failed | 24 passed, both
carriers reporting `expected undefined`, which is the dropped warning itself;
restored to 26 passed. The third case asserts an absence and stays green under
the mutation by construction - it pins shape, not the defect.

* fix(agent-launch): combine both launch warnings instead of dropping one

Round 2 found the comment here was false. A create warning and a surface warning
CAN both be set, on two reachable paths:

  1. The create warns precisely BECAUSE it produced no startup terminal -
     didSpawnStartup stays false when that spawn throws, and
     orca-runtime-create-managed-worktree.ts:283 gates startupTerminal on it - so
     the executor's early return is skipped and a second surface is built, which
     can warn too.
  2. An untracked-copy warning, then a definitive structured refusal downgrading
     to a terminal that also warns.

`??` kept the first and lost the second with nothing saying so. They are now
combined the way the create combines its own failures - appendFailure in
runtime-local-worktree-terminal-startup.ts, and the startup-terminal catch in
runtime-remote-managed-worktree-create.ts - which append rather than replace.

The comment is rewritten to say what is true, and records the gap NOT fixed
here: a create warning about a failed startup terminal is stale once the launch
recovers by building a working one, so a user can be told the agent did not start
while looking at it. Distinguishing those needs createManagedWorktree to stop
multiplexing two unrelated failures into one string.

Guarded and ablated: restoring `??` reddens exactly the new test, with the
surface clause missing from the received string; restored to 27 passed. The
structured-create stub had to admit its real ok-or-refusal union for the
downgrade path to be modellable at all - it previously declared only the ok arm.

Also: mobile.yml gains src/shared/agent-launch-intent.ts. It is the sole holder
of the agent.launch RESULT shape - the rpc-contract catalog holds params only -
and mobile imports it as a value. CROSS_VERSION_WIRE_PREFIXES already treats it
as wire-critical; without this, one gate does and the other cannot see it.

And the agent-first warning test no longer pairs "startup terminal failed" with a
returned handle, a combination the producer cannot emit.

* fix(mobile): read a launch warning an older host nests on the outcome

agent.launch moved `warning` from the terminal outcome to the top level of the
result. That is the right shape - a reader should not branch on `outcome.kind`
to learn the workspace it just opened is incomplete - but on the wire it is a
REMOVAL, and mobile only read the new place.

A host built before the move still advertises the same `agent.launch.v1`
capability, so the capability probe cannot tell the two apart and mobile takes
this route against one:

  protocol-version.ts:360       AGENT_LAUNCH_RUNTIME_CAPABILITY is in
                                RUNTIME_CAPABILITIES, the host list
  orca-runtime-get-status.ts:64 publishes it via status.get; the filter drops
                                only browser.screencast.v1 and three E2E-gated
                                capabilities, never agent.launch
  agent-launch-executor.ts      such a host writes warning INSIDE outcome

The result was a regression rather than a contract cleanup: the worktree.create
path this replaces returned the warning at the top level and mobile read it, so
a create that seated the workspace but could not start the agent surface - pty
exhaustion, untracked files not copied - stopped explaining itself on the phone.

Read both shapes for as long as such a host can be paired. Top level wins, and
cannot be shadowed: AgentLaunchOutcome has no `warning` on either arm, so a
current host cannot nest one.

The test that pinned the old behaviour is inverted here. Its comment was the
actual defect - it framed a legitimate warning from an older peer as a stale
shape to defend against, which is what made dropping it look deliberate.

* chore(mobile): raise the unchecked-reader ceiling for the agent.launch receipt

main landed `unchecked-rpc-reader-inventory.ts`, a ratchet on RpcOperation
readers that re-type their reply instead of validating it. Its ceiling for
mobile-workspace-create-operations.ts is 4, counted on a tree without this
branch's `agentLaunchRun`, so the merge produced "listed 4, found 5".

The inventory's own header prescribes this case: a merge is the one time a line
goes up without a migration undoing itself, and the instruction is to raise it
and name the PR that brought it. It describes main landing an operation the
branch never saw; here it is the mirror - the branch holds one main had not
seen - so the line is annotated with #19850 rather than left bare.

Not converted to `rpcResultVariant(variant, schema)`, which would lower the line
instead. That is a validation change rather than a migration, which is exactly
what the file's own comment says these five readers deliberately are not; the
agent.launch reply is already guarded at the consumer, where
readAgentLaunchCreateOutcome returns null on a malformed payload and the create
surfaces "Failed to create workspace". Writing a schema now would also target a
reply shape #20999 is actively redefining.

Ablated: with the line back at 4 the ratchet fails "listed 4, found 5"; at 5 it
passes.

---------

Co-authored-by: Merge Sim <sim@local>
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Resolved the merge conflicts with current main in 9e73d7bdac.

The resolution preserves the host's newer complete-launch deduplication, setup cancellation, and top-level warning behavior. It also updates the mobile caller for the v2 contract: top-level warnings are authoritative, and mixed-version peers retain the existing worktree.create fallback.

Validation after resolution:

  • Host launch/orchestration/cross-version suite: 91 tests passed
  • Mobile launch/retry/workspace/capability suite: 97 tests passed
  • Node and mobile typechecks passed
  • Changed-code quality gate passed with zero findings across 9 files
  • Working tree is clean

GitHub reports the PR as mergeable; CI is running on the updated head.

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

Reviewed changes (delta against the prior pullfrog review at 06b0f8614)

  • Merged current origin/main (97aa5ff1) — the merge pulled in main's new mobile agent.launch caller and reconciled it with the v2 contract this PR defines.
  • Mobile create decoder reads an incomplete-create warning only from the result's top level — main's nested outcome.warning fallback is removed, and the mobile test now pins that a nested warning is ignored. The fallback was unreachable: readAgentLaunchCreateOutcome is only reached when the host advertised agent.launch.v2 (worktree-create-capability.ts:62, worktree-create-retry.ts:150-151), and a v2 host writes the warning top level.
  • Capability reference updated — isAgentLaunchUnsupportedRefusal's doc now names agent.launch.v2.
  • PR description rewritten to match the head contract, addressing the prior review's stale-body concern.

The rest of the contract (prompt outcome union, top-level warning, shared mode/receipt types, the agent.launch.v2 bump, and the bounded clientMutationId create guard) is unchanged from the prior review at 06b0f8614. pnpm tc:node is clean and the 41 focused host tests pass; mobile vitest could not run in this environment because the mobile Expo dependencies are not installed.

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

@brennanb2025
brennanb2025 merged commit 4b87bc7 into main Sep 16, 2026
29 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…agent (stablyai#19850)

* refactor(agent-launch): make the launch-mode decision surface-neutral

`decideWorkerStartMode` was the only shared answer to "structured chat session
or terminal agent?", but it lived in an orchestration-named module and spoke
orchestration's vocabulary, so the other launch surfaces could not call it.
Move the decision to `main/agent-launch/agent-launch-mode` unchanged and leave
`orchestration-worker-start-mode` as the adapter that supplies the noun.

A worker is not a special kind of launch; it is the same launch with a dispatch
attached. Naming the receipt's subject is the only thing orchestration actually
contributed, so that is the only thing the adapter keeps: "worker" in both
sentences, plus the `--terminal` wording, which reads as nonsense anywhere a
`--terminal` flag does not exist. Both are pinned, because they are asserted.

No behavior change. The receipts are byte-identical for every reachable case,
proven by running the new pin against both implementations.

Also pins the wording, which nothing was holding. The existing suites assert
`toContain` fragments ('terminal agent', 'cannot create') and the CLI suite
asserts a receipt handed to it by a mock rather than one this code produced;
all six files stayed green against a deliberately corrupted vocabulary. A
dispatch receipt is the only place a structured-to-terminal downgrade explains
itself, so the whole sentence is the contract, not a fragment of it.

* feat(agent-launch): add the launch intent and the one executor that runs it

The sequencing around the launch decision was duplicated per surface, and the
duplicate is where the bug lives. A new worktree was created agent-first, so
its startup terminal WAS the agent and the structured branch below it could
never be reached — every new-worktree launch was a PTY regardless of the user's
default. Orchestration fixed that for itself in stablyai#19431; mobile and the CLI
still have it.

`executeAgentLaunch` inverts the order once, for everyone. When the preference
is structured the worktree is created with NO startup agent, the executing host
is then asked whether it can host a session for the workspace that now exists,
and only then is a surface created. The host verdict cannot be hoisted above
creation: `agentSession.createSupport` only answers for a workspace it can
resolve, which is why the decision stays in two halves.

Agent-first creation is deliberately preserved for PTY launches — it is what
sequences the agent's startup command behind the setup runner, so wait-for-setup
comes for free there.

What actually differs per surface is only how a surface is built (an
orchestration worker's session takes a dispatch hold and a mailbox a plain
launch must not take), so that is injected as a factory rather than branched on.

The intent also strips the reserved agent fields from a migrated create payload:
a caller moving off `worktree.create` passes its existing params, and a stale
`startupAgent` in there would re-create the very path this replaces.

Tests assert order and arguments, not just the resulting mode. Reintroducing
agent-first creation reddens 4 of 11.

* feat(agent-launch): expose the launch executor as the agent.launch RPC

Adds `agent.launch` — one host-side method that decides structured-vs-terminal and
creates the surface — wired to the real runtime factories: `createManagedWorktree`
for the workspace, forking on `startupAgent` exactly as the orchestration worker
path does; `createStructuredAgentSessionForWorktree` for a chat session; and
`createTerminal` for a PTY agent. Allowlisted for mobile, which is the surface the
routing gap was reported on.

`worktree.create` is untouched. Its `startupAgent` keeps meaning "spawn a PTY agent"
verbatim, because it answers with `agentTerminalHandle` only on that path: a host
that quietly routed it to a structured session would hand every older client a
response with no handle and no error. All new behaviour sits behind
`agent.launch.v1`, which the host now advertises and a remote client must negotiate,
so a client that does not gets today's behaviour unchanged.

* feat(mobile): route workspace creates through agent.launch

Picking an agent on the mobile create sheet always produced a terminal, even
when the user's default was native chat, because all three create paths put
`startupAgent` on `worktree.create`. That means "create the worktree
agent-first", so its startup terminal IS the agent and the structured branch
below it is unreachable — while the same phone's in-workspace "+" button opened
a chat.

The blank, branch and new-branch creates now send the same payload through
`agent.launch` and let the host settle the surface. `worktree.create` is
untouched, and a host that does not advertise `agent.launch.v1` (read from the
existing `status.get` probe) keeps today's path exactly.

Work-item creates stay on `worktree.create`: they pre-fill the issue/PR URL as
an unsent `startupDraft`, which a structured session cannot hold yet, so routing
them would submit the URL as a first turn.

* fix(agent-launch): drop the deleted draft-prompt blocker from the reason map

main removed the draft-prompt blocker in stablyai#19681 (a structured session now holds
an unsent draft), so the exhaustive Record no longer typechecks.

* chore(agent-launch): carry a SAFETY rationale on the agent placement cast

The type-assertion gate landed after this branch's base, so the new file's
copy of the worker-start cast is now a changed-code finding.

* chore(agent-launch): carry agent.launch through main's RPC typing and casting gates

The typed-method contract, the generated params catalog and the
`assertionStyle: never` casting scan all landed after this branch's base.

- AGENT_LAUNCH_METHODS kept an `RpcMethod[]` annotation, which widened its
  method name to `string` and broke assignability; every sibling infers instead.
- `agent.launch` binds a schema under src/main, so it joins the catalog's
  RPC_METHODS_WITHOUT_SHARED_PARAMS and the parity gate's hand-listed twin.
- The now-typed methods make most test casts unnecessary; the few that remain
  carry the line-specific SAFETY rationale the casting gate requires.

* test(mobile): supply the agent-launch fixture the create-submit recording needs

The golden RPC recordings landed upstream while this branch was out, so they
first met agent.launch here. Three things had to happen, and only one of them is
a fixture bump.

1. workspace-settings-mounts.ts mounts useNewWorkspaceCreateSubmit against a
   fixture model that throws on any member it was not given. This PR added a
   required getAgentLaunchSupport, so the submit aborted with "Missing model
   fixture" before it ever issued the create, and three cleanup checkpoints
   vanished. That read like a product regression and was not one. Supplying the
   member restores the recording byte-for-byte; it is pinned false for the same
   reason the cutover probe is, so the baseline stays on worktree.create.

2. Editing that adapter moves adapterSha256 for the twelve settings goldens it
   mounts. Their recordings are unchanged - header only, by design: the digest
   is per-golden so editing a module fails exactly the goldens that mounted it.

3. Five goldens changed behaviourally, and both changes are this PR's:
   the capability probe now reports agentLaunch, and a create whose reply
   carries no worktree returns "Failed to create workspace" instead of throwing
   a TypeError off an unguarded result.worktree read. The launch route needs
   that guard, since a receipt can arrive without a worktreeId.

* refactor(mobile): decode the launch receipt instead of asserting its shape

The changed-code quality gate refuses type assertions, and the eight it flagged
were worth removing rather than suppressing.

The production one was the point. readAgentLaunchCreateOutcome asserted the RPC
payload into Partial<AgentLaunchResult> and then runtime-checked it anyway, so
the assertion bought nothing and claimed a contract the host had not proven. It
now narrows with `in` and validates each hop, which is the same nullability
question readCreateResult already answers on the sibling path - a launch receipt
can legitimately arrive without a worktreeId. AgentLaunchCreateOutcome ties
worktreeId to the shared contract so a change there fails this reader's
typecheck rather than passing a differently-typed field through.

The test fakes claimed a whole RpcClient via `as unknown as RpcClient` while
implementing one member. They now build a typed literal, matching the pattern in
use-mobile-structured-agent-options.test.ts. The read sites cast params and then
read one field; they now assert the payload with toMatchObject, which removes
the cast and pins more of the shape than the cast did.

Also pins the warning passthrough, which nothing covered: a terminal launch that
seats the workspace but cannot start the pty reports why, and the absent, blank,
non-string and structured-surface cases report nothing. Writing that test caught
a real drop I had introduced in the reader.

* ci(mobile): re-run Mobile Checks when a shared capability changes

Mobile Checks is path-filtered to mobile/**, but mobile imports the negotiated
capability names straight from src/shared/protocol-version.ts and records the
whole capability read verbatim in its goldens. So a capability added desktop-side
rewrites a mobile fixture while never triggering the suite that would catch it.

That is what happened here: stablyai#19849 introduced agent.launch.v1 and Mobile Checks
never ran on it. Verified at the run level rather than by check name - the
window-free check-runs API on 3837ae8 returns 49 check-runs across six runs
(PR Checks x2, PR test LoC x2, Track Community PRs, Review) and no Mobile Checks
among them. The breakage surfaced only in this PR, which happens to touch mobile/**.

The workflow already concedes this pattern for terminal-file-link-conformance.ts;
protocol-version.ts has the stronger claim, since mobile records its output.

Also corrects the mount adapter's SAFETY comment. It claimed the recorder supplies
only the members the hook reads, which was false the moment the hook gained a
required getAgentLaunchSupport - and the assertion it annotates is exactly what
stopped the compiler from saying so. The twelve goldens are adapterSha256 churn
from that comment: every body is byte-identical, which is the digest doing its job.

* docs(agent-launch): stop the receipt-wording comment claiming a migration

The decision was never moved out of orchestration-worker-start-mode; this PR
adds a second copy beside it. Say so, and name the unenforced agreement.

* docs(agent-launch): stop the executor comment claiming a migration that has not happened

The header asserted two things the tree does not support: that every launch
surface routes through the executor, and that the mode decision "already lived"
in `agent-launch-mode`. `agent.launch` is the executor's only consumer, and
`orchestration-worker-start-mode.ts` is byte-identical (blob 92dc5c6, 217
lines) at the merge base and all three stack heads, still used by workers.ts.
Describe the two live copies and leave the cutover to later stack work.

* fix(agent-launch): preserve setup and refusal fallbacks

* refactor(mobile): parse the launch outcome into a named type at its boundary

anti-slop/no-object-parameters flagged terminalLaunchWarning's `result: object`.
The rule is pointing at a real seam rather than a style nit: the helper advertised
a loose object and did the narrowing inside itself, so every caller handed it
unparsed wire data and nothing downstream held a real type.

Parsed at the boundary instead. parseTerminalLaunchOutcome takes `unknown` and
returns TerminalLaunchOutcome | null, so the narrowing happens once, where the
untrusted payload enters, and the consumer works with a named type.

The type is taken from the shared contract rather than restated - a Pick over the
terminal member of AgentLaunchOutcome - so a change to that union fails here
instead of flowing through. `handle` is deliberately excluded: nothing reads it,
and requiring it would drop the warning off a reply that omitted one, which is a
behaviour change smuggled in under a typing change.

No assertion and no config exemption: reintroducing `as Partial<AgentLaunchResult>`
would trade this finding for the defect removed earlier in this branch, and the
rule is correct here.

The rule arrived with the merge-forward (stablyai#20781, newer than this branch's
merge-base), and anti-slop is not one of the changed-code gate's six scans - it
runs only repo-wide - which is why a clean local gate did not predict it.

Behaviour is unchanged across all five warning cases, and the positive case was
re-ablated on the new parser: dropping the warning reddens exactly it,
1 failed | 18 passed, restored byte-identical to 19 passed.

* fix(agent-launch): dedupe complete launch and cancel setup wait

* fix(agent-launch): memoize the whole launch so a replay cannot mint a second session

A replayed agent.launch could create a second structured session in the same
worktree, with activate: true.

dedupeWorktreeCreate wrapped only the worktree half, inside the workspace
factory. On a replay the create was reused, and the executor then continued to
createSurface and built another surface inside it. The terminal route hid this:
its cached create carries a startup terminal handle, so the executor returns on
early. A structured create has no handle by construction - that is the whole
point of the structured fork - so it fell through every time. Mobile replays
this method deliberately on a delivery-ambiguous response, up to five attempts,
so the path is reachable by design rather than in theory.

The handler now wraps the entire launch in the same dedupe, on the same
(repo, clientMutationId) identity, exactly as worktree.create wraps its own
body. A replay returns the original AgentLaunchResult instead of re-running
createSurface, which makes the two routes replay-identical.

The inner dedupe is removed rather than kept. Wrapping both levels on one key
deadlocks: dedupeWorktreeCreate stores the in-flight promise before the inner
call runs, so the inner call would be handed the outer's promise, which is
waiting on it. The launch-level memo subsumes the worktree-level one.

Failures are still dropped rather than cached, so an unknown outcome stays
unknown instead of replaying as a fabricated success.

The guard replays a STRUCTURED launch: the terminal route cannot reproduce this
and a test there would pass either way. Ablated against the pre-fix files -
1 failed | 22 passed, "expected vi.fn() to be called 1 times, but got 2 times",
which is the duplicate session - then restored to 23 passed. The stub's dedupe
had to be made faithful for that to be observable; the shared one passes through
so other tests can see raw calls.

* Revert "fix(agent-launch): memoize the whole launch so a replay cannot mint a second session"

This reverts commit 59bc5e9.

The same defect was already fixed upstream on this stack's base branch by
539e283, which landed while this was being written. That change is broader
(it also cancels the setup wait) and namespaces the dedupe key, so it supersedes
this one. Reverting rather than hand-merging keeps a single implementation
instead of a hybrid nobody chose.

The behavioural guard from this commit is ported back on top of the upstream
implementation separately: it asserts exactly one structured session survives a
replay, where the upstream tests assert the dedupe wiring.

* ci(mobile): close the round-1 signal gaps around agent.launch

Three review findings, all narrow.

Mobile Checks is path-filtered, and this branch made mobile's types depend on the
shared RPC contract: rpc-params-contract.ts is a type-only re-export of the
generated params catalog, and mobile/tsconfig.json includes **/*.ts. So a
desktop-only edit under src/shared/rpc-contract/ could break mobile's typecheck
with no mobile signal at all - the same blind spot the protocol-version.ts entry
closed, one directory over. Added src/shared/rpc-contract/** to the paths filter.

agent.launch had no cross-version trigger. Added the three prefixes a paired peer
actually exchanges: the intent contract, the wire schema, and the RPC method.
src/main/agent-launch/ is deliberately NOT listed - the executor shapes behaviour
but is not itself wire, and AgentLaunchResult's shape is already covered by
agent-launch-intent. Extending the cross-version SUITE to cover a negotiated
handshake is separate work, not this.

The break branch that answers an accepted-but-empty reply with "Failed to create
workspace" had no unit coverage; the golden that used to discriminate it
collapsed five partitions into one shared error when the null guard replaced the
unchecked read. Covered on BOTH routes - worktree.create with no worktree.id and
agent.launch with no worktreeId - since the branch serves both. Ablated by
bypassing the guard: 2 failed | 11 passed, the two new cases returning a
fabricated worktree instead of the error, restored to 13 passed.

* fix(agent-launch): give a launch one place to say the workspace is incomplete

createManagedWorktree reports an unspawned startup terminal or an uncopied
working tree as a top-level `warning`, and worktree.create hands it straight to
mobile. The launch path narrowed that result down to
{worktreeId, startupTerminalHandle} and dropped it, so every agent.launch create
lost a warning the old method surfaces - on both arms.

The channel was also asymmetric by accident rather than design: a terminal
outcome could carry `warning`, a structured one had nowhere to put it, so the
arm this PR exists to enable was the arm that could not report an incomplete
create at all.

Now there is exactly one place a launch warning lives: AgentLaunchResult.warning,
at the top level. It is about the create as often as the surface, it applies to a
structured session and a terminal alike, and a reader should not branch on
outcome.kind to discover the workspace it just opened is missing something. The
terminal arm's own `warning?` is removed rather than left beside it - two homes
for one fact is how they drift. Every producer folds in: the create, the surface,
and the refusal downgrade.

Consumer census before removing it: one production reader (mobile's
readAgentLaunchCreateOutcome) and no others - the renderer and mobile launch
call sites never read it. The mobile reader now reads the top-level field, which
also lets its outcome parser go away entirely.

Guard ablated by restoring the pre-fix narrowing: 2 failed | 24 passed, both
carriers reporting `expected undefined`, which is the dropped warning itself;
restored to 26 passed. The third case asserts an absence and stays green under
the mutation by construction - it pins shape, not the defect.

* fix(agent-launch): combine both launch warnings instead of dropping one

Round 2 found the comment here was false. A create warning and a surface warning
CAN both be set, on two reachable paths:

  1. The create warns precisely BECAUSE it produced no startup terminal -
     didSpawnStartup stays false when that spawn throws, and
     orca-runtime-create-managed-worktree.ts:283 gates startupTerminal on it - so
     the executor's early return is skipped and a second surface is built, which
     can warn too.
  2. An untracked-copy warning, then a definitive structured refusal downgrading
     to a terminal that also warns.

`??` kept the first and lost the second with nothing saying so. They are now
combined the way the create combines its own failures - appendFailure in
runtime-local-worktree-terminal-startup.ts, and the startup-terminal catch in
runtime-remote-managed-worktree-create.ts - which append rather than replace.

The comment is rewritten to say what is true, and records the gap NOT fixed
here: a create warning about a failed startup terminal is stale once the launch
recovers by building a working one, so a user can be told the agent did not start
while looking at it. Distinguishing those needs createManagedWorktree to stop
multiplexing two unrelated failures into one string.

Guarded and ablated: restoring `??` reddens exactly the new test, with the
surface clause missing from the received string; restored to 27 passed. The
structured-create stub had to admit its real ok-or-refusal union for the
downgrade path to be modellable at all - it previously declared only the ok arm.

Also: mobile.yml gains src/shared/agent-launch-intent.ts. It is the sole holder
of the agent.launch RESULT shape - the rpc-contract catalog holds params only -
and mobile imports it as a value. CROSS_VERSION_WIRE_PREFIXES already treats it
as wire-critical; without this, one gate does and the other cannot see it.

And the agent-first warning test no longer pairs "startup terminal failed" with a
returned handle, a combination the producer cannot emit.

* fix(mobile): read a launch warning an older host nests on the outcome

agent.launch moved `warning` from the terminal outcome to the top level of the
result. That is the right shape - a reader should not branch on `outcome.kind`
to learn the workspace it just opened is incomplete - but on the wire it is a
REMOVAL, and mobile only read the new place.

A host built before the move still advertises the same `agent.launch.v1`
capability, so the capability probe cannot tell the two apart and mobile takes
this route against one:

  protocol-version.ts:360       AGENT_LAUNCH_RUNTIME_CAPABILITY is in
                                RUNTIME_CAPABILITIES, the host list
  orca-runtime-get-status.ts:64 publishes it via status.get; the filter drops
                                only browser.screencast.v1 and three E2E-gated
                                capabilities, never agent.launch
  agent-launch-executor.ts      such a host writes warning INSIDE outcome

The result was a regression rather than a contract cleanup: the worktree.create
path this replaces returned the warning at the top level and mobile read it, so
a create that seated the workspace but could not start the agent surface - pty
exhaustion, untracked files not copied - stopped explaining itself on the phone.

Read both shapes for as long as such a host can be paired. Top level wins, and
cannot be shadowed: AgentLaunchOutcome has no `warning` on either arm, so a
current host cannot nest one.

The test that pinned the old behaviour is inverted here. Its comment was the
actual defect - it framed a legitimate warning from an older peer as a stale
shape to defend against, which is what made dropping it look deliberate.

* chore(mobile): raise the unchecked-reader ceiling for the agent.launch receipt

main landed `unchecked-rpc-reader-inventory.ts`, a ratchet on RpcOperation
readers that re-type their reply instead of validating it. Its ceiling for
mobile-workspace-create-operations.ts is 4, counted on a tree without this
branch's `agentLaunchRun`, so the merge produced "listed 4, found 5".

The inventory's own header prescribes this case: a merge is the one time a line
goes up without a migration undoing itself, and the instruction is to raise it
and name the PR that brought it. It describes main landing an operation the
branch never saw; here it is the mirror - the branch holds one main had not
seen - so the line is annotated with stablyai#19850 rather than left bare.

Not converted to `rpcResultVariant(variant, schema)`, which would lower the line
instead. That is a validation change rather than a migration, which is exactly
what the file's own comment says these five readers deliberately are not; the
agent.launch reply is already guarded at the consumer, where
readAgentLaunchCreateOutcome returns null on a malformed payload and the create
surfaces "Failed to create workspace". Writing a schema now would also target a
reply shape stablyai#20999 is actively redefining.

Ablated: with the line back at 4 the ratchet fails "listed 4, found 5"; at 5 it
passes.

---------

Co-authored-by: Merge Sim <sim@local>
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…20999)

* refactor(agent-launch): redefine the agent.launch contract

`agent.launch` has no clients yet, so the contract is redefined in place
rather than versioned.

- params require `operation.id`, pinned to the shipped operation-id mint so
  the host can read the embedded timestamp back. No caller-supplied
  fingerprint: the host derives its own.
- the result carries `disposition` ('created' | 'replayed', the same
  vocabulary `RuntimeCreateAgentSessionResult` already uses) and a single
  top-level `warning` instead of one on the terminal arm only.
- the prompt receipt becomes an outcome enum, so a receipt can under-claim
  instead of reporting a bare `delivered: false`.
- the dead `customization` field is deleted, and the mode-reason union and
  receipt are declared once in shared with main re-exporting.
- `clientMutationId` joins the reserved create fields, with a test pinning
  the list to the create schema in both directions.

Contract only; no behaviour change and no ledger wiring.

* docs(agent-launch): stop calling the stripped set "agent fields"

`clientMutationId` joined AGENT_LAUNCH_RESERVED_CREATE_FIELDS, so three
comments describing the stripped set as agent fields now teach the wrong
model — including a SAFETY rationale, where a reader is trusting it most.
The rationale's claim is unchanged and still sound: deleting keys from a
parsed object leaves the rest the parsed shape.

* refactor(agent-launch): make the attempt id the launch's only idempotency key

Review follow-ups on the contract redefinition.

`operation: { id }` becomes a flat `clientOperationId`, spelled the way
`terminal.createAgentSession` and the structured mutation envelope already
spell the same concept, and admitted by the shipped
`parseAgentSessionOperationTimestamp` rather than a second copy of its
pattern — so `agent-session-host-authority` keeps the regex private.

The handler now dedupes on that id instead of the create payload's
`clientMutationId`. That field is optional, so keying on it left any launch
that omitted one with no idempotency at all, while the required attempt id
did nothing. Reserving `clientMutationId` is still right, but for the reason
the comments now give: `createManagedWorktree` never reads it, so a copy left
in the forwarded payload is inert while still reading as a guarantee. The
previous rationale — that it was a second live dedupe key — was not true.

`messageId` moves onto the prompt receipt's `journaled` arm so a producer
cannot report the text as committed without saying where, and `rpcCallerKey`
picks up the `terminal.create` call site it was lifted from instead of
shipping with no callers.

* docs(agent-launch): record why disposition is two-valued only for now

The ledger admits attempts whose outcome was never recorded, and neither
`created` nor `replayed` can say "I cannot tell you" — a caller handed
`created` for an unresolved attempt starts a second agent. Noted at the type
rather than in review, so whoever wires the ledger reads it where they edit.

* fix(agent-launch): keep contract within implemented guarantees
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