Skip to content

The agent that grows with you

fix(webapp): Alt / ⌃⌘ + the same key for every browser-reserved default

Teknium5ba3243fc4cc
diff --git a/apps/desktop/src/app/hooks/use-keybinds-browser.test.tsx b/apps/desktop/src/app/hooks/use-keybinds-browser.test.tsx
index 1e8f91aeb5a..ee255d9ee7a 100644
--- a/apps/desktop/src/app/hooks/use-keybinds-browser.test.tsx
+++ b/apps/desktop/src/app/hooks/use-keybinds-browser.test.tsx
@@ -53,7 +53,9 @@ async function mountKeybinds(inTerminal = false) {
const press = (init: KeyboardEventInit) => {
const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ctrlKey: true, ...init })
- act(() => { input.dispatchEvent(event) })
+ act(() => {
+ input.dispatchEvent(event)
+ })
return event
}
@@ -61,7 +63,8 @@ async function mountKeybinds(inTerminal = false) {
return { deps, press }
}
-it('dispatches browser defaults and remaps from text fields, leaving browser keys and AltGr alone', async () => {
+it('dispatches the Alt defaults and remaps from text fields, leaving browser keys and AltGr alone', async () => {
+ vi.spyOn(navigator, 'platform', 'get').mockReturnValue('Linux x86_64')
const { deps, press } = await mountKeybinds()
const { setBinding } = await import('@/store/keybinds')
@@ -72,7 +75,12 @@ it('dispatches browser defaults and remaps from text fields, leaving browser key
// Windows AltGr reports Ctrl+Alt; Linux can report AltGraph without Ctrl.
// Polish ń, German @, French AZERTY dead tilde / ʒ are text, not commands.
for (const ctrlKey of [true, false]) {
- for (const [key, code] of [['ń', 'KeyN'], ['@', 'KeyQ'], ['Dead', 'KeyN'], ['ʒ', 'KeyW']]) {
+ for (const [key, code] of [
+ ['ń', 'KeyN'],
+ ['@', 'KeyQ'],
+ ['Dead', 'KeyN'],
+ ['ʒ', 'KeyW']
+ ]) {
const event = press({ key, code, altKey: true, ctrlKey, modifierAltGraph: true })
expect(event.getModifierState('AltGraph')).toBe(true)
expect(event.defaultPrevented).toBe(false)
@@ -83,8 +91,8 @@ it('dispatches browser defaults and remaps from text fields, leaving browser key
expect(deps.openNewSessionTab).not.toHaveBeenCalled()
expect(closeTab).not.toHaveBeenCalled()
- for (const key of ['F7', 'F8', 'F9']) {
- expect(press({ key, code: key, shiftKey: true }).defaultPrevented).toBe(true)
+ for (const key of ['n', 't', 'w']) {
+ expect(press({ key, code: `Key${key.toUpperCase()}`, altKey: true, ctrlKey: false }).defaultPrevented).toBe(true)
}
expect(deps.startFreshSession).toHaveBeenCalledOnce()
@@ -92,7 +100,7 @@ it('dispatches browser defaults and remaps from text fields, leaving browser key
expect(closeTab).toHaveBeenCalledOnce()
act(() => setBinding('session.new', ['mod+shift+f6']))
- expect(press({ key: 'F7', code: 'F7', shiftKey: true }).defaultPrevented).toBe(false)
+ expect(press({ key: 'n', code: 'KeyN', altKey: true, ctrlKey: false }).defaultPrevented).toBe(false)
expect(press({ key: 'F6', code: 'F6', shiftKey: true }).defaultPrevented).toBe(true)
expect(deps.startFreshSession).toHaveBeenCalledTimes(2)
})
@@ -113,3 +121,27 @@ it('dispatches the macOS ⌃⌘ browser defaults, including ⌃⌘W over an inte
expect(deps.openNewSessionTab).toHaveBeenCalledOnce()
expect(closeTab).toHaveBeenCalledOnce()
})
+
+it('steps the session switcher with Alt+] and commits when Alt is released', async () => {
+ vi.spyOn(navigator, 'platform', 'get').mockReturnValue('Linux x86_64')
+ const { $selectedStoredSessionId, $sessions } = await import('@/store/session')
+ const { $switcherOpen, switcherActive } = await import('@/store/session-switcher')
+ $sessions.set(['a', 'b', 'c'].map(id => ({ id }) as never))
+ $selectedStoredSessionId.set('a')
+ const { press } = await mountKeybinds()
+
+ const release = (key: string, init: KeyboardEventInit = {}) =>
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, key, ...init }))
+ })
+
+ expect(press({ key: ']', code: 'BracketRight', altKey: true, ctrlKey: false }).defaultPrevented).toBe(true)
+ expect(press({ key: ']', code: 'BracketRight', altKey: true, ctrlKey: false }).defaultPrevented).toBe(true)
+ expect($switcherOpen.get()).toBe(true)
+
+ release(']', { altKey: true })
+ expect($switcherOpen.get()).toBe(true)
+ release('Alt')
+ expect($switcherOpen.get()).toBe(false)
+ expect(switcherActive()).toBe(false)
+})
diff --git a/apps/desktop/src/app/hooks/use-keybinds.ts b/apps/desktop/src/app/hooks/use-keybinds.ts
index 18c351535b0..d5749e78776 100644
--- a/apps/desktop/src/app/hooks/use-keybinds.ts
+++ b/apps/desktop/src/app/hooks/use-keybinds.ts
@@ -132,6 +132,8 @@ export interface KeybindRuntimeDeps {
* return value (void, a navigate() promise, …) means it ran. */
type HandlerMap = Record<string, () => unknown>
+const SWITCHER_MODIFIER_KEYS = new Set(['Alt', 'Control', 'Meta', 'Shift'])
+
function hasWordEraseModifier(event: KeyboardEvent): boolean {
return IS_MAC ? event.metaKey && !event.ctrlKey : event.ctrlKey
}
@@ -628,11 +630,12 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {
releaseApprovalKey()
}
- if (event.key === 'Tab') {
+ // The cycle chord is ⌃Tab natively but Alt+] / ⌃⌘] in a browser tab:
+ // releasing its step key ends the hold, and releasing the last
+ // non-Shift modifier commits.
+ if (!SWITCHER_MODIFIER_KEYS.has(event.key)) {
onSwitcherTabUp()
- }
-
- if (event.key === 'Control') {
+ } else if (event.key !== 'Shift' && !event.ctrlKey && !event.altKey && !event.metaKey) {
commitSwitcherRef.current()
}
}
diff --git a/apps/desktop/src/app/settings/sessions-settings.tsx b/apps/desktop/src/app/settings/sessions-settings.tsx
index bd28e610041..906ed2c7ebe 100644
--- a/apps/desktop/src/app/settings/sessions-settings.tsx
+++ b/apps/desktop/src/app/settings/sessions-settings.tsx
@@ -20,8 +20,10 @@ import { pathLeaf } from '@/lib/display-path'
import { triggerHaptic } from '@/lib/haptics'
import { Archive, ArchiveOff, FolderOpen, Loader2, Trash2 } from '@/lib/icons'
import { purgeInFlightTurnJournals } from '@/lib/inflight-turn-journal'
+import { formatCombo } from '@/lib/keybinds/combo'
import { isBrowserHostedDesktop } from '@/lib/platform'
import { confirm } from '@/store/confirm'
+import { bindingsFor } from '@/store/keybinds'
import { notify, notifyError } from '@/store/notifications'
import { $connection, applyConfiguredDefaultProjectDir, ensureDefaultWorkspaceCwd } from '@/store/session'
import { untombstoneSessions } from '@/store/session-removal'
@@ -34,6 +36,14 @@ import { SETTING_IDS, settingElementId } from './settings-manifest'
import { useDeepLinkHighlight } from './use-deep-link-highlight'
import { useSettingDeepLink } from './use-setting-deep-link'
+// The toast names the chord the user actually has: a browser tab and a remap
+// both differ from ⌘/Ctrl+N.
+function newSessionShortcut(): null | string {
+ const combo = bindingsFor('session.new')[0]
+
+ return combo ? formatCombo(combo) : null
+}
+
const DEFAULT_AUTO_ARCHIVE_DAYS = 3
interface SessionsSettingsProps {
@@ -394,7 +404,7 @@ function DefaultProjectDirSetting() {
const result = await settings.setDefaultProjectDir(picked.dir)
setDir(result.dir)
applyConfiguredDefaultProjectDir(result.dir)
- notify({ durationMs: 4_000, kind: 'success', message: s.defaultDirUpdated })
+ notify({ durationMs: 4_000, kind: 'success', message: s.defaultDirUpdated(newSessionShortcut()) })
} catch (err) {
notifyError(err, s.updateDirFailed)
} finally {
diff --git a/apps/desktop/src/i18n/ar_settings.ts b/apps/desktop/src/i18n/ar_settings.ts
index 67845dc87d4..f86e309a272 100644
--- a/apps/desktop/src/i18n/ar_settings.ts
+++ b/apps/desktop/src/i18n/ar_settings.ts
@@ -936,7 +936,8 @@ export const arSettings = {
deleteConfirm: title => `حذف "${title}" نهائياً؟ لا يمكن التراجع عن هذا.`,
defaultDirTitle: 'مجلد المشروع الافتراضي',
defaultDirDesc: 'تبدأ الجلسات الجديدة في هذا المجلد ما لم تختر غيره. اتركه غير مضبوط لاستخدام مجلدك الرئيسي.',
- defaultDirUpdated: 'تم تحديث مجلد المشروع الافتراضي، ابدأ محادثة جديدة (Ctrl/⌘+N) ليطبق التغيير',
+ defaultDirUpdated: shortcut =>
+ `تم تحديث مجلد المشروع الافتراضي، ابدأ محادثة جديدة${shortcut ? ` (${shortcut})` : ''} ليطبق التغيير`,
defaultsTo: label => `الافتراضي هو ${label}.`,
change: 'تغيير',
choose: 'اختيار',
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index 4a6cd714e1e..a2159af3e6c 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -2259,8 +2259,8 @@ export const deOverrides = {
defaultDirTitle: 'Standard-Projektordner',
defaultDirDesc:
'Neue Sessions starten in diesem Ordner, sofern Sie keinen anderen wählen. Nicht festlegen, um Ihr Home-Verzeichnis zu verwenden.',
- defaultDirUpdated:
- 'Standard-Projektordner aktualisiert – starten Sie einen neuen Chat (Strg/⌘+N), damit er wirksam wird',
+ defaultDirUpdated: shortcut =>
+ `Standard-Projektordner aktualisiert – starten Sie einen neuen Chat${shortcut ? ` (${shortcut})` : ''}, damit er wirksam wird`,
defaultsTo: label => `Standardmäßig ${label}.`,
change: 'Ändern',
choose: 'Auswählen',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 71bda372ce4..8d2b1b0c1c0 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -1898,7 +1898,8 @@ export const en: Translations = {
defaultDirTitle: 'Default project directory',
defaultDirDesc:
'New sessions start in this folder unless you pick another. Leave it unset to use your home directory.',
- defaultDirUpdated: 'Default project directory updated — start a new chat (Ctrl/⌘+N) for it to take effect',
+ defaultDirUpdated: shortcut =>
+ `Default project directory updated — start a new chat${shortcut ? ` (${shortcut})` : ''} for it to take effect`,
defaultsTo: label => `Defaults to ${label}.`,
change: 'Change',
choose: 'Choose',
diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.ts
index bc5da139557..c8a596ee597 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -2245,8 +2245,8 @@ export const esOverrides = {
defaultDirTitle: 'Directorio de proyecto predeterminado',
defaultDirDesc:
'Las sesiones nuevas empiezan en esta carpeta salvo que elijas otra. Déjala sin definir para usar tu directorio de inicio.',
- defaultDirUpdated:
- 'Directorio de proyecto predeterminado actualizado; inicia un chat nuevo (Ctrl/⌘+N) para que el cambio surta efecto.',
+ defaultDirUpdated: shortcut =>
+ `Directorio de proyecto predeterminado actualizado; inicia un chat nuevo${shortcut ? ` (${shortcut})` : ''} para que el cambio surta efecto.`,
defaultsTo: label => `Predeterminado: ${label}.`,
change: 'Cambiar',
choose: 'Elegir',
diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.ts
index e88ba109cee..bc4eb55a6e8 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -2262,8 +2262,8 @@ export const frOverrides = {
defaultDirTitle: 'Répertoire de projet par défaut',
defaultDirDesc:
'Les nouvelles sessions commencent dans ce dossier sauf si vous en choisissez un autre. Laissez-le non défini pour utiliser votre répertoire personnel.',
- defaultDirUpdated:
- "Répertoire de projet par défaut mis à jour — commencez une nouvelle conversation (Ctrl/⌘+N) pour qu'il prenne effet",
+ defaultDirUpdated: shortcut =>
+ `Répertoire de projet par défaut mis à jour — commencez une nouvelle conversation${shortcut ? ` (${shortcut})` : ''} pour qu'il prenne effet`,
defaultsTo: label => `Par défaut : ${label}.`,
change: 'Modifier',
choose: 'Choisir',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 80f5285f391..9f56af501ae 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -1203,7 +1203,7 @@ export const jaOverrides = {
defaultDirTitle: 'デフォルトのプロジェクトディレクトリ',
defaultDirDesc:
'別のフォルダーを選択しない限り、新しいセッションはこのフォルダーで開始します。未設定の場合はホームディレクトリが使用されます。',
- defaultDirUpdated: 'デフォルトのプロジェクトディレクトリを更新しました',
+ defaultDirUpdated: () => 'デフォルトのプロジェクトディレクトリを更新しました',
defaultsTo: label => `デフォルト: ${label}。`,
change: '変更',
choose: '選択',
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index 7f6e5635f46..64a863c9534 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -1317,8 +1317,8 @@ export const ruOverrides = {
defaultDirTitle: 'Папка проекта по умолчанию',
defaultDirDesc:
'Новые сеансы начинаются в этой папке, если вы не выбрали другую. Оставьте пустым, чтобы использовать домашнюю директорию.',
- defaultDirUpdated:
- 'Папка проекта по умолчанию обновлена — начните новый чат (Ctrl/⌘+N), чтобы она вступила в силу',
+ defaultDirUpdated: shortcut =>
+ `Папка проекта по умолчанию обновлена — начните новый чат${shortcut ? ` (${shortcut})` : ''}, чтобы она вступила в силу`,
defaultsTo: label => `По умолчанию: ${label}.`,
change: 'Изменить',
choose: 'Выбрать',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 34e726f5cd0..e29eb4e486b 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -1716,7 +1716,7 @@ catalog: CatalogTranslations
autoArchiveFailed: string
defaultDirTitle: string
defaultDirDesc: string
- defaultDirUpdated: string
+ defaultDirUpdated: (shortcut: null | string) => string
defaultsTo: (label: string) => string
change: string
choose: string
diff --git a/apps/desktop/src/i18n/zh-hant_settings.ts b/apps/desktop/src/i18n/zh-hant_settings.ts
index 80a5201ed7e..542657055ca 100644
--- a/apps/desktop/src/i18n/zh-hant_settings.ts
+++ b/apps/desktop/src/i18n/zh-hant_settings.ts
@@ -1531,7 +1531,7 @@ export const zhHantSettings = {
autoArchiveFailed: '無法更新自動封存設定',
defaultDirTitle: '預設專案目錄',
defaultDirDesc: '新工作階段預設從此資料夾開始,除非您選擇其他目錄。留空則使用您的家目錄。',
- defaultDirUpdated: '預設專案目錄已更新',
+ defaultDirUpdated: () => '預設專案目錄已更新',
defaultsTo: label => `預設使用 ${label}。`,
change: '變更',
choose: '選擇',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 50eb542b0a4..6ce1a14d998 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -1879,7 +1879,7 @@ export const zhOverrides = {
autoArchiveFailed: '无法更新自动归档设置',
defaultDirTitle: '默认项目目录',
defaultDirDesc: '新会话默认从此文件夹开始,除非你选择其他目录。留空则使用你的 home 目录。',
- defaultDirUpdated: '默认项目目录已更新',
+ defaultDirUpdated: () => '默认项目目录已更新',
defaultsTo: label => `默认使用 ${label}。`,
change: '更改',
choose: '选择',
diff --git a/apps/desktop/src/lib/keybinds/actions.ts b/apps/desktop/src/lib/keybinds/actions.ts
index 879ba2a8c26..1486df7af69 100644
--- a/apps/desktop/src/lib/keybinds/actions.ts
+++ b/apps/desktop/src/lib/keybinds/actions.ts
@@ -11,16 +11,34 @@ import { isBrowserHostedDesktop, isMacPlatform } from '@/lib/platform'
export type KeybindCategory = 'composer' | 'profiles' | 'session' | 'navigation' | 'view'
-// A browser tab owns mod+n/t/w (new window, new tab, close tab). On macOS,
-// Control+Cmd keeps the letter without Option's text input; elsewhere
-// Control+Alt is AltGr and Alt+Shift letters are browser commands, so
-// modified function keys stand in.
-function sessionChord(letter: string, functionKey: string): string {
+// A browser tab acts on some chords before the page sees the keydown: new
+// window / tab / private window, close tab / window, reopen tab, and tab
+// cycling (Chrome, Edge and Firefox: Ctrl/⌘+N, T, W, their Shift forms,
+// Ctrl+Tab, Ctrl+PageUp/PageDown). Actions bound there get a browser default
+// instead: Alt + the same key on Windows and Linux (plain left Alt types no
+// character there; AltGr arrives as Ctrl+Alt or AltGraph), ⌃⌘ + the same key
+// on macOS (Option types a character). Alt+Tab is the OS window switcher, so
+// tab cycling takes ] and [. Native Desktop keeps the native chords.
+interface BrowserChords {
+ /** Omitted: the native default already reaches the page on macOS. */
+ mac?: string
+ other: string
+}
+
+type HostDefaults = Pick<KeybindActionMeta, 'defaults' | 'editableTargetPolicy'>
+
+function hostDefaults(native: readonly string[], browser: BrowserChords): HostDefaults {
if (!isBrowserHostedDesktop()) {
- return `mod+${letter}`
+ return { defaults: native }
+ }
+
+ if (isMacPlatform()) {
+ return { defaults: browser.mac ? [browser.mac] : native }
}
- return isMacPlatform() ? `mod+ctrl+${letter}` : `mod+shift+${functionKey}`
+ // Alt+letter has no Cmd/Ctrl, so it needs the editable-target opt-in to
+ // fire from the composer the way the native ⌘/Ctrl chord does.
+ return { defaults: [browser.other], editableTargetPolicy: 'modified' }
}
// The self-referential opener — bound + dispatched like any action, but shown in
@@ -129,13 +147,25 @@ export const KEYBIND_ACTIONS: readonly KeybindActionMeta[] = [
// `shift+n` was dropped from the defaults (#76185): a bare shifted letter
// hijacked normal typing — pressing uppercase N outside an input (or via an
// IME) created a new session unexpectedly.
- { id: 'session.new', category: 'session', defaults: [sessionChord('n', 'f7')] },
- { id: 'session.newTab', category: 'session', defaults: [sessionChord('t', 'f8')] },
- { id: 'session.newWindow', category: 'session', defaults: ['mod+shift+n'] },
+ { id: 'session.new', category: 'session', ...hostDefaults(['mod+n'], { mac: 'mod+ctrl+n', other: 'alt+n' }) },
+ { id: 'session.newTab', category: 'session', ...hostDefaults(['mod+t'], { mac: 'mod+ctrl+t', other: 'alt+t' }) },
+ {
+ id: 'session.newWindow',
+ category: 'session',
+ ...hostDefaults(['mod+shift+n'], { mac: 'mod+ctrl+shift+n', other: 'alt+shift+n' })
+ },
// ⌃Tab / ⌃⇧Tab — the universal tab-cycle chord. Literally Control, not Cmd
// (macOS reserves Cmd+Tab for app switching); see `ctrl` in combo.ts.
- { id: 'session.next', category: 'session', defaults: ['ctrl+tab', 'ctrl+pagedown'] },
- { id: 'session.prev', category: 'session', defaults: ['ctrl+shift+tab', 'ctrl+pageup'] },
+ {
+ id: 'session.next',
+ category: 'session',
+ ...hostDefaults(['ctrl+tab', 'ctrl+pagedown'], { mac: 'mod+ctrl+]', other: 'alt+]' })
+ },
+ {
+ id: 'session.prev',
+ category: 'session',
+ ...hostDefaults(['ctrl+shift+tab', 'ctrl+pageup'], { mac: 'mod+ctrl+[', other: 'alt+[' })
+ },
...SESSION_SLOT_ACTIONS,
{ id: 'session.focusSearch', category: 'session', defaults: ['mod+shift+f'] },
{ id: 'session.togglePin', category: 'session', defaults: [] },
@@ -209,14 +239,18 @@ export const KEYBIND_ACTIONS: readonly KeybindActionMeta[] = [
// so these stay on `ctrl` — distinct on macOS, folding to Ctrl elsewhere.
{ id: 'view.nextTerminal', category: 'view', defaults: ['ctrl+shift+down'] },
{ id: 'view.prevTerminal', category: 'view', defaults: ['ctrl+shift+up'] },
- { id: 'view.closeTerminal', category: 'view', defaults: ['ctrl+shift+w'] },
+ { id: 'view.closeTerminal', category: 'view', ...hostDefaults(['ctrl+shift+w'], { other: 'alt+shift+w' }) },
// ⌘\ — the backslash reads like a mirror line flipping the layout.
{ id: 'view.flipPanes', category: 'view', defaults: ['mod+\\'] },
// ⌘W closes the focused zone's active tab — its own tab strip (preview) or
// the tree tab (session tiles, files, terminal). The uncloseable workspace
// is a no-op. ⌘⇧T reopens the last closed tab where it was.
- { id: 'view.closeTab', category: 'view', defaults: [sessionChord('w', 'f9')] },
- { id: 'view.reopenTab', category: 'view', defaults: ['mod+shift+t'] },
+ { id: 'view.closeTab', category: 'view', ...hostDefaults(['mod+w'], { mac: 'mod+ctrl+w', other: 'alt+w' }) },
+ {
+ id: 'view.reopenTab',
+ category: 'view',
+ ...hostDefaults(['mod+shift+t'], { mac: 'mod+ctrl+shift+t', other: 'alt+shift+t' })
+ },
// ⌘F — open the find-in-page bar. `actionAllowedInInput` lets this action
// fire from inside a textarea / contenteditable (matches browser behavior
// so typing in the composer and pressing ⌘F focuses find, not 'f').
diff --git a/apps/desktop/src/lib/keybinds/browser-defaults.test.ts b/apps/desktop/src/lib/keybinds/browser-defaults.test.ts
index a03ef72b497..38b0fe4b8b2 100644
--- a/apps/desktop/src/lib/keybinds/browser-defaults.test.ts
+++ b/apps/desktop/src/lib/keybinds/browser-defaults.test.ts
@@ -1,20 +1,67 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+// Chords Chrome, Edge and Firefox act on before the page's keydown handler can
+// cancel them (new window/tab/private window, close tab/window, reopen tab,
+// tab cycling, quit), in the canonical form `comboFromEvent` emits per OS.
+// Alt+Tab is the OS window switcher off macOS.
+const BROWSER_RESERVED = {
+ mac: [
+ 'mod+n',
+ 'mod+t',
+ 'mod+w',
+ 'mod+q',
+ 'mod+shift+n',
+ 'mod+shift+t',
+ 'mod+shift+w',
+ 'mod+shift+p',
+ 'ctrl+tab',
+ 'ctrl+shift+tab'
+ ],
+ other: [
+ 'mod+n',
+ 'mod+t',
+ 'mod+w',
+ 'mod+shift+n',
+ 'mod+shift+t',
+ 'mod+shift+w',
+ 'mod+shift+p',
+ 'mod+shift+q',
+ 'mod+tab',
+ 'mod+shift+tab',
+ 'mod+pagedown',
+ 'mod+pageup',
+ 'alt+tab',
+ 'alt+shift+tab'
+ ]
+}
+
const shortcuts = [
- { id: 'session.new', native: 'mod+n', mac: 'mod+ctrl+n', other: 'mod+shift+f7' },
- { id: 'session.newTab', native: 'mod+t', mac: 'mod+ctrl+t', other: 'mod+shift+f8' },
- { id: 'view.closeTab', native: 'mod+w', mac: 'mod+ctrl+w', other: 'mod+shift+f9' }
+ { id: 'session.new', native: ['mod+n'], mac: 'mod+ctrl+n', other: 'alt+n' },
+ { id: 'session.newTab', native: ['mod+t'], mac: 'mod+ctrl+t', other: 'alt+t' },
+ { id: 'session.newWindow', native: ['mod+shift+n'], mac: 'mod+ctrl+shift+n', other: 'alt+shift+n' },
+ { id: 'session.next', native: ['ctrl+tab', 'ctrl+pagedown'], mac: 'mod+ctrl+]', other: 'alt+]' },
+ { id: 'session.prev', native: ['ctrl+shift+tab', 'ctrl+pageup'], mac: 'mod+ctrl+[', other: 'alt+[' },
+ { id: 'view.closeTab', native: ['mod+w'], mac: 'mod+ctrl+w', other: 'alt+w' },
+ { id: 'view.reopenTab', native: ['mod+shift+t'], mac: 'mod+ctrl+shift+t', other: 'alt+shift+t' },
+ // ⌃⇧W is literal Control on macOS, which the browser leaves to the page.
+ { id: 'view.closeTerminal', native: ['ctrl+shift+w'], mac: 'ctrl+shift+w', other: 'alt+shift+w' }
]
-// The keydown each platform's browser default arrives as: macOS reports Cmd and
-// Control separately; Windows and Linux report Control (or Meta) with Shift.
-const keydownFor = (combo: string, mac: boolean) => {
- const key = combo.split('+').at(-1)!
- const code = key.length === 1 ? `Key${key.toUpperCase()}` : key.toUpperCase()
-
- return mac
- ? [new KeyboardEvent('keydown', { key, code, metaKey: true, ctrlKey: true })]
- : [{ metaKey: true }, { ctrlKey: true }].map(m => new KeyboardEvent('keydown', { key: code, code, shiftKey: true, ...m }))
+// The keydown a real keyboard sends for a combo: macOS reports Cmd (`mod`)
+// and Control separately; Windows and Linux report the key with Alt held.
+function keydownFor(combo: string): KeyboardEvent {
+ const parts = combo.split('+')
+ const key = parts.pop()!
+ const code = /^[a-z]$/.test(key) ? `Key${key.toUpperCase()}` : key === ']' ? 'BracketRight' : 'BracketLeft'
+
+ return new KeyboardEvent('keydown', {
+ altKey: parts.includes('alt'),
+ code,
+ ctrlKey: parts.includes('ctrl'),
+ key,
+ metaKey: parts.includes('mod'),
+ shiftKey: parts.includes('shift')
+ })
}
const setPlatform = (value: string) => Object.defineProperty(navigator, 'platform', { configurable: true, value })
@@ -31,18 +78,55 @@ afterEach(() => {
localStorage.clear()
})
-describe('browser session shortcuts', () => {
- describe.each([['macOS', 'MacIntel'], ['Windows and Linux', 'Win32']])('on %s', (_, platform) => {
+describe('browser-hosted shortcut defaults', () => {
+ describe.each([
+ ['macOS', 'MacIntel'],
+ ['Windows and Linux', 'Win32']
+ ])('on %s', (_, platform) => {
const mac = platform === 'MacIntel'
- it.each(['webapp', 'authenticated', 'bridge', 'native'])(
- 'resolves defaults before the store starts in the %s host',
+ it('ships no default the browser takes first, and leaves native defaults alone', async () => {
+ setPlatform(platform)
+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'
+ const browser = await import('./actions')
+ const { canonicalizeCombo } = await import('./combo')
+ const reserved = new Set(BROWSER_RESERVED[mac ? 'mac' : 'other'])
+
+ const offenders = browser
+ .allKeybindActions()
+ .flatMap(action => action.defaults.map(combo => `${action.id}=${canonicalizeCombo(combo)}`))
+ .filter(entry => reserved.has(entry.split('=')[1]))
+
+ expect(offenders).toEqual([])
+
+ delete window.document.documentElement.dataset.hermesDesktopHost
+ vi.resetModules()
+ const native = await import('./actions')
+
+ for (const shortcut of shortcuts) {
+ expect(native.keybindAction(shortcut.id)?.defaults).toEqual(shortcut.native)
+ }
+
+ const changed = native.KEYBIND_ACTIONS.filter(
+ action => JSON.stringify(action.defaults) !== JSON.stringify(browser.keybindAction(action.id)?.defaults)
+ ).map(action => action.id)
+
+ expect(changed.sort()).toEqual(
+ shortcuts
+ .filter(shortcut => !(mac && shortcut.mac === shortcut.native[0]))
+ .map(shortcut => shortcut.id)
+ .sort()
+ )
+ })
+
+ it.each(['webapp', 'authenticated', 'bridge'])(
+ 'resolves browser defaults before the store starts in the %s host, and a real keydown dispatches them',
async host => {
setPlatform(platform)
if (host === 'bridge') {
window.document.documentElement.dataset.hermesDesktopHost = 'browser'
- } else if (host !== 'native') {
+ } else {
vi.stubGlobal('hermesDesktop', undefined)
vi.stubGlobal(
host === 'webapp' ? '__HERMES_UI_SURFACE__' : '__HERMES_AUTH_REQUIRED__',
@@ -54,23 +138,25 @@ describe('browser session shortcuts', () => {
const { $comboIndex, bindingsFor, conflictsFor, resetBinding, setBinding } = await import('@/store/keybinds')
for (const shortcut of shortcuts) {
- const expected = host === 'native' ? shortcut.native : mac ? shortcut.mac : shortcut.other
+ const expected = mac ? shortcut.mac : shortcut.other
expect(bindingsFor(shortcut.id)).toEqual([expected])
expect(actionAllowedInInput(shortcut.id, expected)).toBe(true)
expect(conflictsFor(shortcut.id, expected)).toEqual([])
- if (host !== 'native') {
- expect($comboIndex.get().has(shortcut.native)).toBe(false)
+ for (const native of shortcut.native.filter(combo => combo !== expected)) {
+ expect($comboIndex.get().has(native)).toBe(false)
+ }
- if (mac) {
- expect(formatCombo(expected)).toBe(`⌃⌘${shortcut.native.at(-1)!.toUpperCase()}`)
- }
+ if (mac && expected.startsWith('mod+ctrl+')) {
+ expect(formatCombo(expected).startsWith('⌃⌘')).toBe(true)
+ }
- for (const event of keydownFor(expected, mac)) {
- expect($comboIndex.get().get(comboFromEvent(event)!)).toEqual([shortcut.id])
- }
+ if (!mac) {
+ expect(formatCombo(expected).startsWith('Alt+')).toBe(true)
}
+ expect($comboIndex.get().get(comboFromEvent(keydownFor(expected))!)).toEqual([shortcut.id])
+
setBinding(shortcut.id, ['mod+shift+f6'])
expect(bindingsFor(shortcut.id)).toEqual(['mod+shift+f6'])
resetBinding(shortcut.id)
@@ -81,19 +167,23 @@ describe('browser session shortcuts', () => {
})
it('preserves saved remaps and explicit unbinding across a browser reload', async () => {
+ setPlatform('Win32')
window.document.documentElement.dataset.hermesDesktopHost = 'browser'
- localStorage.setItem('hermes.desktop.keybinds', JSON.stringify({
- 'session.new': ['mod+shift+f6'],
- 'session.newTab': [],
- 'view.closeTab': ['mod+w']
- }))
+ localStorage.setItem(
+ 'hermes.desktop.keybinds',
+ JSON.stringify({
+ 'session.new': ['mod+shift+f6'],
+ 'session.newTab': [],
+ 'view.closeTab': ['mod+w']
+ })
+ )
const { bindingsFor, resetAllBindings } = await import('@/store/keybinds')
expect(bindingsFor('session.new')).toEqual(['mod+shift+f6'])
expect(bindingsFor('session.newTab')).toEqual([])
expect(bindingsFor('view.closeTab')).toEqual(['mod+w'])
resetAllBindings()
- expect(bindingsFor('session.new')).toEqual(['mod+shift+f7'])
+ expect(bindingsFor('session.new')).toEqual(['alt+n'])
expect(JSON.parse(localStorage.getItem('hermes.desktop.keybinds')!)).toEqual({})
})
})
diff --git a/apps/desktop/src/lib/keybinds/browser-hints.test.tsx b/apps/desktop/src/lib/keybinds/browser-hints.test.tsx
index 643eafe4f88..f9505649c1d 100644
--- a/apps/desktop/src/lib/keybinds/browser-hints.test.tsx
+++ b/apps/desktop/src/lib/keybinds/browser-hints.test.tsx
@@ -38,17 +38,23 @@ it('renders the resolved browser binding in the first-run tip, tooltips and sett
</I18nProvider>
)
- expect(within(view.getByRole('status')).getByText('F7')).toBeTruthy()
+ const status = () => view.getByRole('status').textContent
+ expect(status()).toContain('Alt')
+ expect(within(view.getByRole('status')).getByText('N')).toBeTruthy()
const labels = within(view.getByTestId('shortcut-labels'))
+ const labelText = view.getByTestId('shortcut-labels').textContent
- for (const key of ['F7', 'F8', 'F9']) {
- expect(labels.getByText(new RegExp(`${key}$`))).toBeTruthy()
+ for (const key of ['N', 'T', 'W']) {
+ expect(labelText).toContain(`Alt+${key}`)
}
+ expect(labelText).not.toContain('Ctrl')
+
const search = view.getByRole('textbox', { name: 'Search shortcuts…' })
fireEvent.change(search, { target: { value: 'session.new' } })
const row = within(view.getByTestId('settings')).getByText('New session').parentElement!
- expect(within(row).getByText('F7')).toBeTruthy()
+ expect(within(row).getByText('Alt')).toBeTruthy()
+ expect(within(row).getByText('N')).toBeTruthy()
expect(within(row).queryByRole('button', { name: 'Reset to default' })).toBeNull()
act(() => setBinding('session.new', ['mod+shift+f6']))
@@ -56,9 +62,9 @@ it('renders the resolved browser binding in the first-run tip, tooltips and sett
expect(labels.getByText(/F6$/)).toBeTruthy()
expect(within(row).getByText('F6')).toBeTruthy()
fireEvent.click(within(row).getByRole('button', { name: 'Reset to default' }))
- expect(within(row).getByText('F7')).toBeTruthy()
+ expect(within(row).getByText('N')).toBeTruthy()
act(() => setBinding('session.new', []))
expect(view.getByRole('status').querySelector('kbd')).toBeNull()
- expect(labels.queryByText(/F7$/)).toBeNull()
+ expect(view.getByTestId('shortcut-labels').textContent).not.toContain('Alt+N')
})
diff --git a/apps/desktop/src/lib/keybinds/combo.ts b/apps/desktop/src/lib/keybinds/combo.ts
index be67f2a4f87..8f37437d0a8 100644
--- a/apps/desktop/src/lib/keybinds/combo.ts
+++ b/apps/desktop/src/lib/keybinds/combo.ts
@@ -139,6 +139,13 @@ export function comboFromEvent(event: KeyboardEvent): string | null {
return null
}
+ // AltGr typing a character. Windows reports it as Ctrl+Alt; Linux can
+ // report Alt with AltGraph but no Ctrl, which must not read as a plain
+ // Alt chord (the browser-tab defaults are Alt+letter off macOS).
+ if (event.altKey && !event.ctrlKey && !event.metaKey && event.getModifierState?.('AltGraph')) {
+ return null
+ }
+
const base = baseKeyFromEventKey(event.key, event.shiftKey) ?? baseKeyFromCode(event.code)
if (!base) {