Skip to content

feat(agent-launch): one executor for agent launches, exposed as agent.launch - #19849

Merged
brennanb2025 merged 16 commits into
mainfrom
brennanb2025/agent-launch-rpc
Sep 15, 2026
Merged

brennanb2025 merged 16 commits into
mainfrom
brennanb2025/agent-launch-rpc

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​761 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​760
Prod 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​796 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​792

ELI5

When you create a new worktree with an agent, the app used to make the worktree and start the agent in a terminal in one step. That meant the "should this be a chat instead?" branch could never be reached — the terminal already existed. This flips the order: make the worktree empty, ask whether a chat is possible, then create whichever surface is right. One piece of code now does that for everyone.

Stack: 2 of 5. Stacked on #19848 — review that first. No client uses this yet; PR 3 is the first caller.

What Changed

  • src/shared/agent-launch-intent.ts — the intent every launch surface builds, and the result it gets back.
  • src/main/agent-launch/agent-launch-executor.ts — executeAgentLaunch, the single place an agent is started.
  • src/main/runtime/rpc/methods/agent-launch.ts + schemas — the agent.launch RPC, gated on a new agent.launch.v1 capability.
  • Worktree/surface factories reusing createManagedWorktree and the generic createStructuredAgentSessionForWorktree.
  • 'agent.launch' added to the mobile method allowlist.

Why

The routing decision was already shared. The sequencing around it was not, and that is where the bug lives:

create the worktree agent-first  ->  its startup terminal IS the agent
                                 ->  the structured branch below it is unreachable

So every new-worktree launch was a PTY regardless of the user's default. Orchestration fixed this for itself in #19431; mobile and the CLI still have it.

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. A refusal becomes a terminal agent in the worktree just created, never a failed launch.

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.

Bug found while wiring

An existing target arrives as a selector, but worktreeId is an id and everything below the executor re-prefixes id: — so a caller's id:wt-7 reached the runtime as id:id:wt-7. Now resolved through showManagedTerminalWorkspace (not showManagedWorktree, so folder workspaces stay addressable). Pinned by a test.

Linked Issue

Fixes #

Visual Proof

N/A — no client calls agent.launch in this PR, so there is no user-visible change. The first visible change is PR 3.

Testing

  • agent-launch.test.ts 16/16; with the executor suite, 27/27 across 2 files.
  • Regression: mobile allowlist / remote-runtime-client / PR-suppression / worktree-create-navigation 38/38; client-events + structured-agent-session + worker-start-mode 77/77; cross-version wire compat 23/23.
  • Capability sweep: adding to RUNTIME_CAPABILITIES is the classic way to redden exact-list assertions while targeted runs stay green. Swept 292 test files / 3,133 tests across five search axes. Nothing breaks — every assertion on the host list is membership (toContain), not identity; there is no toEqual([...]) or snapshot of that list in the repo.
  • tsc clean, oxlint clean, oxfmt --check clean, changed-code quality gate 0 findings across 15 files.

Ablations, re-proved at final HEAD after formatting:

Break Result
Reinstate agent-first creation 5 tests red
Delete the capability gate refusal test red
Drop agentTerminalHandle from worktree.create compat test red

Known-unrelated: release-checkout.unit.test.ts fails on this machine because the clone is shallow with no reachable merge commits, so git rev-parse ~2^{commit} fails. Confirmed pre-existing against an ancestor commit.

Platforms: macOS.

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

Revival onto the current base

This branch was stale against its own base: #19848 is 361 commits ahead of the merge base while this branch is 2. Merged rather than rebased. One conflict, one hunk — protocol-version.ts, where both sides appended a different final entry to RUNTIME_CAPABILITIES. Resolved by keeping both, so agent.launch.v1 survives alongside main's notifications.remote-push.v1. Confirmed in the committed blob at all three of its sites: the const declaration, NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES, and RUNTIME_CAPABILITIES.

Three changes that dangled outside the conflict region

