The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): keep session shortcuts clear of browser commands
dokterdok968d55b5260e
diff --git a/apps/desktop/src/app/hooks/use-keybinds-browser.test.tsx b/apps/desktop/src/app/hooks/use-keybinds-browser.test.tsxnew file mode 100644index 00000000000..1e8f91aeb5a--- /dev/null+++ b/apps/desktop/src/app/hooks/use-keybinds-browser.test.tsx@@ -0,0 +1,115 @@+import { act, cleanup, renderHook } from '@testing-library/react'+import type { ReactNode } from 'react'+import { MemoryRouter } from 'react-router'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++const { closeTab } = vi.hoisted(() => ({ closeTab: vi.fn() }))++vi.mock('@/app/chat/close-tab', () => ({ closeActiveTab: closeTab }))+vi.mock('@/themes/context', () => ({+ useTheme: () => ({ resolvedMode: 'light', setMode: vi.fn() })+}))++beforeEach(() => {+ vi.resetModules()+ localStorage.clear()+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+ closeTab.mockClear()+})++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ window.document.body.replaceChildren()+ delete window.document.documentElement.dataset.hermesDesktopHost+})++async function mountKeybinds(inTerminal = false) {+ const { useKeybinds } = await import('./use-keybinds')++ const deps = {+ archiveSelectedSession: vi.fn(),+ openNewSessionTab: vi.fn(),+ requestGateway: vi.fn(),+ startFreshSession: vi.fn(),+ toggleCommandCenter: vi.fn(),+ toggleSelectedPin: vi.fn()+ }++ renderHook(() => useKeybinds(deps), {+ wrapper: ({ children }: { children: ReactNode }) => <MemoryRouter>{children}</MemoryRouter>+ })++ const scope = window.document.createElement('div')++ if (inTerminal) {+ scope.dataset.interactiveTerminal = ''+ }++ const input = window.document.createElement('textarea')+ scope.append(input)+ window.document.body.append(scope)+ input.focus()++ const press = (init: KeyboardEventInit) => {+ const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ctrlKey: true, ...init })+ act(() => { input.dispatchEvent(event) })++ return event+ }++ return { deps, press }+}++it('dispatches browser defaults and remaps from text fields, leaving browser keys and AltGr alone', async () => {+ const { deps, press } = await mountKeybinds()+ const { setBinding } = await import('@/store/keybinds')++ for (const key of ['n', 't', 'w']) {+ expect(press({ key, code: `Key${key.toUpperCase()}` }).defaultPrevented).toBe(false)+ }++ // 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']]) {+ const event = press({ key, code, altKey: true, ctrlKey, modifierAltGraph: true })+ expect(event.getModifierState('AltGraph')).toBe(true)+ expect(event.defaultPrevented).toBe(false)+ }+ }++ expect(deps.startFreshSession).not.toHaveBeenCalled()+ 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)+ }++ expect(deps.startFreshSession).toHaveBeenCalledOnce()+ expect(deps.openNewSessionTab).toHaveBeenCalledOnce()+ expect(closeTab).toHaveBeenCalledOnce()++ act(() => setBinding('session.new', ['mod+shift+f6']))+ expect(press({ key: 'F7', code: 'F7', shiftKey: true }).defaultPrevented).toBe(false)+ expect(press({ key: 'F6', code: 'F6', shiftKey: true }).defaultPrevented).toBe(true)+ expect(deps.startFreshSession).toHaveBeenCalledTimes(2)+})++it('dispatches the macOS ⌃⌘ browser defaults, including ⌃⌘W over an interactive terminal', async () => {+ vi.spyOn(navigator, 'platform', 'get').mockReturnValue('MacIntel')+ const { deps, press } = await mountKeybinds(true)++ for (const key of ['n', 't', 'w']) {+ expect(press({ key, code: `Key${key.toUpperCase()}`, metaKey: true, ctrlKey: false }).defaultPrevented).toBe(false)+ }++ for (const key of ['n', 't', 'w']) {+ expect(press({ key, code: `Key${key.toUpperCase()}`, metaKey: true }).defaultPrevented).toBe(true)+ }++ expect(deps.startFreshSession).toHaveBeenCalledOnce()+ expect(deps.openNewSessionTab).toHaveBeenCalledOnce()+ expect(closeTab).toHaveBeenCalledOnce()+})diff --git a/apps/desktop/src/app/hooks/use-keybinds.ts b/apps/desktop/src/app/hooks/use-keybinds.tsindex 79c2b818c0d..18c351535b0 100644--- a/apps/desktop/src/app/hooks/use-keybinds.ts+++ b/apps/desktop/src/app/hooks/use-keybinds.ts@@ -132,6 +132,10 @@ export interface KeybindRuntimeDeps {* return value (void, a navigate() promise, …) means it ran. */type HandlerMap = Record<string, () => unknown>+function hasWordEraseModifier(event: KeyboardEvent): boolean {+ return IS_MAC ? event.metaKey && !event.ctrlKey : event.ctrlKey+}+// Mount once near the top of the app. Owns the single global keydown listener// for every rebindable hotkey: it runs the matched action, or — while capture// mode is active (edit overlay / panel rebind) — records the pressed combo.@@ -583,11 +587,12 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {// dispatcher anyway, plus a chord rebound onto another key with the// same bare shape. Returning without preventDefault hands the key to// xterm, whose data handler writes the ^W byte to the PTY. Read-only- // agent mirrors carry only [data-terminal], so they keep close.+ // agent mirrors carry only [data-terminal], so they keep close. A+ // browser tab's ⌃⌘W is the close chord itself, not ^W.if (actionId === 'view.closeTab' &&event.key.toLowerCase() === 'w' &&- (IS_MAC ? event.metaKey : event.ctrlKey) &&+ hasWordEraseModifier(event) &&!event.altKey &&!event.shiftKey &&isFocusWithin('[data-interactive-terminal]')diff --git a/apps/desktop/src/lib/keybinds/actions.ts b/apps/desktop/src/lib/keybinds/actions.tsindex 97c0a666b99..879ba2a8c26 100644--- a/apps/desktop/src/lib/keybinds/actions.ts+++ b/apps/desktop/src/lib/keybinds/actions.ts@@ -7,10 +7,22 @@import { registry } from '@/contrib/registry'import type { Contribution } from '@/contrib/types'-import { isMacPlatform } from '@/lib/platform'+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 {+ if (!isBrowserHostedDesktop()) {+ return `mod+${letter}`+ }++ return isMacPlatform() ? `mod+ctrl+${letter}` : `mod+shift+${functionKey}`+}+// The self-referential opener — bound + dispatched like any action, but shown in// the panel subtitle (not as its own row).export const KEYBIND_PANEL_ACTION = 'keybinds.openPanel'@@ -116,10 +128,9 @@ export const KEYBIND_ACTIONS: readonly KeybindActionMeta[] = [// ── Session ──────────────────────────────────────────────────────────────// `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. The deliberate ⌘/Ctrl+N chord- // stays; users who liked ⇧N can rebind it in the panel.- { id: 'session.new', category: 'session', defaults: ['mod+n'] },- { id: 'session.newTab', category: 'session', defaults: ['mod+t'] },+ // 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'] },// ⌃Tab / ⌃⇧Tab — the universal tab-cycle chord. Literally Control, not Cmd// (macOS reserves Cmd+Tab for app switching); see `ctrl` in combo.ts.@@ -204,7 +215,7 @@ export const KEYBIND_ACTIONS: readonly KeybindActionMeta[] = [// ⌘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: ['mod+w'] },+ { id: 'view.closeTab', category: 'view', defaults: [sessionChord('w', 'f9')] },{ id: 'view.reopenTab', category: 'view', defaults: ['mod+shift+t'] },// ⌘F — open the find-in-page bar. `actionAllowedInInput` lets this action// fire from inside a textarea / contenteditable (matches browser behaviordiff --git a/apps/desktop/src/lib/keybinds/browser-defaults.test.ts b/apps/desktop/src/lib/keybinds/browser-defaults.test.tsnew file mode 100644index 00000000000..a03ef72b497--- /dev/null+++ b/apps/desktop/src/lib/keybinds/browser-defaults.test.ts@@ -0,0 +1,99 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++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' }+]++// 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 }))+}++const setPlatform = (value: string) => Object.defineProperty(navigator, 'platform', { configurable: true, value })++beforeEach(() => {+ vi.resetModules()+ localStorage.clear()+})++afterEach(() => {+ delete window.document.documentElement.dataset.hermesDesktopHost+ setPlatform('')+ vi.unstubAllGlobals()+ localStorage.clear()+})++describe('browser session shortcuts', () => {+ 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',+ async host => {+ setPlatform(platform)++ if (host === 'bridge') {+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+ } else if (host !== 'native') {+ vi.stubGlobal('hermesDesktop', undefined)+ vi.stubGlobal(+ host === 'webapp' ? '__HERMES_UI_SURFACE__' : '__HERMES_AUTH_REQUIRED__',+ host === 'webapp' ? 'webapp' : true+ )+ }++ const { actionAllowedInInput, comboFromEvent, formatCombo } = await import('./combo')+ 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+ 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)++ if (mac) {+ expect(formatCombo(expected)).toBe(`⌃⌘${shortcut.native.at(-1)!.toUpperCase()}`)+ }++ for (const event of keydownFor(expected, mac)) {+ expect($comboIndex.get().get(comboFromEvent(event)!)).toEqual([shortcut.id])+ }+ }++ setBinding(shortcut.id, ['mod+shift+f6'])+ expect(bindingsFor(shortcut.id)).toEqual(['mod+shift+f6'])+ resetBinding(shortcut.id)+ expect(bindingsFor(shortcut.id)).toEqual([expected])+ }+ }+ )+ })++ it('preserves saved remaps and explicit unbinding across a browser reload', async () => {+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+ 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(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.tsxnew file mode 100644index 00000000000..643eafe4f88--- /dev/null+++ b/apps/desktop/src/lib/keybinds/browser-hints.test.tsx@@ -0,0 +1,64 @@+import { act, cleanup, fireEvent, render, within } from '@testing-library/react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++beforeEach(() => {+ vi.resetModules()+ localStorage.clear()+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+})++afterEach(() => {+ cleanup()+ window.document.body.replaceChildren()+ delete window.document.documentElement.dataset.hermesDesktopHost+})++it('renders the resolved browser binding in the first-run tip, tooltips and settings, including remaps', async () => {+ const { TipBubble } = await import('@/components/tips/tip-bubble')+ const { TipKeybindLabel } = await import('@/components/ui/tooltip')+ const { KeybindSettings } = await import('@/app/settings/keybind-settings')+ const { I18nProvider } = await import('@/i18n')+ const { TIP_CATALOG } = await import('@/lib/tips/catalog')+ const { setBinding } = await import('@/store/keybinds')+ const tip = TIP_CATALOG.find(entry => entry.id === 'new-session')!+ const anchor = window.document.createElement('button')+ window.document.body.append(anchor)++ const view = render(+ <I18nProvider configClient={null} initialLocale="en">+ <TipBubble anchor={anchor} keybind={tip.keybind} onClose={() => {}} side="right" text="Start a new session" />+ <div data-testid="shortcut-labels">+ <TipKeybindLabel actionId="session.new" />+ <TipKeybindLabel actionId="session.newTab" />+ <TipKeybindLabel actionId="view.closeTab" />+ </div>+ <div data-testid="settings">+ <KeybindSettings subpage="shortcuts" />+ </div>+ </I18nProvider>+ )++ expect(within(view.getByRole('status')).getByText('F7')).toBeTruthy()+ const labels = within(view.getByTestId('shortcut-labels'))++ for (const key of ['F7', 'F8', 'F9']) {+ expect(labels.getByText(new RegExp(`${key}$`))).toBeTruthy()+ }++ 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).queryByRole('button', { name: 'Reset to default' })).toBeNull()++ act(() => setBinding('session.new', ['mod+shift+f6']))+ expect(within(view.getByRole('status')).getByText('F6')).toBeTruthy()+ 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()++ act(() => setBinding('session.new', []))+ expect(view.getByRole('status').querySelector('kbd')).toBeNull()+ expect(labels.queryByText(/F7$/)).toBeNull()+})diff --git a/apps/desktop/src/lib/keybinds/combo.ts b/apps/desktop/src/lib/keybinds/combo.tsindex ad4fe12b2ee..be67f2a4f87 100644--- a/apps/desktop/src/lib/keybinds/combo.ts+++ b/apps/desktop/src/lib/keybinds/combo.ts@@ -231,6 +231,11 @@ export function comboTokens(combo: string): string[] {const parts = combo.split('+')const base = parts.pop() ?? ''+ // Canonical order keeps `mod` first; macOS writes Control before Command (⌃⌘N).+ if (IS_MAC && parts[0] === 'mod' && parts[1] === 'ctrl') {+ parts.splice(0, 2, 'ctrl', 'mod')+ }+return [...parts.map(formatModifierToken), labelForBase(base)]}