Repository navigation
fix(native-chat): unify launch routing and support structured worker placement - #19431
Conversation
`orchestration.workerStart` reads the user's "open agent tabs in chat" default, but two placement checks downgraded a structured-preferring worker to a PTY terminal agent for the two flags a routine dispatch always passes: --worktree new-child / new-top-level -> worktree_creation --model / --effort -> launch_preferences so in practice a structured worker never happened. launch_preferences was stale. PR #19040 gave AgentSessionAttachParams `options` and added resolveStructuredLaunchSeedOptions, which narrows a saved selection to exactly `model` and `effort` — the two ids both structured providers accept as strings. --model/--effort now go through that same narrowing (extracted as narrowStructuredLaunchSeedOptions) and seed the worker's session instead of forcing a terminal. An option set that narrows to nothing resolves to undefined, never `{}`, which would fail the record's bounded-string guard under a code that is not a wire refusal and strand the launch with no fallback. worktree_creation was a consequence of createWorkerWorktree creating agent-first: its startup terminal WAS the worker, so the structured branch below it was unreachable for any new worktree. A structured worker now creates the worktree with no startup agent and creates its session for the worktree afterwards — the order the renderer's own structured worktree create already uses. Because the executing host can only answer agentSession.createSupport for a workspace that exists, that verdict moved after creation: a refusal (WSL, and the rest) becomes a terminal agent in the worktree just created, never a failed start. --on and --terminal still downgrade, with their reasons intact, and every remaining downgrade still states itself in the mode receipt. The wait-for-setup gate is preserved explicitly. A PTY worker got it for free — agent-first creation sequences the agent's startup command behind the setup runner, so tui-idle could not arrive until setup exited. A structured session has no startup command to sequence, so the gate is now awaited directly, bounded by the start's own timeout. Split out worker-worktree-creation.ts and worker-start-agent-placement.ts rather than growing two files that were both pinned at the max-lines cap.
There was a problem hiding this comment.
Important
The wait-for-setup gate is only taken when a structured session is produced, so the terminal fallback that a host refusal triggers starts its agent ungated — see the inline comment for the specifics.
Reviewed changes
Removes the two placement downgrades that made structured worker-start unreachable and plumbs the dispatch's --model/--effort into the session's seed options.
- Drop the
worktree_creation/launch_preferencesdowngrades —--worktree new-childand--model/--effortno longer force a PTY worker, and both reasons leave the vocabulary rather than lingering as values nothing can emit. - Extract
placeWorkerAgent/worker-worktree-creation.ts— a structured worker creates its worktree without a startup agent terminal (withAgentTerminal: false) and creates the session afterwards; the host verdict moves after creation so a refusal becomes a terminal in the just-created worktree, never a failed start. - Seed
--model/--effortvianarrowStructuredLaunchSeedOptions— the narrow is extracted into shared code, returnsundefinedrather than{}, and replaces the settings-resolved seed options without moving the attach fingerprint. awaitStructuredWorkerSetupGate— preserves the repo'swait-for-setuppolicy for the structured path, bounded by the start timeout and forgiving on missing evidence.- Tests — mode-selection and seed-option coverage, plus an ablation table confirming each fix flips a test red.
ℹ️ Nitpicks
- The structured failure message in
local-worker-start.tssays "Setup did not finish before the structured worker started" for both a timeout and a non-zero exit; the latter did finish, it failed.failedStageis set correctly (setup_wait) — only the wording is off.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| }) | ||
| // gap and no terminal title to read an idle edge from. Only the repo's wait-for-setup policy | ||
| // still holds it back, and that gate has to be waited on explicitly here. | ||
| const wait = structuredSession |
There was a problem hiding this comment.
The setup gate is only taken for structuredSession. When a structured-preferring new-child/new-top-level dispatch creates its worktree with withAgentTerminal: false and the host then refuses the structured session (WSL, codex_on_windows, remote, etc.), placeInCreatedWorktree falls back to createExistingWorktreeWorkerTerminal. That terminal's startup command is not sequenced behind setup — the sequencing only comes from agent-first creation — so waitForTerminal(tui-idle) returns satisfied while setup is still running, applyWaitForSetupOutcome records succeeded, and task input is delivered before wait-for-setup completes. The old always-agent-first path never had this gap, because structured new-child was unreachable.
Technical details
# Terminal-fallback worker bypasses the wait-for-setup gate
## Affected sites
- src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts:168 — the `structuredSession ? gate : waitForTerminal` ternary gates only the structured case.
- src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts:121 — `withAgentTerminal: args.mode.mode !== 'structured'` creates the worktree agent-less for the structured path.
- src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts:136-142 — host refusal downgrades to terminal, then `createExistingWorktreeWorkerTerminal` starts the agent ungated.
## Required outcome
- A terminal fallback in a worktree this start created must honor `wait-for-setup` the same way the structured path does: task input must not be delivered (and setup must not be recorded `succeeded`) until setup completes.
## Suggested approach (optional)
- Gate the terminal fallback too — either route it through `awaitStructuredWorkerSetupGate` (rename to a mode-agnostic `awaitWorkerSetupGate`) when `setupReceipt.startupPolicy === 'wait-for-setup'`, or have the fallback terminal wait on the setup marker.
## Open questions for the human (optional)
- Is the terminal fallback supposed to run setup at all? The structured path's host refusal happens only for hosts that can't do structured; on those hosts a PTY worker is the honest fallback, but it still must respect the repo's setup policy.
📝 WalkthroughWalkthroughStructured workers remain available when dispatches specify a new worktree, model, or effort. Shared helpers handle worktree creation and agent placement. Structured sessions receive narrowed launch options without changing their attach fingerprint. Setup readiness uses a timeout-aware gate. Shared support resolution handles reused terminals and unknown host capability. Tests cover routing, placement, option propagation, saved-option fallback, and terminal fallback. Priority: ➖ Normal Severity of issue fixed: Medium Merge Risk: 🟡 Moderate · up to Structured worker launches may report a different mode than the one actually started, and failures after creating a worktree may leave resources behind or record inaccurate setup details. A terminal fallback may also proceed before setup completes. These lifecycle and observability risks should be addressed before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the motivation, implementation, compatibility impact, testing, and visual proof. However, it omits several template sections, including the required Linked Issue with a Fixes reference, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist. Resolution Add all missing template sections. Include a valid linked issue using the required
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: e2c20479-7762-4356-8667-b028ebbc7140
📒 Files selected for processing (13)
src/main/runtime/rpc/methods/orchestration-structured-worker-session.tssrc/main/runtime/rpc/methods/orchestration-worker-start-mode-selection.test.tssrc/main/runtime/rpc/methods/orchestration-worker-start-mode.test.tssrc/main/runtime/rpc/methods/orchestration-worker-start-mode.tssrc/main/runtime/rpc/methods/orchestration/worker/local-worker-start.tssrc/main/runtime/rpc/methods/orchestration/worker/structured-worker-launch-seed-options.test.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-topology.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.tssrc/main/runtime/rpc/methods/structured-agent-session-create.tssrc/shared/native-chat-session-option-defaults.test.tssrc/shared/native-chat-session-option-defaults.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| } | ||
| throw new Error( | ||
| wait.blockedReason | ||
| 'blockedReason' in wait && wait.blockedReason |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Narrow wait.blockedReason before the template literal.
wait is a union of StructuredWorkerSetupGate and RuntimeTerminalWait. The latter defines optional blockedReason. Oxlint enables typescript/restrict-template-expressions, and the type-aware check denies warnings, so this interpolation can fail pnpm lint. Add an explicit string check.
🔧 Proposed fix
- 'blockedReason' in wait && wait.blockedReason
- ? `Agent startup blocked: ${wait.blockedReason}`
+ 'blockedReason' in wait && typeof wait.blockedReason === 'string' && wait.blockedReason
+ ? `Agent startup blocked: ${wait.blockedReason}`| coordinatorWorktree, | ||
| params: args.params, | ||
| agent: args.agent as TuiAgent, | ||
| withAgentTerminal: args.mode.mode !== 'structured', |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Find every call site of the structured setup gate and every readiness wait in worker start.
rg -n -C6 'awaitStructuredWorkerSetupGate|waitForTerminal\(' src/main/runtime/rpc/methods/orchestration
# Confirm resolveWorkerStartModeOnHost downgrades rather than throws on refusal.
ast-grep run --pattern $'function downgradeWorkerStartModeForHost($$$) { $$$ }' --lang typescript src/main/runtime/rpc/methods/orchestration-worker-start-mode.tsRepository: stablyai/orca
Length of output: 7255
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 36290
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- changed file outline ---'
ast-grep outline src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts
printf '%s\n' '--- placement implementation ---'
sed -n '1,240p' src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts
printf '%s\n' '--- local worker start ---'
sed -n '1,230p' src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts
printf '%s\n' '--- mode resolver ---'
sed -n '1,220p' src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts
printf '%s\n' '--- setup gate ---'
sed -n '1,180p' src/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.tsRepository: stablyai/orca
Length of output: 27469
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- worktree creation and terminal surface ---'
ast-grep outline src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.ts
ast-grep outline src/main/runtime/rpc/methods/orchestration/worker/worker-topology.ts
printf '%s\n' '--- relevant implementations ---'
rg -n -C12 'createWorkerWorktree|withAgentTerminal|createExistingWorktreeWorkerTerminal|startupPolicy|wait-for-setup|kind: .setup' \
src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.ts \
src/main/runtime/rpc/methods/orchestration/worker/worker-topology.ts
printf '%s\n' '--- all gate and readiness call sites ---'
rg -n -C5 'awaitStructuredWorkerSetupGate|waitForTerminal\(' \
src/main/runtime/rpc/methods/orchestration/workerRepository: stablyai/orca
Length of output: 32936
Preserve the setup gate for downgraded worktree workers. createWorkerWorktree receives withAgentTerminal: false for the preferred structured mode. If host support then downgrades the mode, createExistingWorktreeWorkerTerminal creates a terminal without agent-first sequencing. Because structuredSession is null, local-worker-start.ts calls runtime.waitForTerminal(...) and skips awaitStructuredWorkerSetupGate(...). A wait-for-setup hook can therefore still run when the dispatch preamble is delivered. Track whether placement created a non-agent-first worktree and apply the setup gate for that path.
…ngrade' into brennanb2025/native-chat-unify
|
Too many files changed for review (465 files, 100 file limit). Bypass the limit by tagging |
There was a problem hiding this comment.
ℹ️ No new issues in this increment — the shared-feasibility refactor is sound. Not approving yet because the
wait-for-setupterminal-fallback gate from the prior review is still unaddressed by these commits (the existing thread onlocal-worker-start.tsremains open).
Reviewed changes
- Made the shared feasibility predicate authoritative — removed orchestration's private
resolvePlacementReasonladder;--onnow flows into the sharedexecutionHostIdinput and--terminalintoreusesTerminal, so orchestration no longer owns a second copy of the structured-support policy that can drift from the renderer's. - Distinguished an unanswered host from an explicit refusal — added
structured_support_unknown; a throwngetStructuredAgentSessionCreateSupportprobe now returnsnulland downgrades with that reason instead ofstructured_unsupported_on_host, so a disconnected host reads "has not established structured session support" rather than a false refusal. - Aligned renderer routing with the shared predicate —
resolveAgentLaunchRoutenow decides structured first, sodecideInitialAgentTabViewModepresentation rules can no longer veto a supported structured launch;structuredAgentLaunchSupportedcalls the same predicate. - Added cross-caller authority tests — a mock-backed test pins both callers to the shared verdict across placement/provider/customization/prompt cases, plus a support-unknown vs refusal test.
The null-vs-refusal handling and the renderer reorder both check out: --on and --terminal map to the same downgrades as before, and structured launches remain restricted to claude/codex, which never require a locally-readable terminal transcript, so skipping the legacy decideInitialAgentTabViewMode gates is safe.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…absent The merge conflict was one call, and it was a design question rather than a text clash: main's #19608 records worker-terminal custody at CREATION, so tearDownFailedWorkerStart no longer resolves a residual terminal and takes only the dispatch id and the structured session. This branch had changed where that session comes from, because a structured worker's worktree is now created with no startup agent. The resolution keeps both: main's custody-era signature, this branch's `placed`-sourced session. The catch block reads `placed?.` on purpose — a failure before placement has no session to discard. Separately, a review found that awaitStructuredWorkerSetupGate flattened two different outcomes into the same silent null. A wait that cannot be TAKEN is an absent precondition and needs no receipt. A wait that was taken and then THREW is a lost observation, and it was being discarded with no trace — the same class of dishonest receipt this branch exists to remove. It now records a `wait_unevaluated` effect carrying the error, so the start's residual resources say the gate went unevaluated and why. The outcome is deliberately unchanged: it still returns no verdict and the start still proceeds, because a worker start must not fail on missing evidence. Only the silence is fixed. The same review flagged that a created worktree can survive a later start failure. That is pre-existing and already reported: worktree creation pushes a `kind: 'worktree'` effect and the failure receipt carries residualResources, so the worktree is surfaced for recovery rather than leaked silently. Teardown has never removed worktrees, before or after this branch, so it is not a regression here and is left alone.
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
ℹ️ No new issues in this increment. The
wait-for-setupterminal-fallback gate from the prior review is still unaddressed by these commits (the existing thread onlocal-worker-start.tsremains open), so I'm not approving.
Reviewed changes
- Recorded a lost setup wait as
wait_unevaluated—awaitStructuredWorkerSetupGatenow catches a rejectedwaitForSetupTerminalCompletionand records asetup/wait_unevaluatedeffect, so a taken-then-thrown wait is distinguishable from an absent precondition in the receipt. - Reconciled with the merged custody-at-creation rework —
recordCreatedWorkerTerminalCustodynow records custody when the terminal exists (before the boot wait) andtearDownFailedWorkerStartno longer returns a residual agent terminal.
ℹ️ Nitpicks
- The
wait_unevaluatedbranch has no test: no spec exercises a rejectingwaitForSetupTerminalCompletion, so the new effect is unverified.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts (1)
108-143: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winWait for setup completion on host-downgraded terminal placements. After
resolveWorkerStartModeOnHostdowngrades structured mode,local-worker-startwaits for the fallback terminal to becometui-idleinstead of applyingawaitStructuredWorkerSetupGatetosetupReceipt. When the setup policy iswait-for-setup,deliverWorkerDispatchPreamblecan therefore run while the setup terminal is still active. Apply the setup gate in the shared placement/readiness transition, without changingstart-immediatelybehavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 1782bf11-4c56-4d3b-b15b-ff9abecd57d4
📒 Files selected for processing (18)
src/main/runtime/rpc/methods/orchestration-structured-worker-session.tssrc/main/runtime/rpc/methods/orchestration-worker-start-mode-selection.test.tssrc/main/runtime/rpc/methods/orchestration-worker-start-mode.test.tssrc/main/runtime/rpc/methods/orchestration-worker-start-mode.tssrc/main/runtime/rpc/methods/orchestration-worker-support-unknown.test.tssrc/main/runtime/rpc/methods/orchestration/worker/local-worker-start.tssrc/main/runtime/rpc/methods/orchestration/worker/structured-worker-launch-seed-options.test.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-topology.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.tssrc/main/runtime/rpc/methods/structured-agent-session-create.tssrc/renderer/src/lib/agent-launch-routing.tssrc/shared/native-chat-session-option-defaults.test.tssrc/shared/native-chat-session-option-defaults.tssrc/shared/structured-native-chat-launch-route.test.tssrc/shared/structured-native-chat-launch-route.tstests/e2e/structured-native-chat-routing-authority.unit.test.ts
🚧 Files skipped from review as they are similar to previous changes (11)
- src/shared/native-chat-session-option-defaults.ts
- src/main/runtime/rpc/methods/orchestration-structured-worker-session.ts
- src/main/runtime/rpc/methods/structured-agent-session-create.ts
- src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts
- src/main/runtime/rpc/methods/orchestration-worker-start-mode-selection.test.ts
- src/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.ts
- src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.ts
- src/main/runtime/rpc/methods/orchestration/worker/structured-worker-launch-seed-options.test.ts
- src/shared/native-chat-session-option-defaults.test.ts
- src/main/runtime/rpc/methods/orchestration/worker/worker-topology.ts
- src/main/runtime/rpc/methods/orchestration-worker-start-mode.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
|
Review status: PASS WITH RISK. Parallel adversarial review and readiness-checklist passes found no proven P0/P1/P2 issues. The diff remains focused on structured native chat worker routing, host capability handling, and launch option seeding; no mobile-facing files were touched. Targeted routing tests pass (19/19), and typecheck completed successfully. The broader Vitest batch stalled after startup in this environment, so full-suite validation and SSH/Electron runtime evidence remain residual risks. |
…uctured-downgrade
…ion stays property-typed The type-aware audit rejected the blocked-reason template literal: narrowing the wait union with an 'in' check left the field typed unknown. Declaring that a structured setup gate never carries a blocked reason restores the direct read.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts (2)
146-146: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winPersist the effective worker mode.
placeInCreatedWorktreecan downgradestructuredtoterminalafter worktree creation.createStartingWorkerDispatchserializesstartOptionsbefore that resolution, andmode = placed.modeupdates only the local variable. The dispatch observation can therefore report a different mode from the mode used by the worker. Updatestart_optionswith the finalWorkerStartModeReceipt, including its fallback reason and detail.
127-143: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftPreserve partial placement state when worker placement fails.
If
runtime.listTerminalsor startup-terminal validation rejects aftercreateManagedWorktreesucceeds,placeWorkerAgentrejects beforeplacedreceives the worktree or setup receipt. The catch path then usesEXISTING_WORKTREE_SETUPand passes no worktree to cleanup. Add rollback inside placement or extend failure handling to preserve and clean up the partial placement.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 51cfd4c5-28ff-474b-b27b-4b0cb0d00739
📒 Files selected for processing (2)
src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
Electron QA — codex structured worker launch (PR #19431)Validated at head Instance ownership proven before any scenario: Settings for A and B: Headline: no downgrade. Both codex dispatches launched structured, honoured model and effort, and completed real work. Scenario receipts
Scenario A also emitted Structured-vs-legacy proof
The xterm count is the sharpest discriminator. In both codex panes the only Both codex workers actually executed. Their transcripts show a completed ScreenshotsScenario A — child worktree Scenario B — existing worktree, Codex Chat pane. Composer reads GPT-5.6-Sol / High, matching Scenario C — legacy lane for contrast. Tab is labelled with the raw Baseline before any dispatch, for reference: Commands./out/bin/orca-dev orchestration run-create --objective "QA 19431 codex" --from term_7f594c2b-… --json
# A
./out/bin/orca-dev orchestration worker-start --from term_7f594c2b-… --run run_a07784238013 \
--spec "…" --task-title "qa19431c codex child" --worktree new-child --name qa19431c-codex \
--agent codex --model gpt-5.6-sol --effort xhigh --timeout-ms 180000 --json
# B
./out/bin/orca-dev orchestration worker-start --from term_7f594c2b-… --run run_a07784238013 \
--spec "…" --task-title "qa19431c codex current" --worktree current \
--agent codex --model gpt-5.6-sol --effort high --timeout-ms 180000 --json
# C, after setting experimentalStructuredNativeChat: false + reload
./out/bin/orca-dev orchestration worker-start --from term_7f594c2b-… --run run_a07784238013 \
--spec "Reply with the single word DONE." --task-title "qa19431c legacy claude control" \
--worktree current --agent claude --model claude-sonnet-5 --effort medium --timeout-ms 120000 --jsonLogsNo errors. The renderer console held only ignorable noise (React DevTools notice, React Grab version warning, a Radix tooltip controlled/uncontrolled warning, one xterm task-queue deadline warning). The main-process log was clean apart from an unrelated Notes and non-blocking observations
Not coveredWindows and WSL hosts, remote execution hosts, and the genuine downgrade reasons ( |
….launch (#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 #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 #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>
…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>
….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>
…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>








ELI5
Workers configured to open in native chat were silently routed to PTY agents when dispatches selected a model, effort, or new worktree. Launch feasibility now has one shared policy for renderer and orchestration callers, and supported dispatches create structured sessions with their requested options.
What Changed
--onsupplies a remote execution-host input and--terminalsupplies the sharedreused-terminalblocker. Model/effort and new-worktree placement no longer downgrade.structured_support_unknown, distinct from explicit refusal. Every fallback retains its reason and detail; structured creation failure still fails worker-start without retrying into a terminal.Why this architecture
Chose a shared feasibility policy with caller adapters rather than merely pruning the private ladder. The old ladder duplicated the shared remote-host restriction and accumulated model/worktree restrictions that contradicted capabilities elsewhere. Removing its ownership prevents the same divergence as structured capabilities grow.
Creation already converges:
agentSession.createand orchestration usestructured-agent-session-create.ts's prepare/commit pair. Quick commands and notes' new-agent action already enter renderer launch routing; CLI worker-start invokes the orchestration adapter. Existing-session sends retain their target transport.A new universal async launcher would replace working lifecycle ownership without fixing an additional demonstrated defect. Orca retains synchronous feasibility before provisioning and an authoritative host probe after workspace resolution, rather than one event reactor sequencing every launch. Workflow placement/delivery stays with callers; feasibility belongs to the shared predicate and session creation to prepare/commit.
This extends the original worktree/options fix in this PR because those changes are prerequisites for removing its stale restrictions. It does not modify the readiness settlement or turn observation files being changed in #19423.
Compatibility
Remote execution, WSL, terminal reuse, non-structured providers and TUI customization remain real fallbacks. Unknown capability is distinct from refusal. Folder workspaces retain their existing route; floating workspaces remain blocked. No process or platform-specific command changes were added. The new receipt reason is an opaque string to CLI consumers; existing wire fields and frame shapes are unchanged.
Testing
pnpm tc: passed across node, CLI and web.local-worker-start.ts(thein-narrowed wait union leftblockedReasontypedunknown); fixed by declaring the structured setup gate never carries a blocked reason, so the field reads directly again.audit:code-quality:type-awarenow exits 0 locally.The new authority tests inject both shared allow and refusal verdicts across placement, provider, customization and prompt cases. A caller-local override fails independently of today's capability list.
Visual Proof
Electron validation on an isolated hidden dev instance (CDP only): two real
worker-startdispatches —--worktree new-child --model claude-sonnet-5 --effort mediumand--worktree current --model claude-opus-5 --effort high— both producedmode: structured / user_default, anagent-session"Claude Chat" tab with the seeded model/effort, and aworker_doneround-trip through the structured session. Before/after screenshots and the full step log: #19431 (comment)