None of these produced a conflict marker. Each auto-merged silently and would have shipped broken on a clean git status; all three were caught by typecheck and the changed-code quality gate rather than by the merge.

  1. The typed-method contract. defineMethod now preserves a method's literal name. AGENT_LAUNCH_METHODS carried an RpcMethod[] annotation that collapsed that name to string and broke assignability at the registry boundary. It was the only file under methods/ with such an annotation — the ~25 siblings infer — so it was removed to match.
  2. The generated RPC params catalog. agent.launch was absent from it. Regenerated with pnpm generate:rpc-params-catalog; the generator placed it in RPC_METHODS_WITHOUT_SHARED_PARAMS on its own, correctly, because its zod schema lives under src/main like emulator.install. The diff is exactly +1 line. Its hand-maintained twin, UncataloguedMethod in rpc-params-type-parity.ts, needed the same entry or the parity gate fails its AssertNever.
  3. The casting gate, described next.

Test-internal cast cleanup, and why it belongs in this PR

The assertionStyle: never casting gate postdates this branch's base, so clearing it is not elective scope — the PR cannot go green otherwise. It reported 23 findings in this PR's own test files plus 2 in production files.

Wherever the now-flowing types carry the guarantee, casts were removed rather than suppressed, since a suppression preserves the unsafe shape and hides it. methodNamed became a generic with a type predicate, and launch results are typed by the real AgentLaunchResult, so the per-test result casts disappeared outright.

Four casts genuinely remain, each carrying the line-specific SAFETY: rationale the gate requires, in the form established in #19848:

Site Why it cannot be typed away
agent-launch-schemas.ts The superRefine above it rejects anything isTuiAgent refuses, so the transform only ever runs on a TuiAgent — a narrowing zod cannot express.
agent-launch-worktree-creation.ts The create payload is already validated by AgentLaunch; the executor only stripped the reserved agent fields.
agent-launch.test.ts The runtime stub implements only the surface agent.launch reaches, so a method it omits throws on call rather than reading a wrong value.
agent-launch-executor.test.ts The same, for the two runtime methods the executor reaches.

Test counts are unchanged — agent-launch.test.ts 16/16 and 27/27 across both files, the same numbers as before the merge — and no assertion was weakened.

AI Disclosure

Review

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

Backwards compatibility is the main review axis here. worktree.create is byte-for-byte unchanged: startupAgent still means "spawn a PTY agent" and still returns agentTerminalHandle. This is deliberate and load-bearing — per Rule 3 in docs/reference/remote-wire-compatibility.md, a host that quietly routed that call to a structured session would hand an old client a response with no handle and no error. A dedicated test asserts worktree.create returns the handle and that neither the create-support probe nor the structured create is reached; it goes red if anyone routes that call.

A client not advertising agent.launch.v1 gets agent_launch_unsupported and falls back to today's behavior.

Security: new RPC is capability-gated and on the mobile allowlist deliberately. Cross-platform: no platform-dependent paths. Remote SSH: remote hosts downgrade to terminal via the existing reason. Mobile: allowlisted but not yet called. Performance: one extra createSupport round-trip on structured launches only.

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)

