From 0f13c5d7bb40fc4b17e364b92f0812ddc7fe2ff0 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 25 May 2026 23:01:15 -0700 Subject: [PATCH] Fix floating terminal tab switch shortcuts Route tab-switch shortcuts to the focused floating workspace instead of the background terminal. --- src/renderer/src/components/Terminal.tsx | 20 +- .../FloatingTerminalPanel.test.tsx | 60 ++++++ .../FloatingTerminalPanel.tsx | 34 ++- src/renderer/src/hooks/useIpcEvents.ts | 36 +++- ...loating-workspace-terminal-actions.test.ts | 78 ++++++- .../floating-workspace-terminal-actions.ts | 204 +++++++++++++++++- tests/e2e/terminal-shortcuts.spec.ts | 127 +++++++++++ 7 files changed, 545 insertions(+), 14 deletions(-) diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index 745f9de89..a4b431af4 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -73,7 +73,8 @@ import { } from '@/runtime/web-runtime-session' import { createFloatingWorkspaceTerminalTab, - isFloatingWorkspacePanelFocused + isFloatingWorkspacePanelFocused, + switchFloatingWorkspaceTab } from '@/lib/floating-workspace-terminal-actions' import { keybindingMatchesAction, @@ -1105,6 +1106,7 @@ function Terminal(): React.JSX.Element | null { : 'linux' const onKeyDown = (e: KeyboardEvent): void => { const context = getKeybindingContext(e.target) + const floatingWorkspaceFocused = isFloatingWorkspacePanelFocused() const matchShortcut = (actionId: KeybindingActionId): boolean => keybindingMatchesAction(actionId, e, shortcutPlatform, keybindings, { context, @@ -1127,7 +1129,7 @@ function Terminal(): React.JSX.Element | null { if (!e.repeat && matchShortcut('tab.newTerminal')) { e.preventDefault() notifyTerminalCapture('tab.newTerminal') - if (isFloatingWorkspacePanelFocused()) { + if (floatingWorkspaceFocused) { void createFloatingWorkspaceTerminalTab(useAppStore.getState()) return } @@ -1261,7 +1263,13 @@ function Terminal(): React.JSX.Element | null { ? 'tab.nextSameType' : 'tab.previousSameType' ) - if (switchAllTypesDirection !== null) { + if (floatingWorkspaceFocused) { + switchFloatingWorkspaceTab( + useAppStore.getState(), + switchAllTypesDirection ?? switchSameTypeDirection ?? 1, + switchAllTypesDirection !== null ? 'all-types' : 'same-type' + ) + } else if (switchAllTypesDirection !== null) { handleSwitchTabAcrossAllTypes(switchAllTypesDirection) } else { handleSwitchTab(switchSameTypeDirection ?? 1) @@ -1295,7 +1303,11 @@ function Terminal(): React.JSX.Element | null { e.preventDefault() e.stopPropagation() e.stopImmediatePropagation() - handleSwitchTerminalTab(terminalTabDirection) + if (floatingWorkspaceFocused) { + switchFloatingWorkspaceTab(useAppStore.getState(), terminalTabDirection, 'terminal') + } else { + handleSwitchTerminalTab(terminalTabDirection) + } } } window.addEventListener('keydown', onKeyDown, { capture: true }) diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.test.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.test.tsx index 02e3cbce9..313ab468e 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.test.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.test.tsx @@ -21,6 +21,7 @@ type FloatingPanelStoreState = { groupsByWorktree: Record unifiedTabsByWorktree: Record openFiles: OpenFile[] + activeGroupIdByWorktree: Record activeTabIdByWorktree: Record expandedPaneByTabId: Record createTab: ( @@ -349,6 +350,7 @@ function setFloatingTabs(tabs: TerminalTab[]): void { } ] } + state.activeGroupIdByWorktree = { [FLOATING_TERMINAL_WORKTREE_ID]: groupId } state.activeTabIdByWorktree = { [FLOATING_TERMINAL_WORKTREE_ID]: tabs[0]?.id ?? null } state.tabBarOrderByWorktree = { [FLOATING_TERMINAL_WORKTREE_ID]: tabs.map((tab) => tab.id) } } @@ -381,6 +383,7 @@ function setFloatingEditorTabs(files: OpenFile[]): void { } ] } + state.activeGroupIdByWorktree = { [FLOATING_TERMINAL_WORKTREE_ID]: groupId } } function resetStore(tabs: TerminalTab[] = []): void { @@ -391,6 +394,7 @@ function resetStore(tabs: TerminalTab[] = []): void { groupsByWorktree: {}, unifiedTabsByWorktree: {}, openFiles: [], + activeGroupIdByWorktree: {}, activeTabIdByWorktree: { [FLOATING_TERMINAL_WORKTREE_ID]: tabs[0]?.id ?? null }, expandedPaneByTabId: {}, activateTab: mocks.activateTab, @@ -662,6 +666,62 @@ describe('FloatingTerminalPanel close behavior', () => { expect(mocks.pickFloatingMarkdownDocument).toHaveBeenCalledWith() }) + it('routes focused floating tab switch shortcuts to the floating workspace', async () => { + setFloatingTabs([makeTab({ id: 'tab-1' }), makeTab({ id: 'tab-2' })]) + const element = await renderPanel(true) + const panel = findByProp(element, 'data-floating-terminal-panel') + const panelElement = { contains: vi.fn().mockReturnValue(true), focus: vi.fn() } + const activeElement = { closest: vi.fn().mockReturnValue(panelElement) } + const target = { + classList: { contains: vi.fn((token: string) => token === 'xterm-helper-textarea') }, + closest: vi.fn((selector: string) => + selector === '[data-floating-terminal-panel]' ? panelElement : null + ) + } + Object.setPrototypeOf(activeElement, HTMLElement.prototype) + Object.setPrototypeOf(target, HTMLElement.prototype) + ;(panel.props.ref as { current: unknown }).current = panelElement + vi.stubGlobal('document', { + activeElement, + addEventListener: vi.fn(), + removeEventListener: vi.fn() + }) + runEffects() + const keydownListener = vi + .mocked(window.addEventListener) + .mock.calls.find(([type]) => type === 'keydown')?.[1] as + | ((event: unknown) => void) + | undefined + if (!keydownListener) { + throw new Error('keydown listener not registered') + } + const preventDefault = vi.fn() + const stopPropagation = vi.fn() + const stopImmediatePropagation = vi.fn() + + keydownListener({ + altKey: false, + code: 'BracketRight', + ctrlKey: false, + defaultPrevented: false, + key: ']', + metaKey: true, + preventDefault, + repeat: false, + shiftKey: true, + stopImmediatePropagation, + stopPropagation, + target + }) + + expect(preventDefault).toHaveBeenCalledWith() + expect(stopPropagation).toHaveBeenCalledWith() + expect(stopImmediatePropagation).toHaveBeenCalledWith() + expect(mocks.activateTab).toHaveBeenCalledWith('tab-2') + expect(mocks.setActiveTab).toHaveBeenCalledWith('tab-2') + expect(mocks.focusTerminalTabSurface).toHaveBeenCalledWith('tab-2') + }) + it('keeps the empty floating workspace focused after Cmd+W closes the last tab', async () => { setFloatingTabs([makeTab({ id: 'tab-1' })]) const element = await renderPanel(true) diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx index 3896fb73b..49723d5d6 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx @@ -29,7 +29,8 @@ import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' import { isOrcaCliAvailableOnPath } from '@/lib/agent-skill-cli-prerequisite' import { isFloatingWorkspacePanelShortcut, - isFloatingWorkspaceTerminalInputTarget + isFloatingWorkspaceTerminalInputTarget, + switchFloatingWorkspaceTab } from '@/lib/floating-workspace-terminal-actions' import { extractIpcErrorMessage } from '@/lib/ipc-error' import { getShortcutPlatform } from '@/lib/shortcut-platform' @@ -839,6 +840,37 @@ export function FloatingTerminalPanel({ } else { onOpenChange(false) } + return + } + + const switchSameTypeDirection = matches('tab.nextSameType') + ? 1 + : matches('tab.previousSameType') + ? -1 + : null + const switchAllTypesDirection = matches('tab.nextAllTypes') + ? 1 + : matches('tab.previousAllTypes') + ? -1 + : null + if (switchSameTypeDirection !== null || switchAllTypesDirection !== null) { + consume() + switchFloatingWorkspaceTab( + useAppStore.getState(), + switchAllTypesDirection ?? switchSameTypeDirection ?? 1, + switchAllTypesDirection !== null ? 'all-types' : 'same-type' + ) + return + } + + const terminalTabDirection = matches('tab.nextTerminal') + ? 1 + : matches('tab.previousTerminal') + ? -1 + : null + if (terminalTabDirection !== null) { + consume() + switchFloatingWorkspaceTab(useAppStore.getState(), terminalTabDirection, 'terminal') } } diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 9a60c2dcc..fdee5dc12 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -72,7 +72,8 @@ import { } from '@/runtime/web-runtime-session' import { createFloatingWorkspaceTerminalTab, - isFloatingWorkspacePanelFocused + isFloatingWorkspacePanelFocused, + switchFloatingWorkspaceTab } from '@/lib/floating-workspace-terminal-actions' import { observeAgentHookCompletionForNotification, @@ -1613,10 +1614,37 @@ export function useIpcEvents(): void { }) ) - unsubs.push(window.api.ui.onSwitchTab(handleSwitchTab)) - unsubs.push(window.api.ui.onSwitchTabAcrossAllTypes(handleSwitchTabAcrossAllTypes)) + unsubs.push( + window.api.ui.onSwitchTab((direction) => { + const store = useAppStore.getState() + if (isFloatingWorkspacePanelFocused()) { + switchFloatingWorkspaceTab(store, direction, 'same-type') + return + } + handleSwitchTab(direction) + }) + ) + unsubs.push( + window.api.ui.onSwitchTabAcrossAllTypes((direction) => { + const store = useAppStore.getState() + if (isFloatingWorkspacePanelFocused()) { + switchFloatingWorkspaceTab(store, direction, 'all-types') + return + } + handleSwitchTabAcrossAllTypes(direction) + }) + ) unsubs.push(window.api.ui.onSwitchRecentTab(handleSwitchRecentTab)) - unsubs.push(window.api.ui.onSwitchTerminalTab(handleSwitchTerminalTab)) + unsubs.push( + window.api.ui.onSwitchTerminalTab((direction) => { + const store = useAppStore.getState() + if (isFloatingWorkspacePanelFocused()) { + switchFloatingWorkspaceTab(store, direction, 'terminal') + return + } + handleSwitchTerminalTab(direction) + }) + ) // Hydrate initial rate limit state then subscribe to push updates window.api.rateLimits.get().then((state) => { diff --git a/src/renderer/src/lib/floating-workspace-terminal-actions.test.ts b/src/renderer/src/lib/floating-workspace-terminal-actions.test.ts index e869bef3f..ec8693eda 100644 --- a/src/renderer/src/lib/floating-workspace-terminal-actions.test.ts +++ b/src/renderer/src/lib/floating-workspace-terminal-actions.test.ts @@ -1,6 +1,8 @@ +/* eslint-disable max-lines -- Focus, shortcut, creation, and switching cases share + * the same floating-workspace DOM/store fixtures. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import type { TerminalTab } from '../../../shared/types' +import type { Tab, TerminalTab } from '../../../shared/types' import { createFloatingWorkspaceTerminalTab, isFloatingWorkspacePanelFocused, @@ -8,14 +10,19 @@ import { isFloatingWorkspacePanelShortcutTarget, isFloatingWorkspaceTerminalInputTarget, isFloatingWorkspacePanelVisible, - shouldMinimizeFloatingWorkspacePanelOnCloseShortcut + shouldMinimizeFloatingWorkspacePanelOnCloseShortcut, + switchFloatingWorkspaceTab } from './floating-workspace-terminal-actions' +const activateWebRuntimeSessionTabMock = vi.hoisted(() => vi.fn()) const createWebRuntimeSessionTerminalMock = vi.hoisted(() => vi.fn()) const focusTerminalTabSurfaceMock = vi.hoisted(() => vi.fn()) +const isWebRuntimeSessionActiveMock = vi.hoisted(() => vi.fn()) vi.mock('@/runtime/web-runtime-session', () => ({ - createWebRuntimeSessionTerminal: createWebRuntimeSessionTerminalMock + activateWebRuntimeSessionTab: activateWebRuntimeSessionTabMock, + createWebRuntimeSessionTerminal: createWebRuntimeSessionTerminalMock, + isWebRuntimeSessionActive: isWebRuntimeSessionActiveMock })) vi.mock('./focus-terminal-tab-surface', () => ({ @@ -79,6 +86,21 @@ function makeTab(id: string): TerminalTab { } } +function makeUnifiedTerminalTab(id: string, groupId = 'floating-group'): Tab { + return { + id, + entityId: id, + groupId, + worktreeId: FLOATING_TERMINAL_WORKTREE_ID, + contentType: 'terminal', + label: 'Terminal', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0 + } +} + afterEach(() => { vi.unstubAllGlobals() }) @@ -234,8 +256,10 @@ describe('isFloatingWorkspacePanelShortcut', () => { describe('createFloatingWorkspaceTerminalTab', () => { beforeEach(() => { + activateWebRuntimeSessionTabMock.mockReset() createWebRuntimeSessionTerminalMock.mockReset() focusTerminalTabSurfaceMock.mockReset() + isWebRuntimeSessionActiveMock.mockReset() }) it('creates and focuses a local floating workspace terminal in the active floating group', async () => { @@ -293,6 +317,54 @@ describe('createFloatingWorkspaceTerminalTab', () => { }) }) +describe('switchFloatingWorkspaceTab', () => { + beforeEach(() => { + activateWebRuntimeSessionTabMock.mockReset() + focusTerminalTabSurfaceMock.mockReset() + isWebRuntimeSessionActiveMock.mockReset() + isWebRuntimeSessionActiveMock.mockReturnValue(false) + }) + + it('cycles terminal tabs inside the floating workspace active group', () => { + const store = { + activeGroupIdByWorktree: { [FLOATING_TERMINAL_WORKTREE_ID]: 'floating-group' }, + activateTab: vi.fn(), + browserPagesByWorkspace: {}, + browserTabsByWorktree: {}, + groupsByWorktree: { + [FLOATING_TERMINAL_WORKTREE_ID]: [ + { + id: 'floating-group', + worktreeId: FLOATING_TERMINAL_WORKTREE_ID, + activeTabId: 'tab-1', + tabOrder: ['tab-1', 'tab-2'], + recentTabIds: ['tab-1'] + } + ] + }, + openFiles: [], + setActiveTab: vi.fn(), + settings: { activeRuntimeEnvironmentId: null }, + tabsByWorktree: { + [FLOATING_TERMINAL_WORKTREE_ID]: [makeTab('tab-1'), makeTab('tab-2')] + }, + unifiedTabsByWorktree: { + [FLOATING_TERMINAL_WORKTREE_ID]: [ + makeUnifiedTerminalTab('tab-1'), + makeUnifiedTerminalTab('tab-2') + ] + } + } + + expect(switchFloatingWorkspaceTab(store as never, 1, 'same-type')).toBe(true) + + expect(store.activateTab).toHaveBeenCalledWith('tab-2') + expect(store.setActiveTab).toHaveBeenCalledWith('tab-2') + expect(focusTerminalTabSurfaceMock).toHaveBeenCalledWith('tab-2') + expect(activateWebRuntimeSessionTabMock).not.toHaveBeenCalled() + }) +}) + describe('shouldMinimizeFloatingWorkspacePanelOnCloseShortcut', () => { const base = { activeView: 'terminal', diff --git a/src/renderer/src/lib/floating-workspace-terminal-actions.ts b/src/renderer/src/lib/floating-workspace-terminal-actions.ts index 3c0692ed5..6b5323f7f 100644 --- a/src/renderer/src/lib/floating-workspace-terminal-actions.ts +++ b/src/renderer/src/lib/floating-workspace-terminal-actions.ts @@ -1,7 +1,18 @@ import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import type { TerminalTab } from '../../../shared/types' +import type { BrowserTab, TabGroup, TerminalTab } from '../../../shared/types' +import { getGroupVisibleTabOrder } from '@/components/tab-bar/group-tab-order' +import { + getNextTabAcrossAllTypes, + getNextTabWithinActiveType, + type TabCycleType, + type TypeCyclableTab +} from '@/components/terminal/tab-type-cycle' import type { AppState } from '@/store/types' -import { createWebRuntimeSessionTerminal } from '@/runtime/web-runtime-session' +import { + activateWebRuntimeSessionTab, + createWebRuntimeSessionTerminal, + isWebRuntimeSessionActive +} from '@/runtime/web-runtime-session' import { focusTerminalTabSurface } from './focus-terminal-tab-surface' type FloatingWorkspaceTerminalStore = Pick< @@ -9,6 +20,21 @@ type FloatingWorkspaceTerminalStore = Pick< 'activeGroupIdByWorktree' | 'createTab' | 'activateTab' | 'settings' > +type FloatingWorkspaceTabSwitchMode = 'same-type' | 'all-types' | 'terminal' + +type FloatingWorkspaceTabSwitchStore = Pick< + AppState, + | 'activeGroupIdByWorktree' + | 'activateTab' + | 'browserTabsByWorktree' + | 'groupsByWorktree' + | 'openFiles' + | 'setActiveTab' + | 'settings' + | 'tabsByWorktree' + | 'unifiedTabsByWorktree' +> + type FloatingWorkspaceShortcutEvent = Pick< KeyboardEvent, 'altKey' | 'ctrlKey' | 'key' | 'metaKey' | 'shiftKey' | 'target' @@ -17,6 +43,133 @@ type FloatingWorkspaceShortcutEvent = Pick< const FLOATING_WORKSPACE_PANEL_SELECTOR = '[data-floating-terminal-panel]' const FLOATING_WORKSPACE_SHORTCUT_SURFACE_SELECTOR = '[data-floating-terminal-shortcut-surface]' +function getActiveFloatingWorkspaceGroup(store: FloatingWorkspaceTabSwitchStore): TabGroup | null { + const groups = store.groupsByWorktree[FLOATING_TERMINAL_WORKTREE_ID] ?? [] + const activeGroupId = store.activeGroupIdByWorktree[FLOATING_TERMINAL_WORKTREE_ID] + if (activeGroupId) { + const activeGroup = groups.find((group) => group.id === activeGroupId) + if (activeGroup) { + return activeGroup + } + } + return groups.find((group) => group.activeTabId != null) ?? groups[0] ?? null +} + +function getFloatingWorkspaceVisibleTabs( + store: FloatingWorkspaceTabSwitchStore, + group: TabGroup +): TypeCyclableTab[] { + const groupTabs = (store.unifiedTabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID] ?? []).filter( + (tab) => tab.groupId === group.id + ) + return getGroupVisibleTabOrder( + group, + groupTabs, + new Set((store.tabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID] ?? []).map((tab) => tab.id)), + new Set( + store.openFiles + .filter((file) => file.worktreeId === FLOATING_TERMINAL_WORKTREE_ID) + .map((file) => file.id) + ), + new Set((store.browserTabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID] ?? []).map((tab) => tab.id)) + ) +} + +function getFloatingWorkspaceActiveEntry( + visibleTabs: readonly TypeCyclableTab[], + group: TabGroup +): TypeCyclableTab | null { + if (group.activeTabId) { + const active = visibleTabs.find((tab) => tab.tabId === group.activeTabId) + if (active) { + return active + } + } + return visibleTabs[0] ?? null +} + +function getActiveIdsForFloatingEntry(entry: TypeCyclableTab): { + activeBrowserTabId: string | null + activeFileId: string | null + activeTabId: string | null + activeTabType: TabCycleType +} { + return { + activeBrowserTabId: entry.type === 'browser' ? entry.id : null, + activeFileId: entry.type === 'editor' ? entry.id : null, + activeTabId: entry.type === 'terminal' ? entry.id : null, + activeTabType: entry.type + } +} + +function getFloatingWorkspaceBrowserTab( + store: FloatingWorkspaceTabSwitchStore, + browserTabId: string +): BrowserTab | null { + return ( + (store.browserTabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID] ?? []).find( + (tab) => tab.id === browserTabId + ) ?? null + ) +} + +function activateFloatingWorkspaceCyclableTab( + store: FloatingWorkspaceTabSwitchStore, + next: TypeCyclableTab +): void { + if (next.tabId) { + store.activateTab(next.tabId) + } + + const runtimeEnvironmentId = store.settings?.activeRuntimeEnvironmentId?.trim() + if (next.type === 'terminal') { + if (isWebRuntimeSessionActive(runtimeEnvironmentId)) { + void activateWebRuntimeSessionTab({ + worktreeId: FLOATING_TERMINAL_WORKTREE_ID, + tabId: next.id, + environmentId: runtimeEnvironmentId + }) + } + store.setActiveTab(next.id) + focusTerminalTabSurface(next.id) + return + } + + if (next.type === 'browser') { + if (isWebRuntimeSessionActive(runtimeEnvironmentId)) { + void activateWebRuntimeSessionTab({ + worktreeId: FLOATING_TERMINAL_WORKTREE_ID, + tabId: next.tabId ?? next.id, + environmentId: runtimeEnvironmentId + }) + } + const workspace = getFloatingWorkspaceBrowserTab(store, next.id) + if (workspace?.activePageId && typeof window !== 'undefined' && window.api?.browser) { + void window.api.browser.notifyActiveTabChanged({ browserPageId: workspace.activePageId }) + } + } +} + +function getNextFloatingWorkspaceTerminalTab( + visibleTabs: readonly TypeCyclableTab[], + active: TypeCyclableTab, + direction: number +): TypeCyclableTab | null { + const terminalTabs = visibleTabs.filter((tab) => tab.type === 'terminal') + if (terminalTabs.length === 0) { + return null + } + const currentIndex = terminalTabs.findIndex((tab) => tab.id === active.id) + if (terminalTabs.length === 1 && currentIndex === 0 && active.type === 'terminal') { + return null + } + const normalizedCurrentIndex = + currentIndex === -1 && direction > 0 ? -1 : currentIndex === -1 ? 0 : currentIndex + return terminalTabs[ + (normalizedCurrentIndex + direction + terminalTabs.length) % terminalTabs.length + ] +} + function defaultIsMacPlatform(): boolean { return typeof navigator !== 'undefined' && navigator.userAgent.includes('Mac') } @@ -94,6 +247,53 @@ export function shouldMinimizeFloatingWorkspacePanelOnCloseShortcut({ ) } +export function switchFloatingWorkspaceTab( + store: FloatingWorkspaceTabSwitchStore, + direction: number, + mode: FloatingWorkspaceTabSwitchMode +): boolean { + const group = getActiveFloatingWorkspaceGroup(store) + if (!group) { + return false + } + const visibleTabs = getFloatingWorkspaceVisibleTabs(store, group) + if (visibleTabs.length <= 1) { + return false + } + const active = getFloatingWorkspaceActiveEntry(visibleTabs, group) + if (!active) { + return false + } + const groupTabIdInNav = + group.activeTabId && visibleTabs.some((entry) => entry.tabId === group.activeTabId) + ? group.activeTabId + : null + + const next = + mode === 'terminal' + ? getNextFloatingWorkspaceTerminalTab(visibleTabs, active, direction) + : mode === 'all-types' + ? getNextTabAcrossAllTypes({ + tabs: visibleTabs, + ...getActiveIdsForFloatingEntry(active), + activeGroupTabId: groupTabIdInNav, + direction + }) + : getNextTabWithinActiveType({ + tabs: visibleTabs, + ...getActiveIdsForFloatingEntry(active), + activeGroupTabId: groupTabIdInNav, + direction + }) + + if (!next) { + return false + } + + activateFloatingWorkspaceCyclableTab(store, next) + return true +} + export async function createFloatingWorkspaceTerminalTab( store: FloatingWorkspaceTerminalStore, shellOverride?: string diff --git a/tests/e2e/terminal-shortcuts.spec.ts b/tests/e2e/terminal-shortcuts.spec.ts index 9f61534e3..ba5972f1a 100644 --- a/tests/e2e/terminal-shortcuts.spec.ts +++ b/tests/e2e/terminal-shortcuts.spec.ts @@ -17,6 +17,7 @@ import { test, expect } from './helpers/orca-app' import type { ElectronApplication, Page } from '@stablyai/playwright-test' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../src/shared/constants' import { execInTerminal, countVisibleTerminalPanes, @@ -75,6 +76,89 @@ async function focusActiveTerminal(page: Page): Promise { }) } +async function focusFloatingTerminal(page: Page): Promise { + await page + .locator( + `[data-floating-terminal-panel][aria-hidden="false"] [data-terminal-tab-id] .xterm-helper-textarea` + ) + .first() + .focus() +} + +async function seedFloatingTerminalTabSwitchScenario(page: Page): Promise<{ + backgroundFirstTabId: string + floatingFirstTabId: string + floatingSecondTabId: string +}> { + return page.evaluate((floatingWorktreeId) => { + const store = window.__store + if (!store) { + throw new Error('Store unavailable') + } + const state = store.getState() + const backgroundWorktreeId = state.activeWorktreeId + if (!backgroundWorktreeId) { + throw new Error('No active background worktree') + } + + const backgroundFirst = + state.tabsByWorktree[backgroundWorktreeId]?.find( + (tab) => tab.id === state.activeTabIdByWorktree[backgroundWorktreeId] + ) ?? + state.tabsByWorktree[backgroundWorktreeId]?.find((tab) => tab.id === state.activeTabId) ?? + state.createTab(backgroundWorktreeId) + state.createTab(backgroundWorktreeId) + state.setActiveTab(backgroundFirst.id) + state.setActiveTabType('terminal') + + const floatingFirst = state.createTab(floatingWorktreeId, undefined, undefined, { + activate: false + }) + state.activateTab(floatingFirst.id) + const floatingGroupId = + state.activeGroupIdByWorktree[floatingWorktreeId] ?? + state.groupsByWorktree[floatingWorktreeId]?.[0]?.id + const floatingSecond = state.createTab(floatingWorktreeId, floatingGroupId, undefined, { + activate: false + }) + state.activateTab(floatingFirst.id) + + return { + backgroundFirstTabId: backgroundFirst.id, + floatingFirstTabId: floatingFirst.id, + floatingSecondTabId: floatingSecond.id + } + }, FLOATING_TERMINAL_WORKTREE_ID) +} + +async function getActiveFloatingTerminalTabId(page: Page): Promise { + return page.evaluate((floatingWorktreeId) => { + const state = window.__store?.getState() + if (!state) { + return null + } + const groupId = state.activeGroupIdByWorktree[floatingWorktreeId] + const group = + (groupId + ? state.groupsByWorktree[floatingWorktreeId]?.find((candidate) => candidate.id === groupId) + : null) ?? + state.groupsByWorktree[floatingWorktreeId]?.find((candidate) => candidate.activeTabId) ?? + null + const activeTab = group?.activeTabId + ? state.unifiedTabsByWorktree[floatingWorktreeId]?.find((tab) => tab.id === group.activeTabId) + : null + return activeTab?.contentType === 'terminal' ? activeTab.entityId : null + }, FLOATING_TERMINAL_WORKTREE_ID) +} + +async function getActiveBackgroundTerminalTabId(page: Page): Promise { + return page.evaluate(() => { + const state = window.__store?.getState() + const worktreeId = state?.activeWorktreeId + return worktreeId ? (state.activeTabIdByWorktree[worktreeId] ?? state.activeTabId) : null + }) +} + async function enableKittyKeyboardReporting(page: Page, flags: number): Promise { await page.evaluate(async (flags) => { const state = window.__store?.getState() @@ -289,6 +373,49 @@ test.describe('Terminal Shortcuts', () => { ) }) + test('floating terminal owns tab switch shortcuts while focused', async ({ orcaPage }) => { + const scenario = await seedFloatingTerminalTabSwitchScenario(orcaPage) + await orcaPage.evaluate(async () => { + const state = window.__store?.getState() + if (state?.settings?.floatingTerminalEnabled !== true) { + await state?.updateSettings({ floatingTerminalEnabled: true }) + } + if (!document.querySelector('[data-floating-terminal-panel][aria-hidden="false"]')) { + window.dispatchEvent(new CustomEvent('orca-toggle-floating-terminal')) + } + }) + await expect( + orcaPage.locator('[data-floating-terminal-panel][aria-hidden="false"]') + ).toBeVisible() + await focusFloatingTerminal(orcaPage) + + await orcaPage.keyboard.press(`${mod}+Shift+BracketRight`) + await expect + .poll(() => getActiveFloatingTerminalTabId(orcaPage), { + timeout: 5_000, + message: 'floating terminal did not switch to the next tab' + }) + .toBe(scenario.floatingSecondTabId) + await expect + .poll(() => getActiveBackgroundTerminalTabId(orcaPage), { + timeout: 1_000, + message: 'background terminal tab changed while floating terminal was focused' + }) + .toBe(scenario.backgroundFirstTabId) + + await focusFloatingTerminal(orcaPage) + await orcaPage.keyboard.press(`${mod}+Shift+BracketLeft`) + await expect + .poll(() => getActiveFloatingTerminalTabId(orcaPage), { + timeout: 5_000, + message: 'floating terminal did not switch back to the previous tab' + }) + .toBe(scenario.floatingFirstTabId) + await expect(getActiveBackgroundTerminalTabId(orcaPage)).resolves.toBe( + scenario.backgroundFirstTabId + ) + }) + test('all terminal chords reach the PTY or fire their action', async ({ orcaPage, electronApp