feat(desktop): make Cmd/Ctrl+L focus the composer from anywhere

The chord previously only acted when a terminal or preview selection
existed. A new bubble-phase window fallback now moves focus to the
composer on an unclaimed press, like the address-bar chord in a browser.

Existing owners keep priority: selection handlers claim the press on the
capture phase, a user-rebound action marks the event handled, and a
focused terminal with no selection keeps Ctrl+L as clear-screen via
composerFocusBlockedBySurface().

The chord matcher moves from the terminal feature to
src/lib/keybinds/chords.ts as isComposerChord: it now has three
consumers and the old name (isAddSelectionShortcut) was wrong at the
composer call site. The fixed panel row view.terminalSelection becomes
view.selectionToComposer because it covers preview selections too.
This commit is contained in:
ethernet
2026-08-24 11:42:39 -07:00
parent a0795acc83
commit 28b758d5ca
11 changed files with 155 additions and 15 deletions
@@ -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<string[]> {
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([])
})
})
@@ -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')
}
@@ -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
}
@@ -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)
}
}, [])
}
@@ -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()
@@ -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
}
+1 -1
View File
@@ -279,7 +279,7 @@ export const ar = defineLocale({
'view.showTerminal': 'إظهار الطرفية',
'view.closeTab': 'إغلاق علامة التبويب',
'view.reopenTab': 'إعادة فتح علامة التبويب المغلقة',
'view.terminalSelection': 'إرسال تحديد الطرفية إلى المحرّر',
'view.selectionToComposer': 'إرسال التحديد إلى المحرّر',
'view.terminalCopy': 'نسخ تحديد الطرفية',
'view.terminalPaste': 'لصق في الطرفية',
'view.closePreviewTab': 'إغلاق علامة تبويب المعاينة',
+1 -1
View File
@@ -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',
+1 -1
View File
@@ -307,7 +307,7 @@ export const zh: Translations = {
'view.showFiles': '显示文件浏览器',
'view.showBrowser': '打开浏览器',
'view.showTerminal': '显示终端',
'view.terminalSelection': '将终端选区发送到输入框',
'view.selectionToComposer': '将选区发送到输入框',
'view.terminalCopy': '复制终端选区',
'view.terminalPaste': '粘贴到终端',
'view.closeTab': '关闭标签',
+12 -2
View File
@@ -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.
+13
View File
@@ -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'
}