Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(settings): keyboard shortcuts section with recording, conflicts and reset

enesbce03ea20bf6
diff --git a/src/renderer/components/settings/SettingsIcons.tsx b/src/renderer/components/settings/SettingsIcons.tsx
index 3df4e9a6c..be34e2a6f 100644
--- a/src/renderer/components/settings/SettingsIcons.tsx
+++ b/src/renderer/components/settings/SettingsIcons.tsx
@@ -42,6 +42,13 @@ const PATHS: Record<SettingsSectionId, React.JSX.Element> = {
<path d="M4 8.2a4 4 0 0 0 8 0M8 12.2v1.6M6.2 13.8h3.6" />
</>
),
+ // A keyboard: the outline, two key rows, and a wide space bar.
+ shortcuts: (
+ <>
+ <rect x="1.5" y="4" width="13" height="8" rx="1.8" />
+ <path d="M4 6.5h.01M6.5 6.5h.01M9 6.5h.01M11.5 6.5h.01M4 9.6h8" />
+ </>
+ ),
agents: (
<path d="M8 2.3 9.4 5.9 13 7.3 9.4 8.7 8 12.3 6.6 8.7 3 7.3 6.6 5.9z" />
),
diff --git a/src/renderer/components/settings/SettingsPage.tsx b/src/renderer/components/settings/SettingsPage.tsx
index d69d9d67d..bc9f82b32 100644
--- a/src/renderer/components/settings/SettingsPage.tsx
+++ b/src/renderer/components/settings/SettingsPage.tsx
@@ -11,6 +11,7 @@ import { AppearanceSection } from './sections/AppearanceSection'
import { NotchSection } from './sections/NotchSection'
import { PhoneSection } from './sections/PhoneSection'
import { SpeechSection } from './sections/SpeechSection'
+import { ShortcutsSection } from './sections/ShortcutsSection'
import { AgentsSection } from './sections/AgentsSection'
import { UsageSection } from './sections/UsageSection'
import { AccountsSection } from './sections/AccountsSection'
@@ -79,6 +80,7 @@ export function SettingsPage({
{isMac && <NotchSection isActive={active === 'notch'} />}
<PhoneSection isActive={active === 'phone'} />
<SpeechSection isActive={active === 'speech'} onNavigate={setActive} />
+ <ShortcutsSection isActive={active === 'shortcuts'} />
<AgentsSection isActive={active === 'agents'} />
<UsageSection isActive={active === 'usage'} />
<AccountsSection isActive={active === 'accounts'} />
diff --git a/src/renderer/components/settings/nav.test.ts b/src/renderer/components/settings/nav.test.ts
index 60acd2e6c..d2033cdd7 100644
--- a/src/renderer/components/settings/nav.test.ts
+++ b/src/renderer/components/settings/nav.test.ts
@@ -2,10 +2,10 @@ import { describe, it, expect } from 'vitest'
import { SETTINGS_GROUPS, allSectionIds, FIRST_SECTION_ID, visibleSettingsGroups } from './nav'
describe('SETTINGS_GROUPS', () => {
- it('lists exactly 24 sections with no duplicates', () => {
+ it('lists exactly 25 sections with no duplicates', () => {
const ids = allSectionIds()
- expect(ids).toHaveLength(24)
- expect(new Set(ids).size).toBe(24)
+ expect(ids).toHaveLength(25)
+ expect(new Set(ids).size).toBe(25)
})
it('starts at a section that exists in the groups', () => {
expect(allSectionIds()).toContain(FIRST_SECTION_ID)
@@ -13,7 +13,7 @@ describe('SETTINGS_GROUPS', () => {
it('hides mac-only sections off macOS, keeps them on', () => {
const off = visibleSettingsGroups(false).flatMap((g) => g.sections.map((s) => s.id))
expect(off).not.toContain('notch')
- expect(off).toHaveLength(23)
+ expect(off).toHaveLength(24)
expect(visibleSettingsGroups(true)).toEqual(SETTINGS_GROUPS)
// No group is left empty by the filter.
expect(visibleSettingsGroups(false).every((g) => g.sections.length > 0)).toBe(true)
diff --git a/src/renderer/components/settings/nav.ts b/src/renderer/components/settings/nav.ts
index 4c89a2f5a..a5b1cd0c2 100644
--- a/src/renderer/components/settings/nav.ts
+++ b/src/renderer/components/settings/nav.ts
@@ -6,6 +6,7 @@ export type SettingsSectionId =
| 'notch'
| 'phone'
| 'speech'
+ | 'shortcuts'
| 'agents'
| 'usage'
| 'accounts'
@@ -70,7 +71,8 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [
{ id: 'appearance', title: 'Appearance' },
{ id: 'notch', title: 'Notch', macOnly: true },
{ id: 'notifications', title: 'Notifications' },
- { id: 'speech', title: 'Speech' }
+ { id: 'speech', title: 'Speech' },
+ { id: 'shortcuts', title: 'Keyboard Shortcuts' }
]
},
{
diff --git a/src/renderer/components/settings/sections/ShortcutsSection.test.tsx b/src/renderer/components/settings/sections/ShortcutsSection.test.tsx
new file mode 100644
index 000000000..2039fbeb5
--- /dev/null
+++ b/src/renderer/components/settings/sections/ShortcutsSection.test.tsx
@@ -0,0 +1,150 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { COMMAND_DEFINITIONS } from '@shared/keybindings'
+import { DEFAULT_SETTINGS } from '@shared/types'
+import { useSettings } from '../../../state/settings'
+import { ShortcutsSection, commitCandidate } from './ShortcutsSection'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+// jsdom reports a non-mac platform; the chips and the refusal messages are platform-formatted,
+// so pin macOS here — `isMacPlatform()` is read at call time, never captured at module load.
+Object.defineProperty(window.navigator, 'platform', { value: 'MacIntel', configurable: true })
+
+const setKb = (kb: unknown): void =>
+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, keybindings: kb as never } })
+
+const kb = (): Record<string, readonly string[]> =>
+ (useSettings.getState().settings.keybindings ?? {}) as Record<string, readonly string[]>
+
+let host: HTMLDivElement
+let root: Root | null = null
+
+function render(): void {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root!.render(<ShortcutsSection isActive={true} />))
+}
+
+const row = (id: string): HTMLElement => host.querySelector<HTMLElement>(`[data-command="${id}"]`)!
+const button = (id: string, label: string): HTMLButtonElement | null =>
+ row(id).querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`)
+/** The recorder button carries no per-command aria-label (it is a shared component), so it is
+ * found by its idle text within the row. */
+const recorder = (id: string, text: string): HTMLButtonElement | undefined =>
+ [...row(id).querySelectorAll('button')].find((b) => b.textContent === text)
+const click = (el: HTMLElement): void => {
+ act(() => el.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+}
+
+beforeEach(() => {
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ settings: { save: vi.fn() },
+ shortcuts: { setRecording: vi.fn() }
+ }
+ setKb(undefined)
+})
+
+afterEach(() => {
+ if (!root) return
+ const r = root
+ root = null
+ act(() => r.unmount())
+ host.remove()
+})
+
+describe('ShortcutsSection rows', () => {
+ it('renders one row per command, in registry order, with its chips', () => {
+ render()
+ const ids = [...host.querySelectorAll('[data-command]')].map((el) =>
+ el.getAttribute('data-command')
+ )
+ expect(ids).toEqual(COMMAND_DEFINITIONS.map((d) => d.id))
+ const palette = row('app.commandPalette')
+ expect(palette.textContent).toContain('Command palette')
+ expect([...palette.querySelectorAll('kbd')].map((k) => k.textContent)).toEqual(['⌘', 'K'])
+ })
+
+ it('shows an em-dash placeholder and a record button for an unbound command', () => {
+ render()
+ const fitAll = row('canvas.fitAll')
+ expect(fitAll.querySelectorAll('kbd')).toHaveLength(0)
+ expect(fitAll.textContent).toContain('—')
+ expect(recorder('canvas.fitAll', 'Record shortcut')).toBeTruthy()
+ // Nothing to add to, disable, or reset yet.
+ expect(recorder('canvas.fitAll', 'Add')).toBeUndefined()
+ expect(button('canvas.fitAll', 'Disable Fit all nodes in view')).toBeNull()
+ expect(button('canvas.fitAll', 'Reset Fit all nodes in view')).toBeNull()
+ })
+
+ it('Disable writes an empty list through the override write path', () => {
+ render()
+ click(button('app.commandPalette', 'Disable Command palette')!)
+ expect(kb()['app.commandPalette']).toEqual([])
+ expect(row('app.commandPalette').textContent).toContain('Disabled')
+ })
+
+ it('Reset appears only with an override, and deletes the key', () => {
+ render()
+ expect(button('canvas.undo', 'Reset Undo')).toBeNull()
+ click(button('canvas.undo', 'Disable Undo')!)
+ expect(kb()['canvas.undo']).toEqual([])
+ click(button('canvas.undo', 'Reset Undo')!)
+ expect('canvas.undo' in kb()).toBe(false)
+ expect([...row('canvas.undo').querySelectorAll('kbd')].map((k) => k.textContent)).toEqual([
+ '⌘',
+ 'Z'
+ ])
+ })
+
+ // Ruling 1(a): the disabled-dictation render case. `[]` is the load-bearing "off" value —
+ // `dictationBinding()` returns '' for it, and this row must SAY so rather than looking unbound.
+ it('renders the dictation row as disabled when its override is []', () => {
+ setKb({ 'speech.dictation': [] })
+ render()
+ const dictate = row('speech.dictation')
+ expect(dictate.querySelectorAll('kbd')).toHaveLength(0)
+ expect(dictate.textContent).toContain('Disabled')
+ expect(dictate.textContent).toContain('hold to talk')
+ })
+})
+
+describe('commitCandidate', () => {
+ it('refuses a conflicting candidate, naming the other command, and writes nothing', () => {
+ setKb({ 'canvas.fitAll': [] })
+ const r = commitCandidate('canvas.fitAll', 'Cmd+K', 'replace')
+ expect(r.ok).toBe(false)
+ expect(r.ok === false && r.error).toContain('Command palette')
+ expect(kb()['canvas.fitAll']).toEqual([])
+ })
+
+ it('refuses a candidate that would be swallowed app-wide before another surface', () => {
+ const r = commitCandidate('node.close', 'Cmd+F', 'replace')
+ expect(r.ok).toBe(false)
+ expect(r.ok === false && r.error).toContain('swallowed app-wide')
+ expect(r.ok === false && r.error).toContain('Find in terminal')
+ expect('node.close' in kb()).toBe(false)
+ })
+
+ // Ruling 2: the two detectors can both see a same-bucket collision for a main-intercepted
+ // command. One candidate, ONE message — the conflict message, not both.
+ it('reports a same-bucket collision on an intercepted command exactly once', () => {
+ const r = commitCandidate('node.close', 'Cmd+K', 'replace')
+ expect(r.ok).toBe(false)
+ expect(r.ok === false && r.error).toContain('Command palette')
+ expect(r.ok === false && r.error).not.toContain('swallowed app-wide')
+ })
+
+ it('accepts a free chord, replacing or adding to the list', () => {
+ expect(commitCandidate('canvas.fitAll', 'Cmd+Alt+F', 'replace')).toEqual({ ok: true })
+ expect(kb()['canvas.fitAll']).toEqual(['Cmd+Alt+F'])
+ expect(commitCandidate('canvas.fitAll', 'Cmd+Alt+G', 'add')).toEqual({ ok: true })
+ expect(kb()['canvas.fitAll']).toEqual(['Cmd+Alt+F', 'Cmd+Alt+G'])
+ // Re-adding an existing chord is idempotent, not a self-conflict.
+ expect(commitCandidate('canvas.fitAll', 'Cmd+Alt+F', 'add')).toEqual({ ok: true })
+ expect(kb()['canvas.fitAll']).toEqual(['Cmd+Alt+G', 'Cmd+Alt+F'])
+ })
+})
diff --git a/src/renderer/components/settings/sections/ShortcutsSection.tsx b/src/renderer/components/settings/sections/ShortcutsSection.tsx
new file mode 100644
index 000000000..eda4bf3c7
--- /dev/null
+++ b/src/renderer/components/settings/sections/ShortcutsSection.tsx
@@ -0,0 +1,248 @@
+/**
+ * The Keyboard Shortcuts settings section: one row per registry command, with its live chips,
+ * a recorder, and Add / Disable / Reset.
+ *
+ * **The pre-save gate is `commitCandidate`, and it is where the refusal messages are decided.**
+ * Design D3 is "same detector, different surfacing": `sanitizeKeybindingOverrides` applies what
+ * survives on LOAD, while this section refuses a bad candidate BEFORE anything is written, so the
+ * user learns which chord was refused and why instead of watching a saved shortcut disappear on
+ * the next launch. Three checks, in this order, and the order is the whole dedupe:
+ * 1. `normalizeBindingForCommand` — already inside `ShortcutRecorderButton`, so an invalid chord
+ * never reaches `onCommit` (its own hint is shown in the recorder button itself).
+ * 2. `findKeybindingConflicts` over the candidate map — a same-bucket collision.
+ * 3. `findMainInterceptShadowing` — a CROSS-bucket hit the conflict check cannot see.
+ * (2) returns early, so a candidate that trips both detectors (a main-intercepted command taking
+ * a chord another GLOBAL command already holds — `node.close` ← `Cmd+K`) produces exactly ONE
+ * message. The shadow message is reserved for what only it can see: `node.close` ← `Cmd+F`, where
+ * the two commands live in different buckets and nothing collides, yet main swallows the key
+ * before the terminal surface is ever offered it.
+ *
+ * Writes go through `setKeybindingOverride` (the single write path — it also mirrors
+ * `speech.dictation` into the legacy `settings.speech.shortcut` field for one release).
+ */
+import { useMemo, useState } from 'react'
+import {
+ COMMANDS_BY_ID,
+ COMMAND_DEFINITIONS,
+ findKeybindingConflicts,
+ findMainInterceptShadowing,
+ type CommandDefinition,
+ type CommandGroup,
+ type CommandId
+} from '@shared/keybindings'
+import { formatShortcut } from '@shared/shortcut'
+import { isMacPlatform, keyLabel } from '@shared/platform-utils'
+import {
+ activeKeybindingOverrides,
+ commandKeysFor,
+ effectiveBindings,
+ setKeybindingOverride
+} from '../../../lib/keybindingOverrides'
+import { useSettings } from '../../../state/settings'
+import { SettingsSection } from '../SettingsSection'
+import { SearchableRow } from '../SearchableRow'
+import { FieldRow } from '../FieldRow'
+import { ShortcutRecorderButton } from '../ShortcutRecorderButton'
+import { Button } from '@renderer/ui/Button'
+import type { SettingsSearchEntry } from '../search'
+
+/** Per-command help text. Only commands whose BEHAVIOR needs explaining get one — a row that
+ * merely repeats its own title is noise in a 20-row list. */
+const NOTES: Partial<Record<CommandId, string>> = {
+ // Reused verbatim from the old SpeechSection row: the mode is derived from the chord's SHAPE,
+ // which is not guessable from a chip.
+ 'speech.dictation':
+ 'With a key = toggle (press to start, press again to stop and insert); modifiers only = hold to talk (hold to record, release to stop and insert). The Dock mic uses the same shortcut.',
+ 'canvas.deleteSelection': 'Bare keys are allowed here; the typing guard keeps Backspace safe.',
+ 'terminal.copySelection': 'Applies to a selection xterm owns — a tmux drag copies through OSC 52.'
+}
+
+function rowEntry(def: CommandDefinition): SettingsSearchEntry {
+ return {
+ title: def.title,
+ description: NOTES[def.id],
+ keywords: ['shortcut', 'keybinding', 'hotkey', 'key', def.group, def.id]
+ }
+}
+
+function groupEntry(group: CommandGroup, defs: CommandDefinition[]): SettingsSearchEntry {
+ // The header must survive any query that keeps one of its rows, so its keywords are the union
+ // of what those rows match on — otherwise a filtered list shows rows under the wrong heading.
+ return {
+ title: group,
+ keywords: ['shortcut', 'keybinding', 'hotkey', ...defs.flatMap((d) => [d.title, d.id])]
+ }
+}
+
+/**
+ * The testable core the row controls delegate to: gate a candidate binding, then write it.
+ * `mode` is `'replace'` (the recorder's primary action) or `'add'` (a second chord for the same
+ * command). Re-adding a chord the command already holds is idempotent rather than a
+ * self-conflict — it is filtered out of the list before being appended.
+ *
+ * Assumes `combo` is already canonical: `ShortcutRecorderButton` runs
+ * `normalizeBindingForCommand` and never emits an invalid chord.
+ */
+export function commitCandidate(
+ id: CommandId,
+ combo: string,
+ mode: 'replace' | 'add'
+): { ok: true } | { ok: false; error: string } {
+ const isMac = isMacPlatform()
+ const current = activeKeybindingOverrides()
+ const existing = effectiveBindings(id)
+ const nextList = mode === 'add' ? [...existing.filter((b) => b !== combo), combo] : [combo]
+ const chord = formatShortcut(combo, isMac)
+
+ const conflicts = findKeybindingConflicts({ ...current, [id]: nextList }, isMac).filter((c) =>
+ c.commandIds.includes(id)
+ )
+ if (conflicts.length) {
+ const titles = [
+ ...new Set(
+ conflicts
+ .flatMap((c) => c.commandIds)
+ .filter((cid) => cid !== id)
+ .map((cid) => COMMANDS_BY_ID.get(cid)?.title ?? cid)
+ )
+ ]
+ return { ok: false, error: `${chord} is already used by ${titles.join(', ')}.` }
+ }
+
+ const shadowed = findMainInterceptShadowing(id, combo, current, isMac)
+ if (shadowed.length) {
+ const titles = shadowed.map((cid) => COMMANDS_BY_ID.get(cid)?.title ?? cid).join(', ')
+ return { ok: false, error: `${chord} would be swallowed app-wide before ${titles} could see it.` }
+ }
+
+ setKeybindingOverride(id, nextList)
+ return { ok: true }
+}
+
+function Chips({ id }: { id: CommandId }): React.JSX.Element {
+ const keys = commandKeysFor(id)
+ if (keys.length === 0) return <></>
+ return (
+ <span className="flex items-center gap-2">
+ {keys.map((parts, i) => (
+ <span key={i} className="flex items-center gap-1">
+ {i > 0 ? <span className="text-[11px] text-muted">or</span> : null}
+ {parts.map((p, j) => (
+ <kbd key={j} className="kbd">
+ {keyLabel(p)}
+ </kbd>
+ ))}
+ </span>
+ ))}
+ </span>
+ )
+}
+
+export function ShortcutsSection({ isActive }: { isActive: boolean }): React.JSX.Element {
+ // Any remap re-renders every row: chips, and the Add/Disable/Reset visibility, are all derived
+ // from the override map.
+ const overrides = useSettings((s) => s.settings.keybindings)
+ const [errors, setErrors] = useState<Partial<Record<CommandId, string>>>({})
+
+ const groups = useMemo(() => {
+ const byGroup = new Map<CommandGroup, CommandDefinition[]>()
+ for (const def of COMMAND_DEFINITIONS) {
+ byGroup.set(def.group, [...(byGroup.get(def.group) ?? []), def])
+ }
+ return [...byGroup.entries()]
+ }, [])
+
+ const entries = useMemo(
+ () => [
+ ...groups.map(([group, defs]) => groupEntry(group, defs)),
+ ...COMMAND_DEFINITIONS.map(rowEntry)
+ ],
+ [groups]
+ )
+
+ const apply = (id: CommandId, combo: string, mode: 'replace' | 'add'): void => {
+ const r = commitCandidate(id, combo, mode)
+ setErrors((prev) => ({ ...prev, [id]: r.ok ? undefined : r.error }))
+ }
+ const write = (id: CommandId, bindings: readonly string[] | null): void => {
+ setKeybindingOverride(id, bindings)
+ setErrors((prev) => ({ ...prev, [id]: undefined }))
+ }
+
+ return (
+ <SettingsSection
+ id="shortcuts"
+ title="Keyboard Shortcuts"
+ description="Remap any command. Overrides are stored in settings.json under `keybindings`; Disable turns a command's shortcut off, Reset restores its default. macOS owns ⌘M for Window ▸ Minimize, so that one chord cannot be recorded here."
+ isActive={isActive}
+ searchEntries={entries}
+ >
+ {groups.map(([group, defs]) => (
+ <div key={group} className="space-y-4">
+ <SearchableRow {...groupEntry(group, defs)}>
+ <h3 className="text-[13px] font-semibold uppercase tracking-wide text-muted">
+ {group}
+ </h3>
+ </SearchableRow>
+ {defs.map((def) => {
+ const override = overrides?.[def.id]
+ const disabled = Array.isArray(override) && override.length === 0
+ const bound = commandKeysFor(def.id).length > 0
+ return (
+ <SearchableRow key={def.id} {...rowEntry(def)}>
+ <div data-command={def.id}>
+ <FieldRow
+ label={def.title}
+ description={NOTES[def.id]}
+ note={errors[def.id]}
+ control={
+ <div className="flex items-center gap-2">
+ {bound ? (
+ <Chips id={def.id} />
+ ) : (
+ <span className="text-[13px] text-muted">
+ {disabled ? 'Disabled' : '—'}
+ </span>
+ )}
+ <ShortcutRecorderButton
+ commandId={def.id}
+ idleLabel={bound ? 'Record' : 'Record shortcut'}
+ onCommit={(combo) => apply(def.id, combo, 'replace')}
+ />
+ {bound ? (
+ <ShortcutRecorderButton
+ commandId={def.id}
+ idleLabel="Add"
+ onCommit={(combo) => apply(def.id, combo, 'add')}
+ />
+ ) : null}
+ {bound ? (
+ <Button
+ variant="ghost"
+ aria-label={`Disable ${def.title}`}
+ onClick={() => write(def.id, [])}
+ >
+ Disable
+ </Button>
+ ) : null}
+ {override !== undefined ? (
+ <Button
+ variant="ghost"
+ aria-label={`Reset ${def.title}`}
+ onClick={() => write(def.id, null)}
+ >
+ Reset
+ </Button>
+ ) : null}
+ </div>
+ }
+ />
+ </div>
+ </SearchableRow>
+ )
+ })}
+ </div>
+ ))}
+ </SettingsSection>
+ )
+}
diff --git a/src/renderer/components/settings/sections/SpeechSection.tsx b/src/renderer/components/settings/sections/SpeechSection.tsx
index 02c1c6300..ef2d0f53a 100644
--- a/src/renderer/components/settings/sections/SpeechSection.tsx
+++ b/src/renderer/components/settings/sections/SpeechSection.tsx
@@ -1,16 +1,8 @@
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useState } from 'react'
import type { SpeechModelInfo } from '@shared/types'
import { hasSpeechModel, modelAfterDelete, modelAfterDownload, SPEECH_MODEL_NONE } from '@shared/speech'
-import { DEFAULT_SETTINGS } from '@shared/types'
-import {
- buildModifierChord,
- captureToShortcut,
- formatShortcut,
- isHoldChord,
- isModifierEventKey,
- type ChordModifiers,
- type ShortcutKeyEvent
-} from '@shared/shortcut'
+import { formatShortcut, isHoldChord } from '@shared/shortcut'
+import { dictationBinding } from '../../../lib/keybindingOverrides'
import { useSettings } from '../../../state/settings'
import { useEntitlement } from '../../../state/entitlement'
import { SettingsSection } from '../SettingsSection'
@@ -22,7 +14,6 @@ import { Button } from '@renderer/ui/Button'
import type { SettingsSectionId } from '../nav'
const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
-const DEFAULT_SHORTCUT = DEFAULT_SETTINGS.speech.shortcut
const ROWS = {
engine: {
@@ -68,114 +59,6 @@ const ROWS = {
}
const ENTRIES = Object.values(ROWS)
-/**
- * Focus -> "Press keys…" -> capture -> saves the canonical combo. Two shapes commit
- * differently (v3):
- * - A real key (Cmd/Ctrl + a non-modifier key) commits IMMEDIATELY on keydown, same as before
- * — toggle mode.
- * - Modifier keys only (Cmd/Ctrl [+ Alt] [+ Shift], no other key yet) commit on KEYUP, once
- * every key has been released — hold-to-talk mode. Each modifier keydown along the way
- * remembers the strongest state seen (`modsRef`) and previews it, since the keyup event
- * itself no longer carries that state once everything's up (see `buildModifierChord`'s doc).
- * Esc cancels; blur cancels; a separate Reset button restores the default (`Cmd+Alt`, itself a
- * hold-to-talk chord). Pure combo logic lives in `@shared/shortcut`.
- */
-function ShortcutCaptureField({
- value,
- onChange
-}: {
- value: string
- onChange: (combo: string) => void
-}): React.JSX.Element {
- const [capturing, setCapturing] = useState(false)
- const [hint, setHint] = useState('')
- const modsRef = useRef<ChordModifiers | null>(null)
-
- const stopCapturing = (): void => {
- setCapturing(false)
- setHint('')
- modsRef.current = null
- }
-
- const startCapturing = (): void => {
- modsRef.current = null
- setCapturing(true)
- setHint('')
- }
-
- const onKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>): void => {
- if (!capturing) return
- e.preventDefault()
- if (e.key === 'Escape') {
- stopCapturing()
- return
- }
-
- if (isModifierEventKey(e.key)) {
- // Only modifier keys pressed so far — remember the strongest state for a possible keyUp
- // commit (hold-to-talk) and preview it; still lets the user continue on to press a real
- // key instead (toggle mode) below.
- const primaryPressed = isMac ? e.metaKey : e.ctrlKey
- if (!primaryPressed) {
- setHint(isMac ? `Hold ⌘…` : `Hold Ctrl…`)
- return
- }
- const mods: ChordModifiers = { cmd: true, alt: e.altKey, shift: e.shiftKey }
- modsRef.current = mods
- const preview = buildModifierChord(mods)
- setHint(preview ? `Release now for hold-to-talk (${formatShortcut(preview, isMac)}) — or press a key for toggle` : '')
- return
- }
-
- const evt: ShortcutKeyEvent = {
- metaKey: e.metaKey,
- ctrlKey: e.ctrlKey,
- shiftKey: e.shiftKey,
- altKey: e.altKey,
- key: e.key
- }
- const combo = captureToShortcut(evt, isMac)
- if (!combo) {
- setHint(isMac ? `Hold ⌘ and press a key` : `Hold Ctrl and press a key`)
- return
- }
- onChange(combo)
- stopCapturing()
- }
-
- const onKeyUp = (e: React.KeyboardEvent<HTMLButtonElement>): void => {
- if (!capturing || !modsRef.current) return
- const anyModDown = (isMac ? e.metaKey : e.ctrlKey) || e.altKey || e.shiftKey
- if (anyModDown) return // not fully released yet — keep waiting
- const combo = buildModifierChord(modsRef.current)
- if (!combo) return
- onChange(combo)
- stopCapturing()
- }
-
- return (
- <div className="flex items-center gap-2">
- <button
- type="button"
- className="min-w-[140px] cursor-pointer rounded-md border border-border bg-panel-header px-3 py-1.5 text-[13px] font-medium text-text outline-none hover:bg-[rgba(255,255,255,0.06)]"
- onClick={startCapturing}
- onKeyDown={onKeyDown}
- onKeyUp={onKeyUp}
- onBlur={stopCapturing}
- >
- {capturing ? hint || 'Press keys…' : formatShortcut(value, isMac)}
- </button>
- <Button
- variant="ghost"
- disabled={value === DEFAULT_SHORTCUT}
- onClick={() => onChange(DEFAULT_SHORTCUT)}
- >
- Reset
- </Button>
- </div>
- )
-}
-
const LANGUAGES: { value: string; label: string }[] = [
{ value: 'auto', label: 'Auto-detect' },
{ value: 'en', label: 'English' },
@@ -211,6 +94,10 @@ export function SpeechSection({
}): React.JSX.Element {
const settings = useSettings((s) => s.settings)
const update = useSettings((s) => s.update)
+ // The chord's single source is the registry override (`speech.shortcut` is only the legacy
+ // downgrade mirror), and a string selector keeps an unrelated settings write from re-rendering
+ // this section. `''` = the user disabled dictation's shortcut.
+ const dictationChord = useSettings(() => dictationBinding())
const isPremium = useEntitlement((s) => s.isPremium)
const [models, setModels] = useState<SpeechModelInfo[]>([])
@@ -261,9 +148,6 @@ export function SpeechSection({
const setLanguage = (language: string): void => {
update({ speech: { ...settings.speech, language } })
}
- const setShortcut = (shortcut: string): void => {
- update({ speech: { ...settings.speech, shortcut } })
- }
const selectModel = (m: SpeechModelInfo): void => {
if (m.pro && !isPremium) {
@@ -354,13 +238,19 @@ export function SpeechSection({
<SearchableRow {...ROWS.shortcut}>
<FieldRow
label="Shortcut"
- description="Press a combo — with a key = toggle (press to start, press again to stop and insert); modifiers only = hold to talk (hold to record, release to stop and insert). The Dock mic uses the same shortcut."
+ description="Dictation's shortcut is managed with every other keyboard shortcut."
note={
- isHoldChord(settings.speech.shortcut)
- ? `Currently hold-to-talk: hold ${formatShortcut(settings.speech.shortcut, isMac)}.`
- : `Currently toggle: press ${formatShortcut(settings.speech.shortcut, isMac)}.`
+ dictationChord === ''
+ ? 'Currently disabled.'
+ : isHoldChord(dictationChord)
+ ? `Currently hold-to-talk: hold ${formatShortcut(dictationChord, isMac)}.`
+ : `Currently toggle: press ${formatShortcut(dictationChord, isMac)}.`
+ }
+ control={
+ <Button variant="ghost" onClick={() => onNavigate('shortcuts')}>
+ Open Keyboard Shortcuts
+ </Button>
}
- control={<ShortcutCaptureField value={settings.speech.shortcut} onChange={setShortcut} />}
/>
</SearchableRow>
diff --git a/src/shared/keybindings.ts b/src/shared/keybindings.ts
index 773a2b4b2..7f397f9b6 100644
--- a/src/shared/keybindings.ts
+++ b/src/shared/keybindings.ts
@@ -386,7 +386,8 @@ export function resolveCommandForKeyEvent(
// the window listener — resolving them here would fire Commit with no composer focused.
if (def.scope === 'scm') continue
// speech.dictation dispatches from its own dedicated listeners (the keyed gesture and the
- // hold-mode effect, both reading settings.speech.shortcut), never from the registry — its
+ // hold-mode effect, both reading `dictationBinding()` — the registry override; the legacy
+ // settings.speech.shortcut field is only its downgrade mirror), never from here — its
// row here is display-only, for ShortcutsPanel and the Settings section. A hand-edited KEYED
// override would otherwise RESOLVE, find no handler, and spend the chord: the dispatcher's
// claim protocol stops a resolved command from reaching the trailing gestures, so
diff --git a/src/shared/shortcut.test.ts b/src/shared/shortcut.test.ts
index 3e0cc75a2..c7aba6afa 100644
--- a/src/shared/shortcut.test.ts
+++ b/src/shared/shortcut.test.ts
@@ -262,6 +262,15 @@ describe('isHoldChord', () => {
expect(isHoldChord('Cmd+Alt+D')).toBe(false)
expect(isHoldChord('Cmd+D')).toBe(false)
})
+
+ // DOCUMENTATION OF A HAZARD, not a desirable property: `''` parses to a chord with no key, so
+ // it reads as a HOLD chord. `dictationBinding()` returns `''` for a DISABLED dictation shortcut
+ // (override `[]`), so any caller that asks `isHoldChord(chord)` without first testing for the
+ // empty string classifies "off" as "hold-to-talk" — which is why SpeechSection's note checks
+ // `chord === ''` FIRST, and why the hold listener must not arm on it.
+ it('is TRUE for the empty string — every caller owes it an explicit empty check', () => {
+ expect(isHoldChord('')).toBe(true)
+ })
})
describe('isModifierEventKey', () => {
@@ -440,6 +449,13 @@ describe('strict modifier matching', () => {
const e = { metaKey: true, ctrlKey: true, shiftKey: false, altKey: true, key: 'Control' }
expect(chordHeld(e, 'Cmd+Alt', true)).toBe(false)
})
+ // The other half of the `''` guard (see isHoldChord above): the KEYED path is safe on its own —
+ // an empty chord parses to `key: null`, which no event key equals — so a disabled dictation
+ // shortcut can never be pressed into existence, however the modifiers happen to be held.
+ it('never matches the empty string, whatever is held', () => {
+ const e = { metaKey: true, ctrlKey: false, shiftKey: false, altKey: true, key: 'd' }
+ expect(matchesShortcut(e, '', true)).toBe(false)
+ })
})
describe('named punctuation keys', () => {