diff --git a/apps/desktop/src/app/chat/composer/focus-chord.test.ts b/apps/desktop/src/app/chat/composer/focus-chord.test.ts new file mode 100644 index 0000000000..40730fcf1c --- /dev/null +++ b/apps/desktop/src/app/chat/composer/focus-chord.test.ts @@ -0,0 +1,80 @@ +import { afterEach, describe, expect, it } from 'vitest' + +import { $workspaceIsPage } from '@/app/routes' +import { closeSwitcher } from '@/store/session-switcher' + +import { onComposerFocusRequest } from './focus' +import { handleComposerFocusChord } from './focus-chord' + +// jsdom is not macOS, so the chord is Ctrl+L. isComposerChord reads +// ctrlKey on other systems and metaKey on macOS. +function chordEvent(init: KeyboardEventInit = {}): KeyboardEvent { + return new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ctrlKey: true, key: 'l', ...init }) +} + +/** The bus defers dispatch by one macrotask. This helper flushes it. */ +const flushBus = () => new Promise(resolve => setTimeout(resolve, 1)) + +async function focusRequests(event: KeyboardEvent): Promise { + const targets: string[] = [] + const off = onComposerFocusRequest(({ target }) => targets.push(target)) + + handleComposerFocusChord(event) + await flushBus() + off() + + return targets +} + +afterEach(() => { + $workspaceIsPage.set(false) + closeSwitcher() + document.body.replaceChildren() +}) + +describe('handleComposerFocusChord', () => { + it('focuses the active composer on the bare chord and swallows the key', async () => { + const event = chordEvent() + + expect(await focusRequests(event)).toEqual(['main']) + expect(event.defaultPrevented).toBe(true) + }) + + it('ignores non-chord keys (plain letter, shifted chord)', async () => { + expect(await focusRequests(chordEvent({ ctrlKey: false }))).toEqual([]) + // Shift+chord is the default for view.showBrowser, not for this handler. + expect(await focusRequests(chordEvent({ shiftKey: true }))).toEqual([]) + }) + + it('yields to a press someone else already claimed', async () => { + const event = chordEvent() + event.preventDefault() + + expect(await focusRequests(event)).toEqual([]) + }) + + it('leaves the key with a focused terminal: no selection means clear-screen', async () => { + const term = document.createElement('div') + term.setAttribute('data-terminal', '') + const inner = document.createElement('textarea') + term.append(inner) + document.body.append(term) + inner.focus() + + const event = chordEvent() + + expect(await focusRequests(event)).toEqual([]) + expect(event.defaultPrevented).toBe(false) + }) + + it('stands down behind blocking surfaces (dialog, full page)', async () => { + const dialog = document.createElement('div') + dialog.setAttribute('role', 'dialog') + document.body.append(dialog) + expect(await focusRequests(chordEvent())).toEqual([]) + + document.body.replaceChildren() + $workspaceIsPage.set(true) + expect(await focusRequests(chordEvent())).toEqual([]) + }) +}) diff --git a/apps/desktop/src/app/chat/composer/focus-chord.ts b/apps/desktop/src/app/chat/composer/focus-chord.ts new file mode 100644 index 0000000000..491c4fb782 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/focus-chord.ts @@ -0,0 +1,38 @@ +/** + * ⌘/Ctrl+L moves focus to the composer from anywhere. This matches the + * address-bar muscle memory of a browser. The other handlers of the chord + * keep priority: + * + * - A terminal or preview selection sends itself to the composer through + * its own capture-phase listener. That listener stops propagation, so + * this handler never sees the press. This handler registers on the + * BUBBLE phase for that reason. + * - A user-rebound action on the same chord dispatches in the capture + * listener of use-keybinds and marks the event handled. This handler + * yields on `defaultPrevented`. + * - A focused terminal with no selection keeps the chord as clear-screen. + * `composerFocusBlockedBySurface()` owns that gate. The same gate covers + * type-to-focus and paste-to-focus, dialogs, full workspace pages, and + * the session switcher. + */ + +import { isComposerChord } from '@/lib/keybinds/chords' +import { composerFocusBlockedBySurface } from '@/lib/keybinds/composer-focus-keys' + +import { requestComposerFocus } from './focus' + +/** The window-level keydown fallback. use-keybinds registers it beside the + * paste listener. When this handler claims the press, it prevents the + * default action. */ +export function handleComposerFocusChord(event: KeyboardEvent): void { + if (event.defaultPrevented || !isComposerChord(event)) { + return + } + + if (composerFocusBlockedBySurface()) { + return + } + + event.preventDefault() + requestComposerFocus('active') +} diff --git a/apps/desktop/src/app/chat/right-rail/preview-file.tsx b/apps/desktop/src/app/chat/right-rail/preview-file.tsx index ffbc96d7e2..f3723f19d7 100644 --- a/apps/desktop/src/app/chat/right-rail/preview-file.tsx +++ b/apps/desktop/src/app/chat/right-rail/preview-file.tsx @@ -13,7 +13,6 @@ import { Streamdown } from 'streamdown' import { requestComposerFocus, requestComposerInsertRefs } from '@/app/chat/composer/focus' import { droppedFileInlineRef } from '@/app/chat/composer/inline-refs' import { HERMES_PATHS_MIME } from '@/app/chat/hooks/use-composer-actions' -import { isAddSelectionShortcut } from '@/app/right-sidebar/terminal/selection' import { RichCodeBlock } from '@/components/assistant-ui/embeds' import { CodeEditor } from '@/components/chat/code-editor' import { FileDiffPanel } from '@/components/chat/diff-lines' @@ -32,6 +31,7 @@ import { } from '@/lib/desktop-fs' import { Check, Pencil, X } from '@/lib/icons' import { createMemoizedMathPlugin } from '@/lib/katex-memo' +import { isComposerChord } from '@/lib/keybinds/chords' import { shikiLanguageForFilename } from '@/lib/markdown-code' import { normalizeFilePreviewMath } from '@/lib/markdown-preprocess' import { cn } from '@/lib/utils' @@ -605,7 +605,7 @@ export function SourceView({ filePath, language, text }: { filePath?: string; la } const onKeyDown = (event: KeyboardEvent) => { - if (!isAddSelectionShortcut(event)) { + if (!isComposerChord(event)) { return } diff --git a/apps/desktop/src/app/hooks/use-keybinds.ts b/apps/desktop/src/app/hooks/use-keybinds.ts index e8292ad3d5..3dec2933c7 100644 --- a/apps/desktop/src/app/hooks/use-keybinds.ts +++ b/apps/desktop/src/app/hooks/use-keybinds.ts @@ -66,6 +66,7 @@ import { openNewWindow } from '@/store/windows' import { useTheme } from '@/themes/context' import { requestComposerFocus, requestModelMenuToggle, requestVoiceToggle } from '../chat/composer/focus' +import { handleComposerFocusChord } from '../chat/composer/focus-chord' import { handleWindowPaste } from '../chat/composer/paste-to-focus' import { openSession } from '../open-session' import { @@ -455,6 +456,9 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void { // clipboard (text AND images) into the active composer. Bubble phase so // editables' own paste handlers run first and mark the event handled. window.addEventListener('paste', handleWindowPaste) + // ⌘/Ctrl+L moves focus to the composer. Bubble phase so capture-phase + // claimants run first; the priority ladder lives in focus-chord.ts. + window.addEventListener('keydown', handleComposerFocusChord) return () => { window.removeEventListener('keydown', onKeyDown, { capture: true }) @@ -462,6 +466,7 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void { window.removeEventListener('blur', onBlur) window.removeEventListener('contextmenu', onContextMenu, { capture: true }) window.removeEventListener('paste', handleWindowPaste) + window.removeEventListener('keydown', handleComposerFocusChord) } }, []) } diff --git a/apps/desktop/src/app/right-sidebar/terminal/selection.ts b/apps/desktop/src/app/right-sidebar/terminal/selection.ts index 239f549591..af72dc6f13 100644 --- a/apps/desktop/src/app/right-sidebar/terminal/selection.ts +++ b/apps/desktop/src/app/right-sidebar/terminal/selection.ts @@ -100,12 +100,6 @@ export function resolveSurfaceColor(fallback: string): string { export { isMacPlatform } -export function isAddSelectionShortcut(event: KeyboardEvent) { - const mod = isMacPlatform() ? event.metaKey : event.ctrlKey - - return mod && !event.shiftKey && event.key.toLowerCase() === 'l' -} - export function terminalSelectionLabel(term: Terminal, shellName: string, text: string) { const pos = term.getSelectionPosition() diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts index 09fd431ee8..9f9aec104e 100644 --- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts +++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts @@ -9,6 +9,7 @@ import type { CSSProperties } from 'react' import { writeClipboardText } from '@/components/ui/copy-button' import { markRightPanePerf } from '@/debug/right-pane-events' import { triggerHaptic } from '@/lib/haptics' +import { isComposerChord } from '@/lib/keybinds/chords' import { $previewTarget } from '@/store/preview' import { useTheme } from '@/themes/context' @@ -19,7 +20,6 @@ import { makeTerminalReader, registerTerminalReader } from './buffer' import { mirrorSelection, terminalClipboardIntent } from './clipboard' import { terminalLinkHandler, terminalWebLinksAddon } from './links' import { - isAddSelectionShortcut, isMacPlatform, resolveSurfaceColor, terminalSelectionAnchor, @@ -476,7 +476,7 @@ export function useTerminalSession({ // must reach the shell as clear-screen. useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { - if (!isAddSelectionShortcut(event) || !readSelection().trim()) { + if (!isComposerChord(event) || !readSelection().trim()) { return } diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts index 0f18ac2a7b..52d5d6dd37 100644 --- a/apps/desktop/src/i18n/ar.ts +++ b/apps/desktop/src/i18n/ar.ts @@ -279,7 +279,7 @@ export const ar = defineLocale({ 'view.showTerminal': 'إظهار الطرفية', 'view.closeTab': 'إغلاق علامة التبويب', 'view.reopenTab': 'إعادة فتح علامة التبويب المغلقة', - 'view.terminalSelection': 'إرسال تحديد الطرفية إلى المحرّر', + 'view.selectionToComposer': 'إرسال التحديد إلى المحرّر', 'view.terminalCopy': 'نسخ تحديد الطرفية', 'view.terminalPaste': 'لصق في الطرفية', 'view.closePreviewTab': 'إغلاق علامة تبويب المعاينة', diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 9b55af9d6e..bc039510aa 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -320,7 +320,7 @@ export const en: Translations = { 'view.nextTerminal': 'Next terminal', 'view.prevTerminal': 'Previous terminal', 'view.closeTerminal': 'Close terminal', - 'view.terminalSelection': 'Send terminal selection to composer', + 'view.selectionToComposer': 'Send selection to composer', 'view.terminalCopy': 'Copy terminal selection', 'view.terminalPaste': 'Paste into terminal', 'view.closeTab': 'Close tab', diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts index 316a80d145..9a07fb4e24 100644 --- a/apps/desktop/src/i18n/zh.ts +++ b/apps/desktop/src/i18n/zh.ts @@ -307,7 +307,7 @@ export const zh: Translations = { 'view.showFiles': '显示文件浏览器', 'view.showBrowser': '打开浏览器', 'view.showTerminal': '显示终端', - 'view.terminalSelection': '将终端选区发送到输入框', + 'view.selectionToComposer': '将选区发送到输入框', 'view.terminalCopy': '复制终端选区', 'view.terminalPaste': '粘贴到终端', 'view.closeTab': '关闭标签', diff --git a/apps/desktop/src/lib/keybinds/actions.ts b/apps/desktop/src/lib/keybinds/actions.ts index f6bd021573..a6c3b6a228 100644 --- a/apps/desktop/src/lib/keybinds/actions.ts +++ b/apps/desktop/src/lib/keybinds/actions.ts @@ -256,8 +256,18 @@ export const KEYBIND_READONLY: readonly KeybindReadonly[] = [ { id: 'composer.help', category: 'composer', keys: ['?'] }, { id: 'composer.history', category: 'composer', keys: ['up', 'down'] }, { id: 'composer.cancel', category: 'composer', keys: ['escape'] }, - // Fixed, context-local shortcuts surfaced for discoverability. - { id: 'view.terminalSelection', category: 'view', keys: ['mod+l'] }, + // ⌘/Ctrl+L moves focus to the composer from anywhere, like the address-bar + // chord in a browser. The row reuses the id of the rebindable soft-focus + // action above. As a result, the panel shows one "Focus composer" label + // for both. The row is fixed because the selection shortcut below uses the + // same chord. Who claims a contested press: see the priority ladder in + // app/chat/composer/focus-chord.ts. + { id: 'composer.focus', category: 'composer', keys: ['mod+l'] }, + // Fixed, context-local shortcuts, listed so users can find them. This row + // uses the same ⌘/Ctrl+L chord as `composer.focus` above. It is the + // selection half of the chord: the selected text (terminal text, preview + // lines) goes into the composer as context. + { id: 'view.selectionToComposer', category: 'view', keys: ['mod+l'] }, // Terminal clipboard. ⌘C/⌘V on macOS, Ctrl+Shift+C/V elsewhere — matching VS // Code. Plain Ctrl+C also copies when text is selected (Windows Terminal / // Tabby behavior); with no selection it stays SIGINT, so it isn't listed. diff --git a/apps/desktop/src/lib/keybinds/chords.ts b/apps/desktop/src/lib/keybinds/chords.ts new file mode 100644 index 0000000000..05d02ac55d --- /dev/null +++ b/apps/desktop/src/lib/keybinds/chords.ts @@ -0,0 +1,13 @@ +import { isMacPlatform } from '@/lib/platform' + +/** + * True when the event is the ⌘/Ctrl+L chord (no shift). The chord routes + * input to the composer: a terminal or preview selection goes in as context, + * and a bare press moves focus. The priority ladder between those consumers + * lives in app/chat/composer/focus-chord.ts. + */ +export function isComposerChord(event: KeyboardEvent): boolean { + const mod = isMacPlatform() ? event.metaKey : event.ctrlKey + + return mod && !event.shiftKey && event.key.toLowerCase() === 'l' +}