Repository navigation
fix(worktrees): stop background agent launches from stealing the viewed pane - #10924
brennanb2025 wants to merge 2 commits into
Conversation
…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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (10)
📝 WalkthroughWalkthroughThe editor store now exposes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
|
Closing as superseded. Both changes this PR proposed are already on
The rest of #9944 is covered by #23974 (a finished workspace create no longer pulls you away) and #24244 ( |
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:
launchAgentInNewTabcalledstore.setActiveTabType('terminal'), and that setter stampsactiveTabTypeByWorktree[activeWorktreeId]— the viewed worktree, not the launch target. So B got flipped to terminal and mis-stamped with A's intent.createTabrepointed the globalactiveTabIdat the new tab whenevershouldActivatewas 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-459callsfocusTerminalTabSurface(state.activeTabId)wheneveractiveTabTypeisterminalandactiveTabIdhas 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-561snapshots focus before a dispatch and manually restoresactiveView/activeWorktree/activeTab/activeTabTypeafterwards, 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
setActiveTabTypeForWorktree(worktreeId, type)(store/slices/editor.ts). It always stampsactiveTabTypeByWorktree[target], but only writes the globalactiveTabTypewhen the target is the viewed worktree. No-ops preserve the root state reference so session persistence and runtime sync don't fan out.setActiveTabType:launch-agent-in-new-tab.ts,launch-agent-web-host-tab.ts(the paired / remote-host path), andrun-quick-command-in-new-tab.ts.createTabonly repoints the globalactiveTabIdwhenworktreeId === s.activeWorktreeId. This mirrors the guard already present inactivateTaba few hundred lines down (terminals.ts:1524): "only pin global activeTabId to active-worktree tabs." The per-worktreeactiveTabIdByWorktree[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.mdopen in the editor, then launching an agent into worktree A:activeTabType(viewing B)editor→terminaleditor→editordata-activefalse→truefalse→falseactiveTabTypeByWorktree[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:
activeTabTypeeditor→terminal, the new tab becomes the global active tab,activeTabIdByWorktreeis correct, the terminal renders and the editor swaps out. The guard suppresses only cross-worktree steals, not real activation.Tests
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).isViewedguard fails the new test; restoring it passes.5035 passed | 1 skippedacross 462 files (rendererlib/+store/slices/).typecheckclean.oxlintclean.Trade-offs
Real, but small and intentional:
activeWorktreeId(worktree-activation.ts:321) before creating its default tabs, floating-workspace terminals passactivate: falseand activate explicitly through the already-guardedactivateTab, and folder workspaces keyactiveTabTypeByWorktree/activeWorktreeIdby the sameworkspaceKey— so no caller regressed. Verified live via the negative control above.Deliberately out of scope
The CLI/runtime IPC path (
activateTerminalInitiatedWorktree,useIpcEvents.ts:291) also navigates across worktrees, but it is gated onpresentation === '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
worktree-activation.ts:321callssetActiveWorktreebefore itscreateTabcalls at:547/:618/:697. Floating-workspace terminals passactivate: falseand activate through the already-guardedactivateTab.activeTabTypeByWorktreeandactiveWorktreeIdby the sameworkspaceKey(worktrees.ts:4843,:4912).activeTabTypeByWorktreeis pruned on worktree purge (worktrees.ts:1806,:2242) plus four other sites.activeTabTypehas drifted. Traced and confirmed correct, then locked in with a dedicated regression test and mutation-proved: collapsing the condition to justmap[target] === typefails it.Round 2 vectors and outcomes — all clear.
fix-checks-agent-launch.ts, and it callsactivateAndRevealWorktree(target)at:190immediately before launching at:199;setActiveWorktreeruns 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 keyedgroupsByWorktree[worktreeId]so a split never mixes worktrees.launchAgentInWebHostTabis only called fromlaunchAgentInNewTabwith the sameworktreeId. No caller depended on the old global side effect for a different worktree.createTaboption paths — theactivate: truecallers are either the viewed worktree (recently-closed-tabs.ts:138,terminal-tab-create.ts:36) or deliberately background (launch-agent-background-session.ts:104passesactivate: false).terminals.ts:1159andterminal-pane-tab-detach.ts:285both callsetActiveTabstraight after, andsetActiveTabhas carried the identical guard since before this change (terminals.ts:1529) — so those paths were already guarded and the newcreateTabguard changes nothing for them.createTabstill writes the per-worktree fields (activeTabIdByWorktreeat:1094, the group'sactiveTabIdat:1078), andsetActiveWorktreerestores the global from them on switch-in (worktrees.ts:4628-4638), so nothing is lost.activeTabIdreaders — the guard makes the global more consistent withactiveWorktreeId, not less;terminal-tab-actions.ts:207already pairs the two, andactivateTabhas carried this same guard for some time.One further behavioural delta, checked and dismissed: when
activeWorktreeIdisnull, the old setter still wrote the globalactiveTabTypeand the new one cannot (a string id never equalsnull). 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/slicesre-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 clonedactiveTabTypeByWorktree. 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:292subscribes toactiveTabType. 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.activeTabTypeByWorktreefeeds 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 thetabsByWorktreewritecreateTabalready made in the same tick.Object.is(nextState, state)and no middleware wrapssetState. It fires in the common case, since activation (worktrees.ts:4695-4698) and hydration already stamp the type.worktrees.ts:2242,:3435-3598,repos.ts:3042,main/persistence.ts:2420,editor.ts:4648) — no unbounded growth.createTabguard is one string comparison inside an updater that already builds ~10 spread objects, andactiveTabId(also a persisted + synced field) now changes less often.One pre-existing, out-of-scope item noted for the backlog:
WorktreeJumpPalette.tsx:383subscribes to the rawactiveTabTypeByWorktreeidentity 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.