Skip to content

fix(worktrees): stop background agent launches from stealing the viewed pane - #10924

Closed
brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/sta-2350-agent-focus-steal
Closed

brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/sta-2350-agent-focus-steal

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9944

What was wrong

Launching an agent into worktree A while you are looking at worktree B wrote global viewed-surface state keyed to the launch target. Nothing compared that target against the worktree actually on screen, so a background launch reached in and changed what you were looking at.

Two writes were responsible:

  • launchAgentInNewTab called store.setActiveTabType('terminal'), and that setter stamps activeTabTypeByWorktree[activeWorktreeId] — the viewed worktree, not the launch target. So B got flipped to terminal and mis-stamped with A's intent.
  • createTab repointed the global activeTabId at the new tab whenever shouldActivate was set, even when that tab belonged to a worktree the user was not viewing.

Those two writes are also what moved keyboard focus, which is why the report describes being interrupted mid-typing: TabBar.tsx:453-459 calls focusTerminalTabSurface(state.activeTabId) whenever activeTabType is terminal and activeTabId has changed. A background launch satisfied both conditions, so typing focus jumped to the new tab in the other worktree. Both guards break that chain.

The codebase already knew this was wrong. useAutomationDispatchEvents.ts:551-561 snapshots focus before a dispatch and manually restores activeView / activeWorktree / activeTab / activeTabType afterwards, commented "Run Now and scheduled dispatches should create workspaces/tabs in the background; only an explicit row click should navigate there." That hand-rolled restore exists precisely because the shared launch path had no guard — and the other cross-worktree launchers had no equivalent workaround.

The fix

  1. New store action setActiveTabTypeForWorktree(worktreeId, type) (store/slices/editor.ts). It always stamps activeTabTypeByWorktree[target], but only writes the global activeTabType when the target is the viewed worktree. No-ops preserve the root state reference so session persistence and runtime sync don't fan out.
  2. The three launch paths use it instead of setActiveTabType: launch-agent-in-new-tab.ts, launch-agent-web-host-tab.ts (the paired / remote-host path), and run-quick-command-in-new-tab.ts.
  3. createTab only repoints the global activeTabId when worktreeId === s.activeWorktreeId. This mirrors the guard already present in activateTab a few hundred lines down (terminals.ts:1524): "only pin global activeTabId to active-worktree tabs." The per-worktree activeTabIdByWorktree[worktreeId] is still written, so the target worktree opens on its new tab when you go there.

ELI5

Orca has one sticky note that says "this is the tab the user is looking at right now." When you started an agent over in another workspace, Orca rewrote that sticky note to point at the new tab — even though you were somewhere else entirely — so your screen jumped away from the file you were reading. Now Orca writes the note for the workspace it belongs to, and only changes the "looking at right now" note if that workspace is the one actually on your screen.

Evidence

Live, in a real Electron instance (dev build of this branch, CDP-attached, isolated user-data profile, scratch two-worktree repo). Viewing worktree B with readme.md open in the editor, then launching an agent into worktree A:

observable before fix after fix
activeTabType (viewing B) editor → terminal editor → editor
B's terminal tab data-active false → true false → false
editor elements in the DOM 5 → 0 5 → 5
target A got its tab yes yes (activeTabTypeByWorktree[A] === 'terminal')

Before the fix the editor was literally torn out of the pane the user was reading. After the fix B is untouched and A is still set up correctly.

Negative control — the intended case still works. Launching into the worktree you are viewing: activeTabType editor → terminal, the new tab becomes the global active tab, activeTabIdByWorktree is correct, the terminal renders and the editor swaps out. The guard suppresses only cross-worktree steals, not real activation.

Tests

  • New store/slices/background-worktree-launch-focus.test.ts — 4 cases (background target leaves the pane alone; viewed target still switches it; no-op preserves the state reference; already-stamped background target stays inert).
  • Mutation-proven: reverting the isViewed guard fails the new test; restoring it passes.
  • 5035 passed | 1 skipped across 462 files (renderer lib/ + store/slices/). typecheck clean. oxlint clean.

Trade-offs

