Skip to content

fix(automations): stop mounted worktrees from fresh-spawning a shell into background run tabs - #8229

Closed
MaxZarev wants to merge 1 commit into
stablyai:mainfrom
MaxZarev:fix/automation-blank-terminal-2989
Closed

MaxZarev wants to merge 1 commit into
stablyai:mainfrom
MaxZarev:fix/automation-blank-terminal-2989

Conversation

@MaxZarev

@MaxZarev MaxZarev commented Jul 11, 2026 •

Copy link
Copy Markdown

Summary

Fixes #2989.

Automations that run in an existing worktree (worktree_policy: existing) opened a blank terminal: the run-linked tab showed a default shell while the agent kept working in an orphaned PTY.

Root cause: launchAgentBackgroundSession created the tab (and a layout snapshot with no PTY binding) before awaiting the PTY spawn. If the target worktree was already mounted, Terminal.tsx rendered the new tab's TerminalPane immediately; with no PTY binding and no eager buffer, the pane took the fresh-spawn path and spawned a default shell into the tab. When the agent PTY finished spawning, persistLayoutSnapshot kept the live shell transport's binding, leaving the agent PTY orphaned. new_per_run worktrees were unaffected because they aren't mounted at spawn time.

Fix: mirror the existing CLI/IPC launch pattern (useIpcEvents.ts → createTab({ id, initialPtyId })): pre-allocate the tab/leaf ids, spawn the PTY first against the reserved tabId, then create the tab in one synchronous block (adoptAgentBackgroundSessionTab) already bound to the live PTY — tab creation with initialPtyId, launch-config registration, updateTabPtyId, and layout snapshot with the PTY attached. There is no longer any await between tab creation and PTY binding, so the fresh-spawn race window is gone. Cleanup paths now guard on whether tab adoption happened.

Screenshots

No visual change — no new UI. Behavior fix only: the run-linked tab now shows the live agent session that previously landed in an orphaned PTY behind a blank shell.

Testing

  • pnpm lint — passes in full on the rebased branch (oxlint, switch-exhaustiveness, reliability gates, max-lines ratchet, localization catalog + coverage).
  • pnpm typecheck — passes (node, cli, web).
  • pnpm test — the full suite needs the native node-pty build, which requires the Node 24 toolchain my environment doesn't have. Instead I ran the complete src/renderer/src/lib vitest suite (2452 passed, 1 skipped; includes the 20 tests of this module): all pass.
  • pnpm build — not run locally for the same Node 24 / native-toolchain reason.
  • Added regression tests that would catch this bug: spawn must complete before createTab (invocation order assert), no tab is created while the spawn is pending or after a failed spawn, the tab is created with { id, initialPtyId }, and cleanup clears PTY bindings only when adoption happened. Both launch paths (local spawn and runtime environment) are covered.
  • Manual verification: reproduced the bug on Orca v1.4.126 via the orca CLI (automation on an existing worktree → run tab = blank zsh, agent in an orphaned PTY confirmed with orca terminal read), and confirmed the fixed flow binds the run tab to the agent PTY.

AI Review Report

Ran a multi-model review of the diff with four independent AI reviewers (GPT-5.5 via Codex CLI, Claude, Gemini, GLM). Main risks checked:

  • Race between agent-status IPC and the (now later) registerAgentLaunchConfig — not reachable: the spawn promise continuation runs as a microtask before any subsequent IPC event is handled, and launch-config lookup is lazy.
  • Ordering of tab adoption vs requestBackgroundTerminalWorktreeMount on the runtime-environment path — safe: the tab is created already bound (initialPtyId + layout), so the fresh-spawn path can't trigger; ordering matches the pre-change code.
  • Reserved-tab-id collision fallback — createTab mints a fresh id and warns; store-side routing keys off the actual tab id, only env-baked pane-key attribution degrades for that one terminal.
  • Tab leak if a store setter threw mid-adoption — flagged Low/awareness-only by two reviewers; verified all involved setters are pure synchronous zustand updates with no throwing paths, and the same theoretical window existed before this change. No action taken.

Result: no actionable findings; no changes required.

Cross-platform: explicitly checked — the diff is renderer/store-level TypeScript only. No shortcuts, labels, filesystem paths, shell behavior, or Electron platform branches are touched. The PTY spawn RPCs are unchanged except for passing the pre-allocated tabId and the same env vars (ORCA_PANE_KEY, ORCA_TAB_ID, ORCA_WORKTREE_ID, ORCA_AGENT_LAUNCH_TOKEN) the CLI launch path already bakes, so macOS/Linux/Windows behavior is identical by construction.

