Skip to content

refactor(native-chat): unify agent session launch and open drafts in structured chat - #19681

Merged
brennanb2025 merged 36 commits into
mainfrom
brennanb2025/unify-agent-session-launch
Sep 10, 2026
Merged

brennanb2025 merged 36 commits into
mainfrom
brennanb2025/unify-agent-session-launch

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 30 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3190 $\color{#cf222e}{\Huge{\mathbf{−}}}$​646 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2544
Prod 46 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1654 $\color{#cf222e}{\Huge{\mathbf{−}}}$​897 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​757

ELI5

Eight buttons start an agent session, and each one had its own copy of "decide where it runs, start it, and fall back to a terminal if that fails." The copies drifted, and one of them quietly kept PR context out of the new Codex chat. Now there is one decision path and one settle path, and PR context opens in Codex chat as an editable draft.

What Changed

Six steps, each committed green on its own, plus review fixes:

  1. One route-input builder. buildAgentLaunchRouteInput gathers host, capabilities, workspace kind, project runtime and TUI customization for every route decision, and works for workspaces that do not exist yet. A ratchet fails on any resolver call outside it. The draft-prompt blocker is deleted from the shared resolver.
  2. One settle loop. settleStructuredAgentLaunch owns start, refusal-fallback claim, await, and a five-way settlement (structured, refused-then-legacy, cancelled, visibility-unknown, failed). Direct work-item, full create, folder workspace, both onboarding folder paths, and vault resume consume it. A ratchet lists its callers.
  3. New-tab launcher joins. Its structured branch runs through the loop; launchAgentInNewTab stays synchronous and exposes structuredSettlement.
  4. One legacy delivery, one trust preflight. The direct work-item seed-and-paste copy is folded onto the canonical function, and the four private trust-preflight copies — folder workspace, terminal fork, agent-session continuation, and direct work-item — are deleted in favour of preflightAgentTrust, whose workspacePath was widened to accept null so it is a drop-in for all of them (the nullable agent it already had). Quick create never held its own copy; its wrapper already delegated to the canonical function. The one surviving direct call is the deliberate background-session launcher.
  5. Quick create joins. Abandoning a creation aborts the launch before a staged prompt can reach the provider. The loop takes an AbortSignal for this and cancels on the abort event, not only by polling after awaits.
  6. Draft mode. The structured draft seed writes the launch-draft store directly (no terminal mirror gate); closing a settled structured tab clears an unadopted seed; the structured session treats idle and loading as unsettled.
  7. One funnel. planAgentSessionLaunch is the only production caller of the route resolver, and its launch is the only production caller of the settle loop; both census tests pin exactly that file. Sites that need the route before the workspace exists read plan.route, then launch with the created id. Quick create persists the verdict as data on its request and re-enters through adoptAgentSessionLaunchVerdict without re-resolving. Delivery mode is fixed on the request once, so the route and the launch can never disagree.

Asking whether a structured session is possible is a separate operation from deciding a route, so the planner exports a predicate for it. Returning a plan whose launch closure the caller is expected to throw away misstates what the caller may do with the value; the AI Vault row list asks the question directly instead. Both census tests pass unedited, because the predicate is exported from the planner module they already permit. This is an API-shape correction, not a speedup: the predicate runs the same builder work the plan did.

Why

Every launch entrypoint assembled the resolver's inputs by hand and disagreed: only three of seven passed the project-runtime blocker. Five copies of the settle loop drifted: two reported unexpected launch errors as success, the new-tab launcher never awaited its fallback, and resume handled neither refusal nor unknown outcomes.

The draft-prompt blocker was live on main for every new-tab draft launch, so any editable draft was refused structured chat. Deleting it is the actual fix, and it flips every draft caller, not only PR and issue context. The one caller that was not ready for that, terminal fork, now activates with providesInitialSurface and gates its toast on the settlement.

Route resolution now runs through the single planner: planAgentSessionLaunch builds the input, resolves the route once, and hands back a plan whose launch is the only way into the settle loop. Two census tests fail if any other production file calls the resolver or the loop, and a third pins every file that re-enters on an already-decided verdict.

Deliberate behavior changes

  • A WSL-pinned or repair-required project is now refused structured chat from the quick and full create dialogs, matching the tab bar. Folder workspaces and the onboarding folder flow have no repo and keep their previous behavior.
  • Quick, full, and folder create now agree with the new-tab launcher on transcript readability, though by a different branch of the shared builder: they resolve it from the execution host, the new-tab launcher from the worktree's connection. An SSH project group with a runtime environment now opens legacy chat rather than the terminal on the legacy branch.
  • Direct work-item and full create no longer report a failed structured launch as success. launchWorkItemDirect returns false when the structured launch opened no surface, so the boolean now means what it says: callers gate follow-up work on it, and a true there fired the fix-checks dialog's onLaunched for a launch that never opened a tab. No current caller does irreversible host work on that boolean — today the cost is a misleading success toast and a settings write — but the contract is what the other launch sites already honour. Full create keeps the dialog draft on a failed launch instead of clearing it. Direct work-item never pastes a prompt into a non-agent tab on a failed launch.
  • Direct work-item releases its caller on an unknown outcome like every other site, so a later reconcile into refusal no longer opens a terminal with the stale prompt.
  • Vault resume no longer toasts on an unknown outcome and never receives a terminal fallback.
  • A folder project group that is SSH-held and pins a runtime environment now reports its transcript as locally readable, because the builder prefers the runtime host over the project group's SSH host. Those launches open legacy chat where they previously opened the terminal. This only reaches agents that require a local transcript (grok/omp), and for a nested-SSH runtime the transcript may still live on the remote host, so treat this one as a known ambiguity rather than a clean correction. Quick create is unaffected: its prospective host is the SSH connection.
  • Quick create's structured launch keeps its own agent-eligibility check, so a dismissed creation carrying an agent that cannot hold a structured session reports that it did nothing rather than that it was cancelled. Unreachable through both callers today.
  • One launch identity now has one prompt delivery mode. A caller joining a pending launch delivers its text the way that launch already decided, so two entrypoints racing the same workspace can no longer both seed the composer and submit.
  • A cancel that lands after the refusal fallback opened its terminal reports that terminal, rather than the pre-launch tab the user cannot see the agent in.

Review pass

A review loop after the original steps landed the following, each with a regression test proven red on the pre-fix code:

  • Route readability lost its repo-level fallback. The builder resolved the connection id from the worktree alone, where the merge base fell back to the repo. A worktree whose owner is ambiguous resolves undefined, which reads as "not locally readable" and downgraded legacy-native-chat to terminal-tui. It only bites agents that require a local transcript (grok/omp), never the structured route. The fallback now lives in the builder, so every caller gets it, and a resolved local null still wins over the repo.
  • Route resolution moved inside one planner. planAgentSessionLaunch is the only production caller of the resolver and plan.launch the only caller of the settle loop; both censuses pin that single file. Feasibility is a separate boolean query, so a caller asking "can this open a chat" no longer builds a launch plan it must discard. This is an API-shape correction, not a speedup: the query runs the same builder work the plan did.
  • A coalesced joiner could have its draft sent. When the launch it joined had established no delivery mode, the joiner's mode was stripped, and an absent mode reads as submit.
  • One launch identity, one delivery mode, and no draft seed is written onto a launch already refused.
  • Cancellation now uses AbortSignal instead of a bespoke poll-plus-subscribe pair, keeping the eager cancel that discards a staged prompt before it reaches the provider.
  • Cancel-after-fallback reports the fallback's surface rather than the pre-launch one; the abandon check runs before the rename write; the two plan.launch sites without an error boundary got one; and the dead terminal-tui route default is gone in favour of a required field.

Deviations from the design plan

  • The funnel is two-phase (plan, then launch) rather than one call, because three sites need the route before the workspace exists and quick create carries its request across the create. (That request lives in renderer session memory and dies with the renderer — it is not persisted, and two comments that said so are corrected.) Pre-launch activation stays inline at each site, branching on plan.route; the surface census guards it.
  • The route reorder (structured eligibility before the view-mode decider) had already landed on main in fix(native-chat): unify launch routing and support structured worker placement #19431 and reduced to a comment at merge.

Linked Issue

No tracked issue. This started from the report that PR context opened in the legacy terminal-backed chat instead of Codex structured chat.

Visual Proof

Hidden Electron run (fresh profile, ORCA_BACKGROUND_LAUNCH=1, Playwright over CDP) on this branch with experimental native chat, structured native chat, and "open agent tabs in chat by default" enabled, Codex as the agent. The real launchWorkItemDirect was invoked with a synthetic 60-line issue context and promptDelivery: 'draft'.

Before this branch the same launch opened the terminal-backed legacy chat (the draft blocker refused structured chat for every draft, and the route order sent anything over forty lines to the plain terminal).

After. The only tab for the new worktree is a structured agent-session tab owned by NativeChatStructuredSession (no .xterm node in the document). The composer holds all 60 lines, and the launch-draft store shows the seed adopted:

01-structured-tab-after-draft-launch.png

The draft is editable, and nothing has been sent: empty state still shown, the structured outbox has zero entries, data-native-chat-working="false":

02-composer-edited-not-sent.png

After clicking Send: the user turn carries all 60 lines plus the edit, the seed is cleared, and Codex replies live:

03-after-send-user-turn.png

Not exercised in Electron: the "Use" button click on a real PR page (the module was invoked directly, offline), and the legacy path for contrast.

Testing

  • Targeted suites for every step, both census ratchets, the shared resolver, and the worker-start mode tests.

  • The connection-fallback regression test runs the owner resolution un-mocked over real store rows, so it fails against the previous head rather than characterizing the fix.

  • Broad sweeps: renderer lib, runtime, right-sidebar, terminal-pane, hooks, native-chat, tab-group, store, sidebar, shared, and main RPC methods. One pre-existing timing test (ai-vault-session-worktree-map) failed under CPU contention and passes in isolation; it is untouched by this branch.

  • pnpm tc:web, pnpm tc:node, pnpm tc:cli, and check:code-quality:changed (68 gated files, 0 findings across code quality, type-aware, and React Doctor).

  • Platforms exercised: macOS unit tests. SSH, Windows, and Linux paths are covered by the route matrix tests only.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

No wire change; delivery mode is renderer-local. Structured chat remains local-only, so remote hosts keep the legacy path through the same builder. Folder workspaces route through the builder with kind: 'folder'.

The transcript-readability input falls back to the repo's connection when the worktree row has not landed in the store yet, which is the normal window right after "Use" creates a workspace. Only "cannot determine the host" defers to the repo; a resolved local answer stays local.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Merge Sim added 12 commits September 8, 2026 18:20
Every launch entrypoint assembled the route resolver's inputs by hand and
they disagreed: only three of seven passed the project runtime blocker, so
a WSL-pinned project was refused structured chat from the tab bar but
admitted from the create dialogs. buildAgentLaunchRouteInput is now the
one place that gathers host, capabilities, workspace kind, project runtime
and TUI customization, and works for workspaces that do not exist yet.

Also deletes the dead draft-prompt blocker from the shared resolver; the
renderer stopped passing it and the main process never did.
Five entrypoints copied the same loop around startStructuredAgentLaunch:
start, claim a refusal fallback, await, branch on refusal or unknown. The
copies drifted: direct work-item and full create reported an unexpected
launch error as success, and resume handled neither refusal nor unknown.

settleStructuredAgentLaunch now owns that loop and returns one settlement
(structured, refused-then-legacy, cancelled, visibility-unknown, failed).
Direct work-item, full create, folder workspace, both onboarding folder
paths and vault resume consume it; each keeps only its own legacy fallback.
Resume deliberately has no fallback. Unknown outcomes release the caller
uniformly so a stale fallback closure cannot fire on a later reconcile.
…settle loop

The new-tab launcher fired its refusal fallback and forgot it: nobody
learned whether the terminal fallback ran, and a visibility-unknown outcome
was never surfaced. Its structured branch now runs through
settleStructuredAgentLaunch with the terminal launch as the legacy fallback.
launchAgentInNewTab stays synchronous; the result gains a structuredSettlement
promise, and promptDeliveryResult keeps following the terminal fallback's
delivery on refusal as it did through the callers bridge before.
…preflight

The direct work-item flow kept its own seed-and-paste copy of the legacy
prompt delivery; it now uses deliverLaunchPromptToAgentTab with its own
timeout notice supplied as a callback. Three private copies of the trust
preflight (session continuation, worktree creation, folder workspace) fold
onto preflightAgentTrust. The direct work-item pre-launch mark keeps its own
entry because it differs in timing, not mechanism.
Quick create was the last entrypoint driving the launch handle itself,
because its cancel lifecycle is real: when the creation is abandoned the
structured launch must be cancelled immediately so a staged prompt never
reaches the provider. The shared loop now takes a cancellation hook with an
eager subscription plus a post-await check; it cancels the launch once,
unsubscribes on settle, and reports cancelled without running the fallback.
Quick create keeps its two-branch legacy fallback and retire-on-late-cancel.

Also updates the surface-caller census for the onboarding launch module
that step 2 introduced.
…e local Codex launches

Route order asked the default-view-mode question first, and that decider
applies the terminal mirror gate (a TUI cannot clear more than forty lines
of prefilled draft), so a PR body over forty lines reached the plain
terminal before structured eligibility was checked. Structured eligibility
now comes first; the mirror gate applies only on the legacy branch.

The structured draft seed writes the launch-draft store directly with no
mirror gate, since a structured session has no terminal copy to fall back
on. Closing a settled structured tab clears an unadopted seed. The
structured session treats idle and loading as unsettled so the adoption
hook takes its baseline from the loaded transcript. Each caller passes one
delivery-mode value to both the route builder and the settle loop.

The structured session component test is split with a shared harness so
it stays under the test file line cap.
- Claim a refusal fallback only when the caller supplies one, so vault
  resume no longer reports a terminal fallback it never opened.
- A failed or cancelled direct work-item launch returns no tab id, so the
  caller never pastes the prompt into a setup shell.
- Terminal fork activates with providesInitialSurface for structured
  launches and gates its toast on the settlement; the draft blocker
  deletion made fork route structured too.
- A failed launch clears its draft seed. The failure toast moves to its own
  module to keep the launch-state file under the line cap.
- Ratchet for settle-loop callers; cancel-during-fallback documented.
- Restore the local agent label lookup that the pane-agent identity
  inventory expects instead of the inventoried helper.
…ktree

A failed or unknown structured settlement returned false after the fork
worktree already existed, so the dialog stayed open and a second click
created another worktree. Unknown now closes the dialog (the launch badge
already reports it); failed copies the context the way a null launch does.

@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

This is a well-structured unification with strong ratchet coverage, but one shared-resolver authority test was left stale and now fails the suite.

Reviewed changes

  • One route-input builder — buildAgentLaunchRouteInput (src/renderer/src/lib/agent-launch-route-input.ts) gathers host, capabilities, workspace kind, project runtime, and TUI customization for every route decision, including prospective workspaces; a census ratchet forbids direct resolveAgentLaunchRoute/structuredAgentLaunchSupported calls outside the builder.
  • One shared settle loop — settleStructuredAgentLaunch (structured-agent-launch-settlement.ts) owns start, refusal-fallback claim, await, and a five-way settlement (structured / refused-then-legacy / cancelled / visibility-unknown / failed), consumed by the new-tab launcher, direct work-item, full/quick create, folder create, onboarding folder, and vault resume.
  • Canonical legacy delivery and trust preflight — the direct work-item paste copy and three private preflightAgentTrust copies fold onto the shared functions; the fork keeps only its WSL-specific variant.
  • Quick-create cancellation hook — an eager subscription cancels a pending launch before a staged prompt reaches the provider.
  • Draft mode — the structured draft seeds the launch-draft store directly (no terminal mirror gate), and closing a settled structured tab clears an unadopted seed.
  • draft-prompt blocker removal — deleted from resolveStructuredNativeChatSupport and orchestration-worker-start-mode.ts, flipping every draft caller to structured chat.

⚠️ Stale shared-resolver authority test still references the removed draft-prompt blocker

tests/e2e/structured-native-chat-routing-authority.unit.test.ts was not updated and still asserts that 'draft-prompt' is a valid StructuredNativeChatBlocker and that resolveStructuredNativeChatSupport receives isDraftPrompt — both of which this PR deletes. The file is included by config/vitest.config.ts (tests/e2e/**/*.unit.test.ts), so pnpm test fails on the toHaveBeenLastCalledWith(objectContaining({ isDraftPrompt })) assertion, and pnpm typecheck:e2e reports a type error for the orphaned 'draft-prompt' union member.

Technical details
# Update the stale shared-resolver authority test

## Affected sites
- `tests/e2e/structured-native-chat-routing-authority.unit.test.ts:45` — `'draft-prompt'` in the `blockers: StructuredNativeChatBlocker[]` array; the union member no longer exists, so this is a type error and the loop now asserts a blocker the resolver can never return.
- `tests/e2e/structured-native-chat-routing-authority.unit.test.ts:111` — `isDraftPrompt: promptDelivery === 'draft'` inside the `objectContaining(...)` on the mocked `resolveStructuredNativeChatSupport`; the field is no longer passed, so the assertion always fails.

## Required outcome
- Drop `'draft-prompt'` from `blockers`.
- Remove the `isDraftPrompt` expectation (and its `promptDelivery` loop if it exists only to drive it), so `pnpm test` and `pnpm typecheck:e2e` pass.
- Optionally add coverage asserting a draft prompt routes to `structured-native-chat` now that the blocker is gone (the renderer-side `agent-launch-routing.test.ts` already covers this; the e2e authority test should simply stop expecting the removed field).

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

@coderabbitai

coderabbitai Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 1e4209b1-cf37-4cef-b7b7-8abd884945a8

📥 Commits

Reviewing files that changed from the base of the PR and between 7e3911d and b99e0d1.

📒 Files selected for processing (2)
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx

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


📝 Walkthrough

Walkthrough

The pull request centralizes agent launch planning and structured-launch settlement. Draft prompts can seed native chat and clear after launch, failure, cancellation, refusal, or tab closure. Creation, onboarding, Vault resume, work-item, fork, and trust flows use the new helpers. Native chat transport tests move to a dedicated suite. Draft prompts no longer block structured native chat.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to b99e0

This refactor expands structured chat launch and draft handling across creation and resume flows. Prompt-delivery errors and remote-repository route selection may still behave unexpectedly in bounded cases, so these issues should be addressed or explicitly accepted before broader rollout.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 68 functions across 56 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description covers the required change summary, rationale, visual proof, testing, AI disclosure section, platform considerations, and checklist. However, the required Linked Issue section explicit… Add a valid linked issue reference under Linked Issue, using the required Fixes #<issue-number> format.
✅ 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 primary changes: unifying native-chat agent session launches and enabling drafts in structured chat.
Full details: Description check

Explanation

The description covers the required change summary, rationale, visual proof, testing, AI disclosure section, platform considerations, and checklist. However, the required Linked Issue section explicitly states that no tracked issue exists.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b87ce490-c366-4c20-b0fd-3f34750adcc3

📥 Commits

Reviewing files that changed from the base of the PR and between 210ac1f and 95a3a95.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (69)
  • src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.transport-probe.test.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
  • src/renderer/src/components/right-sidebar/AiVaultPanel.tsx
  • src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.test.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-workspace.ts
  • src/renderer/src/components/sidebar/NonGitFolderDialog.tsx
  • src/renderer/src/components/sidebar/folder-workspace-agent-startup.ts
  • src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts
  • src/renderer/src/components/tab-group/useTabGroupTabCloseCommands.structured-session.test.ts
  • src/renderer/src/components/tab-group/workspace-tab-close-commands.ts
  • src/renderer/src/components/terminal-pane/terminal-agent-session-fork-agent-preflight.ts
  • src/renderer/src/components/terminal-pane/terminal-agent-session-fork.test.ts
  • src/renderer/src/components/terminal-pane/terminal-agent-session-fork.ts
  • src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts
  • src/renderer/src/hooks/composer-state/folder-submit-orchestration.ts
  • src/renderer/src/hooks/composer-state/full-creation-execution.test.ts
  • src/renderer/src/hooks/composer-state/full-creation-execution.ts
  • src/renderer/src/hooks/composer-state/full-creation-structured-launch.test.ts
  • src/renderer/src/hooks/composer-state/full-creation-structured-launch.ts
  • src/renderer/src/hooks/composer-state/quick-creation-execution.ts
  • src/renderer/src/hooks/composer-state/quick-creation-request.test.ts
  • src/renderer/src/hooks/composer-state/quick-creation-request.ts
  • src/renderer/src/lib/agent-launch-route-input.test.ts
  • src/renderer/src/lib/agent-launch-route-input.ts
  • src/renderer/src/lib/agent-launch-routing-caller-census.test.ts
  • src/renderer/src/lib/agent-launch-routing.test.ts
  • src/renderer/src/lib/agent-launch-routing.ts
  • src/renderer/src/lib/agent-trust-preflight.test.ts
  • src/renderer/src/lib/agent-trust-preflight.ts
  • src/renderer/src/lib/launch-agent-in-new-tab-structured.test.ts
  • src/renderer/src/lib/launch-agent-in-new-tab-structured.ts
  • src/renderer/src/lib/launch-agent-in-new-tab.ts
  • src/renderer/src/lib/launch-agent-session-continuation.ts
  • src/renderer/src/lib/launch-agent-structured-chat-guard.test.ts
  • src/renderer/src/lib/launch-work-item-direct-agent-routing.test.ts
  • src/renderer/src/lib/launch-work-item-direct-agent-routing.ts
  • src/renderer/src/lib/launch-work-item-direct-agent.test.ts
  • src/renderer/src/lib/launch-work-item-direct-agent.ts
  • src/renderer/src/lib/launch-work-item-direct-prompt-delivery.ts
  • src/renderer/src/lib/launch-work-item-direct-route-preparation.ts
  • src/renderer/src/lib/launch-work-item-direct.test.ts
  • src/renderer/src/lib/launch-work-item-direct.ts
  • src/renderer/src/lib/onboarding-folder-agent-launch.ts
  • src/renderer/src/lib/onboarding-folder-agent-startup.ts
  • src/renderer/src/lib/pending-worktree-creation.ts
  • src/renderer/src/lib/structured-agent-launch-settlement-caller-census.test.ts
  • src/renderer/src/lib/structured-agent-launch-settlement.test.ts
  • src/renderer/src/lib/structured-agent-launch-settlement.ts
  • src/renderer/src/lib/structured-agent-session-launch-callers.ts
  • src/renderer/src/lib/structured-agent-session-launch-draft.ts
  • src/renderer/src/lib/structured-agent-session-launch-failure-toast.ts
  • src/renderer/src/lib/structured-agent-session-launch-label.ts
  • src/renderer/src/lib/structured-agent-session-launch-prompt.ts
  • src/renderer/src/lib/structured-agent-session-launch-refusal-fallback.test.ts
  • src/renderer/src/lib/structured-agent-session-launch.test.ts
  • src/renderer/src/lib/structured-agent-session-launch.ts
  • src/renderer/src/lib/worktree-activation-surface-caller-wiring.test.ts
  • src/renderer/src/lib/worktree-creation-flow-agent-trust-preflight.test.ts
  • src/renderer/src/lib/worktree-creation-flow-execute.ts
  • src/renderer/src/lib/worktree-creation-structured-session.test.ts
  • src/renderer/src/lib/worktree-creation-structured-session.ts
  • src/renderer/src/store/repos/repo-add-actions.ts
  • src/shared/structured-native-chat-launch-route.test.ts
  • src/shared/structured-native-chat-launch-route.ts
💤 Files with no reviewable changes (8)
  • src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts
  • src/renderer/src/hooks/composer-state/full-creation-execution.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts
  • src/shared/structured-native-chat-launch-route.test.ts
  • src/shared/structured-native-chat-launch-route.ts
  • src/renderer/src/lib/launch-work-item-direct-prompt-delivery.ts
  • src/renderer/src/components/sidebar/folder-workspace-agent-startup.ts
  • src/renderer/src/hooks/composer-state/folder-submit-orchestration.ts

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

Comment on lines +27 to +56
export async function resumeAiVaultSessionInNewChat(
session: AiVaultSession,
agent: AgentSessionHandleProvider,
worktreeId: string
): Promise<void> {
try {
// Codex rows can live under a shared legacy home; the same preparation the terminal resume
// runs re-pins them, and its result is what names the conversation the host will look for.
const preparedSession = await prepareAiVaultSessionForResume(session)
const settlement = await settleStructuredAgentLaunch(
worktreeId,
agent,
{ resumeFrom: { providerSessionId: preparedSession.sessionId } },
{}
)
if (settlement.kind === 'failed') {
notifyAiVaultSessionResumeInChatFailure(settlement.error)
return
}
// Why: an unknown outcome is not a failure; the launch layer reconciles it on the next attempt.
if (settlement.kind !== 'structured') {
return
}
if (useAppStore.getState().activeWorktreeId !== worktreeId) {
activateAiVaultResumeWorkspace(worktreeId)
}
} catch (error) {
notifyAiVaultSessionResumeInChatFailure(error)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Suppress the generic launch toast for Vault resume

A definitive refusal without a legacy fallback resolves refusalSettlement as false, so trackStructuredLaunchFailureToast shows the generic launch toast. Known launch errors also reach that toast directly. settleStructuredAgentLaunch then returns failed, and resumeAiVaultSessionInNewChat shows its conflict, identity, or generic resume toast for the same attempt. Add a per-call notification-suppression flag and disable the launch toast for this resume path.

Comment on lines +298 to +305
void deliverLaunchPromptToAgentTab({
tabId: primaryTabId,
agent,
content: draftContent,
submit,
forcePaste: submit,
onTimeout: () => notifyDirectWorkItemAgentStartTimeout(agent, submit)
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Attach a rejection handler to the fire-and-forget delivery.

deliverLaunchPromptToAgentTab rethrows in its rejection branch (src/renderer/src/lib/agent-launch-prompt-delivery.ts lines 74-80). The call here is discarded with void and has no .catch, so a rejection becomes an unhandled promise rejection in the renderer.

🛠️ Proposed fix
-    void deliverLaunchPromptToAgentTab({
+    void deliverLaunchPromptToAgentTab({
       tabId: primaryTabId,
       agent,
       content: draftContent,
       submit,
       forcePaste: submit,
       onTimeout: () => notifyDirectWorkItemAgentStartTimeout(agent, submit)
-    })
+    }).catch(() => {
+      // Delivery already reports its own failure state; keep the rejection from escaping.
+    })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void deliverLaunchPromptToAgentTab({
tabId: primaryTabId,
agent,
content: draftContent,
submit,
forcePaste: submit,
onTimeout: () => notifyDirectWorkItemAgentStartTimeout(agent, submit)
})
void deliverLaunchPromptToAgentTab({
tabId: primaryTabId,
agent,
content: draftContent,
submit,
forcePaste: submit,
onTimeout: () => notifyDirectWorkItemAgentStartTimeout(agent, submit)
}).catch(() => {
// Delivery already reports its own failure state; keep the rejection from escaping.
})

The routing-authority test expected the shared predicate to receive
isDraftPrompt; delivery mode is prompt metadata and never reaches
feasibility now, so assert its absence instead.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Retired the stale draft-prompt authority assertion — tests/e2e/structured-native-chat-routing-authority.unit.test.ts dropped 'draft-prompt' from the blockers list and the isDraftPrompt expectation, and now asserts the predicate is never handed isDraftPrompt (expect.not.objectContaining), matching the deleted feasibility input. This resolves the sole must-fix from the prior review.

Verified locally: pnpm test tests/e2e/structured-native-chat-routing-authority.unit.test.ts passes (10/10), and the file reports no typecheck:e2e errors.

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

Merge Sim added 2 commits September 9, 2026 00:54
The route was still resolved at seven callers, each also calling the settle
loop; two census tests only stopped an eighth. planAgentSessionLaunch is now
the one production caller of the resolver and its launch() the one caller of
the settle loop, and both censuses pin exactly that file.

The funnel is two-phase because three sites need the route before the
workspace exists and quick create persists its request for recovery: a plan
exposes route before creation and launches with the created worktree id;
a persisted quick-create request carries the verdict as data and re-enters
through adoptAgentSessionLaunchVerdict without re-resolving. Delivery mode
is fixed on the request once, so route and launch cannot disagree.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • One launch planner — new agent-session-launch-plan.ts adds planAgentSessionLaunch (the only production caller of resolveAgentLaunchRoute / structuredAgentLaunchSupported) and adoptAgentSessionLaunchVerdict (re-entry for a persisted verdict); its plan.launch is now the only production caller of settleStructuredAgentLaunch, with delivery mode fixed on the verdict so the route and the launch can never disagree.
  • Route-input builder slimmed — resolveAgentLaunchRouteForWorkspace and structuredAgentLaunchSupportedForWorkspace are deleted from agent-launch-route-input.ts; the module now only assembles inputs via buildAgentLaunchRouteInput and workspaceKindForWorktreeId.
  • Call sites migrated — the new-tab launcher, direct work-item, full/quick/folder create, vault resume, and onboarding folder all plan first and launch (or re-enter) instead of resolving the route by hand.
  • Quick-create persistence — agentLaunchRoute and promptDelivery are persisted on WorktreeCreationRequest and re-entered through adoptAgentSessionLaunchVerdict on recovery, so a retry never re-resolves on a changed host.
  • Census ratchets — both caller censuses now pin exactly agent-session-launch-plan.ts as the sole resolver and settle-loop caller.

Verified locally: pnpm tc:web passes, and the targeted suites (agent-session-launch-plan, both caller censuses, launch-agent-in-new-tab-structured, full-creation-structured-launch, launch-work-item-direct-agent-routing, launch-work-item-direct, worktree-creation-structured-session, agent-launch-route-input, ai-vault-session-resume-in-chat-launch, and the e2e authority test) pass.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Verdict-adopter census ratchet — agent-launch-routing-caller-census.test.ts gains a pins every production adopter of a planned verdict test that enumerates the two files allowed to call adoptAgentSessionLaunchVerdict (ai-vault-session-resume-in-chat-launch.ts, worktree-creation-structured-session.ts), closing the loop on the funnel introduced in the prior commit so a new adopter can no longer bypass the resolver by convention.

Verified locally: the census suite passes (4 tests), and the two pinned adopters are exactly the production adoptAgentSessionLaunchVerdict call sites.

Pullfrog  | 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/renderer/src/hooks/composer-state/quick-creation-execution.ts (1)

200-212: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve remote transcript readability for prospective workspaces. A repository with connectionId: 'nested-target' and executionHostId: 'runtime:vm-1' is remote, but buildAgentLaunchRouteInput marks its transcript as locally readable because the host is not ssh:. Both composer flows pass only the repository and host, so the planner can select legacy native chat for a remote transcript.

Pass nativeChatTranscriptIsLocalReadable: !selectedRepoIsRemote (or equivalent resolved repository state) through planAgentSessionLaunch in both flows. Do not infer readability only from the ssh: prefix of executionHostId.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: ce9ca02c-f165-4552-b663-78b84a372021

📥 Commits

Reviewing files that changed from the base of the PR and between 91fa5db and 7e3911d.

📒 Files selected for processing (26)
  • src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-workspace.ts
  • src/renderer/src/components/sidebar/NonGitFolderDialog.tsx
  • src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts
  • src/renderer/src/hooks/composer-state/full-creation-execution.ts
  • src/renderer/src/hooks/composer-state/full-creation-structured-launch.test.ts
  • src/renderer/src/hooks/composer-state/full-creation-structured-launch.ts
  • src/renderer/src/hooks/composer-state/quick-creation-execution.ts
  • src/renderer/src/lib/agent-launch-route-input.test.ts
  • src/renderer/src/lib/agent-launch-route-input.ts
  • src/renderer/src/lib/agent-launch-routing-caller-census.test.ts
  • src/renderer/src/lib/agent-session-launch-plan.test.ts
  • src/renderer/src/lib/agent-session-launch-plan.ts
  • src/renderer/src/lib/launch-agent-in-new-tab-structured.test.ts
  • src/renderer/src/lib/launch-agent-in-new-tab-structured.ts
  • src/renderer/src/lib/launch-agent-in-new-tab.ts
  • src/renderer/src/lib/launch-work-item-direct-agent-routing.test.ts
  • src/renderer/src/lib/launch-work-item-direct-agent-routing.ts
  • src/renderer/src/lib/launch-work-item-direct-route-preparation.ts
  • src/renderer/src/lib/launch-work-item-direct.ts
  • src/renderer/src/lib/onboarding-folder-agent-launch.ts
  • src/renderer/src/lib/onboarding-folder-agent-startup.ts
  • src/renderer/src/lib/structured-agent-launch-settlement-caller-census.test.ts
  • src/renderer/src/lib/worktree-creation-structured-session.test.ts
  • src/renderer/src/lib/worktree-creation-structured-session.ts
  • src/renderer/src/store/repos/repo-add-actions.ts
💤 Files with no reviewable changes (1)
  • src/renderer/src/lib/onboarding-folder-agent-startup.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/sidebar/NonGitFolderDialog.tsx

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

@brennanb2025 brennanb2025 reopened this Sep 9, 2026
Merge Sim added 5 commits September 9, 2026 01:42
…ktree row is absent

The planner's transcript-readability input dropped the repo-level connection
fallback the direct work-item path still computes for its startup payload, so a
route planned in the window right after workspace creation saw `undefined` —
which reads as "not locally readable" — and downgraded grok/omp launches from
native chat to a raw terminal. Only `undefined` ("cannot determine the host")
now defers to the repo; a resolved `null` stays the local answer.
…t a launch plan

Every rendered AI Vault row built a whole launch plan — execution-host lookup,
project-runtime resolution, capability read, plus a plan object and a launch
closure it threw away — to read one boolean off it. Feasibility and a launch
decision are different operations, so the planner now exports the predicate for
the first and keeps the plan for the second, and the census pins the query's
callers separately. Settings arrive by argument, which makes the AI Vault
callback's dependency on them real rather than a comment the linter contradicts.

The plan's `explicitStructured` branch had that gate as its only caller and goes
with it; the vault's launch already re-enters on an adopted verdict.
…onical one

`preflightForkAgentTrust` was a behavioural duplicate of `preflightAgentTrust`,
whose signature now accepts a nullable agent and workspace path and so is a
drop-in replacement. Its file is left holding only the launch-platform resolver
— which is not a duplicate, since it returns an override rather than a default —
so the file is renamed for what it now contains.
The settle loop's launch cancellation re-derived the standard poll-plus-eager-
event primitive that `AbortSignal` already is, so it now takes one. The eager
semantics are unchanged: the loop still cancels on the abort event rather than
only polling after awaits, so a staged prompt is discarded before it reaches the
provider, and it drops its listener on settle instead of leaving the signal
holding the closure. Quick create owns the controller and bridges its store
subscription to it.

A cancel that lands after the refusal fallback already opened a terminal now
carries that surface on the settlement. It is the fallback's tab that exists, so
reporting the pre-launch one handed the caller a workspace with no agent in it.
…ed under

The launch draft seed is keyed on `structuredAgentSessionTabId(sessionId)`
before the tab exists, while the mirror mints ids with collision avoidance that
can append a `:history-N` suffix. The two agree today only because a fresh
session's base id is unique. Pin that where the id is actually minted, with the
collision arm alongside it so the divergence the seed depends on staying away is
visible rather than assumed.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Repo-readability fallback for unlanded worktrees — resolveTranscriptIsLocalReadable now falls back to the repo's connection id via getRepoConnectionIdFromState when the worktree row has not landed yet, so a freshly created workspace is not downgraded to a terminal; a resolved local owner always wins over the repo's answer.
  • Feasibility query — structuredAgentSessionLaunchFeasible replaces the explicitStructured short-circuit so the vault resume gate answers "is structured possible" without building a launch plan; a census test pins its single caller and keeps it out of every launch decision.
  • Fork trust preflight folded — the fork's private preflightForkAgentTrust copy is deleted in favor of the canonical preflightAgentTrust; the fork keeps only getForkAgentLaunchPlatform.
  • AbortSignal cancellation — the settle loop cancels on an AbortSignal event rather than post-await polling, and a cancel that lands after the refusal fallback opened its terminal now reports that terminal via settlement.fallback.
  • One identity, one delivery mode — joinLaunchDelivery forces a joiner to the mode fixed by the opener, and a refused launch is never re-seeded.
  • Failed direct launches report failure — settleDirectWorkItemStructuredLaunch returns a failed flag and launchWorkItemDirect returns false when the structured launch opened no surface, so callers hanging irreversible follow-up work off true no longer fire.
  • Quick-create settle tightening — launchStructuredWorktreeSession takes a required agentLaunchRoute, aborts on pending-creation disappearance via its own AbortController, and reorders cancel checks before the first-message rename flag.
  • First-publication id pinned — a test pins that the first structured publication mints under the same id the launch-draft seed is keyed on.

The new tests assert exact routes, settlement shapes, and seed/outbox outcomes rather than loose truthiness, so they can actually fail on a regression.

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

Merge Sim added 2 commits September 9, 2026 19:42
… resolver

The suite that covers the builder stages `getConnectionIdFromState`, so it can
characterize the fallback but cannot catch a defect that lives in owner
resolution itself. This one runs the real resolution over real store rows: two
repos publishing the same worktree id on different hosts, which is the
documented case where the owner cannot be named and `undefined` is returned.
Red with both fix files at the previous head, green with them.

Reverts the two caller pins added to the route census — the feasibility
predicate is exported from the planner, which the census already permits, so it
passes unedited and needs no permit clause.
…check

Quick create's structured launch narrowed its guard to a bare `agent` presence
check, so a creation carrying an agent that cannot hold a structured session
reported itself cancelled once dismissed, where it previously reported that it
had done nothing. Unreachable through both callers today, but it is the last
local eligibility check in a module that otherwise trusts its callers for the
route, so it is restored rather than left to the required-route typing — which
says nothing about the agent.

Also corrects two comments that called the quick-create request "persisted".
It lives in renderer session memory and dies with the renderer; calling it
persisted made the plan/adopt split read as restart recovery, when what it
actually buys is a route decided before the worktree exists.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Un-mocked connection-fallback regression test — new agent-launch-route-connection-fallback.test.ts runs the real owner resolution over real store rows (rival repos publishing one worktree id on different hosts), pinning that an ambiguous worktree defers to the repo rather than downgrading to a terminal. The two feasibility-query census pins are reverted because the predicate is a planner export already covered by the resolver-authority ratchet.
  • Restored agent-eligibility guard — launchStructuredWorktreeSession now gates on isAgentSessionHandleProvider(agent) instead of bare agent presence, so a dismissed creation carrying a non-provider agent reports "did nothing" rather than "cancelled", matching adoptAgentSessionLaunchVerdict's own launch guard. A new test pins the untouched-settlement outcome.
  • Comment corrections — the "persisted quick-create request" phrasing is corrected to "renderer memory" across agent-session-launch-plan.ts and worktree-creation-structured-session.ts.

Verified locally: the new/changed suites pass — agent-launch-route-connection-fallback.test.ts (4), agent-launch-routing-caller-census.test.ts (4), worktree-creation-structured-session.test.ts (15) — 23/23.

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

The query threaded its narrow settings through the store, but the route
store's settings must satisfy the full GlobalSettings that two of its
resolvers require, so the narrow copy never fit. Ride the named settings
on the built input instead: the caller still names them, so a React memo
still depends on them, and no store-shaped object is needed.

Also give the launch state its delivery mode unconditionally; the key is
required, and a conditional spread makes it optional under
exactOptionalPropertyTypes.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Feasibility query overlays named settings on the built input — structuredAgentSessionLaunchFeasible now builds the route input from the raw store and overlays the request's settings onto the result, instead of spreading settings onto the store first. This is a type-level correction; the sole caller (AiVaultPanel) passes the same full settings object in both positions, so there is no runtime change, and the React caller's memo still depends on exactly the settings the answer turns on.
  • StructuredLaunchState.promptDelivery populated unconditionally — the field is now assigned options.promptDelivery rather than a conditional spread, matching its required type with no runtime change (a missing property and an explicit undefined read the same).
  • Feasibility-query test tightened — the updated test pins that the builder receives the raw store and the predicate receives the built input with the named settings overlaid.

Verified locally: agent-session-launch-plan.test.ts and structured-agent-session-launch.test.ts pass (43/43).

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

Merge Sim added 2 commits September 9, 2026 20:14
…s asymmetry

The builder reads launch customization off the store while the routing gate
reads the named settings, so one answer has two settings sources. It cannot
diverge with the single caller passing the object the store already holds, but a
PR about removing split sources should not leave that unstated.
…ent-session-launch

# Conflicts:
#	src/renderer/src/lib/worktree-creation-structured-session.test.ts
#	src/renderer/src/lib/worktree-creation-structured-session.ts

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Merged origin/main and resolved the two structured-session conflicts — launchStructuredWorktreeSession regains the "activate the workspace before selecting the chat" step inside onStructuredReady (which main already had and the settle-loop refactor had dropped), with const → let so the ready hook can reassign activation/primaryTabId.
  • Updated the providesInitialSurface caller census — SURFACE_PROVIDING_CALLERS now lists terminal-agent-session-fork.ts and onboarding-folder-agent-launch.ts, and drops NonGitFolderDialog.tsx and repo-add-actions.ts, whose opt-out moved with main's onboarding-folder refactor.
  • Added a regression test — pins that activateAndRevealWorktree(worktreeId, { providesInitialSurface: true }) runs before activateStructuredAgentSessionById for a deferred-activation creation.
  • Documented the feasibility query's settings asymmetry — a comment names that the builder still reads launch customization off store.settings while the routing gate reads the named settings.

Verified locally: worktree-creation-structured-session.test.ts (16) and worktree-activation-surface-caller-wiring.test.ts (13) pass — 29/29 — and pnpm tc:web is clean.

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

joinLaunchDelivery stripped the joiner's delivery mode when the launch it
joined had established none, and an absent mode reads as submit. A joiner
that asked for a draft therefore had its text sent — the send-without-
consent this PR exists to prevent. Fall back to the joiner's own mode only
when nothing was established, so the first caller still wins otherwise.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Coalesced joiner draft kept unsent — joinLaunchDelivery now falls back to the joiner's own promptDelivery when the launch it joined established no mode (const mode = established ?? options.promptDelivery), so a joiner carrying promptDelivery: 'draft' seeds the composer instead of having its prompt read as submit and dispatched. A new structured-agent-session-launch-join-delivery.test.ts pins the exact outcome: empty outbox, no agentSession.send, and the draft seeded under the session's tab id.

The fix is minimal and correct: whenever a mode was established, established ?? options.promptDelivery is identical to the prior established ? ... : ..., so only the no-mode draft case changes behavior. The test is exact rather than truthiness-based and would fail against the pre-fix code (the prompt would be enqueued and submitted instead of seeded).

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron QA evidence from the hidden dev renderer over Playwright/CDP at PR head c0b2434f47.

Exercised: enabled experimental native chat, structured native chat, and “open agent tabs in chat by default”; selected Codex; then used the real background worktree-launch path with a 60-line synthetic PR context and promptDelivery: 'draft'.

Source provenance: the app identity reported devRepoRoot=/Users/brennanbenson/orca/workspaces/orca/pr19681-electron-qa. From the renderer dev server, agent-session-launch-plan.ts | rg -n structuredAgentSessionLaunchFeasible returned 33:export function structuredAgentSessionLaunchFeasible(store, request) {; structured-native-chat-launch-route.ts | rg -n draft-prompt returned no match.

  1. Initial structured session. CDP state showed exactly one unified tab (contentType: agent-session, agentSessionAgent: codex), one visible native-chat root, and document.querySelectorAll('.xterm').length === 0.

Initial structured Codex session

  1. Unsent draft. The visible composer had 60 paragraph nodes matching all 60 source lines; the empty transcript state remained visible, structured outbox length was 0, and data-native-chat-working="false".

Unsent 60-line draft

  1. Editable draft. A Playwright keyboard edit appended QA edit marker: editable draft confirmed.; all original 60 lines remained intact and the edit persisted after blur.

Editable draft with persisted edit

  1. After Send. The rendered user turn contained every original context line plus the edit; the composer seed and composer were cleared, the structured outbox returned to 0, and Codex replied with the requested QA acknowledgment.

Sent user turn with full context and edit

Not exercised: the optional legacy contrast with the default-chat setting off, remote/SSH/WSL paths, or non-Codex agents. This is execution evidence, not a review verdict.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready to merge

Reviewed across four rounds (architecture, correctness/regressions, funnel design, and a final gate), plus a start- and end-of-session readiness pass. Final verdicts: code review CLEAN, readiness READY, no P0 or P1.

Does it fix the reported problem

Yes, and the mechanism is the fix rather than a guard around it: the draft-prompt blocker is deleted from the shared resolver, not special-cased. Traced end to end, and proven by ablation at the current head — restoring the blocker (both structured-native-chat-launch-route.ts and agent-launch-routing.ts, since either alone is inert) turns 3 tests red, including the short-draft and 60-line-draft routing cases. Un-ablated: 0 failures.

What the review changed

Fourteen fixes landed after the original steps. Every behavioural one carries a regression test proven red on the pre-fix code:

  • Route readability lost its repo-level fallback. The builder resolved the connection id from the worktree alone where the merge base fell back to the repo; an ambiguous owner resolves undefined, which reads as "not locally readable" and downgraded legacy-native-chat to terminal-tui. Reaches only agents that require a local transcript (grok/omp), never the structured route. Restored inside the builder so every caller benefits — and deliberately not as the merge base's ??, which also fell back on a resolved null and so wrongly deferred a local worktree to a remote repo.
  • Route resolution now runs through one planner. planAgentSessionLaunch is the only production caller of the resolver and plan.launch the only caller of the settle loop; both censuses pin that single file. Feasibility is a separate boolean query, so a caller asking "can this open a chat" no longer builds a launch plan it must discard. An API-shape correction, not a speedup — the query runs the same builder work.
  • A coalesced joiner could have its draft sent. With no delivery mode established, the joiner's mode was stripped, and an absent mode reads as submit.
  • One delivery mode per launch identity; no draft seed onto an already-refused launch; cancellation moved to AbortSignal keeping the eager cancel that discards a staged prompt before it reaches the provider; cancel-after-fallback reports the fallback's surface; the abandon check precedes the rename write; error boundaries at the two unguarded plan.launch sites; the dead terminal-tui route default replaced by a required field; the fourth private trust-preflight copy deleted (one of them was a local function named preflightAgentTrust, shadowing the canonical one); and launchWorkItemDirect returns false when the structured launch opened no surface.

Body claims were audited against the code and five corrected, including the trust-preflight count and which flows held copies.

Verification

  • CI at c0b2434f47: 18 success, 0 failure (read per-check, not off the pending count).
  • tc:web / tc:node / tc:cli run individually: all exit 0.
  • check:code-quality:changed: 68 gated files, 0 findings across code quality, type-aware, and React Doctor.
  • Full-suite sweep: 28,013 tests, 1 failure — remote-runtime-shared-control-connection.test.ts, which has zero diff against this branch and passes in isolation. Contention flake, not this PR.
  • Electron QA at this exact head is in the comment above, with provenance proof that the running renderer served this branch.

Merge of main

Resolved two conflicts. Main's #19753 added an activation guard in the exact function this branch had rewritten into an onStructuredReady hook, so taking "ours" would have silently dropped it. Ported, with the activation bindings made mutable so the port actually takes effect. Proven load-bearing by ablation — removing it reddens 2 tests including main's own, which pins the invocation order against chat selection. Merge commit verified to have two parents.

Known follow-ups (not fixed here)

  • Duplicate toast on Vault resume failure: the shared launch layer's generic toast and the caller's specific one both fire. Verified pre-existing — identical at the merge base; this PR only extracted the module, and it removes toast noise on unknown outcomes. A clean fix means letting a caller opt out of the shared toast, which changes behaviour for every launch site.
  • Unhandled rejection on the fire-and-forget prompt delivery in launch-work-item-direct.ts. Verified pre-existing and present at both call sites, including the new-tab launcher.
  • Nested-SSH transcript readability: a folder project group that is SSH-held and pins a runtime environment now reports its transcript as locally readable, because the builder prefers the runtime host over the group's SSH host. grok/omp only, view-mode toggle works around it, quick create unaffected. Disclosed in the description as a known ambiguity rather than a clean correction.

Gaps

Platform coverage is macOS unit tests plus this Electron run; SSH, Windows and Linux paths are covered by the route-matrix tests only. The legacy contrast case and non-Codex agents were not exercised in the app.

Merge Sim added 5 commits September 10, 2026 00:03
…ent-session-launch

# Conflicts:
#	src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx
…ent-session-launch

# Conflicts:
#	src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx
GitHub created no workflow run for e935ea5 — the pull_request
synchronize event was dropped. No content change.
…ent-session-launch

# Conflicts:
#	src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx
@brennanb2025
brennanb2025 merged commit 33436c3 into main Sep 10, 2026
28 checks passed
brennanb2025 added a commit that referenced this pull request Sep 15, 2026
…son map

main removed the draft-prompt blocker in #19681 (a structured session now holds
an unsent draft), so the exhaustive Record no longer typechecks.
brennanb2025 added a commit that referenced this pull request Sep 15, 2026
…#19848)

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

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

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

---------

Co-authored-by: Merge Sim <sim@local>
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
…stablyai#19848)

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

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

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

---------

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