Skip to content

fix(native-chat): unify launch routing and support structured worker placement - #19431

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/orch-structured-downgrade
Sep 9, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/orch-structured-downgrade

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​396 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​390
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​515 $\color{#cf222e}{\Huge{\mathbf{−}}}$​255 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​260

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

  • Removed orchestration's private placement ladder. --on supplies a remote execution-host input and --terminal supplies the shared reused-terminal blocker. Model/effort and new-worktree placement no longer downgrade.
  • Structured workers create their workspace without a startup agent terminal, obtain the executing host's support verdict, then use the existing structured prepare/commit service. Model and effort seed its options through the same narrowing as renderer launches. The setup-wait gate is retained for structured workers.
  • Renderer routing consults shared structured feasibility before choosing a legacy presentation. Presentation rules cannot veto a supported structured launch.
  • Failed host-support probes produce 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.create and orchestration use structured-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.
  • Affected suites: 303 files passed; 2,667 tests passed and one skipped, covering runtime RPC, orchestration CLI, shared options/routing and renderer launch paths.
  • Changed-file oxlint and max-lines ratchet: passed. Full oxlint: zero errors; seven pre-existing warnings in untouched files.
  • Changed-code quality: zero native or React Doctor findings. The type-aware audit flagged one template literal in local-worker-start.ts (the in-narrowed wait union left blockedReason typed unknown); fixed by declaring the structured setup gate never carries a blocked reason, so the field reads directly again. audit:code-quality:type-aware now exits 0 locally.
  • macOS automated validation; physical Windows, WSL and SSH execution were not exercised. Their routing/refusal cases use fixtures.

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.

Ablation (restored after observing failure) New tests failing
Add unconditional caller-local worker downgrade 9 placement cases
Restore original remote/terminal/worktree/model/effort ladder 7 placement cases
Ignore shared worker refusal 9 placement cases
Add renderer presentation veto before shared support 1
Remove shared terminal-reuse blocker 1
Collapse failed host probe into refusal 1

Visual Proof

Electron validation on an isolated hidden dev instance (CDP only): two real worker-start dispatches — --worktree new-child --model claude-sonnet-5 --effort medium and --worktree current --model claude-opus-5 --effort high — both produced mode: structured / user_default, an agent-session "Claude Chat" tab with the seeded model/effort, and a worker_done round-trip through the structured session. Before/after screenshots and the full step log: #19431 (comment)

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

@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 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_preferences downgrades — --worktree new-child and --model/--effort no 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/--effort via narrowStructuredLaunchSeedOptions — the narrow is extracted into shared code, returns undefined rather than {}, and replaces the settings-resolved seed options without moving the attach fingerprint.
  • awaitStructuredWorkerSetupGate — preserves the repo's wait-for-setup policy 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.ts says "Setup did not finish before the structured worker started" for both a timeout and a non-zero exit; the latter did finish, it failed. failedStage is set correctly (setup_wait) — only the wording is off.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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

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.

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.

@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

Structured 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 ba888

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.92% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 18 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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 … Add all missing template sections. Include a valid linked issue using the required Fixes #<issue-number> format, complete the AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections, and retain the existing tes…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main changes: unified native-chat launch routing and structured worker placement.
Full details: Description check

Explanation

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 Fixes #&lt;issue-number&gt; format, complete the AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections, and retain the existing testing and visual-proof details.

  • 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: Team

Run ID: e2c20479-7762-4356-8667-b028ebbc7140

📥 Commits

Reviewing files that changed from the base of the PR and between c1e15c4 and 7c6c433.

📒 Files selected for processing (13)
  • src/main/runtime/rpc/methods/orchestration-structured-worker-session.ts
  • src/main/runtime/rpc/methods/orchestration-worker-start-mode-selection.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-start-mode.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts
  • src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts
  • src/main/runtime/rpc/methods/orchestration/worker/structured-worker-launch-seed-options.test.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-topology.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.ts
  • src/main/runtime/rpc/methods/structured-agent-session-create.ts
  • src/shared/native-chat-session-option-defaults.test.ts
  • src/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

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.

📐 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',

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 | 🏗️ 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.ts

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

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

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

@brennanb2025 brennanb2025 changed the title fix(orchestration): let worker-start actually produce a structured chat fix(native-chat): unify launch routing and support structured worker placement Sep 8, 2026
@greptile-apps

greptile-apps Bot commented Sep 8, 2026

Copy link
Copy Markdown

Too many files changed for review (465 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@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 increment — the shared-feasibility refactor is sound. Not approving yet because the wait-for-setup terminal-fallback gate from the prior review is still unaddressed by these commits (the existing thread on local-worker-start.ts remains open).

Reviewed changes

  • Made the shared feasibility predicate authoritative — removed orchestration's private resolvePlacementReason ladder; --on now flows into the shared executionHostId input and --terminal into reusesTerminal, 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 thrown getStructuredAgentSessionCreateSupport probe now returns null and downgrades with that reason instead of structured_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 — resolveAgentLaunchRoute now decides structured first, so decideInitialAgentTabViewMode presentation rules can no longer veto a supported structured launch; structuredAgentLaunchSupported calls 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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.
@coderabbitai

coderabbitai Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

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.

@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 increment. The wait-for-setup terminal-fallback gate from the prior review is still unaddressed by these commits (the existing thread on local-worker-start.ts remains open), so I'm not approving.

Reviewed changes

  • Recorded a lost setup wait as wait_unevaluated — awaitStructuredWorkerSetupGate now catches a rejected waitForSetupTerminalCompletion and records a setup/wait_unevaluated effect, so a taken-then-thrown wait is distinguishable from an absent precondition in the receipt.
  • Reconciled with the merged custody-at-creation rework — recordCreatedWorkerTerminalCustody now records custody when the terminal exists (before the boot wait) and tearDownFailedWorkerStart no longer returns a residual agent terminal.

ℹ️ Nitpicks

  • The wait_unevaluated branch has no test: no spec exercises a rejecting waitForSetupTerminalCompletion, so the new effect is unverified.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (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.

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 win

Wait for setup completion on host-downgraded terminal placements. After resolveWorkerStartModeOnHost downgrades structured mode, local-worker-start waits for the fallback terminal to become tui-idle instead of applying awaitStructuredWorkerSetupGate to setupReceipt. When the setup policy is wait-for-setup, deliverWorkerDispatchPreamble can therefore run while the setup terminal is still active. Apply the setup gate in the shared placement/readiness transition, without changing start-immediately behavior.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 1782bf11-4c56-4d3b-b15b-ff9abecd57d4

📥 Commits

Reviewing files that changed from the base of the PR and between 12f2c6b and ec0b3b4.

📒 Files selected for processing (18)
  • src/main/runtime/rpc/methods/orchestration-structured-worker-session.ts
  • src/main/runtime/rpc/methods/orchestration-worker-start-mode-selection.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-start-mode.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts
  • src/main/runtime/rpc/methods/orchestration-worker-support-unknown.test.ts
  • src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts
  • src/main/runtime/rpc/methods/orchestration/worker/structured-worker-launch-seed-options.test.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-topology.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.ts
  • src/main/runtime/rpc/methods/structured-agent-session-create.ts
  • src/renderer/src/lib/agent-launch-routing.ts
  • src/shared/native-chat-session-option-defaults.test.ts
  • src/shared/native-chat-session-option-defaults.ts
  • src/shared/structured-native-chat-launch-route.test.ts
  • src/shared/structured-native-chat-launch-route.ts
  • tests/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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron validation (hidden renderer, CDP only) — PR head ec0b3b4c1d

Launched this exact worktree as an isolated dev instance (ORCA_BACKGROUND_LAUNCH=1, fresh ORCA_DEV_USER_DATA_PATH, --use-mock-keychain, private renderer port, CDP 9336), drove it only with Playwright over CDP, and dispatched real worker-start calls through the dev CLI bound to that profile. No show()/focus/OS automation. Ownership proven per attach: getIdentity() reported this worktree + branch, and /@fs returned 200 for this tree vs 403 for a peer.

Setup

  1. Fresh profile → updateSettings({ experimentalNativeChat, experimentalStructuredNativeChat, openAgentTabsInChatByDefault: true }), renderer reload.
  2. Registered a throwaway fixture repo (single commit on main), activated it → plain PTY Terminal 1 (baseline).
  3. orchestration run-create --from <Terminal 1 handle> to bind a coordinator Run.

Scenario A — new-child worktree + model/effort (the case that used to downgrade with worktree_creation / launch_preferences)

orca-dev orchestration worker-start --from <coord> --run <run> --spec "…" \
  --worktree new-child --name qa19431-child --agent claude --model claude-sonnet-5 --effort medium --json
  • exit 0 in ~6s; receipt state: ready, mode: { mode: "structured", preferred: "structured", reason: "user_default" }
  • launch.effective = { agent: claude, model: claude-sonnet-5, effort: medium }
  • effects: worktree created_child, terminal role=agent action=created surface=background (structworker_…), dispatch_input accepted; residualResources: []
  • Renderer: child worktree got contentType: "agent-session" tab "Claude Chat" (agentSessionAgent: claude) alongside its configured Terminal 1; no agent TUI terminal.
  • worker-read → source: transcript, provider claude, assistant replied DONE; worker-show observation live.
  • UI shows the dispatched preamble as the user turn, the reply, the Send a message… composer, and pickers Sonnet / Medium (seeded options).

Scenario B — existing (current) worktree + different model/effort

… --worktree current --agent claude --model claude-opus-5 --effort high --json
  • Same structured receipt (reason: user_default), launch.effective = { claude-opus-5, high }, effects worktree reused, setup not_applicable, background structured agent.
  • Worker ran the full lifecycle over the structured session: worker_done landed in the Run inbox (outcome: succeeded, body structured launch ok), worker-show → dispatch: completed, outcome: succeeded.

Logs: dev log gained no error lines across both dispatches; renderer console had only pre-existing warnings (React Grab version, tooltip controlled/uncontrolled, an xterm deadline warning). No refusal/structured_support_unknown/fallback paths were hit.

Screenshots

Before (fixture worktree, PTY Terminal 1):
01-before-dispatch.png

After A — structured Claude Chat in the freshly created child worktree, Sonnet/Medium seeded, sidebar shows the session row under qa19431-child:
02-after-structured-worker-chat.png

After B — structured Claude Chat in the existing worktree; worker_done sent from inside the session; both session rows visible in the sidebar:
03-after-structured-worker-existing-worktree.png

Observations (non-blocking, outside this PR's files)

  • With --model claude-opus-5 the composer shows the raw id and no effort picker, while claude-sonnet-5 resolved to Sonnet / Medium. The receipt still reports effort: high as effective; this looks like catalog matching for an opaque provider model id, not the routing change. Flagging for awareness only.
  • In scenario A my spec ("reply with exactly DONE") conflicted with the preamble's worker_done rule, so that dispatch stayed in_progress until I stopped it — a spec issue, not a launch issue.

Not exercised: Codex provider, remote/WSL/--terminal fallbacks (fixture-covered in the PR), Windows/Linux.

Merge Sim added 2 commits September 8, 2026 17:07
…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.

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

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 win

Persist the effective worker mode.

placeInCreatedWorktree can downgrade structured to terminal after worktree creation. createStartingWorkerDispatch serializes startOptions before that resolution, and mode = placed.mode updates only the local variable. The dispatch observation can therefore report a different mode from the mode used by the worker. Update start_options with the final WorkerStartModeReceipt, including its fallback reason and detail.


127-143: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Preserve partial placement state when worker placement fails.

If runtime.listTerminals or startup-terminal validation rejects after createManagedWorktree succeeds, placeWorkerAgent rejects before placed receives the worktree or setup receipt. The catch path then uses EXISTING_WORKTREE_SETUP and 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

📥 Commits

Reviewing files that changed from the base of the PR and between ec0b3b4 and ba888cd.

📒 Files selected for processing (2)
  • src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts
  • src/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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron QA — codex structured worker launch (PR #19431)

Validated at head ba888cdbef on macOS (darwin 25.5.0), dev build launched from worktree orch-structured-downgrade into a fresh, isolated profile (ORCA_DEV_USER_DATA_PATH=/tmp/qa19431c/udd, ORCA_BACKGROUND_LAUNCH=1, --use-mock-keychain). Driven over CDP with Playwright only — no computer-use, no OS-level input.

Instance ownership proven before any scenario: /@fs of this worktree's package.json returned 200, the main repo's returned 403, and window.api.app.getIdentity() reported devRepoRoot = /Users/brennanbenson/orca/workspaces/orca/orch-structured-downgrade.

Settings for A and B: experimentalNativeChat: true, experimentalStructuredNativeChat: true, openAgentTabsInChatByDefault: true, applied through the store then reloaded and re-attached so the launch route re-reads capabilities at boot.

Headline: no downgrade. Both codex dispatches launched structured, honoured model and effort, and completed real work.

Scenario receipts

A — codex, new child worktree B — codex, existing worktree C — legacy control, claude
mode.mode structured structured terminal
mode.preferred structured structured terminal
mode.reason user_default user_default user_default
launch.effective codex / gpt-5.6-sol / xhigh codex / gpt-5.6-sol / high claude / claude-sonnet-5 / medium
agent effect structworker_3124e41d…, surface: background structworker_6b33f597…, surface: background term_d0e6d42e…, surface: visible
final state completed / succeeded / settled completed / succeeded / settled dispatched / ready (see note)

launch.requested equalled launch.effective in all three — nothing was silently rewritten.

Scenario A also emitted {"kind":"worktree","action":"created_child","id":"…/workspaces/repo/qa19431c-codex"}; B and C emitted {"kind":"worktree","action":"reused",…}.

Structured-vs-legacy proof

dispatch_input: accepted is not evidence that a worker ran, so each dispatch was confirmed through worker-read transcripts rather than the start receipt.

A B C
tab contentType agent-session agent-session terminal, viewMode: chat
tab id structured-agent-session-7d258313-… structured-agent-session-a679d0a6-… 726c8e2f-… (plain tab id)
agentSessionAgent codex codex —
processIncarnation structured:7d258313-… structured:a679d0a6-… ptyId …@@c066837c:…
worker-read source transcript transcript terminal
worker-read provider codex codex null, fallbackReason: session_not_reported
visible .xterm in pane 0 0 1

The xterm count is the sharpest discriminator. In both codex panes the only .xterm node in the document belonged to the hidden, inactive Terminal 1 tab (visible: 0); the legacy claude pane had a genuinely visible xterm canvas.

Both codex workers actually executed. Their transcripts show a completed shell tool call (exitCode: 0) running orca-dev orchestration send … --type worker_done … --outcome succeeded, returning Sent msg_542291e69cc1 (A) and Sent msg_fbcd944e89f8 (B).

Screenshots

Scenario A — child worktree qa19431c-codex, Codex Chat pane. Composer reads GPT-5.6-Sol / Extra high, matching --effort xhigh. The dispatch preamble renders as structured chat message content.

03-scenarioA-codex-chat-child-worktree.png

Scenario B — existing worktree, Codex Chat pane. Composer reads GPT-5.6-Sol / High, matching --effort high. Sidebar shows both worktrees carrying a Codex Chat - Codex gpt-5.6-sol agent row.

02-scenarioB-codex-chat-current-worktree.png

Scenario C — legacy lane for contrast. Tab is labelled with the raw worker-task_5a9550632514, and its chat view is an empty "Start a chat with Claude" state with a bare unlabelled Model picker, even though the PTY underneath is live. The structured panes above show real content and resolved model/effort labels.

04-scenarioC-legacy-claude-pty-tab.png

Baseline before any dispatch, for reference:

01-before-terminal1.png

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 --json

Logs

No 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 [ws-transport] port-bind fallback and a MaxListenersExceededWarning, both pre-existing and unrelated to worker start.

Notes and non-blocking observations

  1. Scenario C never completed, by environment, not by defect. The legacy claude PTY parked on Claude Code's first-run trust prompt ("Quick safety check: Is this a project you created or one you trust?") because the QA profile was fresh. C was only ever a shape control for the terminal lane, and that shape is fully established by the receipt and the visible xterm. It was stopped during cleanup.
  2. Structured tabs vanish from unifiedTabsByWorktree while experimentalStructuredNativeChat is false. Turning the flag off for scenario C removed both already-created Codex Chat tabs from the store listing; they returned when it was restored. Expected for a gated experiment, and outside this PR, but worth knowing if anyone toggles the flag with live structured sessions.
  3. mode.detail read as the intended sentence throughout: "Started a structured chat session worker, the default for new agent tabs in your settings." for A and B, and the terminal equivalent for C. No downgrade sentence was produced in any run.

Not covered

Windows and WSL hosts, remote execution hosts, and the genuine downgrade reasons (codex_on_windows, wsl_execution_runtime, remote_execution_host, structured_support_unknown) were not exercised; this run was local macOS only, where the host's agentSession.createSupport answers yes. The wait-for-setup structured gate was also not exercised, since the fixture repo had no setup script (startupPolicy: start-immediately, state: not_configured).

@brennanb2025
brennanb2025 merged commit 852495d into main Sep 9, 2026
28 checks passed
brennanb2025 added a commit that referenced this pull request Sep 15, 2026
….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>
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