Security Audit

  • No new input handling from untrusted sources; all ids are locally generated UUIDs.
  • No command-execution changes: spawn command/args are untouched; only the env additions listed above, all plain locally-generated strings passed through the existing spawn plumbing (same values the CLI path already sets).
  • No path handling, auth, secrets, or dependency changes.
  • IPC surface unchanged — same terminal.create / PTY spawn RPCs, no new channels.
  • Launch token remains a client-side random UUID, as before.

No follow-ups needed.

Notes

  • new_per_run automations were never affected (worktree not mounted during spawn); this PR intentionally leaves that path's behavior identical.
  • The adoption helper lives in a new module (launch-agent-background-session-tab.ts) because the max-lines ratchet forbids growing launch-agent-background-session.ts past 300 code lines.
  • Detailed code-path analysis is in my issue comment on [Bug]: Automations still having blank terminal #2989.

🤖 Generated with Claude Code

ELI5

Automations that reused an existing worktree could open a blank shell tab while the real agent ran in an orphaned PTY. The tab now waits for the background PTY before mounting so the visible pane is the one actually running the automation.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Background session startup now reserves tab and pane identifiers while spawning a local or remote PTY. After the PTY is created, a new helper creates an inactive tab, registers the effective launch configuration, updates PTY state, and applies the layout. Cleanup now checks whether tab adoption occurred before clearing or closing tab state. Tests derive tab identifiers from spawn and terminal creation calls instead of assuming a fixed identifier.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 race fix for mounted worktrees and background run tabs.
Description check ✅ Passed The description matches the template and covers summary, screenshots, testing, AI review, security, and notes.

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.

@AmethystLiang AmethystLiang self-assigned this Jul 11, 2026
@AmethystLiang
AmethystLiang self-requested a review July 11, 2026 16:47
@MaxZarev
MaxZarev force-pushed the fix/automation-blank-terminal-2989 branch 2 times, most recently from 1921726 to 7cf445e Compare July 15, 2026 08:40
@MaxZarev

Copy link
Copy Markdown
Author

Rebased onto latest main — the conflict was with #8628 (terminal session retirement), which landed in the same function.

A note on how the two fit together, since this diff rewrites two of #8628's tests rather than keeping them as-is:

  • The retireUnownedTerminal tab check can't survive unchanged on this path. It retires a provider terminal whose tab was closed mid-spawn — but this fix creates the tab after the PTY is live, so the tab never exists during the spawn. isTerminalTabPresent would always be false and every launch would be retired.
  • The invariant it protects still applies, just through a different door: the worktree can disappear across the spawn await, and adopting into a gone worktree would strand a live PTY behind a tab nothing can reach. The launch now calls retireProvider and skips adoption in that case.
  • So fix(terminal): retire sessions when tabs close #8628's two regression tests are rebuilt around that trigger (worktree disappears instead of tab closes), not dropped. Both still fail if the new guard is removed — I verified that.

Also added launch-agent-background-session-tab.test.ts: unit coverage for the new adoption helper, which also keeps the integration file under the 800-line test gate it would otherwise cross.

Locally green: 26 tests, typecheck, and full lint (incl. reliability-gates and the max-lines ratchet).

…into background run tabs

Automation dispatch created the hidden run tab (and persisted its layout)
before the agent PTY spawn resolved. When the target worktree was already
mounted — the common case for existing-workspace automations — Terminal.tsx
mounted a TerminalPane for the new empty tab immediately, and its fresh-spawn
path bound a default shell to the run tab. The agent PTY then lost the
binding race and kept running detached, so 'View run' opened a blank shell
prompt while the agent was only reachable from the sessions list.

Mirror the CLI terminal path instead: spawn the PTY first against a
pre-allocated tab id, then create the inactive tab with initialPtyId and
bind the layout in one synchronous block, leaving no window for the
fresh-spawn race.

Rebased onto stablyai#8628's session retirement work. Its retireUnownedTerminal
guard does not apply once the tab is created after the spawn — the tab
cannot be closed mid-spawn because it does not exist yet, so the check
would retire every launch. The invariant it protects still holds here:
the worktree can disappear across the spawn await, so the launch now
retires the provider terminal and skips tab adoption in that case, and
its two regression tests were rebuilt around that trigger.

Fixes stablyai#2989

Co-Authored-By: Claude Fable 5 <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor

Thanks @MaxZarev -- ended up closing in favor of #10818

LMK if questions!

@MaxZarev MaxZarev closed this Jul 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Automations still having blank terminal

3 participants