From 7fb5363296a32146557d6ba60c4c2bc6ab23cd77 Mon Sep 17 00:00:00 2001 From: Maciej Kobuszewski Date: Thu, 7 May 2026 03:48:39 -0500 Subject: [PATCH] feat(cli): tab switch --focus surfaces the browser pane (#1498) Co-authored-by: Orca Co-authored-by: Maciej Kobuszewski Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com> Co-authored-by: Jinwoo-H --- src/cli/browser.test.ts | 29 +++ src/cli/handlers/browser-tab.ts | 6 + src/cli/specs/browser-basic.ts | 5 +- src/main/runtime/orca-runtime.test.ts | 17 ++ src/main/runtime/orca-runtime.ts | 46 ++++- .../runtime/rpc/methods/browser-schemas.ts | 9 +- src/preload/api-types.ts | 3 + src/preload/index.ts | 11 ++ src/renderer/src/hooks/useIpcEvents.test.ts | 21 ++- src/renderer/src/hooks/useIpcEvents.ts | 25 +++ src/renderer/src/store/slices/browser.test.ts | 174 ++++++++++++++++++ src/renderer/src/store/slices/browser.ts | 85 +++++++++ 12 files changed, 416 insertions(+), 15 deletions(-) diff --git a/src/cli/browser.test.ts b/src/cli/browser.test.ts index c84a0f7e7..3a7b4790b 100644 --- a/src/cli/browser.test.ts +++ b/src/cli/browser.test.ts @@ -128,6 +128,35 @@ describe('orca cli browser page targeting', () => { }) }) + it('passes focus: true through to browser.tabSwitch when --focus is set', async () => { + queueFixtures(callMock, okFixture('req_switch', { switched: 1, browserPageId: 'page-1' })) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + ['tab', 'switch', '--page', 'page-1', '--focus', '--json'], + '/tmp/repo/feature/src' + ) + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('browser.tabSwitch', { + index: undefined, + page: 'page-1', + focus: true + }) + }) + + it('omits focus from the payload when --focus is absent', async () => { + queueFixtures(callMock, okFixture('req_switch', { switched: 1, browserPageId: 'page-1' })) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['tab', 'switch', '--page', 'page-1', '--json'], '/tmp/repo/feature/src') + + expect(callMock).toHaveBeenCalledTimes(1) + const call = callMock.mock.calls[0] + expect(call[0]).toBe('browser.tabSwitch') + expect(call[1]).not.toHaveProperty('focus') + }) + it('passes explicit profile ids to tab create', async () => { queueFixtures(callMock, okFixture('req_create', { browserPageId: 'page-3' })) vi.spyOn(console, 'log').mockImplementation(() => {}) diff --git a/src/cli/handlers/browser-tab.ts b/src/cli/handlers/browser-tab.ts index 0fe3e151b..3e975bb36 100644 --- a/src/cli/handlers/browser-tab.ts +++ b/src/cli/handlers/browser-tab.ts @@ -43,9 +43,15 @@ export const BROWSER_TAB_HANDLERS: Record = { // targeted tab switches should match the rest of the --page command model: // global by default, with --worktree only acting as explicit validation. const target = await getBrowserCommandTarget(flags, cwd, client) + // Why: --focus is an opt-in side effect. The renderer's handler is + // worktree-scoped: it surfaces the browser pane only when the user is + // already on the targeted worktree, otherwise it pre-stages silently. + // Spread conditionally so the RPC payload stays shape-identical to the + // pre-flag form when --focus is absent. const result = await client.call('browser.tabSwitch', { index, page, + ...(flags.has('focus') ? { focus: true } : {}), ...target }) printResult(result, json, (v) => `Switched to tab ${v.switched} (${v.browserPageId})`) diff --git a/src/cli/specs/browser-basic.ts b/src/cli/specs/browser-basic.ts index 42af901ab..95b23e471 100644 --- a/src/cli/specs/browser-basic.ts +++ b/src/cli/specs/browser-basic.ts @@ -172,8 +172,9 @@ export const BROWSER_BASIC_COMMAND_SPECS: CommandSpec[] = [ { path: ['tab', 'switch'], summary: 'Switch the active browser tab', - usage: 'orca tab switch (--index | --page ) [--worktree ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'index', 'worktree'] + usage: + 'orca tab switch (--index | --page ) [--worktree ] [--focus] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'index', 'worktree', 'focus'] }, { path: ['tab', 'create'], diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 2133215a2..b947202e1 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -1393,6 +1393,23 @@ describe('OrcaRuntimeService', () => { expect(captureStartMock).toHaveBeenCalledWith(undefined, 'page-2') }) + it('accepts focus on tab switch without altering bridge args (focus is main-side concern)', async () => { + const runtime = createRuntime() + const tabSwitchMock = vi.fn().mockResolvedValue({ + switched: 0, + browserPageId: 'page-1' + }) + + runtime.setAgentBrowserBridge({ tabSwitch: tabSwitchMock } as never) + + await expect( + runtime.browserTabSwitch({ page: 'page-1', focus: true }) + ).resolves.toEqual({ switched: 0, browserPageId: 'page-1' }) + // Bridge is unchanged — focus is delivered to the renderer via IPC + // (notifyRendererBrowserPaneFocus), not threaded through bridge state. + expect(tabSwitchMock).toHaveBeenCalledWith(undefined, undefined, 'page-1') + }) + it('does not silently drop invalid explicit worktree selectors for page-targeted commands', async () => { vi.mocked(listWorktrees).mockResolvedValue(MOCK_GIT_WORKTREES) const runtime = createRuntime() diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 2500573d3..88ad5277e 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -4830,6 +4830,33 @@ export class OrcaRuntimeService { } } + // Why: `tabSwitch` only flips the bridge's `activeWebContentsId` — it + // does not surface the browser pane in the renderer. Without --focus, the + // switch is invisible to the user. With --focus, we send a dedicated IPC + // so the renderer can update its per-worktree active-tab state. + // + // Why this IPC carries `worktreeId` instead of letting the renderer + // dispatch `setActiveWorktree`: multiple agents drive browsers in parallel + // worktrees. A global focus call from agent X would steal the user's + // screen from agent Y's worktree. The renderer-side handler + // (focusBrowserTabInWorktree) updates per-worktree state unconditionally + // and only flips globals when the user is already on the targeted + // worktree. Cross-worktree --focus calls pre-stage silently. + private notifyRendererBrowserPaneFocus( + worktreeId: string | undefined, + browserPageId: string + ): void { + try { + const win = this.getAuthoritativeWindow() + win.webContents.send('browser:pane-focus', { + worktreeId: worktreeId ?? null, + browserPageId + }) + } catch { + // Window may not exist during shutdown + } + } + async browserSnapshot(params: BrowserCommandTargetParams): Promise { const target = await this.resolveBrowserCommandTarget(params) return this.requireAgentBrowserBridge().snapshot(target.worktreeId, target.browserPageId) @@ -4988,14 +5015,23 @@ export class OrcaRuntimeService { async browserTabSwitch( params: { index?: number + focus?: boolean } & BrowserCommandTargetParams ): Promise { const target = await this.resolveBrowserCommandTarget(params) - return this.requireAgentBrowserBridge().tabSwitch( - params.index, - target.worktreeId, - target.browserPageId - ) + const bridge = this.requireAgentBrowserBridge() + const result = await bridge.tabSwitch(params.index, target.worktreeId, target.browserPageId) + if (params.focus) { + // Why: prefer the explicit --worktree the caller passed; fall back to + // the bridge's owning-worktree map for the just-switched tab. The + // owning worktree is what the renderer needs to scope the focus to. + // The renderer NEVER yanks the user across worktrees on this signal + // (see focusBrowserTabInWorktree). + const worktreeId = + target.worktreeId ?? browserManager.getWorktreeIdForTab(result.browserPageId) ?? undefined + this.notifyRendererBrowserPaneFocus(worktreeId, result.browserPageId) + } + return result } async browserHover( diff --git a/src/main/runtime/rpc/methods/browser-schemas.ts b/src/main/runtime/rpc/methods/browser-schemas.ts index 96e864bb5..e3ff203a4 100644 --- a/src/main/runtime/rpc/methods/browser-schemas.ts +++ b/src/main/runtime/rpc/methods/browser-schemas.ts @@ -76,12 +76,19 @@ export const TabList = z.object({ // Why: --index xor --page must be present. The refine guards that invariant // so the dispatcher surfaces a single legible error instead of either shape // leaking into the runtime. +// +// `focus` is opt-in: when true, the runtime sends `browser:pane-focus` to +// the renderer after the switch lands. The renderer surfaces the browser +// pane only if the user is already on the targeted worktree; otherwise it +// pre-stages per-worktree state silently. This avoids cross-worktree screen +// theft when multiple agents drive browsers in parallel worktrees. export const TabSwitch = BrowserTarget.extend({ index: z .unknown() .transform((v) => (typeof v === 'number' ? v : undefined)) .pipe(z.number().optional()) - .optional() + .optional(), + focus: z.boolean().optional() }).refine( (val) => { if (val.page !== undefined) { diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 43019dc05..c55c2f7b5 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -185,6 +185,9 @@ export type BrowserApi = { callback: (event: { browserPageId: string; url: string; title: string }) => void ) => () => void onActivateView: (callback: (data: { worktreeId: string }) => void) => () => void + onPaneFocus: ( + callback: (data: { worktreeId: string | null; browserPageId: string }) => void + ) => () => void onOpenLinkInOrcaTab: ( callback: (event: { browserPageId: string; url: string }) => void ) => () => void diff --git a/src/preload/index.ts b/src/preload/index.ts index 1e0eed36c..5f1ff17a7 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1192,6 +1192,17 @@ const api = { return () => ipcRenderer.removeListener('browser:activateView', listener) }, + onPaneFocus: ( + callback: (data: { worktreeId: string | null; browserPageId: string }) => void + ): (() => void) => { + const listener = ( + _event: Electron.IpcRendererEvent, + data: { worktreeId: string | null; browserPageId: string } + ) => callback(data) + ipcRenderer.on('browser:pane-focus', listener) + return () => ipcRenderer.removeListener('browser:pane-focus', listener) + }, + onOpenLinkInOrcaTab: ( callback: (event: { browserPageId: string; url: string }) => void ): (() => void) => { diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index 043a52098..eda71044e 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -197,7 +197,8 @@ describe('useIpcEvents updater integration', () => { onGuestLoadFailed: () => () => {}, onOpenLinkInOrcaTab: () => () => {}, onNavigationUpdate: () => () => {}, - onActivateView: () => () => {} + onActivateView: () => () => {}, + onPaneFocus: () => () => {} }, rateLimits: { get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }), @@ -393,7 +394,8 @@ describe('useIpcEvents updater integration', () => { onGuestLoadFailed: () => () => {}, onOpenLinkInOrcaTab: () => () => {}, onNavigationUpdate: () => () => {}, - onActivateView: () => () => {} + onActivateView: () => () => {}, + onPaneFocus: () => () => {} }, rateLimits: { get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }), @@ -591,7 +593,8 @@ describe('useIpcEvents updater integration', () => { onGuestLoadFailed: () => () => {}, onOpenLinkInOrcaTab: () => () => {}, onNavigationUpdate: () => () => {}, - onActivateView: () => () => {} + onActivateView: () => () => {}, + onPaneFocus: () => () => {} }, rateLimits: { get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }), @@ -800,7 +803,8 @@ describe('useIpcEvents browser tab close routing', () => { onGuestLoadFailed: () => () => {}, onOpenLinkInOrcaTab: () => () => {}, onNavigationUpdate: () => () => {}, - onActivateView: () => () => {} + onActivateView: () => () => {}, + onPaneFocus: () => () => {} }, rateLimits: { get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }), @@ -994,7 +998,8 @@ describe('useIpcEvents browser tab close routing', () => { onGuestLoadFailed: () => () => {}, onOpenLinkInOrcaTab: () => () => {}, onNavigationUpdate: () => () => {}, - onActivateView: () => () => {} + onActivateView: () => () => {}, + onPaneFocus: () => () => {} }, rateLimits: { get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }), @@ -1183,7 +1188,8 @@ describe('useIpcEvents browser tab close routing', () => { onGuestLoadFailed: () => () => {}, onOpenLinkInOrcaTab: () => () => {}, onNavigationUpdate: () => () => {}, - onActivateView: () => () => {} + onActivateView: () => () => {}, + onPaneFocus: () => () => {} }, rateLimits: { get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }), @@ -1381,7 +1387,8 @@ describe('useIpcEvents CLI-created worktree activation', () => { onGuestLoadFailed: () => () => {}, onOpenLinkInOrcaTab: () => () => {}, onNavigationUpdate: () => () => {}, - onActivateView: () => () => {} + onActivateView: () => () => {}, + onPaneFocus: () => () => {} }, rateLimits: { get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }), diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 40657a7ed..c9578d82c 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -374,6 +374,31 @@ export function useIpcEvents(): void { }) ) + // Why: `orca tab switch --focus` lands here after the bridge's state-only + // `tabSwitch`. We deliberately DO NOT call `setActiveWorktree` — multiple + // agents drive browsers in parallel worktrees, so a global focus call from + // one agent's tab switch would steal the user's view from whichever + // worktree they're actually reading. Instead `focusBrowserTabInWorktree` + // updates the targeted worktree's per-worktree state in place; globals + // (activeBrowserTabId, activeTabType) only flip when the user is already + // on the targeted worktree. Cross-worktree --focus calls are silent + // pre-staging for whenever the user next visits that worktree. + unsubs.push( + window.api.browser.onPaneFocus(({ worktreeId, browserPageId }) => { + const store = useAppStore.getState() + // Why: main sends `worktreeId: null` if the tab closed between the + // bridge resolving tabSwitch and getWorktreeIdForTab running. Falling + // back to activeWorktreeId means a stale page id in another worktree + // is silently ignored by focusBrowserTabInWorktree (page not found + // in its tabsForWorktree.find), which is the intended no-op. + const targetWt = worktreeId ?? store.activeWorktreeId + if (!targetWt) { + return + } + store.focusBrowserTabInWorktree(targetWt, browserPageId) + }) + ) + unsubs.push( window.api.browser.onOpenLinkInOrcaTab(({ browserPageId, url }) => { const store = useAppStore.getState() diff --git a/src/renderer/src/store/slices/browser.test.ts b/src/renderer/src/store/slices/browser.test.ts index 73fc6561e..f29297d19 100644 --- a/src/renderer/src/store/slices/browser.test.ts +++ b/src/renderer/src/store/slices/browser.test.ts @@ -691,3 +691,177 @@ describe('shutdownWorktreeBrowsers', () => { expect(store.getState().activeTabType).toBe('terminal') }) }) + +// Why: focusBrowserTabInWorktree is the renderer side of `tab switch --focus`. +// The defining invariant is no cross-worktree screen theft: when multiple +// agents drive browsers in parallel worktrees, an agent focusing a tab in +// worktree X must never yank the user's view away from worktree Y. +describe('focusBrowserTabInWorktree', () => { + function seedTwoWorktrees( + store: ReturnType, + activeWt: string, + otherWt: string + ): void { + seedStore(store, { + activeRepoId: 'repo1', + activeWorktreeId: activeWt, + activeTabType: 'terminal', + worktreesByRepo: { + repo1: [ + makeWorktree({ id: activeWt, repoId: 'repo1', path: '/tmp/wt-active' }), + makeWorktree({ id: otherWt, repoId: 'repo1', path: '/tmp/wt-other' }) + ] + }, + groupsByWorktree: { + [activeWt]: [ + makeTabGroup({ id: 'g-active', worktreeId: activeWt, activeTabId: null, tabOrder: [] }) + ], + [otherWt]: [ + makeTabGroup({ id: 'g-other', worktreeId: otherWt, activeTabId: null, tabOrder: [] }) + ] + }, + activeGroupIdByWorktree: { [activeWt]: 'g-active', [otherWt]: 'g-other' }, + activeTabTypeByWorktree: { [activeWt]: 'terminal', [otherWt]: 'terminal' }, + browserTabsByWorktree: {}, + unifiedTabsByWorktree: {} + }) + } + + it('does not yank activeWorktreeId when focusing a tab in a non-active worktree', () => { + const store = createTestStore() + const activeWt = 'repo1::/tmp/wt-active' + const otherWt = 'repo1::/tmp/wt-other' + seedTwoWorktrees(store, activeWt, otherWt) + + const ws = store.getState().createBrowserTab(otherWt, 'https://example.com/a', { title: 'A' }) + const pageId = (store.getState().browserPagesByWorkspace[ws.id] ?? [])[0]?.id + expect(pageId).toBeDefined() + // createBrowserTab on a non-active worktree leaves activeWorktreeId alone; + // re-pin it here in case any future change to that path regresses it. + store.setState({ activeWorktreeId: activeWt, activeTabType: 'terminal' }) + + store.getState().focusBrowserTabInWorktree(otherWt, pageId!, { surfacePane: true }) + + expect(store.getState().activeWorktreeId).toBe(activeWt) + expect(store.getState().activeTabType).toBe('terminal') + }) + + it('updates per-worktree active tab and tab type for the targeted worktree even when not active', () => { + const store = createTestStore() + const activeWt = 'repo1::/tmp/wt-active' + const otherWt = 'repo1::/tmp/wt-other' + seedTwoWorktrees(store, activeWt, otherWt) + + const ws = store.getState().createBrowserTab(otherWt, 'https://example.com/a', { title: 'A' }) + const pageId = (store.getState().browserPagesByWorkspace[ws.id] ?? [])[0]?.id + store.setState({ activeWorktreeId: activeWt, activeTabType: 'terminal' }) + + store.getState().focusBrowserTabInWorktree(otherWt, pageId!, { surfacePane: true }) + + // Per-worktree slots: pre-staged for whenever the user next visits otherWt. + expect(store.getState().activeBrowserTabIdByWorktree[otherWt]).toBe(ws.id) + expect(store.getState().activeTabTypeByWorktree[otherWt]).toBe('browser') + }) + + it('flips global activeBrowserTabId and activeTabType when targeting the active worktree with surfacePane', () => { + const store = createTestStore() + const activeWt = 'repo1::/tmp/wt-active' + const otherWt = 'repo1::/tmp/wt-other' + seedTwoWorktrees(store, activeWt, otherWt) + + const ws = store.getState().createBrowserTab(activeWt, 'https://example.com/a', { title: 'A' }) + const pageId = (store.getState().browserPagesByWorkspace[ws.id] ?? [])[0]?.id + // Reset to terminal so we can prove --focus surfaces the pane. + store.setState((s) => ({ + activeTabType: 'terminal', + activeTabTypeByWorktree: { ...s.activeTabTypeByWorktree, [activeWt]: 'terminal' } + })) + + store.getState().focusBrowserTabInWorktree(activeWt, pageId!, { surfacePane: true }) + + expect(store.getState().activeBrowserTabId).toBe(ws.id) + expect(store.getState().activeTabType).toBe('browser') + }) + + it('without surfacePane, leaves activeTabType alone even on the active worktree', () => { + const store = createTestStore() + const activeWt = 'repo1::/tmp/wt-active' + const otherWt = 'repo1::/tmp/wt-other' + seedTwoWorktrees(store, activeWt, otherWt) + + const ws = store.getState().createBrowserTab(activeWt, 'https://example.com/a', { title: 'A' }) + const pageId = (store.getState().browserPagesByWorkspace[ws.id] ?? [])[0]?.id + // Reset both globals and per-worktree slot so we can prove surfacePane=false + // does NOT flip the user back into the browser pane (createBrowserTab + // itself flips both because it activates the new tab). + store.setState((s) => ({ + activeTabType: 'terminal', + activeTabTypeByWorktree: { ...s.activeTabTypeByWorktree, [activeWt]: 'terminal' } + })) + + store.getState().focusBrowserTabInWorktree(activeWt, pageId!, { surfacePane: false }) + + // Per-worktree active tab still pre-staged, but the user is still on terminal. + expect(store.getState().activeBrowserTabIdByWorktree[activeWt]).toBe(ws.id) + expect(store.getState().activeTabType).toBe('terminal') + expect(store.getState().activeTabTypeByWorktree[activeWt]).toBe('terminal') + }) + + it('finds the owning workspace via pageIds for multi-page workspaces', () => { + const store = createTestStore() + const activeWt = 'repo1::/tmp/wt-active' + const otherWt = 'repo1::/tmp/wt-other' + seedTwoWorktrees(store, activeWt, otherWt) + + const ws = store.getState().createBrowserTab(otherWt, 'https://example.com/a', { title: 'A' }) + const pageB = store + .getState() + .createBrowserPage(ws.id, 'https://example.com/b', { title: 'B', activate: false }) + expect(pageB).not.toBeNull() + + store.getState().focusBrowserTabInWorktree(otherWt, pageB!.id, { surfacePane: true }) + + // The workspace's activePageId must follow the focused page id, not its + // first page. Renderer otherwise shows the wrong tab on next visit. + const updatedWs = store.getState().browserTabsByWorktree[otherWt]?.find((t) => t.id === ws.id) + expect(updatedWs?.activePageId).toBe(pageB!.id) + expect(store.getState().activeBrowserTabIdByWorktree[otherWt]).toBe(ws.id) + }) + + it('is a no-op when the page id is not present in the targeted worktree', () => { + const store = createTestStore() + const activeWt = 'repo1::/tmp/wt-active' + const otherWt = 'repo1::/tmp/wt-other' + seedTwoWorktrees(store, activeWt, otherWt) + + const before = store.getState() + before.focusBrowserTabInWorktree(otherWt, 'page-that-does-not-exist', { surfacePane: true }) + const after = store.getState() + + // Nothing globally or per-worktree should have moved. Best-effort: the + // page may have closed between the bridge switching and the IPC arriving. + expect(after.activeWorktreeId).toBe(before.activeWorktreeId) + expect(after.activeTabType).toBe(before.activeTabType) + expect(after.activeBrowserTabIdByWorktree[otherWt]).toBeUndefined() + }) + + it('surfaces the pane by default when no options are passed (active worktree)', () => { + const store = createTestStore() + const activeWt = 'repo1::/tmp/wt-active' + const otherWt = 'repo1::/tmp/wt-other' + seedTwoWorktrees(store, activeWt, otherWt) + + const ws = store.getState().createBrowserTab(activeWt, 'https://example.com/a', { title: 'A' }) + const pageId = (store.getState().browserPagesByWorkspace[ws.id] ?? [])[0]?.id + store.setState((s) => ({ + activeTabType: 'terminal', + activeTabTypeByWorktree: { ...s.activeTabTypeByWorktree, [activeWt]: 'terminal' } + })) + + store.getState().focusBrowserTabInWorktree(activeWt, pageId!) + + expect(store.getState().activeBrowserTabId).toBe(ws.id) + expect(store.getState().activeTabType).toBe('browser') + expect(store.getState().activeTabTypeByWorktree[activeWt]).toBe('browser') + }) +}) diff --git a/src/renderer/src/store/slices/browser.ts b/src/renderer/src/store/slices/browser.ts index 50cf960eb..92792ab24 100644 --- a/src/renderer/src/store/slices/browser.ts +++ b/src/renderer/src/store/slices/browser.ts @@ -78,6 +78,19 @@ export type BrowserSlice = { closeBrowserPage: (pageId: string) => void reopenClosedBrowserPage: (workspaceId: string) => BrowserPage | null setActiveBrowserPage: (workspaceId: string, pageId: string) => void + // Why: scoped sibling of setActiveBrowserTab+setActiveBrowserPage that + // never yanks the user across worktrees. Multiple agents can drive + // browsers in parallel worktrees; a global focus call from agent X would + // steal the screen from the user reading agent Y. Updates per-worktree + // active tab/page unconditionally; updates the GLOBAL active tab and (if + // surfacePane) global activeTabType only when worktreeId === active + // worktree. Cross-worktree calls pre-stage the targeted worktree's view + // for whenever the user next switches to it. + focusBrowserTabInWorktree: ( + worktreeId: string, + browserPageId: string, + options?: { surfacePane?: boolean } + ) => void consumeAddressBarFocusRequest: (pageId: string) => boolean updateBrowserTabPageState: (pageId: string, updates: BrowserTabPageState) => void updateBrowserPageState: (pageId: string, updates: BrowserTabPageState) => void @@ -882,6 +895,78 @@ export const createBrowserSlice: StateCreator = } }, + focusBrowserTabInWorktree: (worktreeId, browserPageId, options) => { + // Why: bridge identifies the target by browserPageId (CDP page id stored + // on BrowserPage.id), but the renderer's tab strip activates a workspace + // (BrowserWorkspace.id, a local UUID). They diverge whenever a workspace + // owns more than one page. Walk pageIds in the targeted worktree's tab + // list to find the owning workspace. + const tabsForWorktree = get().browserTabsByWorktree[worktreeId] ?? [] + const workspace = tabsForWorktree.find((tab) => (tab.pageIds ?? []).includes(browserPageId)) + if (!workspace) { + // Best-effort: state for this worktree may not be hydrated yet, or the + // page closed between the bridge switching and this IPC arriving. + return + } + // Default to true: the only caller (`tab switch --focus` IPC listener) + // wants the pane surfaced when targeting the active worktree. `false` is + // an opt-out for hypothetical pure-pre-staging callers. + const surfacePane = options?.surfacePane ?? true + const pages = get().browserPagesByWorkspace[workspace.id] ?? [] + const nextWorkspace = mirrorWorkspaceFromActivePage( + { ...workspace, activePageId: browserPageId }, + pages + ) + // TODO: per-worktree writes below duplicate setActiveBrowserTab / + // setActiveBrowserPage. We can't reuse those because they touch globals + // unconditionally (the very behavior --focus is avoiding). If they ever + // grow side-effects (analytics, persistence) those will silently diverge + // here. Consider extracting a private per-worktree-only helper that + // both call paths share. + set((s) => { + const isActiveWorktree = s.activeWorktreeId === worktreeId + // Per-worktree slots: always update (safe pre-staging; only visible + // when user navigates to this worktree). + const nextTabsByWorktree = { + ...s.browserTabsByWorktree, + [worktreeId]: tabsForWorktree.map((tab) => (tab.id === workspace.id ? nextWorkspace : tab)) + } + const nextActiveTabIdByWorktree = { + ...s.activeBrowserTabIdByWorktree, + [worktreeId]: workspace.id + } + const nextActiveTabTypeByWorktree = surfacePane + ? { ...s.activeTabTypeByWorktree, [worktreeId]: 'browser' as const } + : s.activeTabTypeByWorktree + // Globals: only mutate when the targeted worktree is currently active. + // This is the line that keeps cross-worktree --focus calls silent. + return { + browserTabsByWorktree: nextTabsByWorktree, + activeBrowserTabIdByWorktree: nextActiveTabIdByWorktree, + activeTabTypeByWorktree: nextActiveTabTypeByWorktree, + activeBrowserTabId: isActiveWorktree ? workspace.id : s.activeBrowserTabId, + activeTabType: isActiveWorktree && surfacePane ? 'browser' : s.activeTabType + } + }) + + // Why: notify the CDP bridge which guest webContents is now active so + // subsequent agent commands target the correct page. Mirrors the + // notifyActiveTabChanged calls in setActiveBrowserTab/setActiveBrowserPage. + if (typeof window !== 'undefined' && window.api?.browser) { + window.api.browser.notifyActiveTabChanged({ browserPageId }).catch(() => {}) + } + + // Why: keep the unified-tab strip's active entry in sync within the + // targeted worktree. activateTab only mutates per-worktree slices, so + // it's safe to call cross-worktree without yanking the user. + const item = (get().unifiedTabsByWorktree[worktreeId] ?? []).find( + (entry) => entry.contentType === 'browser' && entry.entityId === workspace.id + ) + if (item) { + get().activateTab(item.id) + } + }, + consumeAddressBarFocusRequest: (pageId) => { const state = get() if (