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(speech): configurable dictation shortcut (press-to-talk Task 1)

enes7a64b3ff2edb
diff --git a/src/core/settings-store.test.ts b/src/core/settings-store.test.ts
new file mode 100644
index 000000000..725264680
--- /dev/null
+++ b/src/core/settings-store.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { SettingsStore } from './settings-store'
+import { DEFAULT_SETTINGS } from '../shared/types'
+
+describe('SettingsStore nested-default merge', () => {
+ let dir: string
+
+ beforeEach(() => {
+ dir = mkdtempSync(path.join(tmpdir(), 'nodeterm-settings-store-'))
+ initPlatform(fakePlatform({ userDataDir: dir }))
+ })
+
+ afterEach(() => {
+ resetPlatformForTests()
+ rmSync(dir, { recursive: true, force: true })
+ })
+
+ it('fills a missing nested speech.shortcut from an OLD settings.json (speech present, shortcut absent)', () => {
+ writeFileSync(
+ path.join(dir, 'settings.json'),
+ JSON.stringify({ fontSize: 15, speech: { engine: 'whisper', model: 'tiny', language: 'auto' } }),
+ 'utf-8'
+ )
+ const store = new SettingsStore()
+ store.init()
+ const s = store.get()
+ expect(s.speech.shortcut).toBe(DEFAULT_SETTINGS.speech.shortcut)
+ // Sibling nested fields the old file DID set must survive the merge untouched.
+ expect(s.speech.engine).toBe('whisper')
+ expect(s.speech.model).toBe('tiny')
+ // Top-level fields the old file set must survive too (shallow-merge path unaffected).
+ expect(s.fontSize).toBe(15)
+ })
+
+ it('leaves an already-modern speech object alone', () => {
+ writeFileSync(
+ path.join(dir, 'settings.json'),
+ JSON.stringify({ speech: { engine: 'cloud', model: 'base', language: 'tr', shortcut: 'Cmd+Alt+D' } }),
+ 'utf-8'
+ )
+ const store = new SettingsStore()
+ store.init()
+ expect(store.get().speech).toEqual({
+ engine: 'cloud',
+ model: 'base',
+ language: 'tr',
+ shortcut: 'Cmd+Alt+D'
+ })
+ })
+
+ it('defaults speech entirely when settings.json has no speech object at all', () => {
+ writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ fontSize: 15 }), 'utf-8')
+ const store = new SettingsStore()
+ store.init()
+ expect(store.get().speech).toEqual(DEFAULT_SETTINGS.speech)
+ })
+
+ it('defaults everything when settings.json does not exist', () => {
+ const store = new SettingsStore()
+ store.init()
+ expect(store.get()).toEqual(DEFAULT_SETTINGS)
+ })
+})
diff --git a/src/core/settings-store.ts b/src/core/settings-store.ts
index f238a349b..f8a7e2e13 100644
--- a/src/core/settings-store.ts
+++ b/src/core/settings-store.ts
@@ -4,6 +4,20 @@ import { IPC } from '../shared/ipc'
import { platform } from './platform'
import { DEFAULT_SETTINGS, type Settings } from '../shared/types'
+/**
+ * Merge a possibly-partial/legacy `Settings` object over `DEFAULT_SETTINGS`. A plain
+ * `{ ...DEFAULT_SETTINGS, ...saved }` shallow merge is right for top-level keys (a missing key
+ * picks up the default), but WRONG for nested objects: an old `settings.json` that has a
+ * `speech` object without a newly-added key (e.g. `shortcut`) would have its whole `speech`
+ * object override the default one-for-one, silently dropping the new key. `speech` is merged
+ * one level deeper so old files still pick up new nested defaults.
+ */
+function mergeSettings(saved: Partial<Settings> | null | undefined): Settings {
+ const merged = { ...DEFAULT_SETTINGS, ...saved }
+ merged.speech = { ...DEFAULT_SETTINGS.speech, ...saved?.speech }
+ return merged
+}
+
/**
* Stores user settings in settings.json. Keeps a synchronous cache so the PtyManager
* can read shell/tmux preferences immediately at terminal creation.
@@ -19,7 +33,7 @@ export class SettingsStore {
init(): void {
try {
const raw = readFileSync(this.filePath, 'utf-8')
- this.cache = { ...DEFAULT_SETTINGS, ...JSON.parse(raw) }
+ this.cache = mergeSettings(JSON.parse(raw))
} catch {
this.cache = DEFAULT_SETTINGS
}
@@ -32,7 +46,7 @@ export class SettingsStore {
registerIpc(): void {
platform().handle(IPC.settingsLoad, () => this.cache)
platform().handle(IPC.settingsSave, async (settings: Settings) => {
- this.cache = { ...DEFAULT_SETTINGS, ...settings }
+ this.cache = mergeSettings(settings)
// Atomic write (temp + rename) so a mid-write crash can't corrupt settings.json.
const tmp = `${this.filePath}.tmp`
await fs.writeFile(tmp, JSON.stringify(this.cache, null, 2), 'utf-8')
diff --git a/src/core/speech/register-ipc.test.ts b/src/core/speech/register-ipc.test.ts
index 1439eec44..29d02f3ca 100644
--- a/src/core/speech/register-ipc.test.ts
+++ b/src/core/speech/register-ipc.test.ts
@@ -19,7 +19,10 @@ function setup(engine: 'whisper' | 'cloud' = 'whisper') {
registerSpeechIpc({
handle: (ch, fn) => handlers.set(ch, fn),
service, models,
- settings: () => ({ ...DEFAULT_SETTINGS, speech: { engine, model: 'tiny', language: 'auto' } }),
+ settings: () => ({
+ ...DEFAULT_SETTINGS,
+ speech: { engine, model: 'tiny', language: 'auto', shortcut: DEFAULT_SETTINGS.speech.shortcut }
+ }),
licenseToken: () => null,
apiBase: 'https://api.example.dev',
fetchFn: (async () => ({ ok: false, status: 404, json: async () => ({}) })) as any,
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index a4f0f2f79..ad3835de7 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -186,6 +186,9 @@ import {
} from '@shared/canvas-publish'
import { createCanvasOrder, createReconnectWatch, type CanvasOrder } from '@shared/canvas-order'
import { createMutationGuard } from '@shared/canvas-mutations'
+import { matchesShortcut } from '@shared/shortcut'
+
+const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
import { canvasSyncTarget } from './collab-sync'
import {
applyCanvasMutation,
@@ -2442,13 +2445,18 @@ export function Canvas() {
requireProOr('Remote SSH terminals', () => setRemotePicker(screenPos))
}, [])
- // ⌘T = new terminal, ⌘⇧C = new default agent, ⌘⇧D = toggle dictation (ignored while typing in
- // a field/terminal).
+ // ⌘T = new terminal, ⌘⇧C = new default agent, configured dictation shortcut (default ⌘⇧D) =
+ // toggle dictation (ignored while typing in a field/terminal).
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (!(e.metaKey || e.ctrlKey)) return
const tag = (document.activeElement?.tagName || '').toLowerCase()
if (tag === 'input' || tag === 'textarea') return
+ if (matchesShortcut(e, useSettings.getState().settings.speech.shortcut, isMac)) {
+ e.preventDefault()
+ toggleDictation()
+ return
+ }
const k = e.key.toLowerCase()
if (k === 't' && !e.shiftKey) {
e.preventDefault()
@@ -2456,9 +2464,6 @@ export function Canvas() {
} else if (k === 'c' && e.shiftKey) {
e.preventDefault()
addAgentNode(useSettings.getState().settings.defaultAgent)
- } else if (k === 'd' && e.shiftKey) {
- e.preventDefault()
- toggleDictation()
}
}
window.addEventListener('keydown', onKey)
diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsx
index b005b801e..e905f29b2 100644
--- a/src/renderer/components/Dock.tsx
+++ b/src/renderer/components/Dock.tsx
@@ -1,10 +1,13 @@
import { useState } from 'react'
import { AGENT_CONFIG, BUILTIN_AGENT_IDS, type AgentId } from '@shared/agents/config'
+import { formatShortcut } from '@shared/shortcut'
import { AgentIcon } from '../lib/agentIcons'
import { useSettings } from '../state/settings'
import { useProjects } from '../state/projects'
import { accountsForProject, sshAccountsHint } from '../state/workspace'
+const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
+
interface DockProps {
dirty: boolean
zoomPct: number
@@ -55,6 +58,7 @@ export function Dock({
dictateActive
}: DockProps) {
const [menuOpen, setMenuOpen] = useState(false)
+ const dictationShortcut = useSettings((s) => s.settings.speech.shortcut)
const customAgents = useSettings((s) => s.settings.customAgents)
const disabledAgents = useSettings((s) => s.settings.disabledAgents)
const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)
@@ -183,7 +187,7 @@ export function Dock({
</button>
<button
className={`dock-btn${dictateActive ? ' active' : ''}`}
- title="Dictate (⌘⇧D)"
+ title={`Dictate (${formatShortcut(dictationShortcut, isMac)})`}
onClick={onDictate}
>
<MicIcon />
diff --git a/src/renderer/components/ShortcutsPanel.tsx b/src/renderer/components/ShortcutsPanel.tsx
index 2d4a20c17..a39bbedd7 100644
--- a/src/renderer/components/ShortcutsPanel.tsx
+++ b/src/renderer/components/ShortcutsPanel.tsx
@@ -1,5 +1,9 @@
import { useEffect } from 'react'
import { createPortal } from 'react-dom'
+import { shortcutKeyParts } from '@shared/shortcut'
+import { useSettings } from '../state/settings'
+
+const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
interface ShortcutsPanelProps {
onClose: () => void
@@ -10,52 +14,59 @@ interface Row {
label: string
}
-const SECTIONS: { title: string; rows: Row[] }[] = [
- {
- title: 'General',
- rows: [
- { keys: ['⌘', 'K'], label: 'Command palette' },
- { keys: ['⌘', ','], label: 'Settings' },
- { keys: ['⌘', '/'], label: 'This shortcuts panel' },
- { keys: ['⌘', '⇧', 'D'], label: 'Dictate' },
- { keys: ['⌘', 'Z'], label: 'Undo' },
- { keys: ['⌘', '⇧', 'Z'], label: 'Redo' }
- ]
- },
- {
- title: 'Canvas',
- rows: [
- { keys: ['⌘', 'T'], label: 'New terminal' },
- { keys: ['⌘', '⇧', 'C'], label: 'New Claude Code' },
- { keys: ['⌘', 'W'], label: 'Close selected node' },
- { keys: ['Right-click'], label: 'Actions menu (empty space or node)' },
- { keys: ['Left-drag'], label: 'Box-select (touch to select)' },
- { keys: ['Middle / Right-drag'], label: 'Pan the canvas' },
- { keys: ['Double-click'], label: 'Center & focus a node' },
- { keys: ['⌘', 'wheel'], label: 'Zoom in / out' }
- ]
- },
- {
- title: 'Terminal',
- rows: [
- { keys: ['Hover ~0.6s'], label: 'Enter the terminal (type/select)' },
- { keys: ['Quick drag'], label: 'Move the terminal (before it focuses)' },
- { keys: ['⌘', 'M'], label: 'Toggle markdown view' },
- { keys: ['⌘', 'C'], label: 'Copy selection (markdown view)' },
- { keys: ['✦'], label: 'Name the terminal with AI' }
- ]
- },
- {
- title: 'Source Control',
- rows: [
- { keys: ['⌘', '⇧', 'G'], label: 'Open Source Control' },
- { keys: ['⌘', '↵'], label: 'Commit the staged changes' }
- ]
- }
-]
+/** Everything but "Dictate" is fixed; that row's keys depend on `settings.speech.shortcut`, so
+ * the sections are built at render time instead of module scope. */
+function buildSections(dictationKeys: string[]): { title: string; rows: Row[] }[] {
+ return [
+ {
+ title: 'General',
+ rows: [
+ { keys: ['⌘', 'K'], label: 'Command palette' },
+ { keys: ['⌘', ','], label: 'Settings' },
+ { keys: ['⌘', '/'], label: 'This shortcuts panel' },
+ { keys: dictationKeys, label: 'Dictate' },
+ { keys: ['⌘', 'Z'], label: 'Undo' },
+ { keys: ['⌘', '⇧', 'Z'], label: 'Redo' }
+ ]
+ },
+ {
+ title: 'Canvas',
+ rows: [
+ { keys: ['⌘', 'T'], label: 'New terminal' },
+ { keys: ['⌘', '⇧', 'C'], label: 'New Claude Code' },
+ { keys: ['⌘', 'W'], label: 'Close selected node' },
+ { keys: ['Right-click'], label: 'Actions menu (empty space or node)' },
+ { keys: ['Left-drag'], label: 'Box-select (touch to select)' },
+ { keys: ['Middle / Right-drag'], label: 'Pan the canvas' },
+ { keys: ['Double-click'], label: 'Center & focus a node' },
+ { keys: ['⌘', 'wheel'], label: 'Zoom in / out' }
+ ]
+ },
+ {
+ title: 'Terminal',
+ rows: [
+ { keys: ['Hover ~0.6s'], label: 'Enter the terminal (type/select)' },
+ { keys: ['Quick drag'], label: 'Move the terminal (before it focuses)' },
+ { keys: ['⌘', 'M'], label: 'Toggle markdown view' },
+ { keys: ['⌘', 'C'], label: 'Copy selection (markdown view)' },
+ { keys: ['✦'], label: 'Name the terminal with AI' }
+ ]
+ },
+ {
+ title: 'Source Control',
+ rows: [
+ { keys: ['⌘', '⇧', 'G'], label: 'Open Source Control' },
+ { keys: ['⌘', '↵'], label: 'Commit the staged changes' }
+ ]
+ }
+ ]
+}
/** Keyboard shortcuts reference; shown on first launch and via ⌘/ or the ? button. */
export function ShortcutsPanel({ onClose }: ShortcutsPanelProps) {
+ const speechShortcut = useSettings((s) => s.settings.speech.shortcut)
+ const SECTIONS = buildSections(shortcutKeyParts(speechShortcut, isMac))
+
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
diff --git a/src/renderer/components/settings/sections/SpeechSection.tsx b/src/renderer/components/settings/sections/SpeechSection.tsx
index 928d177d4..fbd1d05a2 100644
--- a/src/renderer/components/settings/sections/SpeechSection.tsx
+++ b/src/renderer/components/settings/sections/SpeechSection.tsx
@@ -1,5 +1,7 @@
import { useCallback, useEffect, useState } from 'react'
import type { SpeechModelInfo } from '@shared/types'
+import { DEFAULT_SETTINGS } from '@shared/types'
+import { captureToShortcut, formatShortcut, type ShortcutKeyEvent } from '@shared/shortcut'
import { useSettings } from '../../../state/settings'
import { useEntitlement } from '../../../state/entitlement'
import { SettingsSection } from '../SettingsSection'
@@ -10,11 +12,18 @@ import { SegmentedPill } from '@renderer/ui/SegmentedPill'
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: {
title: 'Speech engine',
keywords: ['speech', 'dictation', 'whisper', 'cloud', 'engine', 'voice', 'microphone']
},
+ shortcut: {
+ title: 'Dictation shortcut',
+ keywords: ['shortcut', 'dictation', 'hotkey', 'keybinding', 'press-to-talk', 'microphone']
+ },
models: {
title: 'Whisper models',
keywords: ['whisper', 'model', 'download', 'delete', 'tiny', 'base', 'small', 'large', 'pro']
@@ -36,6 +45,72 @@ const ROWS = {
}
const ENTRIES = Object.values(ROWS)
+/** Focus -> "Press keys…" -> keydown capture (must include Cmd/Ctrl + a non-modifier key) ->
+ * saves the canonical combo. Esc cancels; blur cancels; a separate Reset button restores the
+ * default. Pure combo logic lives in `@shared/shortcut` (parse/match/format/capture). */
+function ShortcutCaptureField({
+ value,
+ onChange
+}: {
+ value: string
+ onChange: (combo: string) => void
+}): React.JSX.Element {
+ const [capturing, setCapturing] = useState(false)
+ const [hint, setHint] = useState('')
+
+ const stopCapturing = (): void => {
+ setCapturing(false)
+ setHint('')
+ }
+
+ const onKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>): void => {
+ if (!capturing) return
+ e.preventDefault()
+ if (e.key === 'Escape') {
+ stopCapturing()
+ 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()
+ }
+
+ 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={() => {
+ setCapturing(true)
+ setHint('')
+ }}
+ onKeyDown={onKeyDown}
+ 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' },
@@ -116,6 +191,9 @@ 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) {
@@ -190,6 +268,14 @@ export function SpeechSection({
/>
</SearchableRow>
+ <SearchableRow {...ROWS.shortcut}>
+ <FieldRow
+ label="Shortcut"
+ description="Press-to-talk: starts recording immediately, press again to stop and insert. The Dock mic uses the same shortcut."
+ control={<ShortcutCaptureField value={settings.speech.shortcut} onChange={setShortcut} />}
+ />
+ </SearchableRow>
+
<SearchableRow {...ROWS.models}>
<div className="space-y-3">
<h4 className="text-[13px] font-medium text-text">Whisper models</h4>
diff --git a/src/shared/shortcut.test.ts b/src/shared/shortcut.test.ts
new file mode 100644
index 000000000..9fe9ba199
--- /dev/null
+++ b/src/shared/shortcut.test.ts
@@ -0,0 +1,218 @@
+import { describe, expect, it } from 'vitest'
+import {
+ captureToShortcut,
+ formatShortcut,
+ matchesShortcut,
+ parseShortcut,
+ shortcutKeyParts
+} from './shortcut'
+
+describe('parseShortcut', () => {
+ it('parses the default combo', () => {
+ expect(parseShortcut('Cmd+Shift+D')).toEqual({ cmd: true, shift: true, alt: false, key: 'D' })
+ })
+
+ it('parses a combo without Shift/Alt', () => {
+ expect(parseShortcut('Cmd+D')).toEqual({ cmd: true, shift: false, alt: false, key: 'D' })
+ })
+
+ it('parses Alt', () => {
+ expect(parseShortcut('Cmd+Alt+D')).toEqual({ cmd: true, shift: false, alt: true, key: 'D' })
+ })
+
+ it('parses a named key (F-key)', () => {
+ expect(parseShortcut('Cmd+F5')).toEqual({ cmd: true, shift: false, alt: false, key: 'F5' })
+ })
+
+ it('parses a named key (Space)', () => {
+ expect(parseShortcut('Cmd+Shift+Space')).toEqual({
+ cmd: true,
+ shift: true,
+ alt: false,
+ key: 'SPACE'
+ })
+ })
+
+ it('is tolerant of stray whitespace', () => {
+ expect(parseShortcut(' Cmd + Shift + D ')).toEqual({
+ cmd: true,
+ shift: true,
+ alt: false,
+ key: 'D'
+ })
+ })
+})
+
+describe('formatShortcut', () => {
+ it('formats the default combo on mac with symbols', () => {
+ expect(formatShortcut('Cmd+Shift+D', true)).toBe('⌘⇧D')
+ })
+
+ it('formats the default combo off mac as Ctrl+Shift+D', () => {
+ expect(formatShortcut('Cmd+Shift+D', false)).toBe('Ctrl+Shift+D')
+ })
+
+ it('formats Alt on mac', () => {
+ expect(formatShortcut('Cmd+Alt+D', true)).toBe('⌘⌥D')
+ })
+
+ it('formats Alt off mac', () => {
+ expect(formatShortcut('Cmd+Alt+D', false)).toBe('Ctrl+Alt+D')
+ })
+
+ it('formats a bare Cmd combo', () => {
+ expect(formatShortcut('Cmd+D', true)).toBe('⌘D')
+ expect(formatShortcut('Cmd+D', false)).toBe('Ctrl+D')
+ })
+
+ it('formats named keys with friendly labels', () => {
+ expect(formatShortcut('Cmd+Space', true)).toBe('⌘Space')
+ expect(formatShortcut('Cmd+Shift+F5', false)).toBe('Ctrl+Shift+F5')
+ })
+
+ it('round-trips parse -> format -> parse (mac and non-mac agree on the parsed shape)', () => {
+ for (const combo of ['Cmd+Shift+D', 'Cmd+D', 'Cmd+Alt+Shift+F5']) {
+ const parsed = parseShortcut(combo)
+ // Formatting for either platform is a pure display transform of the same parsed shape —
+ // reformatting a fresh capture (captureToShortcut) must reparse identically.
+ expect(parseShortcut(combo)).toEqual(parsed)
+ }
+ })
+})
+
+describe('shortcutKeyParts', () => {
+ it('splits the default combo into one badge per key on mac', () => {
+ expect(shortcutKeyParts('Cmd+Shift+D', true)).toEqual(['⌘', '⇧', 'D'])
+ })
+
+ it('splits the default combo into one badge per key off mac', () => {
+ expect(shortcutKeyParts('Cmd+Shift+D', false)).toEqual(['Ctrl', 'Shift', 'D'])
+ })
+
+ it('keeps a multi-char named key as a single badge (not split into letters)', () => {
+ expect(shortcutKeyParts('Cmd+Space', true)).toEqual(['⌘', 'Space'])
+ })
+
+ it('joins to the same string formatShortcut returns', () => {
+ for (const [combo, isMac] of [
+ ['Cmd+Shift+D', true],
+ ['Cmd+Shift+D', false],
+ ['Cmd+Alt+Shift+F5', true]
+ ] as const) {
+ const parts = shortcutKeyParts(combo, isMac)
+ const joined = isMac ? parts.join('') : parts.join('+')
+ expect(joined).toBe(formatShortcut(combo, isMac))
+ }
+ })
+})
+
+describe('matchesShortcut', () => {
+ const base = { metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, key: 'd' }
+
+ it('matches on mac with metaKey as the primary modifier', () => {
+ expect(matchesShortcut({ ...base, metaKey: true, shiftKey: true }, 'Cmd+Shift+D', true)).toBe(
+ true
+ )
+ })
+
+ it('does NOT match on mac when ctrlKey stands in for metaKey', () => {
+ expect(matchesShortcut({ ...base, ctrlKey: true, shiftKey: true }, 'Cmd+Shift+D', true)).toBe(
+ false
+ )
+ })
+
+ it('matches off mac with ctrlKey as the primary modifier', () => {
+ expect(
+ matchesShortcut({ ...base, ctrlKey: true, shiftKey: true }, 'Cmd+Shift+D', false)
+ ).toBe(true)
+ })
+
+ it('does NOT match off mac when metaKey stands in for ctrlKey', () => {
+ expect(
+ matchesShortcut({ ...base, metaKey: true, shiftKey: true }, 'Cmd+Shift+D', false)
+ ).toBe(false)
+ })
+
+ it('rejects a missing Shift', () => {
+ expect(matchesShortcut({ ...base, metaKey: true, shiftKey: false }, 'Cmd+Shift+D', true)).toBe(
+ false
+ )
+ })
+
+ it('rejects an extra Alt not in the combo', () => {
+ expect(
+ matchesShortcut({ ...base, metaKey: true, shiftKey: true, altKey: true }, 'Cmd+Shift+D', true)
+ ).toBe(false)
+ })
+
+ it('rejects the wrong letter key', () => {
+ expect(
+ matchesShortcut({ ...base, metaKey: true, shiftKey: true, key: 'e' }, 'Cmd+Shift+D', true)
+ ).toBe(false)
+ })
+
+ it('is case-insensitive on e.key when Shift is held (browsers report the shifted char)', () => {
+ // Shift+d is delivered as e.key === 'D' by the DOM; either case must match.
+ expect(
+ matchesShortcut({ ...base, metaKey: true, shiftKey: true, key: 'D' }, 'Cmd+Shift+D', true)
+ ).toBe(true)
+ expect(
+ matchesShortcut({ ...base, metaKey: true, shiftKey: true, key: 'd' }, 'Cmd+Shift+D', true)
+ ).toBe(true)
+ })
+
+ it('matches a bare Cmd combo with no Shift/Alt required', () => {
+ expect(matchesShortcut({ ...base, metaKey: true }, 'Cmd+D', true)).toBe(true)
+ })
+
+ it('matches named keys (F-key)', () => {
+ expect(
+ matchesShortcut({ ...base, metaKey: true, key: 'F5' }, 'Cmd+F5', true)
+ ).toBe(true)
+ })
+})
+
+describe('captureToShortcut', () => {
+ it('builds a canonical combo from a mac keydown (metaKey primary)', () => {
+ expect(
+ captureToShortcut({ metaKey: true, ctrlKey: false, shiftKey: true, altKey: false, key: 'd' }, true)
+ ).toBe('Cmd+Shift+D')
+ })
+
+ it('builds a canonical combo from a non-mac keydown (ctrlKey primary)', () => {
+ expect(
+ captureToShortcut(
+ { metaKey: false, ctrlKey: true, shiftKey: true, altKey: false, key: 'd' },
+ false
+ )
+ ).toBe('Cmd+Shift+D')
+ })
+
+ it('returns null when the primary modifier is missing', () => {
+ expect(
+ captureToShortcut({ metaKey: false, ctrlKey: false, shiftKey: true, altKey: false, key: 'd' }, true)
+ ).toBeNull()
+ })
+
+ it('returns null when only modifier keys were pressed (no non-modifier key yet)', () => {
+ expect(
+ captureToShortcut(
+ { metaKey: true, ctrlKey: false, shiftKey: false, altKey: false, key: 'Meta' },
+ true
+ )
+ ).toBeNull()
+ expect(
+ captureToShortcut(
+ { metaKey: true, ctrlKey: false, shiftKey: true, altKey: false, key: 'Shift' },
+ true
+ )
+ ).toBeNull()
+ })
+
+ it('a captured combo round-trips through matchesShortcut for the same platform', () => {
+ const e = { metaKey: true, ctrlKey: false, shiftKey: true, altKey: false, key: 'd' }
+ const combo = captureToShortcut(e, true)
+ expect(combo).not.toBeNull()
+ expect(matchesShortcut(e, combo as string, true)).toBe(true)
+ })
+})
diff --git a/src/shared/shortcut.ts b/src/shared/shortcut.ts
new file mode 100644
index 000000000..5d1646350
--- /dev/null
+++ b/src/shared/shortcut.ts
@@ -0,0 +1,142 @@
+/**
+ * Pure keyboard-shortcut parse/match/format helpers, shared by the Canvas listener, the
+ * Settings → Speech capture field, the Dock mic tooltip, and ShortcutsPanel.
+ *
+ * Canonical string shape: modifier tokens joined by "+", ending in one non-modifier key token,
+ * e.g. `"Cmd+Shift+D"`, `"Cmd+F5"`. `Cmd` is a PLATFORM-ABSTRACTED primary modifier — it means
+ * "the primary modifier for this platform": metaKey (⌘) on mac, ctrlKey elsewhere. There is no
+ * separate literal "Ctrl" token; storing shortcuts in terms of the abstract "Cmd" is what lets
+ * one stored string match on every platform via `matchesShortcut(e, s, isMac)`.
+ */
+
+export interface ParsedShortcut {
+ /** Primary modifier required: metaKey on mac, ctrlKey elsewhere. */
+ cmd: boolean
+ shift: boolean
+ alt: boolean
+ /** Uppercased single char (e.g. "D") or named key (e.g. "F5", "SPACE", "ESCAPE"). */
+ key: string
+}
+
+/** Friendly display labels for named (non single-char) keys. Falls back to title-case. */
+const KEY_LABELS: Record<string, string> = {
+ SPACE: 'Space',
+ ENTER: 'Enter',
+ RETURN: 'Enter',
+ TAB: 'Tab',
+ ESCAPE: 'Esc',
+ ESC: 'Esc',
+ BACKSPACE: 'Backspace',
+ DELETE: 'Delete',
+ ARROWUP: '↑',
+ ARROWDOWN: '↓',
+ ARROWLEFT: '←',
+ ARROWRIGHT: '→'
+}
+
+/** Modifier-only `e.key` values — never a valid trailing key on their own. */
+const MODIFIER_KEYS = new Set(['META', 'CONTROL', 'CTRL', 'SHIFT', 'ALT', 'ALTGRAPH', 'OS'])
+
+/** `"d"` / `"D"` / `"Escape"` / `"F5"` -> the uppercased canonical key token. */
+function normalizeKey(key: string): string {
+ return key.toUpperCase()
+}
+
+/** Parse a canonical combo string, e.g. `"Cmd+Shift+D"` -> `{cmd:true, shift:true, alt:false, key:'D'}`. */
+export function parseShortcut(s: string): ParsedShortcut {
+ const parts = s
+ .split('+')
+ .map((p) => p.trim())
+ .filter(Boolean)
+
+ let cmd = false
+ let shift = false
+ let alt = false
+ let key = ''
+ for (const part of parts) {
+ const lower = part.toLowerCase()
+ if (lower === 'cmd' || lower === 'command' || lower === 'ctrl' || lower === 'control') {
+ cmd = true
+ } else if (lower === 'shift') {
+ shift = true
+ } else if (lower === 'alt' || lower === 'option') {
+ alt = true
+ } else {
+ key = normalizeKey(part)
+ }
+ }
+ return { cmd, shift, alt, key }
+}
+
+/** `"D"` -> `"D"`, `"SPACE"` -> `"Space"`, `"F5"` -> `"F5"`, unknown multi-char -> title case. */
+function keyLabel(key: string): string {
+ if (KEY_LABELS[key]) return KEY_LABELS[key]
+ if (key.length <= 1) return key
+ if (/^F\d{1,2}$/.test(key)) return key
+ return key.charAt(0) + key.slice(1).toLowerCase()
+}
+
+/** `"Cmd+Shift+D"` + mac -> `["⌘", "⇧", "D"]`; + non-mac -> `["Ctrl", "Shift", "D"]`. One badge
+ * per element — used by ShortcutsPanel's `<kbd>` row rendering. */
+export function shortcutKeyParts(s: string, isMac: boolean): string[] {
+ const { cmd, shift, alt, key } = parseShortcut(s)
+ const label = keyLabel(key)
+ if (isMac) {
+ const parts: string[] = []
+ if (cmd) parts.push('⌘')
+ if (alt) parts.push('⌥')
+ if (shift) parts.push('⇧')
+ parts.push(label)
+ return parts
+ }
+ const parts: string[] = []
+ if (cmd) parts.push('Ctrl')
+ if (alt) parts.push('Alt')
+ if (shift) parts.push('Shift')
+ parts.push(label)
+ return parts
+}
+
+/** `"Cmd+Shift+D"` + mac -> `"⌘⇧D"`; + non-mac -> `"Ctrl+Shift+D"`. */
+export function formatShortcut(s: string, isMac: boolean): string {
+ const parts = shortcutKeyParts(s, isMac)
+ return isMac ? parts.join('') : parts.join('+')
+}
+
+/** Minimal shape of a KeyboardEvent this module needs — kept structural so callers don't have
+ * to import `KeyboardEvent` (and so it's trivially fakeable in tests). */
+export interface ShortcutKeyEvent {
+ metaKey: boolean
+ ctrlKey: boolean
+ shiftKey: boolean
+ altKey: boolean
+ key: string
+}
+
+/** Does `e` match the canonical combo `s`? `cmd` in `s` means metaKey on mac, ctrlKey elsewhere. */
+export function matchesShortcut(e: ShortcutKeyEvent, s: string, isMac: boolean): boolean {
+ const parsed = parseShortcut(s)
+ const primaryPressed = isMac ? e.metaKey : e.ctrlKey
+ if (parsed.cmd !== primaryPressed) return false
+ if (parsed.shift !== e.shiftKey) return false
+ if (parsed.alt !== e.altKey) return false
+ return normalizeKey(e.key) === parsed.key
+}
+
+/**
+ * Build a canonical combo string from a captured keydown, for the Settings capture field.
+ * Requires the platform's primary modifier (Cmd on mac / Ctrl elsewhere) plus a non-modifier
+ * key; returns null while only modifier keys have been pressed so far, or when the primary
+ * modifier is missing.
+ */
+export function captureToShortcut(e: ShortcutKeyEvent, isMac: boolean): string | null {
+ const primaryPressed = isMac ? e.metaKey : e.ctrlKey
+ if (!primaryPressed) return null
+ const key = normalizeKey(e.key)
+ if (MODIFIER_KEYS.has(key)) return null
+ const parts = ['Cmd']
+ if (e.altKey) parts.push('Alt')
+ if (e.shiftKey) parts.push('Shift')
+ parts.push(key)
+ return parts.join('+')
+}
diff --git a/src/shared/speech.test.ts b/src/shared/speech.test.ts
index bb4a9dcd8..31869ac62 100644
--- a/src/shared/speech.test.ts
+++ b/src/shared/speech.test.ts
@@ -22,6 +22,11 @@ describe('whisper model catalog', () => {
})
it('speech settings default to free local dictation', () => {
- expect(DEFAULT_SETTINGS.speech).toEqual({ engine: 'whisper', model: 'tiny', language: 'auto' })
+ expect(DEFAULT_SETTINGS.speech).toEqual({
+ engine: 'whisper',
+ model: 'tiny',
+ language: 'auto',
+ shortcut: 'Cmd+Shift+D'
+ })
})
})
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 8d34f2ec6..848d3aa17 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -449,6 +449,10 @@ export interface SpeechSettings {
model: string
/** BCP-47-ish hint or 'auto'. */
language: string
+ /** Press-to-talk shortcut, canonical form e.g. "Cmd+Shift+D" (see `shared/shortcut.ts`).
+ * "Cmd" is platform-abstracted: metaKey on mac, ctrlKey elsewhere. Drives the Canvas
+ * listener, the Dock mic tooltip, and the ShortcutsPanel row. */
+ shortcut: string
}
/** User-configurable application settings (settings.json). */
@@ -553,7 +557,7 @@ export const DEFAULT_SETTINGS: Settings = {
claudePermissionMode: 'auto',
telemetryEnabled: false,
phoneAccessEnabled: false,
- speech: { engine: 'whisper', model: 'tiny', language: 'auto' },
+ speech: { engine: 'whisper', model: 'tiny', language: 'auto', shortcut: 'Cmd+Shift+D' },
}
export interface SettingsApi {