Real, but small and intentional:

  • A launch into a background worktree no longer pre-switches that worktree's pane type as a side effect of being launched from the foreground. The target's remembered tab type is still stamped, so when you navigate there it opens on the terminal — but nothing changes on screen at launch time. That is the point of the change.
  • Behaviour change for any caller that relied on the old global side effect to make its tab visible while the worktree was not yet active. Checked: activation sets activeWorktreeId (worktree-activation.ts:321) before creating its default tabs, floating-workspace terminals pass activate: false and activate explicitly through the already-guarded activateTab, and folder workspaces key activeTabTypeByWorktree / activeWorktreeId by the same workspaceKey — so no caller regressed. Verified live via the negative control above.
  • No user-facing regression found. No visual, i18n, or schema changes.

Deliberately out of scope

The CLI/runtime IPC path (activateTerminalInitiatedWorktree, useIpcEvents.ts:291) also navigates across worktrees, but it is gated on presentation === 'focused' — explicit user intent, e.g. orca terminal create --focus. Suppressing it would break intentional CLI navigation, and it was not reproduced here (the CLI targets the installed app, not a dev instance). Left alone on purpose.

Adversarial review

Rounds: 2. Each round opened with a fresh reviewer tasked to break the fix, working from a distinct vector list; every vector below was then verified against the real code and, where possible, against the running app before being called disproven.

Round 1 vectors and outcomes

  • Same-worktree regression — disproven live. Launching into the worktree you are viewing still activates the new tab, renders the terminal, and swaps the editor out.
  • Ordering (tab created before the worktree is activated) — disproven. worktree-activation.ts:321 calls setActiveWorktree before its createTab calls at :547/:618/:697. Floating-workspace terminals pass activate: false and activate through the already-guarded activateTab.
  • Folder-workspace / workspace-key identity mismatch in the new guard — disproven. Folder workspaces key activeTabTypeByWorktree and activeWorktreeId by the same workspaceKey (worktrees.ts:4843, :4912).
  • Unbounded map growth — disproven. activeTabTypeByWorktree is pruned on worktree purge (worktrees.ts:1806, :2242) plus four other sites.
  • No-op early-return correctness — this one found something. The guard must not bail when the target IS viewed, its remembered type already matches, but the global activeTabType has drifted. Traced and confirmed correct, then locked in with a dedicated regression test and mutation-proved: collapsing the condition to just map[target] === type fails it.

