Skip to content

Start real agent terminals after successful Setup - #36325

Closed
brennanb2025 wants to merge 24 commits into
mainfrom
brennanb2025/setup-terminal-launch-owner
Closed

brennanb2025 wants to merge 24 commits into
mainfrom
brennanb2025/setup-terminal-launch-owner

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 29 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4143 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4142
Prod 121 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​5358 $\color{#cf222e}{\Huge{\mathbf{−}}}$​717 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4641

ELI5

When a workspace is configured to wait for Setup, Orca currently starts an agent terminal containing a shell that waits. This change keeps Setup interactive and starts the real agent terminal only after Setup succeeds. Reconnecting observes the accepted launch instead of starting it again.

This PR is useful on its own, but does not complete STA-9961. The existing first-input and returned-shell protections remain. Delivery to argument-dropping wrappers and manually started agents needs the separate owner decision before further delivery work.

What Changed

  • Add an execution-host-owned prepare/accept operation for immediate launches and Setup-dependent launches. Accept retains the complete existing launch command, environment and optional startup prompts before starting either process.
  • Observe Setup completion directly from the selected native process, before ordinary output subscriptions. Nonzero completion, close, cancellation before dispatch and the Setup deadline prevent the unstarted agent from launching.
  • Save an optional operation descriptor and retain it through expiry, unrelated admissions and restart until the exact owner proves retirement. Retaining an expired obligation never grants a new execution right.
  • Publish only real Setup and agent sessions, attach to the exact incarnation, and restore the primary tab position without moving it again on reconnect. Wire workspace creation, desktop folder creation and agent-first worker/agent launch consumers into the capable path.
  • Let a caller timeout return the pending receipt while its accepted worker continuation keeps running. Abandoning a Dispatch still does not cancel accepted terminal work or restore revoked reporting authority.
  • Stage owned oversized POSIX commands in private files before physical creation. Keep them outside age-based cleanup and fail before spawning if staging cannot be completed. Establish physical ownership before installing raw-output observers.

Why

Setup is a dependency of process creation. A waiting shell conflates that dependency with the agent's terminal and forces later code to guess whether the agent exists. The real launch is released only after successful Setup. The execution owner also provides one place to distinguish a known unused launch from an accepted or uncertain one, so connection loss cannot authorize a duplicate.

Design choices:

  • Intended: an optional saved adoption descriptor and generation-scoped host operation accommodate independent client/server/daemon lifetimes, retained daemons and paired hosts. The descriptor grants observation, not replay.
  • Intended: Setup remains an interactive terminal because existing Setup scripts can require user input. Only the dependent agent waits.
  • Intended: old callers and unsupported host/daemon paths retain their shipped launch/readers, without a minimum server version. Windows shell arguments and unfamiliar-shell compatibility transports retain their existing behavior; their live platform validation remains outstanding.
  • Temporary: post-start prompts still use the existing guarded delivery. Uncertain or refused prompt delivery stays retained and is not blindly resubmitted. Command-preserving first-task delivery and resuming an interrupted worker-input continuation across a main-process restart are outside this PR's activation; their delivery architecture remains a separate decision.

Linked Issue

Tracked in STA-9961. This is PR1 of the approved Setup/launch-owner cut; it does not close the ticket.

Visual Proof

Pending the coordinator's runtime QA. This changes process sequencing and when the actual agent pane appears, so running-app evidence is still required before readiness.

Testing

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

319 tests passed across 22 explicitly named Vitest files through the local test gate on commit 5b89329224fecee8d6ec6b4a418f8533c12eace2. Coverage includes expired-obligation admission/restart retention, accepted Setup → abandon → Setup zero, both lost-cancel race orders, caller timeout followed by guarded continuation, returned-shell refusal, publication recovery without replay, primary placement, Setup/native-output ordering, observer-registration failure, private staging failure before spawn, legacy routing, folder workspaces and agent-launch prompt carry.

The normal pre-commit hook passed, including the repository's staged-file static checks and formatter. No standalone lint, typecheck, full test suite, build, install or live agent/app run was performed. CI and runtime QA remain outstanding. Windows tests use recorded/simulated process behavior on macOS; they are not Windows/WSL/SSH live-run evidence.

Review

Full path, one line per classification criterion:

  1. Small: no; 3,872 changed production lines across 72 production files, plus 1,233 changed test lines across 10 test files.
  2. Outside risky areas: no; this changes process creation, ownership, saved operation metadata, ordering, recovery, daemon protocol and orchestration.
  3. Not a repeat: no; the mechanism includes prior Setup/returned-shell incidents, including feat(agent-launch): keep long prompts off the launch line and paste them after readiness (step 1 of 7) #24257, whose protection remains.
  4. Local effect: no; main and the daemon share accepted work across disconnects and version boundaries.

Agent skill upstream boundary

  • Not applicable; this change copies or mechanically translates no upstream skill-installer material.

Notes

The daemon protocol adds a capability boundary for prepared launches. Unsupported paths remain on the shipped mechanism; uncertain modern acceptance cannot select that fallback. No new user setting, SQL column or fabricated live session is introduced. The saved extension contains adoption metadata, not command bodies, raw launch tokens or environment contents.

The coordinator will run the review loop and platform QA. This PR is a draft and is not ready to merge. Existing #28975 remains separately owned and untouched.

Checklist

  • The change is focused on the approved Setup/launch-owner mechanism
  • Explained the before/after, mechanism and alternatives
  • Before/after runtime evidence attached
  • Self-reviewed for correctness, security and performance
  • Cross-platform, paired-host, folder-workspace and version boundaries considered
  • CI lint/typecheck/build checks and required platform QA pass

@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Review in 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.

Walkthrough

The change adds prepared-agent launch support across daemon, runtime, worktree, and worker startup flows. It introduces launch identities, protocol requests, daemon reservations and execution tracking, PTY observation and startup-command staging, and runtime publication and reconciliation. Worktree results can carry pending launches, and the renderer handles pending startup state and launch notices.

Merge Risk: Moderate · up to c4c7e

Prepared launches can be reported as pending after a definite refusal, and startup failures after workspace creation can leave callers without the created workspace and permit duplicate creation on retry. Resolve these paths before merging.

Pre-merge checks: Passed 3 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (tracked in STA-9961, but no 'Fixes #' issue link and the author states it does not close the tick… Add a Risk section that names the riskiest part of the change (process sequencing, saved operation metadata, daemon protocol boundary, and private staging), states who would be affected and what users would see if it failed, and gives a bac…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title clearly and concisely describes the primary change: starting real agent terminals after successful Setup.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (tracked in STA-9961, but no 'Fixes #' issue link and the author states it does not close the ticket), Visual Proof (marked pending runtime QA), Testing, Risk, Review, Agent skill upstream boundary, Notes, and Checklist. The Risk section is missing: it does not state the risk level or how to back out the change, which the template requires. The AI Disclosure section is also absent, though it may be optional for internal contributors. Testing is thorough and states the limits of what was run. Visual Proof is incomplete because no before/after evidence is attached for a change that alters when the agent pane appears.

Resolution

Add a Risk section that names the riskiest part of the change (process sequencing, saved operation metadata, daemon protocol boundary, and private staging), states who would be affected and what users would see if it failed, and gives a backout method. Include the required Level (Low, Medium, or High). Attach before/after runtime evidence under Visual Proof, or state why it is N/A. Complete the Linked Issue section with an actual issue reference if one exists, or confirm the tracking reference is sufficient. Add an AI Disclosure entry if the contributor is not a StablyAI team member. Mark the lint, typecheck, build, and CI checklist items once they pass.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 201e1586-9fe4-485a-861d-c6ba6cfe4fa6
Commits

Reviewing files that changed from the base of the PR and between 4256561 and c4c7e00.

Files selected for processing: 16

  • src/main/daemon/prepared-agent-launch-execution.ts
  • src/main/daemon/prepared-agent-launch-incarnation.ts
  • src/main/runtime/rpc/terminal-send-launch-composer.test.ts
  • src/main/runtime/runtime-terminal-contracts.ts
  • src/main/runtime/terminal/launch/prepared-terminal-prompt-delivery.ts
  • src/main/runtime/terminal/launch/prepared-terminal-publication.test.ts
  • src/main/runtime/terminal/launch/prepared-terminal-publication.ts
  • src/main/runtime/terminal/launch/prepared-terminal-runtime.test.ts
  • src/main/runtime/terminal/launch/terminal-create.ts
  • src/main/runtime/workspaces/prepared-worktree-start.ts
  • src/main/runtime/workspaces/workspace-creation.ts
  • src/renderer/src/store/slices/worktrees-remote-runtime-create.test.ts
  • src/shared/claimed-agent-pty-dispatch.ts
  • src/shared/claimed-agent-pty-owner.ts
  • src/shared/prepared-agent-launch.ts
  • src/shared/startup-command-staging.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

… daemon

Route each daemon generation's operations directly once known, stop the
Setup scan at settlement, write one final Setup notice for failure or
deadline, return the accepted recipe, view and token only to the exact
publication observer, make the first-prompt handoff recoverable with a
fenced attempt and terminal outcomes, name the daemon's process and boot
in its generation, and reclaim owned staged files only after a reboot.
A late waiter reads the daemon's result instead of requiring the saved
descriptor, names the agent and reason when no usable agent started, and
joins the in-flight publication by exact launch identity. Publication
takes the accepted recipe, view and token from the daemon on first
publication and after a restart, settles the first prompt exactly once,
and retires a descriptor only on positive owner demise. A failure before
acceptance keeps the created workspace with the shipped warning, and the
renderer seeds the tab reserved for the eventual agent.
…starts

The Setup terminal that would explain the absent agent is gone, so the
window shows one toast naming the agent and how to start it. Setup
failure and deadline keep their single line in the surviving Setup
terminal and never also toast.
Comment on lines +51 to +88
private discover(
generation: string,
capable: readonly DaemonPtyAdapter[],
identity: PreparedAgentLaunchIdentity
): Promise<DaemonPtyAdapter | null> {
const existing = this.discovering.get(generation)
if (existing) {
return existing
}
const found = new Promise<DaemonPtyAdapter | null>((resolve) => {
let remaining = capable.length
const settle = (adapter: DaemonPtyAdapter | null) => {
if (adapter) {
resolve(adapter)
} else if (--remaining === 0) {
resolve(null)
}
}
if (remaining === 0) {
resolve(null)
}
for (const adapter of capable) {
adapter.preparedAgentLaunch({ action: 'status', identity }).then(
(status) => settle(isPreparedAgentLaunchStatus(status) ? adapter : null),
// Only the named generation can say it holds no such operation.
(error: unknown) => settle(isPreparedLaunchOperationUnknown(error) ? adapter : null)
)
}
}).then((adapter) => {
this.discovering.delete(generation)
if (adapter) {
this.routes.set(generation, adapter)
}
return adapter
})
this.discovering.set(generation, found)
return found
}

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.

Minor · Stability & Availability · Quick win

Supported by static analysis

Script executed:

#!/bin/bash
fd -i 'daemon-client' src/main/daemon --exec rg -nP -C4 '\brequest\s*(<[^>]*>)?\s*\(' {}

Repository: stablyai/orca

Length of output: 1034


Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- relevant files ---'
rg --files | rg '(^|/)(daemon-client|daemon-prepared-agent-launch-routing|daemon-p.*adapter|daemon.*client|.*daemon.*router).*' || true
printf '%s\n' '--- symbols and request implementations ---'
rg -n -F --glob '*.{ts,tsx,js,mjs,cjs}' \
  -e 'class DaemonClient' \
  -e 'interface DaemonClient' \
  -e 'preparedAgentLaunch' \
  -e 'class PreparedAgentLaunchRoutes' \
  -e 'waitForPreparedAgentTerminal' \
  -e 'reconcilePreparedTerminalPublications' \
  -e 'provesPreparedLaunchOwnerGone' \
  -e 'async request(' \
  -e 'request<T' \
  src test tests 2>/dev/null || true
printf '%s\n' '--- target file ---'
nl -ba src/main/daemon/daemon-prepared-agent-launch-routing.ts 2>/dev/null | sed -n '1,240p'
printf '%s\n' '--- client-like request declarations ---'
rg -l -F --glob '*.{ts,tsx,js,mjs,cjs}' -e 'class DaemonClient' -e 'interface DaemonClient' -e 'preparedAgentLaunch' src test tests 2>/dev/null | while IFS= read -r f; do
  printf '\n### %s\n' "$f"
  nl -ba "$f" | sed -n '1,260p'
done

Repository: stablyai/orca

Length of output: 45667


Script executed:

set -u
printf '%s\n' '--- files ---'
rg --files | rg 'daemon|pty' | head -300
printf '%s\n' '--- symbols ---'
rg -n -F --glob '*.ts' --glob '*.tsx' \
  -e 'class DaemonClient' -e 'DaemonClient' -e 'preparedAgentLaunch' \
  -e 'PreparedAgentLaunchRoutes' -e 'waitForPreparedAgentTerminal' \
  -e 'reconcilePreparedTerminalPublications' -e 'provesPreparedLaunchOwnerGone' . || true
printf '%s\n' '--- request methods ---'
rg -n -P --glob '*.ts' --glob '*.tsx' '(async\s+)?request\s*(<[^>]+>)?\s*\(' src mobile tests test 2>/dev/null || true

Repository: stablyai/orca

Length of output: 45667


Script executed:

set -u
for spec in \
  'src/main/daemon/client.ts:1:270' \
  'src/main/daemon/daemon-prepared-agent-launch-client.ts:1:100' \
  'src/main/daemon/daemon-pty-adapter.ts:285:320' \
  'src/main/daemon/daemon-prepared-agent-launch-routing.test.ts:1:180' \
  'src/main/runtime/terminal/launch/prepared-terminal-runtime.ts:80:135' \
  'src/main/runtime/terminal/launch/prepared-terminal-publication.ts:215:310'
do
  file=${spec%%:*}; rest=${spec#*:}; start=${rest%%:*}; end=${rest##*:}
  printf '\n--- %s:%s-%s ---\n' "$file" "$start" "$end"
  nl -ba "$file" | sed -n "${start},${end}p"
done

Repository: stablyai/orca

Length of output: 27249


Script executed:

set -u
printf '%s\n' '--- request RPC implementation ---'
nl -ba src/main/daemon/daemon-client-rpc-request.ts | sed -n '1,280p'
printf '%s\n' '--- prepared launch adapter declaration ---'
rg -n -F -e 'class DaemonPtyAdapter' -e 'extends DaemonPtyPreparedLaunch' -e 'export abstract class DaemonPtyPreparedLaunch' src/main/daemon
nl -ba src/main/daemon/daemon-pty-adapter.ts | sed -n '1,90p'

Repository: stablyai/orca

Length of output: 13017


Bound the shared discovery delay.

When no capable adapter owns the generation, a stalled adapter makes every request sharing that generation wait for the client’s 30-second RPC timeout before discovery returns agent_session_ownership_unknown. This can delay waitForPreparedAgentTerminal and the whole reconciliation pass. Add a shorter per-probe deadline. The timeout must settle that probe as null and retain the saved descriptor.

Suggested fix
       for (const adapter of capable) {
-        adapter.preparedAgentLaunch({ action: 'status', identity }).then(
+        let timer: ReturnType<typeof setTimeout> | undefined
+        const probe = Promise.race([
+          adapter.preparedAgentLaunch({ action: 'status', identity }),
+          new Promise<never>((_, reject) => {
+            timer = setTimeout(() => reject(new Error('prepared_launch_probe_timeout')), 10_000)
+          })
+        ]).finally(() => clearTimeout(timer))
+        probe.then(
           (status) => settle(isPreparedAgentLaunchStatus(status) ? adapter : null),
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

Suggested change
private discover(
generation: string,
capable: readonly DaemonPtyAdapter[],
identity: PreparedAgentLaunchIdentity
): Promise<DaemonPtyAdapter | null> {
const existing = this.discovering.get(generation)
if (existing) {
return existing
}
const found = new Promise<DaemonPtyAdapter | null>((resolve) => {
let remaining = capable.length
const settle = (adapter: DaemonPtyAdapter | null) => {
if (adapter) {
resolve(adapter)
} else if (--remaining === 0) {
resolve(null)
}
}
if (remaining === 0) {
resolve(null)
}
for (const adapter of capable) {
adapter.preparedAgentLaunch({ action: 'status', identity }).then(
(status) => settle(isPreparedAgentLaunchStatus(status) ? adapter : null),
// Only the named generation can say it holds no such operation.
(error: unknown) => settle(isPreparedLaunchOperationUnknown(error) ? adapter : null)
)
}
}).then((adapter) => {
this.discovering.delete(generation)
if (adapter) {
this.routes.set(generation, adapter)
}
return adapter
})
this.discovering.set(generation, found)
return found
}
private discover(
generation: string,
capable: readonly DaemonPtyAdapter[],
identity: PreparedAgentLaunchIdentity
): Promise<DaemonPtyAdapter | null> {
const existing = this.discovering.get(generation)
if (existing) {
return existing
}
const found = new Promise<DaemonPtyAdapter | null>((resolve) => {
let remaining = capable.length
const settle = (adapter: DaemonPtyAdapter | null) => {
if (adapter) {
resolve(adapter)
} else if (--remaining === 0) {
resolve(null)
}
}
if (remaining === 0) {
resolve(null)
}
for (const adapter of capable) {
let timer: ReturnType<typeof setTimeout> | undefined
const probe = Promise.race([
adapter.preparedAgentLaunch({ action: 'status', identity }),
new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error('prepared_launch_probe_timeout')), 10_000)
})
]).finally(() => clearTimeout(timer))
probe.then(
(status) => settle(isPreparedAgentLaunchStatus(status) ? adapter : null),
// Only the named generation can say it holds no such operation.
(error: unknown) => settle(isPreparedLaunchOperationUnknown(error) ? adapter : null)
)
}
}).then((adapter) => {
this.discovering.delete(generation)
if (adapter) {
this.routes.set(generation, adapter)
}
return adapter
})
this.discovering.set(generation, found)
return found
}

Comment on lines +113 to +116
const preparedTerminal = result.startupTerminal?.pending
? await runtime.waitForPreparedAgentTerminal(result.startupTerminal.pending)
: undefined
const startupTerminal = preparedTerminal ?? result.startupTerminal

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.

Major · Stability & Availability · Quick win

Supported by static analysis

Script executed:

#!/bin/bash
rg -nP -C3 "agentLaunch|'agent\.launch'" src/cli src/main/runtime/rpc --type=ts | rg -i 'timeout|clientMutationId|creationId' | head -40

Repository: stablyai/orca

Length of output: 265


Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- worktree creation references ---'
rg -n -F --glob '*.ts' -e 'waitForPreparedAgentTerminal' -e 'PreparedTerminalPendingError' -e 'releaseAutomationWorkspaceProvenanceRequest' -e 'STRUCTURED_SETUP_WAIT_TIMEOUT_MS' src/main src/cli
printf '%s\n' '--- worktree creation file ---'
nl -ba src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts | sed -n '1,260p'
printf '%s\n' '--- helper definitions and owners ---'
rg -n -F --glob '*.ts' -e 'waitForPreparedAgentTerminal' -e 'class PreparedTerminalPendingError' -e 'PreparedTerminalPendingError' src | head -80
printf '%s\n' '--- agent launch identifiers and timeout/retry references ---'
rg -n -P --glob '*.ts' -C4 'agentLaunch|agent\.launch|clientMutationId|creationId' src/cli src/main/runtime/rpc | head -240

Repository: stablyai/orca

Length of output: 33769


Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- prepared terminal runtime ---'
nl -ba src/main/runtime/terminal/launch/prepared-terminal-runtime.ts | sed -n '1,220p'
printf '%s\n' '--- prepared terminal error ---'
nl -ba src/main/runtime/terminal/launch/prepared-terminal-pending.ts | sed -n '1,120p'
printf '%s\n' '--- provenance implementation ---'
nl -ba src/main/automations/workspace-provenance.ts | sed -n '1,220p'
printf '%s\n' '--- worker receipt handling ---'
nl -ba src/main/runtime/rpc/methods/orchestration/worker/worker-start-receipt.ts | sed -n '1,140p'
printf '%s\n' '--- CLI launch recovery ---'
nl -ba src/cli/agent-launch-request.ts | sed -n '1,230p'

Repository: stablyai/orca

Length of output: 32079


Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- publication state handling ---'
rg -n -F --glob '*.ts' -e 'function publishPreparedTerminal' -e 'publishPreparedTerminal' -e 'not-dispatched' -e 'deadline' src/main/runtime/terminal/launch src/shared/prepared-agent-launch.ts
nl -ba src/main/runtime/terminal/launch/prepared-terminal-publication.ts | sed -n '1,280p'
printf '%s\n' '--- dispatch token semantics ---'
nl -ba src/main/automations/dispatch-tokens.ts | sed -n '1,260p'
printf '%s\n' '--- CLI recovery ---'
nl -ba src/cli/agent-launch-recovery.ts | sed -n '1,260p'
printf '%s\n' '--- creation/request identifiers ---'
rg -n -P --glob '*.ts' -C5 'createRequestId|clientMutationId|operationId|withCliAgentLaunchRecovery' src/shared src/main/runtime/rpc/methods/agent-launch.ts src/main/runtime/rpc/methods src/cli | head -320

Repository: stablyai/orca

Length of output: 42618


Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- complete CLI recovery implementation ---'
nl -ba src/cli/agent-launch-recovery.ts | sed -n '1,220p'
printf '%s\n' '--- runtime client timeout implementation ---'
rg -n -F --glob '*.ts' -e 'timeout' -e 'setTimeout' src/cli/runtime-client.ts src/cli | head -120
nl -ba src/cli/runtime-client.ts | sed -n '1,260p'
printf '%s\n' '--- agent launch parameter and worktree mutation IDs ---'
nl -ba src/main/runtime/rpc/methods/agent-launch.ts | sed -n '100,280p'
rg -n -P --glob '*.ts' -C5 'clientMutationId|createRequestId' src/shared/rpc-contract src/cli src/main/runtime/rpc/methods/agent-launch* src/main/runtime/rpc/methods/worktree-create-args.ts

Repository: stablyai/orca

Length of output: 36944


Do not block the launch reply on Setup. Do not release provenance after the worktree exists.

waitForPreparedAgentTerminal can wait until the prepared launch reaches its two-hour deadline. The handler has no server-side bound for this wait. A client transport timeout does not stop the server-side operation.

PreparedTerminalPendingError means that the worktree exists and Setup or agent launch remains owned by the terminal host. The current catch releases the provenance reservation as if worktree creation failed. A retry can then reuse that reservation and create another worktree when no creationId or clientMutationId is present.

Bound this wait. Treat PreparedTerminalPendingError and a wait timeout as a pending agent, not as a failed worktree creation. Finish the provenance request, return the created workspace without startupTerminalHandle, and include a warning that the agent starts after Setup.

Comment on lines +200 to +213
let receipt
try {
receipt = await controller.preparedAgentLaunch({ action: 'accept', identity, ...payload })
} catch {
observe()
return {
pending: {
...identity,
worktreeId: args.worktreeId,
tabId: launch.surface.tabId,
...(setup ? { setupTerminalHandle: setup.surface.terminalHandle } : {})
}
}
}

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.

Minor · Stability & Availability · Quick win

Supported by static analysis

Script executed:

sed -n '150,295p' src/main/runtime/terminal/launch/prepared-worktree-terminal-start.ts

Repository: stablyai/orca

Length of output: 4705


Script executed:

sed -n '200,280p' src/main/daemon/prepared-agent-launch-owner.ts

Repository: stablyai/orca

Length of output: 3130


Script executed:

set -o pipefail
printf '%s\n' '--- status/owner definitions ---'
rg -n -F --glob '*.ts' -e "action: 'status'" -e "action === 'status'" -e "status(" -e "publishPreparedTerminal" src/main/runtime/terminal src/main/daemon src/renderer src/shared || test "$?" -eq 1
printf '%s\n' '--- prepared start references ---'
rg -n -F --glob '*.ts' -e 'startPreparedWorktreeTerminals' -e 'PreparedLaunchNotAcceptedError' -e 'hasBackendStartup' src/main src/renderer src/shared || test "$?" -eq 1
printf '%s\n' '--- owner status implementation ---'
sed -n '1,220p' src/main/daemon/prepared-agent-launch-owner.ts
printf '%s\n' '--- owner remainder ---'
sed -n '280,500p' src/main/daemon/prepared-agent-launch-owner.ts

Repository: stablyai/orca

Length of output: 41634


Script executed:

set -o pipefail
printf '%s\n' '--- publication implementation ---'
sed -n '1,235p' src/main/runtime/terminal/launch/prepared-terminal-publication.ts
printf '%s\n' '--- publication tail ---'
sed -n '235,330p' src/main/runtime/terminal/launch/prepared-terminal-publication.ts
printf '%s\n' '--- runtime startup caller ---'
sed -n '1,90p' src/main/runtime/runtime-prepared-worktree-terminal-startup.ts
printf '%s\n' '--- IPC caller ---'
sed -n '325,380p' src/main/ipc/worktree-remote.ts
printf '%s\n' '--- renderer result handling ---'
sed -n '1,125p' src/renderer/src/lib/worktree-creation-host-agent-launch.ts

Repository: stablyai/orca

Length of output: 21317


Script executed:

set -o pipefail
nl -ba src/main/runtime/terminal/launch/prepared-terminal-publication.ts | sed -n '48,125p'
nl -ba src/main/runtime/terminal/launch/prepared-worktree-terminal-start.ts | sed -n '175,285p'
nl -ba src/main/runtime/runtime-prepared-worktree-terminal-startup.ts | sed -n '25,82p'
nl -ba src/renderer/src/lib/worktree-creation-host-agent-launch.ts | sed -n '42,100p'

Repository: stablyai/orca

Length of output: 13088


Do not treat a refused accept as an uncertain acceptance.

reserveCapacity(), agent_session_operation_conflict, and agent_session_operation_invalid can throw before the daemon sets accepted: true. The current catch still returns pending, so publication can wait until the unaccepted launch retires. The observer then releases the surfaces and swallows errors. The caller and renderer can treat the pending identity as a backend startup instead of reporting the launch failure or using the fallback path.

Read the exact status before keeping the launch pending. Preserve the pending path when the daemon reports accepted: true, because that indicates that the accept may have succeeded even if its reply was lost.

Proposed fix
-    } catch {
+    } catch (error) {
+      const exact = await controller
+        .preparedAgentLaunch({ action: 'status', identity })
+        .catch(() => null)
+      if (isPreparedAgentLaunchStatus(exact) && !exact.accepted) {
+        // The owner answered: nothing was accepted, so the shipped path owns this agent.
+        accepted = false
+        throw new PreparedLaunchNotAcceptedError(error)
+      }
       observe()
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

Suggested change
let receipt
try {
receipt = await controller.preparedAgentLaunch({ action: 'accept', identity, ...payload })
} catch {
observe()
return {
pending: {
...identity,
worktreeId: args.worktreeId,
tabId: launch.surface.tabId,
...(setup ? { setupTerminalHandle: setup.surface.terminalHandle } : {})
}
}
}
let receipt
try {
receipt = await controller.preparedAgentLaunch({ action: 'accept', identity, ...payload })
} catch (error) {
const exact = await controller
.preparedAgentLaunch({ action: 'status', identity })
.catch(() => null)
if (isPreparedAgentLaunchStatus(exact) && !exact.accepted) {
// The owner answered: nothing was accepted, so the shipped path owns this agent.
accepted = false
throw new PreparedLaunchNotAcceptedError(error)
}
observe()
return {
pending: {
...identity,
worktreeId: args.worktreeId,
tabId: launch.surface.tabId,
...(setup ? { setupTerminalHandle: setup.surface.terminalHandle } : {})
}
}
}

…roofs

The daemon grants the first-prompt write once per operation to whichever
request asks first; every later request reads the outstanding attempt or
the retained written/uncertain receipt. A lost grant reply closes that
grant as uncertain; a lost settlement retries settlement only. Publication,
waiters and the desktop read the daemon receipt, and the desktop's one
short notice now covers an uncertain first prompt as well as a closed
Setup, keyed by operation. Reconciliation proves each daemon generation's
demise once per pass, and owned launch files are collected at daemon start
and each main connection, with writer and reader provenance for launches
staged without a boot identity.
… process facts

The first prompt now stays with the main flow that created the launch, as for every
other startup: one continuation per launch writes it once after the exact agent is
published, and every observer and waiter returns that one answer. The daemon no
longer holds prompt bytes or a grant/settlement protocol. A restarted main that finds
a prompt-bearing launch without its continuation reports once that the prompt may not
have been delivered and never sends it. Only the store transaction that retires the
launch shows its desktop notice, and that transaction records the final answer for
late callers.

Process demise now compares separately recorded facts (PID, PID namespace, start,
boot) only where both sides read them, so learning a boot that was unreadable earlier
no longer makes a live daemon look gone or deletes its staged launch file.
Comment on lines +37 to +41
async function collect(directory: string): Promise<void> {
const boot = await readBootIdentity().catch(() => undefined)
if (boot) {
sweepPriorBootOwnedStaging({ directory, bootTag: ownedStagingBootTag(boot) })
}

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.

Minor · Performance & Scalability · Quick win

Supported by static analysis

Script executed:

#!/bin/bash
# Inspect the ratchet scope and how it treats synchronous fs calls reached from the daemon.
fd -t f 'check-daemon-blocking-call-ratchet' config/scripts --exec sed -n '1,120p' {}
rg -nP -C3 'sweepPriorBootOwnedStaging' src

Repository: stablyai/orca

Length of output: 5949


Script executed:

set -e
printf '%s\n' '--- collector imports and implementation ---'
nl -ba src/main/daemon/prepared-agent-launch-staging-collector.ts | sed -n '1,180p'
printf '%s\n' '--- sweep implementation and imports ---'
nl -ba src/shared/startup-command-staging.ts | sed -n '1,330p'
printf '%s\n' '--- DaemonServer references ---'
rg -n -F --glob '*.ts' -e 'collectOwnedStartupStaging' -e 'collect(' -e 'prepared-agent-launch-staging-collector' src/main/daemon src/main/runtime src/main/orcad
printf '%s\n' '--- DaemonServer owner context ---'
rg -n -F --glob '*.ts' -e 'class DaemonServer' -e 'new DaemonServer' -e 'start()' src/main/daemon | head -80

Repository: stablyai/orca

Length of output: 24413


Script executed:

set -e
printf '%s\n' '--- DaemonServer startup and reconnect contexts ---'
nl -ba src/main/daemon/daemon-server.ts | sed -n '110,160p;230,270p'
printf '%s\n' '--- readBootIdentity declaration and implementation ---'
rg -n -F --glob '*.ts' -e 'function readBootIdentity' -e 'export async function readBootIdentity' -e 'export function readBootIdentity' src
printf '%s\n' '--- readBootIdentity source ---'
file=$(rg -l -F --glob '*.ts' -e 'function readBootIdentity' -e 'export async function readBootIdentity' -e 'export function readBootIdentity' src | head -1)
if [ -n "$file" ]; then nl -ba "$file" | sed -n '1,180p'; fi
printf '%s\n' '--- non-test sweep callers ---'
rg -n -F --glob '*.ts' 'sweepPriorBootOwnedStaging(' src --glob '!*.test.ts'

Repository: stablyai/orca

Length of output: 12007


Keep prior-boot collection off the daemon event loop.

On startup and each authenticated reconnect, DaemonServer starts collectOwnedStartupStaging(). When boot identity is available, this calls sweepPriorBootOwnedStaging, which performs synchronous readdirSync and recursive rmSync over tmpdir(). A large staging directory can delay the event loop that serves live terminals. The blocking-call ratchet does not cover these calls, so it cannot validate this path. Use an asynchronous sweep for the daemon path and extend the ratchet to cover synchronous filesystem operations.

…t bundles

After the creator's continuation is gone, every publication and late waiter now reads
the launch's saved final answer from the current operation row. Only a launch created
by an earlier main with no saved answer gets the restart advisory, so a delayed
observer no longer reports a delivered prompt as uncertain. A launch counts as having
a post-start prompt only when it has a draft or followup, so an empty bundle never
produces that advisory after recovery.
Moves prepared agent launch to daemon protocol v56 (main took v55) and ports the
prepared path onto main's moved session modules, terminal-creation evidence,
follow-up readiness and launch-composer watch.
The packaged local-build compatibility contract follows the daemon protocol, now
v56. Tests follow main's async journal close, the worker start's bound run, and
main's own ConPTY data observer, so only the raw observer's registration fails.
Comment on lines +90 to +106
if (args.preparedAgentLaunch && args.startup) {
const started = await spawnLocalStartupAndSetupTerminals({
runtime,
worktree: result.worktree,
startup: args.startup,
setup: undefined,
defaultTabs: undefined,
createdWithAgent: args.createdWithAgent,
automationCreate: args.automationProvenanceRequest !== undefined,
preparedAgentLaunch: true
})
result = {
...result,
...(started.startupTerminal ? { startupTerminal: started.startupTerminal } : {}),
...(started.warning ? { warning: started.warning } : {})
}
}

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.

Major · Data Integrity & Integration · Quick win

A startup failure after the folder workspace exists rejects the whole create.

createFolderWorkspace saves the folder workspace metadata before line 91 runs. spawnLocalStartupAndSetupTerminals rethrows every error except PreparedLaunchNotAcceptedError, including errors from startSetupAgentTerminals and provisionManagedWorktreeTerminals. If one of those errors occurs, the outer catch runs:

  • It releases the provenance reservation.
  • It records telemetry.failed.
  • It rethrows, so the IPC call rejects.
  • It skips notifyWorktreesChanged and the created lifecycle event.

The renderer then reports a failed create, but the folder workspace already exists. A retry creates a second workspace, and the sidebar is not notified about the first one.

Treat a startup failure at this point as a warning on a successful create. Do not handle it as a create failure.

🐛 Proposed fix
             if (args.preparedAgentLaunch && args.startup) {
-              const started = await spawnLocalStartupAndSetupTerminals({
-                ...
-              })
+              const started = await spawnLocalStartupAndSetupTerminals({
+                runtime,
+                worktree: result.worktree,
+                startup: args.startup,
+                setup: undefined,
+                defaultTabs: undefined,
+                createdWithAgent: args.createdWithAgent,
+                automationCreate: args.automationProvenanceRequest !== undefined,
+                preparedAgentLaunch: true
+              }).catch((error: unknown) => ({
+                didSpawnSetup: false,
+                startupTerminal: undefined,
+                warning: `Failed to start the agent for ${result.worktree.path}: ${
+                  error instanceof Error ? error.message : String(error)
+                }`
+              }))

…ublication, and fix CI findings

- Settle a prepared owner dispatch in the creator's own frame, so ordinary claims keep main's order (creator's caller first, then joiners).
- The first publication of a prepared agent starts the launch-composer watch; later reattachments do not.
- An observer of this main's own launch, with no continuation and no saved answer, reports pending instead of inventing an answer.
- Type-only fixes: declare the prepared start on the create layer, and read a retired status after an await.
- Typed property reads replace Reflect.get; test doubles satisfy the controller contract; staging test uses fixed timestamps.
…launch scaling work

- Main's descriptor-removing transaction records the launch's final answer (published, or why not) and is the only place that explains it, through one exhaustive switch.
- A failed or timed-out Setup that is still running gets the sentence as its last line when the daemon confirms the write; every other outcome, or an unconfirmed write, gets one toast. The daemon no longer writes its own Setup notice.
- Agent spawn or staging failures, with or without Setup, now get a toast naming the agent and what to do.
- Setup recovery reads the owner's live Setup pane instead of a host-wide inventory; retirement and answer reads use the exact row key; ordinary claims skip the fresh-launch surface search; warm prepared-launch routing is one map read, and routes are evicted when their adapter retires or its daemon is replaced.
Merge a duplicate type import and give each remaining test cast the required SAFETY suppression.
The desktop create path no longer reads a warning the prepared start never returns; the one outcome projector explains a Setup that could not start.
…atch ready retirements

- The daemon decides a launch's Setup line once and returns that answer to every repeat; main asks before retiring the launch, so a lost reply leaves it for a later observer instead of adding a toast.
- The runtime's record of the exact PTY incarnation owns a prepared launch's one startup (composer hold, first view); an overlapping or late publication of the same process joins it.
- Ready descriptor retirements queued before the store's turn share one draft and commit, are rechecked before any draft, and resolve one winner per descriptor; an already-consumed wave does no store work.
An unannotated empty array was inferred as never[]; give it the store's own retirement request type. Test-only.
…aved scrollback

The daemon now consumes the bound Setup attempt's completion line before the terminal draws, records or snapshots output, while the raw scanner still reads it, so Setup tabs no longer show a raw status line, including after a restart.
The agent's first reveal now carries the launch's saved placement to the window that owns the layout, which puts the new tab before Setup only when it creates it, so a reattach or a later publication keeps the user's own order. The headless phone session and paired clients follow the same rule: a tab nothing lists yet is placed first (on a paired client, before the next tab it already holds in the host's order), and tabs already placed never move.
…and keep Setup's prompt and workspace

A worker-start whose caller times out while Setup runs now prints that the launch is still pending and the task will be delivered, exits 0, and names worker-show, instead of failing. That worker's new workspace is kept open from the moment its terminal exists, as a ready start already was. The Setup failure line now lands above the shell's prompt so the prompt and anything typed stay last. Closing the only Setup tab of an accepted launch keeps its workspace selected on its empty tab group.
…Setup terminal

The Setup tab no longer shows Orca's plumbing. Main types the same short launcher its sequenced Setup uses, with the Setup body held in the environment, and the runner's exit status leaves through a file the daemon creates in its owned staging directory and watches for the bound attempt. The printed completion marker, the raw-output scan and the display filter that hid the marker are removed. Completion stays with the daemon across main restarts, and settling the launch deletes the directory, so a late status after cancel or the deadline cannot revive it. WSL receives the status path translated; a replaced Windows ConPTY attempt still never ends the selected Setup.
The CLI checks each field of the accepted pending launch with an in-guard instead of Reflect.get; the same receipts are accepted and rejected.
Test-only: annotations replace the type assertions the changed-code casting check flags.
Test-only: Date alone is faked from a fixed timestamp and keeps advancing, so the deadline and operation id no longer read the real clock while the host and its Setup still run on real timers.
…rn waiting Setups from main, and never let keep-open block a worker's task

The Setup failure line is now written only while the shell's normal screen shows and the cursor's row is a whole, unwrapped line; under an editor's alternate screen or a wrapped command line the daemon answers "not written", so the one toast shows instead. Whether a Setup tab is the waiting Setup of an accepted launch now comes from main's live publications: main sends the whole list on every change and a loaded or reloaded window asks for it, so closing that Setup after a reload keeps the workspace selected. A worker's keep-open write that fails is logged and tried once more just before its task is delivered, and the task is delivered either way.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing: superseded by #43153, which replaces this launch-gating work with the current shared dispatch and input owners.

@brennanb2025
brennanb2025 deleted the brennanb2025/setup-terminal-launch-owner branch November 19, 2026 22:44
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