Merge Sim added 3 commits September 9, 2026 17:19
`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.
…uns 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.
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.
Merge Sim and others added 7 commits September 11, 2026 10:48
…son map

main removed the draft-prompt blocker in #19681 (a structured session now holds
an unsent draft), so the exhaustive Record no longer typechecks.
…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.
…into brennanb2025/revive-agent-launch-rpc

# Conflicts:
#	src/shared/protocol-version.ts
… 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.
@brennanb2025
brennanb2025 marked this pull request as ready for review September 15, 2026 06:51

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The executor's documented setup-gate contract is not honored by the shipped workspace factory. agentLaunchWorkspaceFactory sets neither awaitTerminalProvisioning nor observeSetupCompletion, and nothing between creating the worktree and attaching the session waits on setup completion — yet agent-launch-executor.ts:64-67 says a structured launch "must await that gate explicitly instead". See the inline comment for the concrete race and the reference implementation.

Reviewed changes

  • src/shared/agent-launch-intent.ts (new) — the surface-neutral AgentLaunchIntent / AgentLaunchResult / AgentLaunchModeReceipt vocabulary every launch surface builds, plus withoutReservedAgentCreateFields, which strips startupAgent/startupCommand/startupPrompt/startupDraft/… out of a create payload migrated off worktree.create.
  • src/main/agent-launch/agent-launch-executor.ts (new) — executeAgentLaunch, the single ordering: create the workspace (agent-first only for a terminal), ask the host's agentSession.createSupport for the workspace that now exists, then build the decided surface.
  • src/main/runtime/rpc/methods/agent-launch*.ts (new) — the agent.launch RPC and its schema, the surface factory (structured create with activate: true, or runtime.createTerminal({ startupAgent })), and the worktree factory. Gated on agent.launch.v1 and added to the mobile method allowlist.
  • src/shared/protocol-version.ts, rpc-params-type-parity.ts, rpc-params-catalog.generated.ts, methods/index.ts — capability, typing/casting, catalog, and registration plumbing.
  • Tests — executor and RPC suites pin call order/arguments, including a worktree.create guard that it still returns agentTerminalHandle without consulting the route.

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

})
// Reserved before creation so a retry can recover; a failed attempt has to release it.
try {
const result = await runtime.createManagedWorktree({

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.

Neither awaitTerminalProvisioning nor observeSetupCompletion is set here, and executeAgentLaunch has no setup wait between creating the worktree and attaching the session. For a repo whose policy is wait-for-setup, the structured session's provider child can run its first turn while .orca setup is still running — the race worker-start-structured-setup-gate.ts was written to prevent, and one this module's own contract calls out.

Technical details
# Structured launches skip the wait-for-setup gate

## Affected sites
- `src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts:49` — the create passes only `createdWithAgent: agent`; `buildManagedWorktreeCreateArgs` maps neither `awaitTerminalProvisioning` nor `observeSetupCompletion`, and `WorktreeCreate` (worktree-create-params.ts) has no fields for them.
- `src/main/agent-launch/agent-launch-executor.ts:107-128` — `resolveWorkspace` → `resolveAgentLaunchModeOnHost` → `createSurface` with no wait in between, and the factory result carries no `setupReceipt` to gate on.
- `src/main/runtime/runtime-local-worktree-terminal-startup.ts:151-165` — with `activate` false and no `awaitTerminalProvisioning`, setup provisioning is fire-and-forget, so the create resolves before setup even spawns.
- `src/main/runtime/runtime-worktree-terminal-provisioning.ts:104-146` — without `observeSetupCompletion` no completion token is recorded, so `waitForSetupTerminalCompletion` has nothing to observe.

## Required outcome
A structured launch that creates its own worktree must not attach its session before the `wait-for-setup` gate; or the executor comment at `agent-launch-executor.ts:64-67` must stop claiming it does.

## Suggested approach
The reference is `worker-worktree-creation.ts:58-59` plus `worker-start-structured-setup-gate.ts`: when `startupAgent` is undefined, set `awaitTerminalProvisioning: true` and `observeSetupCompletion: true` (forcing `activate: false`, as the worker path does, so the setup terminal exists to wait on), return the setup receipt from the factory, and have the executor await `waitForSetupTerminalCompletion` for `startupPolicy === 'wait-for-setup'` before `createSurface`.

## Open questions for the human
The desktop renderer's structured quick-create flow already opens the session with no setup wait (no `waitForSetupTerminalCompletion` anywhere under `src/renderer`), so this may be an accepted product gap rather than an orchestration-only concern. Worth deciding explicitly and making the comment match.

brennanb2025 added a commit that referenced this pull request Sep 15, 2026
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.
…tion

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.
…at 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.
@brennanb2025
brennanb2025 changed the base branch from brennanb2025/agent-launch-mode to main September 15, 2026 20:22
@coderabbitai

coderabbitai Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change adds the negotiated agent.launch RPC and its shared intent model. A central executor resolves workspaces, selects structured or terminal sessions, handles definitive structured-session refusal, and reports prompt receipts. RPC factories create workspaces and launch surfaces. Capability advertisement, method registration, mobile allowlisting, validation, setup waiting, compatibility behavior, and execution tests are included.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 539e2

Local Electron IPC callers cannot use the newly advertised agent launch RPC, and conflicting retry IDs can return the wrong launch result. Fix these before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a detailed ELI5 summary, change rationale, testing evidence, compatibility notes, and completed checklist. However, the required Linked Issue field remains unresolved as “Fixe… Add a valid linked issue reference in the Linked Issue section, such as “Fixes #12345”, or obtain repository approval for an explicit exception to the required issue-link policy.
Docstring Coverage ⚠️ Warning Docstring coverage is 20.83% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 14 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: a centralized agent-launch executor exposed through the agent.launch RPC.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description provides a detailed ELI5 summary, change rationale, testing evidence, compatibility notes, and completed checklist. However, the required Linked Issue field remains unresolved as “Fixes #”, and the text states that no issue was filed.

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

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b9c15767-cdee-4018-950b-2ab39399c976

📥 Commits

Reviewing files that changed from the base of the PR and between 22857cd and 2b7dcf3.

⛔ Files ignored due to path filters (1)
  • src/shared/rpc-contract/rpc-params-catalog.generated.ts is excluded by !**/*.generated.*
📒 Files selected for processing (13)
  • src/main/agent-launch/agent-launch-executor.test.ts
  • src/main/agent-launch/agent-launch-executor.ts
  • src/main/runtime/rpc/methods/agent-launch-schemas.ts
  • src/main/runtime/rpc/methods/agent-launch-surfaces.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/methods/index.ts
  • src/main/runtime/rpc/rpc-params-type-parity.ts
  • src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-allowlist.ts
  • src/shared/agent-launch-intent.ts
  • src/shared/protocol-version.ts
  • src/shared/source-scan/source-tree-walk.test.ts
💤 Files with no reviewable changes (1)
  • src/shared/source-scan/source-tree-walk.test.ts

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

Comment on lines +91 to +95
const preflight = decideAgentLaunchMode({
placement: {
agent: intent.agent,
...(intent.reuseTerminal ? { terminal: intent.reuseTerminal.handle } : {})
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve AgentLaunchIntent.customization through routing and terminal creation.

AgentLaunchIntent accepts customization.agentArgs and cwd, and the shared route treats TUI customization as terminal-only. executeAgentLaunch omits this field from decideAgentLaunchMode and createTerminalAgent. A direct intent caller can therefore select structured mode and lose the customization. Terminal mode also drops the values before OrcaRuntimeService.createTerminal, which accepts cwd and launchConfig.agentArgs.

Thread customization through both calls. Map cwd to TerminalCreateOptions.cwd and agentArgs to launchConfig.agentArgs. The current agent.launch RPC schema intentionally excludes customization, so this fix applies to callers that construct AgentLaunchIntent directly rather than expanding that RPC schema.

)

execution.onStage?.('surface_create')
const outcome = await createSurface(execution, placed.worktreeId, settled)

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Fall back only for definitive pre-commit structured-create refusals.

executeAgentLaunch does not catch createSurface failures. agentLaunchSurfaceFactory.createStructuredSession converts every ok: false result into an Error, so pre-commit refusals and agent_session_operation_unknown take the same path and no terminal fallback runs.

createStructuredAgentSessionForWorktree converts preparation failures before attach into definitive refusals. After attach, it can return an attach refusal, and tab-publication failure returns agent_session_operation_unknown. Preserve the refusal code and fall back only for definitive pre-commit refusals. Propagate unknown or post-commit outcomes to avoid starting a duplicate agent.

@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: 4780b2e2-ea1d-4d54-a88e-dd2309180fdd

📥 Commits

Reviewing files that changed from the base of the PR and between 2b7dcf3 and d5e1402.

📒 Files selected for processing (6)
  • src/main/agent-launch/agent-launch-executor.test.ts
  • src/main/agent-launch/agent-launch-executor.ts
  • src/main/runtime/rpc/methods/agent-launch-surfaces.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

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

await Promise.race([
runtime.waitForSetupTerminalCompletion(receipt.terminalHandle),
new Promise<void>((resolve) => {
timer = setTimeout(resolve, STRUCTURED_SETUP_WAIT_TIMEOUT_MS)

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Require successful setup completion before creating a structured session.

waitForSetupTerminalCompletion returns the setup exit code, including nonzero failures. waitForStructuredSetup ignores that result, catches waiter errors, and races the wait against a 60-second timer. The launch then reaches createStructuredSession after a timeout, rejected wait, or failed setup. Continue only when setup completes with exitCode === 0; otherwise fail or cancel the launch.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The new setup gate only takes effect for a non-activating worktree create. Mobile's worktree.create payload — which this method's create is specified to carry verbatim — always sends activate: true, and that path delegates setup to the renderer, leaving no setup terminal for waitForStructuredSetup to await. Details inline.

Reviewed changes

  • Added a definitive-refusal fallback: AgentLaunchStructuredSessionRefusedError carries the wire refusal code, and executeAgentLaunch downgrades to a terminal in the same workspace only when isDefinitiveAgentSessionCreateRefusal accepts it — unknown/post-attach outcomes still propagate.
  • Extended the workspace factory with the setup gate: awaitTerminalProvisioning/observeSetupCompletion plus waitForStructuredSetup on startupPolicy === 'wait-for-setup'.
  • Validated reuseTerminal at the RPC boundary (existing target required, terminal must belong to the addressed workspace, must be running an agent), retiring the worktreeId: '' path.
  • Tests: definitive vs unknown refusal fallback, setup-gate ordering, and the three reused-terminal rejections.

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

Comment on lines +71 to +75
awaitTerminalProvisioning: true,
observeSetupCompletion: true
})
if (!startupAgent) {
await waitForStructuredSetup(runtime, result.setupReceipt)

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.

waitForStructuredSetup is a no-op for any create that activates. When shouldActivate is true and there is no startup agent (always the case for a structured launch), the runtime skips provisioning and delegates setup to the renderer via ports.activate, so the receipt comes back spawn_failed with no terminalHandle and the guard below returns immediately. Mobile's worktree.create params always send activate: true, and this method's create is that payload verbatim, so the first caller still attaches its session while .orca setup runs.

Technical details
# Activating creates bypass the new structured setup gate

## Affected sites
- `src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts:71-75` — the setup flags and the `if (!startupAgent)` wait; both depend on the runtime having spawned the setup terminal itself.
- `src/main/runtime/runtime-local-worktree-terminal-startup.ts:127-165` — with `shouldActivate` true and `didSpawnStartup` false, `runtimeWillProvision` is false, so the branch calls `ports.activate` with the setup and never spawns it; `setupTerminalHandle` stays null.
- `src/main/runtime/runtime-remote-managed-worktree-create.ts:143-166` — the same fork on the remote path.
- `src/main/runtime/orca-runtime-create-managed-worktree.ts:254-274` — the receipt then resolves to `state: 'spawn_failed'` with no `terminalHandle`, so the guard at `agent-launch-worktree-creation.ts:95-102` returns without waiting.
- `mobile/src/tasks/workspace-create-params.ts:130-132` — mobile's `worktree.create` params set `activate: true` unconditionally, and `agent.launch`'s `create` is documented as that request verbatim.

## Required outcome
A structured launch that creates its own worktree must await the `wait-for-setup` gate regardless of the caller's `activate` flag — or the flags/comment here must stop claiming the setup terminal is provisioned synchronously and the launch waits on it.

## Suggested approach
Force `activate: false` on the worktree create for the structured case (as `worker-worktree-creation.ts:67` does) and let the chat surface's own `activate: true` take the UI, so the runtime spawns the setup terminal and records the completion token the wait needs. If the caller's activation must stay, thread a setup-terminal handle back through activation instead.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron/CDP validation (hidden renderer)

Ran against final head d5e1402ea8 in this worktree with ORCA_BACKGROUND_LAUNCH=1 (windowless, CDP 127.0.0.1:9335, isolated profile). Identity: Orca: pr19849-val / pr19849-agent-launch-val.

Limitation: this PR has no rendered client call to agent.launch. Desktop still starts agents through the existing Create workspace / Agents surfaces. There is no new user-visible launch control to exercise.

What the hidden app did show:

  • Host runtime.getStatus().capabilities includes agent.launch.v1.
  • window.api.runtime.call({ method: 'agent.launch' }) is registered: unknown method → method_not_found; empty/bad params → invalid_argument (Unknown TUI agent / missing target). No worktree was created.
  • A well-formed desktop IPC call (claude + existing missing worktree) returns agent_launch_unsupported, because local runtime:call advertises a hardcoded capability list that does not include agent.launch.v1. There is no window.api.agent.launch.
  • Renderer console: 0 errors. Main log has no agent.launch errors (unrelated ws-transport 6769 bind skip from another instance).

Empty home (isolated profile, no new launch UI)

01-empty-home.png

Agents panel (session history only)

02-agents-panel.png

Existing Create workspace dialog (not submitted; still the desktop launch surface)

03-create-workspace-dialog.png

First visible change remains the later stack PR that actually calls this method.

brennanb2025 added a commit that referenced this pull request Sep 15, 2026
…launch-mobile

The base moved 31 commits: #19849 merged main forward, #19848 landed on main as a
squash, and several mobile domains migrated onto typed RpcOperations.

The only conflicts were 12 settings goldens, and only in two header digests.
Both sides had moved a digest for a legitimate and different reason: upstream
added ~35 files under src/test-support/rpc-recording/, which recorderSha256
covers, while this branch edited workspace-settings-mounts.ts, which
adapterSha256 covers - and upstream never touched that adapter. So neither
side's pair described the merged tree, and taking either wholesale would have
committed a header that lies about the sources it was recorded from.

Resolved by re-recording from the merged tree, which computes both digests from
the actual merged files. The result pairs upstream's recorderSha256 with this
branch's adapterSha256. All 12 bodies are byte-identical to what was already on
disk, so nothing behavioural changed: the conflict was entirely provenance.

The golden set grew 208 -> 509 with upstream's new scenarios; recorded set and
on-disk set match exactly, with no stale and no missing files.

@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 unresolved setup-gate thread from the prior review is untouched by these commits and still gates the PR.

Reviewed changes

  • Moved agent.launch's idempotency wrapping from the worktree factory to the RPC handler: a create-worktree launch carrying clientMutationId now dedupes the whole launch (agent.launch:<id>) instead of only the create, so a concurrent or retried structured launch can no longer create a second chat session.
  • Added optional AbortSignal support to waitForSetupTerminalCompletion, and made waitForStructuredSetup's bounded wait abort its observation on timeout (structured_setup_wait_timeout) rather than leaving the subscription live.
  • Tests: concurrent and sequential dedupe of a structured launch, and the timeout-triggered abort (the runtime fragment runs through orca-runtime.test.ts, since the vitest include pattern only matches *.test.ts).

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

@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

⚠️ Outside the diff (1)

🟠 Major · Add AGENT_LAUNCH_RUNTIME_CAPABILITY to the local IPC contexts.

src/main/runtime/rpc/methods/agent-launch.ts:89-116
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Add AGENT_LAUNCH_RUNTIME_CAPABILITY to the local IPC contexts. src/main/ipc/runtime.ts:75-94 and :120-146 dispatch ALL_RPC_METHODS with clientKind: 'runtime', but both hardcoded capability arrays omit AGENT_LAUNCH_RUNTIME_CAPABILITY. supportsAgentLaunch therefore rejects valid agent.launch requests with agent_launch_unsupported. Add the capability to both arrays.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 57413e49-32ac-48fb-a381-aebe8fc508fd

📥 Commits

Reviewing files that changed from the base of the PR and between d5e1402 and 539e283.

📒 Files selected for processing (5)
  • src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts
  • src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.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

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

if (params.target.kind === 'create-worktree' && params.target.create.clientMutationId) {
return context.runtime.dedupeWorktreeCreate(
params.target.create.repo,
`agent.launch:${params.target.create.clientMutationId}`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Reject conflicting clientMutationId reuse. agent.launch reuses WorktreeCreate, where clientMutationId has no uniqueness or immutable-request constraint. The handler passes only the repository and agent.launch:${clientMutationId} to dedupeWorktreeCreate. A later request with the same key but different launch parameters can receive the earlier result without running executeAgentLaunch. Store and compare a request fingerprint, or include caller identity if mutation IDs are caller-scoped.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready to merge

Reviewed and fixed on commit 539e283c0f.

Changes made

  • Enforced setup provisioning and readiness before structured session creation.
  • Restricted terminal fallback to definitive pre-commit refusal codes; unknown outcomes no longer create duplicate terminal agents.
  • Validated reused terminals against the requested workspace and agent presence.
  • Deduplicated the complete create-worktree agent.launch operation, including surface creation, by clientMutationId.
  • Added abort-aware setup waiting and cleanup of runtime setup observers.

Validation

  • 42 focused launch/refusal tests passed.
  • Full runtime suite: 1,276 passed, 1 skipped.
  • pnpm tc:node passed.
  • Changed-code quality gate passed with 0 findings.
  • oxfmt --check and git diff --check passed.
  • PR checks, including typecheck, static analysis, packaging (macOS and Windows), all test shards, wire compatibility, and verify, are green.
  • Electron/CDP screenshots and capability/RPC validation are attached in the review evidence comment. The current build has no renderer/mobile/CLI caller for agent.launch, so a successful end-to-end launch surface cannot yet be demonstrated.

Remaining finding

Final readiness review found no P0/P1 issues. One valid P2 residual remains: if structured session publication returns agent_session_operation_unknown after a session may have committed, the rejected launch dedupe entry is dropped and a same-clientMutationId retry could duplicate the worktree/session. There is no current shipped caller, so this is latent and not release-blocking; durable reconciliation should be completed when the first caller exposes retry semantics.

Recommendation: merge the PR at 539e283c0f; track the residual as follow-up for the first agent.launch caller.

@brennanb2025
brennanb2025 merged commit 6da7238 into main Sep 15, 2026
28 checks passed
brennanb2025 added a commit that referenced this pull request Sep 16, 2026
#19850 was retargeted to main after #19849 landed as a SQUASH, so this branch
held #19849's original commits while main held the squashed equivalent - the
same content under different SHAs, which git reported as dirty.

Five files conflicted add/add, all of them files this PR also edits. Neither
side was takeable wholesale: theirs would have discarded this PR's work, ours
would have discarded anything main gained. Verified first that main's blob for
each is byte-identical to 539e283 - the #19849 head this work builds on - so
ours is a strict superset and the conflict is purely the squash artifact. Then
took ours on all five.

Two things auto-merged WRONG, outside any conflict region, and neither showed a
marker:

  - rpc-params-type-parity.ts silently reverted to main's copy, putting
    'agent.launch' back in UncataloguedMethod while the catalog still holds the
    entry. Typecheck caught it: TS2344 at :45. Re-applied.
  - the generated params catalog was stale against main's new methods.
    Regenerated; agent.launch stays catalogued and the uncatalogued list is
    back to three.

Audited every file this branch authored against main's copy afterwards: none
other reverted. The only file matching main verbatim is src/relay/pty-handler.ts,
which this branch never touched.
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>
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
….launch (stablyai#19849)

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

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

* 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

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

---------

Co-authored-by: Merge Sim <sim@local>
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>
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