The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): take keyboard focus when the terminal pane is revealed
brooklyn!482349c5e519
diff --git a/apps/desktop/src/app/contrib/controller.tsx b/apps/desktop/src/app/contrib/controller.tsxindex 48e56573a92..72b55229c18 100644--- a/apps/desktop/src/app/contrib/controller.tsx+++ b/apps/desktop/src/app/contrib/controller.tsx@@ -106,6 +106,7 @@ import {import { AppContextMenu } from '../context-menu/app-context-menu'import { HudShell } from '../hud/hud-shell'import { $terminalTakeover, setTerminalTakeover } from '../right-sidebar/store'+import { toggleTerminalPane } from '../right-sidebar/terminal/reveal-focus'import { $workspaceIsPage, WORKSPACE_PAGE_HEADER_AREA } from '../routes'import { BASIC_TREE, DEFAULT_TREE, registerLayoutPresets } from './layout-presets'@@ -610,7 +611,7 @@ registry.register(icon: Terminal,keywords: ['terminal', 'shell', 'console', 'pty'],get: () => isPaneVisible('terminal'),- set: () => togglePaneVisible('terminal')+ set: () => toggleTerminalPane()}))diff --git a/apps/desktop/src/app/hooks/use-keybinds.ts b/apps/desktop/src/app/hooks/use-keybinds.tsindex d28a663554e..e98bceb0380 100644--- a/apps/desktop/src/app/hooks/use-keybinds.ts+++ b/apps/desktop/src/app/hooks/use-keybinds.ts@@ -4,6 +4,7 @@ import { useLocation, useNavigate } from 'react-router'import { closeActiveTab } from '@/app/chat/close-tab'import { hudTargetSessionId } from '@/app/hud/handoff'import { setTerminalTakeover } from '@/app/right-sidebar/store'+import { toggleTerminalPane } from '@/app/right-sidebar/terminal/reveal-focus'import { closeActiveTerminal, createTerminal, cycleTerminal } from '@/app/right-sidebar/terminal/terminals'import { appViewForPath, isOverlayView } from '@/app/routes'import {@@ -11,7 +12,6 @@ import {cycleTreeTabInFocusedZone,isPaneVisible,layoutHasRootSide,- togglePaneVisible,toggleTargetZoneTabStrip} from '@/components/pane-shell/tree/store'import { setWorkspaceScope } from '@/components/pane-shell/workspace-scope'@@ -256,8 +256,7 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {// ⌘J toggles the right sidebar — but a layout with no right side (e.g.// terminal-on-bottom) would leave it a dead key, so it falls back to the// terminal there. The single "secondary panel" toggle.- 'view.toggleRightSidebar': () =>- layoutHasRootSide('right') ? toggleFileBrowserOpen() : togglePaneVisible('terminal'),+ 'view.toggleRightSidebar': () => (layoutHasRootSide('right') ? toggleFileBrowserOpen() : toggleTerminalPane()),'view.toggleReview': toggleReview,'view.toggleStatusbar': toggleStatusbarVisible,'view.toggleProfileRail': toggleProfileRailVisible,@@ -266,7 +265,7 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {'view.showFiles': showFiles,'view.showBrowser': openBrowserTab,'view.toggleHud': () => toggleHud(hudTargetSessionId()),- 'view.showTerminal': () => togglePaneVisible('terminal'),+ 'view.showTerminal': () => toggleTerminalPane(),// Create first so the pane's open-effect ensure sees a non-empty set and// doesn't also spawn one — net effect is exactly one fresh terminal.'view.newTerminal': () => {diff --git a/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.test.ts b/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.test.tsnew file mode 100644index 00000000000..bacc9a7e95d--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.test.ts@@ -0,0 +1,287 @@+import { renderHook } from '@testing-library/react'+import { createElement, type ReactNode } from 'react'+import { MemoryRouter } from 'react-router'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('@/themes/context', () => ({+ useTheme: () => ({ resolvedMode: 'dark' as const, setMode: () => undefined })+}))++import { PALETTE_AREA, type PaletteContribution } from '@/app/command-palette/contrib'+import { useKeybinds } from '@/app/hooks/use-keybinds'+import { setTerminalTakeover } from '@/app/right-sidebar/store'+import { useStatusbarItems } from '@/app/shell/hooks/use-statusbar-items'+import { collapseTreePane, isPaneVisible, revealTreePane, setPaneCollapsed } from '@/components/pane-shell/tree/store'+import { registry } from '@/contrib/registry'++// Ctrl+`, the ⌘K row, and the statusbar pill reveal the terminal. That reveal+// must make the on-screen xterm the keyboard target, and the claim has to+// survive the composer taking focus back on the next frame. Hiding must not.++const wrapper = ({ children }: { children: ReactNode }) => createElement(MemoryRouter, null, children)++let unmountKeybinds: (() => void) | undefined++beforeAll(async () => {+ await import('@/app/contrib/controller')+})++beforeEach(() => {+ // Testing Library unmounts renderHook trees after each test, so the keybind+ // listener has to be installed again or later presses never dispatch.+ unmountKeybinds = renderHook(+ () =>+ useKeybinds({+ archiveSelectedSession: () => undefined,+ openNewSessionTab: () => undefined,+ startFreshSession: () => undefined,+ toggleCommandCenter: () => undefined,+ toggleSelectedPin: () => undefined+ }),+ { wrapper }+ ).unmount+})++afterAll(() => {+ unmountKeybinds?.()+})++afterEach(() => {+ vi.unstubAllGlobals()+ document.body.replaceChildren()+ setTerminalTakeover(false)+ setPaneCollapsed('terminal', true)+})++function installRaf() {+ const frames: FrameRequestCallback[] = []+ let nextId = 1++ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ frames.push(callback)++ return nextId+++ })+ vi.stubGlobal('cancelAnimationFrame', () => undefined)++ return () => frames.splice(0).forEach(callback => callback(0))+}++function mountTerminal(visible: boolean): HTMLTextAreaElement {+ const host = document.createElement('div')++ host.dataset.terminal = ''++ if (!visible) {+ host.className = 'invisible pointer-events-none'+ }++ const textarea = document.createElement('textarea')++ textarea.className = 'xterm-helper-textarea'+ host.append(textarea)+ document.body.append(host)++ return textarea+}++function mountComposer(): HTMLTextAreaElement {+ const composer = document.createElement('textarea')++ composer.dataset.composer = ''+ document.body.append(composer)++ return composer+}++function pressShowTerminal() {+ window.dispatchEvent(+ new KeyboardEvent('keydown', {+ bubbles: true,+ cancelable: true,+ code: 'Backquote',+ ctrlKey: true,+ key: '`'+ })+ )+}++function paletteRun() {+ const row = registry.getArea(PALETTE_AREA).find(item => item.id === 'view.showTerminal')+ const run = (row?.data as PaletteContribution | undefined)?.run++ if (!run) {+ throw new Error('palette toggle view.showTerminal is not registered')+ }++ run()+}++function statusbarSelect() {+ const { result } = renderHook(+ () =>+ useStatusbarItems({+ agentsOpen: false,+ chatOpen: true,+ commandCenterOpen: false,+ extraLeftItems: [],+ extraRightItems: [],+ freshDraftReady: false,+ gatewayState: 'ready',+ inferenceStatus: null,+ openAgents: () => undefined,+ openCommandCenterSection: () => undefined,+ requestGateway: async () => undefined as never,+ statusSnapshot: null,+ toggleCommandCenter: () => undefined+ }),+ { wrapper }+ )++ const terminal = result.current.statusbarItems.find(item => item.id === 'terminal')++ if (!terminal?.onSelect) {+ throw new Error('statusbar terminal toggle is not registered')+ }++ terminal.onSelect({ shiftKey: false })+}++function hideTerminal() {+ setTerminalTakeover(false)+ setPaneCollapsed('terminal', true)++ if (isPaneVisible('terminal')) {+ collapseTreePane('terminal')+ }+}++function showTerminalPane() {+ setTerminalTakeover(true)++ if (!isPaneVisible('terminal')) {+ revealTreePane('terminal')+ }+}++describe('terminal reveal keyboard focus', () => {+ it('takes focus from the keybind on reveal and keeps it when the composer steals it', () => {+ const frame = installRaf()++ hideTerminal()+ expect(isPaneVisible('terminal')).toBe(false)++ const hidden = mountTerminal(false)+ const visible = mountTerminal(true)+ const composer = mountComposer()++ composer.focus()+ pressShowTerminal()+ frame()++ expect(document.activeElement).toBe(visible)+ expect(document.activeElement).not.toBe(hidden)+ expect(document.activeElement).not.toBe(composer)++ composer.focus()+ expect(document.activeElement).toBe(composer)++ frame()+ expect(document.activeElement).toBe(visible)+ })++ it('returns focus to the terminal on every later reveal from the keybind', () => {+ const frame = installRaf()+ const visible = mountTerminal(true)+ const composer = mountComposer()++ hideTerminal()+ expect(isPaneVisible('terminal')).toBe(false)+ composer.focus()+ pressShowTerminal()+ frame()+ expect(document.activeElement).toBe(visible)++ showTerminalPane()+ expect(isPaneVisible('terminal')).toBe(true)+ composer.focus()+ pressShowTerminal()+ frame()+ frame()+ frame()+ expect(document.activeElement).toBe(composer)+ expect(isPaneVisible('terminal')).toBe(false)++ pressShowTerminal()+ frame()+ expect(document.activeElement).toBe(visible)+ })++ it('does not keep refocusing once the terminal already holds the keyboard', () => {+ const frame = installRaf()+ const visible = mountTerminal(true)+ const focusSpy = vi.spyOn(visible, 'focus')++ hideTerminal()+ expect(isPaneVisible('terminal')).toBe(false)+ pressShowTerminal()+ frame()+ frame()+ frame()++ expect(focusSpy).toHaveBeenCalledTimes(1)+ })++ it('takes focus from the palette toggle on reveal and re-asserts if the composer steals it', () => {+ const frame = installRaf()+ const visible = mountTerminal(true)+ const composer = mountComposer()++ hideTerminal()+ expect(isPaneVisible('terminal')).toBe(false)+ composer.focus()+ paletteRun()+ frame()++ expect(document.activeElement).toBe(visible)++ composer.focus()+ frame()+ expect(document.activeElement).toBe(visible)+ })++ it('does not move focus onto the terminal when the palette toggle hides it', () => {+ const frame = installRaf()+ const visible = mountTerminal(true)+ const composer = mountComposer()++ showTerminalPane()+ expect(isPaneVisible('terminal')).toBe(true)+ composer.focus()+ paletteRun()+ frame()+ frame()+ frame()++ expect(document.activeElement).toBe(composer)+ expect(document.activeElement).not.toBe(visible)+ expect(isPaneVisible('terminal')).toBe(false)+ })++ it('takes focus from the statusbar toggle on reveal', () => {+ const frame = installRaf()+ const visible = mountTerminal(true)+ const composer = mountComposer()++ hideTerminal()+ composer.focus()+ statusbarSelect()+ frame()++ expect(document.activeElement).toBe(visible)++ composer.focus()+ frame()+ expect(document.activeElement).toBe(visible)+ })+})diff --git a/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.ts b/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.tsnew file mode 100644index 00000000000..5d073fec81c--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.ts@@ -0,0 +1,58 @@+import { isPaneVisible, togglePaneVisible } from '@/components/pane-shell/tree/store'+import { isFocusWithin } from '@/lib/keybinds/combo'++const TERMINAL_FOCUS_SCOPE = '[data-terminal]'++// Inactive tabs carry `invisible`. The on-screen instance does not, so this+// never targets a keep-alive tab that is not the keyboard surface. xterm's+// helper textarea is its real keyboard input — the same element the clipboard+// helper writes a selection into.+const FOCUS_TARGET = `${TERMINAL_FOCUS_SCOPE}:not(.invisible) .xterm-helper-textarea`++// The pane layout settles over a couple of frames (slot rect chase, theme+// repaint), and the composer focus bus can steal the keyboard on the macrotask+// between them. Three frames covers that settle plus one re-assert, then stops+// so a later deliberate click in the composer is not a focus fight.+const REVEAL_FOCUS_ATTEMPTS = 3++/**+ * Take keyboard focus for the active terminal once its pane has been revealed.+ *+ * Terminals stay mounted while the pane is hidden, so the activation effect+ * that calls `term.focus()` does not re-run on reveal. Every user reveal+ * (Ctrl+`, the palette row, the statusbar pill) has to claim the keyboard+ * itself and take it back if the composer wins the next frame.+ */+function focusRevealedTerminal(): void {+ scheduleFocusAttempt(REVEAL_FOCUS_ATTEMPTS)+}++function scheduleFocusAttempt(attempts: number): void {+ window.requestAnimationFrame(() => {+ // A hide that lands before the settle window ends must not pull the+ // keyboard back onto a pane the user just closed.+ if (!isPaneVisible('terminal') || isFocusWithin(TERMINAL_FOCUS_SCOPE)) {+ return+ }++ document.querySelector<HTMLTextAreaElement>(FOCUS_TARGET)?.focus()++ if (attempts > 1) {+ scheduleFocusAttempt(attempts - 1)+ }+ })+}++/**+ * User toggle of the terminal pane. The reveal direction claims keyboard+ * focus; the hide direction does not.+ */+export function toggleTerminalPane(): void {+ const revealed = !isPaneVisible('terminal')++ togglePaneVisible('terminal')++ if (revealed) {+ focusRevealedTerminal()+ }+}diff --git a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsxindex 47ee6d7b292..1421a6c7eed 100644--- a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx+++ b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx@@ -5,12 +5,13 @@ import { useNavigate } from 'react-router'import { ConnectionSwitcher } from '@/app/chat/sidebar/connection-switcher'import { ProfileSwitcher } from '@/app/chat/sidebar/profile-dropdown-switcher'import type { CommandCenterSection } from '@/app/command-center'+import { toggleTerminalPane } from '@/app/right-sidebar/terminal/reveal-focus'import { useApprovalModeStatusbarItem } from '@/app/shell/approval-mode-menu'import { ContextUsagePanel } from '@/app/shell/context-usage-panel'import { GatewayMenuPanel } from '@/app/shell/gateway-menu-panel'import { useContextBreakdown } from '@/app/shell/hooks/use-context-breakdown'import { useSystemResourcesStatusbarItem } from '@/app/shell/system-resources-statusbar'-import { $paneVisible, togglePaneVisible } from '@/components/pane-shell/tree/store'+import { $paneVisible } from '@/components/pane-shell/tree/store'import { Badge } from '@/components/ui/badge'import { Codicon } from '@/components/ui/codicon'import { GlyphSpinner } from '@/components/ui/glyph-spinner'@@ -708,7 +709,7 @@ export function useStatusbarItems({hidden: !chatOpen,icon: <Terminal className="size-3.5" />,id: 'terminal',- onSelect: () => togglePaneVisible('terminal'),+ onSelect: () => toggleTerminalPane(),title: terminalShowing ? copy.hideTerminal : copy.showTerminal,toggleLabel: copy.toggleTerminal,variant: 'action'