Round 2 vectors and outcomes — all clear.

  • Remaining callers of the three changed launchers — audited all of them. The one genuinely cross-worktree caller is fix-checks-agent-launch.ts, and it calls activateAndRevealWorktree(target) at :190 immediately before launching at :199; setActiveWorktree runs synchronously (worktree-activation.ts:321), so the target is already the viewed worktree by the time the launch lands. runQuickCommandInNewTab's two callers (TabBarQuickCommandsButton.tsx:128, use-terminal-pane-context-menu.ts:440) pass the worktree of the surface they render in, and groups are keyed groupsByWorktree[worktreeId] so a split never mixes worktrees. launchAgentInWebHostTab is only called from launchAgentInNewTab with the same worktreeId. No caller depended on the old global side effect for a different worktree.
  • Other createTab option paths — the activate: true callers are either the viewed worktree (recently-closed-tabs.ts:138, terminal-tab-create.ts:36) or deliberately background (launch-agent-background-session.ts:104 passes activate: false). terminals.ts:1159 and terminal-pane-tab-detach.ts:285 both call setActiveTab straight after, and setActiveTab has carried the identical guard since before this change (terminals.ts:1529) — so those paths were already guarded and the new createTab guard changes nothing for them. createTab still writes the per-worktree fields (activeTabIdByWorktree at :1094, the group's activeTabId at :1078), and setActiveWorktree restores the global from them on switch-in (worktrees.ts:4628-4638), so nothing is lost.
  • Stale global activeTabId readers — the guard makes the global more consistent with activeWorktreeId, not less; terminal-tab-actions.ts:207 already pairs the two, and activateTab has carried this same guard for some time.

One further behavioural delta, checked and dismissed: when activeWorktreeId is null, the old setter still wrote the global activeTabType and the new one cannot (a string id never equals null). No pane is rendered in that state.

Result: one issue found and fixed (the no-op edge, commit 2); final round returned clean across all vectors, with store/slices re-run whole at 127 files / 1987 tests passing.

Performance

Reviewed with the perf skill: no concerns — store fan-out strictly decreases.

The old setActiveTabType (editor.ts:1598-1607) had no bail-out, so every launch allocated a new root state, notified every listener, and cloned activeTabTypeByWorktree. The new action writes at most what the old one wrote and often nothing, so there is no case where a former no-op became a write.

  • Terminal.tsx:292 subscribes to activeTabType. Background launches no longer flip it, so the always-mounted terminal component stops re-rendering and stops tearing down the editor pane — a real render-work reduction on top of the correctness fix.
  • activeTabTypeByWorktree feeds both session persistence (workspace-session.ts:73) and mobile runtime sync (sync-runtime-graph.ts:293,347), both compared by reference. The old code therefore scheduled a debounced session patch and defeated the runtime-sync skip on every launch; now only on a genuine change, and when it does write it coalesces with the tabsByWorktree write createTab already made in the same tick.
  • The no-op guard is genuine: zustand bails on Object.is(nextState, state) and no middleware wraps setState. It fires in the common case, since activation (worktrees.ts:4695-4698) and hydration already stamp the type.
  • The map is pruned at five sites (worktrees.ts:2242, :3435-3598, repos.ts:3042, main/persistence.ts:2420, editor.ts:4648) — no unbounded growth.
  • The createTab guard is one string comparison inside an updater that already builds ~10 spread objects, and activeTabId (also a persisted + synced field) now changes less often.

One pre-existing, out-of-scope item noted for the backlog: WorktreeJumpPalette.tsx:383 subscribes to the raw activeTabTypeByWorktree identity and stays mounted for the app lifetime after the first Cmd+J. It predates this commit and is triggered by ~30 other write sites; this change lowers its trigger rate.

Brennan Benson added 2 commits July 27, 2026 06:27
…ed pane

A launch targeting worktree A wrote global viewed-surface state keyed to the
launch target, so launching an agent in A while reading a file in B tore the
editor out of B.

- setActiveTabTypeForWorktree stamps the target worktree and only touches the
  visible pane when that worktree is the one being viewed
- createTab only repoints the global activeTabId for the viewed worktree
  (mirrors the guard already used in activateTab)

Covers the local, paired-web-host, and quick-command launch paths.
@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 644fe1e9-e498-47a7-8d26-6b204308248d

📥 Commits

Reviewing files that changed from the base of the PR and between 94009f6 and 62b844d.

📒 Files selected for processing (10)
  • src/renderer/src/lib/launch-agent-in-new-tab-cwd.test.ts
  • src/renderer/src/lib/launch-agent-in-new-tab-web-runtime.test.ts
  • src/renderer/src/lib/launch-agent-in-new-tab.test.ts
  • src/renderer/src/lib/launch-agent-in-new-tab.ts
  • src/renderer/src/lib/launch-agent-web-host-tab.ts
  • src/renderer/src/lib/run-quick-command-in-new-tab.test.ts
  • src/renderer/src/lib/run-quick-command-in-new-tab.ts
  • src/renderer/src/store/slices/background-worktree-launch-focus.test.ts
  • src/renderer/src/store/slices/editor.ts
  • src/renderer/src/store/slices/terminals.ts

📝 Walkthrough

Walkthrough

The editor store now exposes setActiveTabTypeForWorktree, updating remembered tab types per worktree and updating visible state only for the viewed worktree. Terminal creation also scopes active tab selection to the viewed worktree. Agent launches and quick commands use the new setter with their target worktree ID. Related tests update mocks and verify background-worktree behavior, no-op state preservation, and failure handling.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed but omits required template sections like Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes. Add the missing template headings and fill in screenshots/no visual change, testing checkboxes, AI review report, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: preventing background worktree launches from stealing the viewed pane.
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.
✨ Finishing Touches
📝 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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing as superseded. Both changes this PR proposed are already on main via #22603 ("keep agent launches from moving the main window's tab"):

  • launchAgentInNewTab now scopes its "show the terminal" step to the launch's own worktree (setActiveTabType('terminal', worktreeId)), so a launch into another worktree no longer flips the pane you are looking at.
  • Terminal createTab only moves the global active tab when the new tab is in the worktree you are viewing (shouldActivate && s.activeWorktreeId === worktreeId).

The rest of #9944 is covered by #23974 (a finished workspace create no longer pulls you away) and #24244 (orca file open / file diff / file open-changed).

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.

Bug: creating/launching an agent in worktree A steals focus from currently viewed worktree B

1 participant