Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): add configurable action shortcuts (#1708)

Call Whitee0c881b83b60
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 1d28fd0bb..28e9510f9 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -34,6 +34,7 @@ import { SettingsLogsPage } from './components/settings/SettingsLogsPage';
import { SettingsMessagingPage } from './components/settings/SettingsMessagingPage';
import { SettingsPlatformsPage } from './components/settings/SettingsPlatformsPage';
import { SettingsServicePage } from './components/settings/SettingsServicePage';
+import { SettingsShortcutsPage } from './components/settings/SettingsShortcutsPage';
import { SettingsLayout } from './components/settings/SettingsLayout';
import { StatusProvider } from './context/StatusProvider';
import { ApiProvider, useApi, ApiError } from './context/ApiContext';
@@ -751,6 +752,7 @@ const router = createBrowserRouter(
<Route index element={null} />
<Route path="appearance" element={<Navigate to="/settings/replies" replace />} />
<Route path="account" element={<Navigate to="/settings/replies" replace />} />
+ <Route path="shortcuts" element={<SettingsShortcutsPage />} />
<Route path="service" element={<SettingsServicePage />} />
<Route path="platforms" element={<SettingsPlatformsPage />} />
<Route path="platforms/groups" element={<ChannelList isPage />} />
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index 9992449db..570fad6e7 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -1,7 +1,7 @@
/* @vitest-environment jsdom */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';
import type { ReactNode } from 'react';
@@ -98,7 +98,9 @@ vi.mock('./workbench/NewSessionSheet', () => ({
vi.mock('./workbench/WorkbenchSidebar', () => ({
WorkbenchSidebar: () => <div data-testid="workbench-sidebar" />,
}));
-vi.mock('./workbench/search/SearchPalette', () => ({ SearchPalette: () => null }));
+vi.mock('./workbench/search/SearchPalette', () => ({
+ SearchPalette: ({ open }: { open: boolean }) => <div data-testid="search-palette" data-open={String(open)} />,
+}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
@@ -147,6 +149,39 @@ describe('AppShell setup recovery', () => {
});
});
+describe('AppShell search shortcut ownership', () => {
+ it('yields a consumed search chord to the focused surface', async () => {
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route index element={<div data-testid="workbench-surface" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+ await screen.findByTestId('workbench-surface');
+
+ const consumed = new KeyboardEvent('keydown', {
+ key: 'k',
+ metaKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ consumed.preventDefault();
+ act(() => window.dispatchEvent(consumed));
+ expect(screen.getByTestId('search-palette').getAttribute('data-open')).toBe('false');
+
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', {
+ key: 'k',
+ metaKey: true,
+ bubbles: true,
+ cancelable: true,
+ })));
+ expect(screen.getByTestId('search-palette').getAttribute('data-open')).toBe('true');
+ });
+});
+
describe('AppShell workbench sidebar', () => {
// The sidebar's own container is hidden below md by CSS, which does not
// unmount it. Its consumers fetch the inbox feed and the project tree on
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 1db8749cb..25aea620c 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -204,11 +204,11 @@ export const AppShell: React.FC = () => {
}).catch(() => {});
}, [api, capabilities.can_manage_instance, i18n]);
- // Global ⌘K / Ctrl+K toggles the message-search palette. Intercept the chord
- // everywhere (it's a deliberate command, so it wins even from the composer);
- // the palette's own input/Esc/arrow handling takes over once it is open.
+ // Global ⌘K / Ctrl+K toggles the message-search palette. A closer surface may
+ // consume the same user-configured chord first; otherwise search owns it.
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
+ if (e.defaultPrevented) return;
if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {
e.preventDefault();
setSearchOpen((prev) => !prev);
diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsx
index a516be8d2..eb51d2522 100644
--- a/ui/src/components/apps/AppWindow.tsx
+++ b/ui/src/components/apps/AppWindow.tsx
@@ -262,6 +262,7 @@ export const AppWindow: React.FC<{
// and React/the browser moves focus out automatically.
inert={win.minimized}
tabIndex={-1}
+ onKeyDown={annotationHost?.annotation.handleShortcutKeyDown}
onPointerDownCapture={() => {
// Capture runs before toolbar controls stop propagation, so every pointer
// activation claims the window without stealing DOM focus from the target.
diff --git a/ui/src/components/apps/ShowPageRoute.tsx b/ui/src/components/apps/ShowPageRoute.tsx
index c36c9734f..9daff6010 100644
--- a/ui/src/components/apps/ShowPageRoute.tsx
+++ b/ui/src/components/apps/ShowPageRoute.tsx
@@ -101,13 +101,17 @@ const MobileShowPage: React.FC<{ sessionId: string }> = ({ sessionId }) => {
state: annotationState,
setIframe,
handleIframeLoad,
+ handleShortcutKeyDown,
enable: enableAnnotation,
disable: disableAnnotation,
setMode: setAnnotationMode,
} = useShowPageAnnotation(src);
return (
- <div className="flex h-full min-h-0 w-full flex-col overflow-hidden bg-background pb-[env(safe-area-inset-bottom)] pt-[env(safe-area-inset-top)]">
+ <div
+ className="flex h-full min-h-0 w-full flex-col overflow-hidden bg-background pb-[env(safe-area-inset-bottom)] pt-[env(safe-area-inset-top)]"
+ onKeyDown={handleShortcutKeyDown}
+ >
<header className="flex shrink-0 items-center gap-3 border-b border-border bg-surface/70 px-4 py-2.5 backdrop-blur">
<Button
type="button"
diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsx
index beeedee4e..d3b40b48f 100644
--- a/ui/src/components/apps/WindowLayer.tsx
+++ b/ui/src/components/apps/WindowLayer.tsx
@@ -128,6 +128,7 @@ export const WindowLayer: React.FC = () => {
// so its Ctrl control-chars (^W/^M) reach the shell (see inTerminalSurface).
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
+ if (e.defaultPrevented) return;
if (!(e.metaKey || e.ctrlKey) || e.altKey) return;
const active = document.activeElement;
if (e.ctrlKey && !e.metaKey && inTerminalSurface(active)) return;
@@ -153,6 +154,7 @@ export const WindowLayer: React.FC = () => {
// keep Option+W for character entry — consistent with the Alt+1-9 chord.
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
+ if (e.defaultPrevented) return;
if (e.code !== 'KeyW' || !e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return;
const active = document.activeElement;
if (inTextEntrySurface(active)) return;
@@ -191,6 +193,7 @@ export const WindowLayer: React.FC = () => {
// for character entry; the Windows layer is desktop-only.
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
+ if (e.defaultPrevented) return;
if (!isDesktopViewport()) return;
const index = dockIndexFromShortcut(e);
const target = e.target instanceof Element ? e.target : document.activeElement;
diff --git a/ui/src/components/apps/windowChords.test.ts b/ui/src/components/apps/windowChords.test.ts
index 67d067d1c..a846cd876 100644
--- a/ui/src/components/apps/windowChords.test.ts
+++ b/ui/src/components/apps/windowChords.test.ts
@@ -123,6 +123,17 @@ describe('bindFrameChord', () => {
frameWindow.emit('keydown', matching);
expect(run).toHaveBeenCalledTimes(1);
expect(matching.preventDefault).toHaveBeenCalledTimes(1);
+
+ const alreadyOwned = {
+ code: 'KeyD',
+ metaKey: true,
+ shiftKey: true,
+ defaultPrevented: true,
+ preventDefault: vi.fn(),
+ };
+ frameWindow.emit('keydown', alreadyOwned);
+ expect(run).toHaveBeenCalledTimes(1);
+ expect(alreadyOwned.preventDefault).not.toHaveBeenCalled();
expect(seen[0]).toBe(active); // the predicate sees the frame's realm, not ours
const other = { code: 'KeyD', metaKey: true, shiftKey: false, preventDefault: vi.fn() };
diff --git a/ui/src/components/apps/windowChords.ts b/ui/src/components/apps/windowChords.ts
index 59fbb90ac..59b9c1723 100644
--- a/ui/src/components/apps/windowChords.ts
+++ b/ui/src/components/apps/windowChords.ts
@@ -42,6 +42,7 @@ export function bindFrameChord(
run: () => void,
): () => void {
const onKeyDown = (event: KeyboardEvent) => {
+ if (event.defaultPrevented) return;
let active: Element | null = null;
try {
active = iframe.contentDocument?.activeElement ?? null;
diff --git a/ui/src/components/apps/windowLayerInventory.test.tsx b/ui/src/components/apps/windowLayerInventory.test.tsx
index 8f3e470e4..70375db3a 100644
--- a/ui/src/components/apps/windowLayerInventory.test.tsx
+++ b/ui/src/components/apps/windowLayerInventory.test.tsx
@@ -7,7 +7,7 @@
// what the document renders decides what is fetched.
import { createInstance } from 'i18next';
-import { cleanup, render } from '@testing-library/react';
+import { act, cleanup, render, screen } from '@testing-library/react';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -17,6 +17,16 @@ import type { WindowInstance } from '../../context/WindowManagerContext';
import { WindowLayer } from './WindowLayer';
const windowsRef = { current: [] as WindowInstance[] };
+const windowManager = vi.hoisted(() => ({
+ close: vi.fn(),
+ focus: vi.fn(),
+ minimize: vi.fn(),
+ openApp: vi.fn(),
+ restore: vi.fn(),
+ setParams: vi.fn(),
+ setTitle: vi.fn(),
+ confirmClose: vi.fn(() => true),
+}));
vi.mock('../../context/DockContext', () => ({
useDock: () => ({ order: [], pins: [] }),
@@ -25,14 +35,7 @@ vi.mock('../../context/DockContext', () => ({
vi.mock('../../context/WindowManagerContext', () => ({
useWindowManager: () => ({
windows: windowsRef.current,
- close: vi.fn(),
- focus: vi.fn(),
- minimize: vi.fn(),
- openApp: vi.fn(),
- restore: vi.fn(),
- setParams: vi.fn(),
- setTitle: vi.fn(),
- confirmClose: () => true,
+ ...windowManager,
}),
}));
@@ -43,7 +46,7 @@ vi.mock('../../context/StandaloneAppTabContext', () => ({
// Every window body is an app of its own (iframe, terminal, editor); the layer's
// own fetch decision is what is under test, so the frame is stubbed out.
vi.mock('./AppWindow', () => ({
- AppWindow: () => <div data-testid="app-window" />,
+ AppWindow: () => <button type="button" data-testid="app-window" data-window-id="win_1" />,
}));
vi.mock('../workbench/ShowPageAnnotationHost', () => ({
ShowPageAnnotationHost: ({ children }: { children: React.ReactNode }) => <>{children}</>,
@@ -104,6 +107,7 @@ describe('WindowLayer show-pages inventory', () => {
api.getSessionResult.mockResolvedValue({ status: null, session: null });
api.connectWorkbenchEvents.mockReset();
api.connectWorkbenchEvents.mockReturnValue(vi.fn());
+ Object.values(windowManager).forEach((mock) => mock.mockClear());
});
afterEach(() => {
@@ -123,4 +127,23 @@ describe('WindowLayer show-pages inventory', () => {
await vi.waitFor(() => expect(api.getShowPages).toHaveBeenCalledTimes(1));
});
+
+ it('yields window chords already consumed by the focused surface', async () => {
+ windowsRef.current = [appWindow()];
+ renderLayer();
+ const windowRoot = await screen.findByTestId('app-window');
+ windowRoot.focus();
+
+ const consumed = new KeyboardEvent('keydown', {
+ key: 'm',
+ code: 'KeyM',
+ metaKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ consumed.preventDefault();
+ act(() => window.dispatchEvent(consumed));
+
+ expect(windowManager.minimize).not.toHaveBeenCalled();
+ });
});
diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsx
index 17c101026..372fe1bf3 100644
--- a/ui/src/components/settings/SettingsLayout.test.tsx
+++ b/ui/src/components/settings/SettingsLayout.test.tsx
@@ -70,6 +70,7 @@ const renderLayout = (path: string) => render(
<Route path="/settings" element={<SettingsLayoutHarness />}>
<Route path="models" element={<div>models-body</div>} />
<Route path="replies" element={<div>replies-body</div>} />
+ <Route path="shortcuts" element={<div>shortcuts-body</div>} />
<Route path="service" element={<div>service-body</div>} />
<Route path="platforms" element={<div>platforms-body</div>} />
<Route path="platforms/users" element={<div>users-body</div>} />
@@ -260,6 +261,7 @@ describe('SettingsLayout', () => {
expect(screen.getByText('replies-body')).toBeTruthy();
expect(screen.getByRole('link', { name: 'settings.sections.replies' })).toBeTruthy();
+ expect(screen.getByRole('link', { name: 'settings.sections.shortcuts' })).toBeTruthy();
expect(screen.getByRole('link', { name: 'settings.sections.access' })).toBeTruthy();
expect(screen.queryByRole('link', { name: 'settings.sections.service' })).toBeNull();
expect(api.getConfig).not.toHaveBeenCalled();
diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsx
index ab43c33b1..836126c10 100644
--- a/ui/src/components/settings/SettingsLayout.tsx
+++ b/ui/src/components/settings/SettingsLayout.tsx
@@ -8,6 +8,7 @@ import {
Cpu,
Globe,
Hash,
+ Keyboard,
MessageCircle,
MessageSquare,
Package,
@@ -89,6 +90,7 @@ const SETTINGS_GROUPS: SettingsGroup[] = [
{
labelKey: 'settings.groups.system',
items: [
+ { path: '/settings/shortcuts', labelKey: 'settings.sections.shortcuts', icon: Keyboard },
{ path: '/settings/service', labelKey: 'settings.sections.service', icon: Server, ownerOnly: true },
{ path: '/settings/dependencies', labelKey: 'settings.sections.dependencies', icon: Package, ownerOnly: true },
{ path: '/settings/diagnostics', labelKey: 'settings.sections.diagnostics', icon: Stethoscope, ownerOnly: true },
diff --git a/ui/src/components/settings/SettingsShortcutsPage.test.tsx b/ui/src/components/settings/SettingsShortcutsPage.test.tsx
new file mode 100644
index 000000000..1508430c6
--- /dev/null
+++ b/ui/src/components/settings/SettingsShortcutsPage.test.tsx
@@ -0,0 +1,141 @@
+/* @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import en from '../../i18n/en.json';
+import { defaultActionShortcuts, readActionShortcuts, writeActionShortcuts } from '../../lib/actionShortcuts';
+import { SettingsShortcutsPage } from './SettingsShortcutsPage';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const renderPage = () => render(
+ <I18nextProvider i18n={i18n}>
+ <SettingsShortcutsPage />
+ </I18nextProvider>,
+);
+
+beforeEach(() => {
+ window.localStorage.clear();
+ Object.defineProperty(navigator, 'platform', { configurable: true, value: 'Linux x86_64' });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('SettingsShortcutsPage', () => {
+ it('records a new chord and restores both defaults', () => {
+ renderPage();
+ const voice = screen.getByRole('button', { name: 'Change Chat voice input shortcut' });
+
+ fireEvent.click(voice);
+ fireEvent.keyDown(voice, { code: 'KeyV', key: 'v', altKey: true });
+ expect(readActionShortcuts().voiceInput).toMatchObject({ code: 'KeyV', altKey: true });
+ expect(voice.textContent).toContain('Alt+V');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Restore defaults' }));
+ expect(readActionShortcuts()).toMatchObject({
+ voiceInput: { code: 'KeyZ', altKey: true },
+ showPageAnnotation: { code: 'KeyX', altKey: true },
+ });
+ });
+
+ it('uses Apple modifier names on macOS', () => {
+ Object.defineProperty(navigator, 'platform', { configurable: true, value: 'MacIntel' });
+ renderPage();
+
+ expect(screen.getByRole('button', { name: 'Change Chat voice input shortcut' }).textContent)
+ .toContain('Option+Z');
+ expect(screen.getByRole('button', { name: 'Change Show Page annotation mode shortcut' }).textContent)
+ .toContain('Option+X');
+ });
+
+ it('rejects modifierless, conflicting, AltGraph, and composer-owned chords', () => {
+ renderPage();
+ const voice = screen.getByRole('button', { name: 'Change Chat voice input shortcut' });
+
+ fireEvent.click(voice);
+ fireEvent.keyDown(voice, { code: 'KeyV' });
+ expect(screen.getByRole('alert').textContent).toBe('Include Option, Alt, Command, or Control.');
+
+ const altGraph = new KeyboardEvent('keydown', {
+ bubbles: true,
+ code: 'KeyQ',
+ key: '@',
+ altKey: true,
+ ctrlKey: true,
+ });
+ Object.defineProperty(altGraph, 'getModifierState', {
+ value: (modifier: string) => modifier === 'AltGraph',
+ });
+ fireEvent(voice, altGraph);
+ expect(screen.getByRole('alert').textContent).toBe('This shortcut is already used by Avibe.');
+
+ fireEvent.keyDown(voice, { code: 'Enter', key: 'Enter', ctrlKey: true });
+ expect(screen.getByRole('alert').textContent).toBe('This shortcut is already used by Avibe.');
+
+ fireEvent.keyDown(voice, { code: 'KeyX', altKey: true });
+ expect(screen.getByRole('alert').textContent).toBe('Already used by Show Page annotation mode.');
+ expect(readActionShortcuts().voiceInput.code).toBe('KeyZ');
+ });
+
+ it('allows shell chords because the focused action surface owns them first', () => {
+ renderPage();
+ const voice = screen.getByRole('button', { name: 'Change Chat voice input shortcut' });
+
+ fireEvent.click(voice);
+ fireEvent.keyDown(voice, { code: 'KeyK', key: 'k', metaKey: true });
+
+ expect(readActionShortcuts().voiceInput).toMatchObject({ code: 'KeyK', metaKey: true });
+ });
+
+ it('keeps capture active and reports a failed customization write', () => {
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('blocked'); });
+ renderPage();
+ const voice = screen.getByRole('button', { name: 'Change Chat voice input shortcut' });
+
+ fireEvent.click(voice);
+ fireEvent.keyDown(voice, { code: 'KeyV', key: 'v', altKey: true });
+
+ expect(screen.getByRole('alert').textContent).toBe("Couldn't save the shortcut in this browser.");
+ expect(voice.getAttribute('aria-pressed')).toBe('true');
+ expect(readActionShortcuts()).toEqual(defaultActionShortcuts());
+ });
+
+ it('reports a failed reset without pretending the shortcut changed', () => {
+ const custom = defaultActionShortcuts();
+ custom.voiceInput.code = 'KeyV';
+ writeActionShortcuts(custom);
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('blocked'); });
+ renderPage();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Restore defaults' }));
+
+ expect(screen.getByRole('alert').textContent).toBe("Couldn't save the shortcut in this browser.");
+ expect(readActionShortcuts().voiceInput.code).toBe('KeyV');
+ });
+
+ it('allows modified Escape while plain Escape cancels capture', () => {
+ renderPage();
+ const voice = screen.getByRole('button', { name: 'Change Chat voice input shortcut' });
+
+ fireEvent.click(voice);
+ fireEvent.keyDown(voice, { code: 'Escape', key: 'Escape', altKey: true });
+ expect(readActionShortcuts().voiceInput).toMatchObject({ code: 'Escape', altKey: true });
+ expect(voice.textContent).toContain('Alt+Esc');
+
+ fireEvent.click(voice);
+ fireEvent.keyDown(voice, { code: 'Escape', key: 'Escape' });
+ expect(voice.getAttribute('aria-pressed')).toBe('false');
+ });
+});
diff --git a/ui/src/components/settings/SettingsShortcutsPage.tsx b/ui/src/components/settings/SettingsShortcutsPage.tsx
new file mode 100644
index 000000000..4a66ece98
--- /dev/null
+++ b/ui/src/components/settings/SettingsShortcutsPage.tsx
@@ -0,0 +1,176 @@
+import { useState } from 'react';
+import { Keyboard, RotateCcw } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+
+import {
+ actionShortcutsEqual,
+ defaultActionShortcuts,
+ isAltGraphShortcutEvent,
+ isReservedActionShortcut,
+ isPlainEscape,
+ readActionShortcuts,
+ shortcutFromKeyboardEvent,
+ useActionShortcutLabel,
+ useActionShortcuts,
+ writeActionShortcuts,
+ type ActionShortcutId,
+} from '@/lib/actionShortcuts';
+import { Button } from '@/components/ui/button';
+import { SettingsPageShell } from './SettingsPageShell';
+import { SettingsPanel, SettingsRow } from './SettingsPrimitives';
+
+const SHORTCUT_IDS: readonly ActionShortcutId[] = ['voiceInput', 'showPageAnnotation'];
+
+export const SettingsShortcutsPage: React.FC = () => {
+ const { t } = useTranslation();
+ const shortcuts = useActionShortcuts();
+ const [capturing, setCapturing] = useState<ActionShortcutId | null>(null);
+ const [error, setError] = useState<{ id: ActionShortcutId; message: string } | null>(null);
+ const [persistError, setPersistError] = useState<string | null>(null);
+ const shortcutLabels: Record<ActionShortcutId, string> = {
+ voiceInput: useActionShortcutLabel(shortcuts.voiceInput),
+ showPageAnnotation: useActionShortcutLabel(shortcuts.showPageAnnotation),
+ };
+
+ const actionLabel = (id: ActionShortcutId): string => t(`settings.shortcuts.${id}.title`);
+
+ const capture = (id: ActionShortcutId, event: React.KeyboardEvent<HTMLButtonElement>) => {
+ if (capturing !== id) return;
+ event.preventDefault();
+ event.stopPropagation();
+ if (isPlainEscape(event)) {
+ setCapturing(null);
+ setError(null);
+ return;
+ }
+ if (isAltGraphShortcutEvent(event.nativeEvent)) {
+ setError({ id, message: t('settings.shortcuts.reserved') });
+ return;
+ }
+
+ const next = shortcutFromKeyboardEvent(event.nativeEvent);
+ if (!next) {
+ setError({ id, message: t('settings.shortcuts.modifierRequired') });
+ return;
+ }
+ if (isReservedActionShortcut(id, next)) {
+ setError({ id, message: t('settings.shortcuts.reserved') });
+ return;
+ }
+ const storedShortcuts = readActionShortcuts();
+ const conflict = SHORTCUT_IDS.find(
+ (candidate) => candidate !== id && actionShortcutsEqual(storedShortcuts[candidate], next),
+ );
+ if (conflict) {
+ setError({
+ id,
+ message: t('settings.shortcuts.conflict', { action: actionLabel(conflict) }),
+ });
+ return;
+ }
+
+ if (!writeActionShortcuts({ ...storedShortcuts, [id]: next })) {
+ setPersistError(t('settings.shortcuts.saveFailed'));
+ return;
+ }
+ setPersistError(null);
+ setCapturing(null);
+ setError(null);
+ };
+
+ const shortcutControl = (id: ActionShortcutId) => {
+ const active = capturing === id;
+ const message = error?.id === id ? error.message : null;
+ return (
+ <div className="flex min-w-[190px] flex-col items-stretch gap-1.5 md:items-end">
+ <button
+ type="button"
+ data-shortcut-capture={active ? 'active' : undefined}
+ aria-label={t('settings.shortcuts.change', { action: actionLabel(id) })}
+ aria-pressed={active}
+ onClick={() => {
+ setCapturing(active ? null : id);
+ setError(null);
+ setPersistError(null);
+ }}
+ onBlur={() => {
+ setCapturing((current) => (current === id ? null : current));
+ }}
+ onKeyDown={(event) => capture(id, event)}
+ className={clsx(
+ 'flex h-9 w-full items-center justify-between gap-3 rounded-lg border bg-surface-2 px-3 text-left transition-colors md:w-[190px]',
+ 'focus:outline-none focus:ring-2 focus:ring-mint/40',
+ active
+ ? 'border-mint/60 text-mint-ink shadow-glow-xs-mint'
+ : 'border-border-strong text-foreground hover:border-mint/35',
+ )}
+ >
+ <Keyboard className="size-3.5 shrink-0 text-muted" />
+ <kbd className="min-w-0 flex-1 truncate text-right font-mono text-[12px] font-semibold">
+ {active ? t('settings.shortcuts.pressKeys') : shortcutLabels[id]}
+ </kbd>
+ </button>
+ <span
+ role={message ? 'alert' : undefined}
+ className={clsx('min-h-4 text-[10px] leading-4', message ? 'text-destructive-ink' : 'text-muted')}
+ >
+ {message ?? (active ? t('settings.shortcuts.escapeToCancel') : '')}
+ </span>
+ </div>
+ );
+ };
+
+ return (
+ <SettingsPageShell
+ activeTab="shortcuts"
+ title={t('settings.shortcuts.title')}
+ subtitle={t('settings.shortcuts.subtitle')}
+ actions={
+ <Button
+ type="button"
+ variant="secondary"
+ size="xs"
+ onClick={() => {
+ if (!writeActionShortcuts(defaultActionShortcuts())) {
+ setPersistError(t('settings.shortcuts.saveFailed'));
+ return;
+ }
+ setCapturing(null);
+ setError(null);
+ setPersistError(null);
+ }}
+ >
+ <RotateCcw className="size-3.5" />
+ {t('settings.shortcuts.reset')}
+ </Button>
+ }
+ >
+ {persistError && (
+ <p role="alert" className="text-xs text-destructive-ink">
+ {persistError}
+ </p>
+ )}
+ <SettingsPanel
+ title={
+ <span className="inline-flex items-center gap-2">
+ <Keyboard className="size-3.5 text-mint-ink" />
+ {t('settings.shortcuts.panelTitle')}
+ </span>
+ }
+ description={t('settings.shortcuts.panelDescription')}
+ >
+ <SettingsRow
+ title={actionLabel('voiceInput')}
+ description={t('settings.shortcuts.voiceInput.description')}
+ control={shortcutControl('voiceInput')}
+ />
+ <SettingsRow
+ title={actionLabel('showPageAnnotation')}
+ description={t('settings.shortcuts.showPageAnnotation.description')}
+ control={shortcutControl('showPageAnnotation')}
+ />
+ </SettingsPanel>
+ </SettingsPageShell>
+ );
+};
diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
index 3718646db..6270f8351 100644
--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
@@ -362,6 +362,7 @@ describe('read-only header withdraws the Show Page controls', () => {
state: null,
iframeRef: { current: null },
handleIframeLoad: () => undefined,
+ handleShortcutKeyDown: () => undefined,
enable: () => undefined,
disable: () => undefined,
setMode: () => undefined,
@@ -404,6 +405,7 @@ describe('read-only header withdraws the Show Page controls', () => {
state: null,
iframeRef: { current: null },
handleIframeLoad: () => undefined,
+ handleShortcutKeyDown: () => undefined,
enable: () => undefined,
disable: () => undefined,
setMode: () => undefined,
@@ -543,6 +545,7 @@ describe('archived conflicts converge whatever the verb', () => {
state: null,
iframeRef: { current: null },
handleIframeLoad: () => undefined,
+ handleShortcutKeyDown: () => undefined,
enable: () => undefined,
disable: () => undefined,
setMode: () => undefined,
@@ -653,6 +656,7 @@ describe('a runtime-owned system session is read-only for its own reason', () =>
state: null,
iframeRef: { current: null },
handleIframeLoad: () => undefined,
+ handleShortcutKeyDown: () => undefined,
enable: () => undefined,
disable: () => undefined,
setMode: () => undefined,
diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsx
index 75043ad29..2e6492f95 100644
--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx
+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx
@@ -100,6 +100,7 @@ vi.mock('./useShowPageAnnotation', () => ({
state: { enabled: false, mode: 'smart' },
setIframe: vi.fn(),
handleIframeLoad: vi.fn(),
+ handleShortcutKeyDown: vi.fn(),
enable: vi.fn(),
disable: vi.fn(),
setMode: vi.fn(),
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 7cfd0c2b3..79c955d66 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -2686,6 +2686,7 @@ export const ChatPage: React.FC = () => {
<div
ref={chatSurfaceRef}
className="fixed inset-0 z-40 flex flex-col bg-background pt-[env(safe-area-inset-top)] md:relative md:inset-auto md:z-auto md:-mx-10 md:-my-8 md:h-[var(--app-vvh)] md:bg-transparent md:pt-0"
+ onKeyDown={annotation.handleShortcutKeyDown}
onPointerDownCapture={focusCanvas}
{...fileDropHandlers}
>
diff --git a/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx b/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx
index 8ec5be7b2..11627e2d6 100644
--- a/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx
+++ b/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx
@@ -116,6 +116,7 @@ vi.mock('./useShowPageAnnotation', () => ({
state: { enabled: false, mode: 'smart' },
setIframe: vi.fn(),
handleIframeLoad: vi.fn(),
+ handleShortcutKeyDown: vi.fn(),
enable: vi.fn(),
disable: vi.fn(),
setMode: vi.fn(),
diff --git a/ui/src/components/workbench/Composer.shortcut.test.tsx b/ui/src/components/workbench/Composer.shortcut.test.tsx
new file mode 100644
index 000000000..ba7205b0d
--- /dev/null
+++ b/ui/src/components/workbench/Composer.shortcut.test.tsx
@@ -0,0 +1,226 @@
+/* @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const voiceMocks = vi.hoisted(() => ({
+ abort: vi.fn(),
+ finish: vi.fn(),
+ getUserMedia: vi.fn(),
+ pipelineStart: vi.fn(),
+ realtimeAbort: vi.fn(),
+ realtimeStart: vi.fn(),
+}));
+vi.hoisted(() => {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: vi.fn().mockReturnValue({ matches: false }),
+ });
+});
+const apiFetch = vi.hoisted(() => vi.fn());
+
+vi.mock('../../lib/apiFetch', () => ({ apiFetch }));
+vi.mock('../../lib/avibeFetch', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../lib/avibeFetch')>(),
+ primeCloudToken: vi.fn(),
+}));
+vi.mock('../../lib/voiceRecording', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../lib/voiceRecording')>(),
+ VoiceRecordingPipeline: class {
+ start = voiceMocks.pipelineStart;
+ finish = voiceMocks.finish;
+ abort = voiceMocks.abort;
+ },
+}));
+vi.mock('../../lib/voiceRealtime', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../lib/voiceRealtime')>(),
+ VoiceRealtimeSession: class {
+ start = voiceMocks.realtimeStart;
+ abort = voiceMocks.realtimeAbort;
+ sendPcm = vi.fn();
+ },
+}));
+
+import { ToastProvider } from '../../context/ToastProvider';
+import en from '../../i18n/en.json';
+import {
+ defaultActionShortcuts,
+ writeActionShortcuts,
+} from '../../lib/actionShortcuts';
+import { Composer } from './Composer';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const renderComposer = (
+ sessionId = 'shortcut-session',
+ state: { disabled?: boolean; initialDraft?: string; mentions?: boolean } = {},
+) => render(
+ <I18nextProvider i18n={i18n}>
+ <ToastProvider>
+ <Composer
+ sessionId={sessionId}
+ onSend={() => undefined}
+ disabled={state.disabled}
+ initialDraft={state.initialDraft}
+ onSearchAgents={state.mentions ? async () => [] : undefined}
+ onSearchSessions={state.mentions ? async () => [] : undefined}
+ />
+ </ToastProvider>
+ </I18nextProvider>,
+);
+
+beforeEach(() => {
+ window.localStorage.clear();
+ voiceMocks.abort.mockReset();
+ voiceMocks.finish.mockReset();
+ voiceMocks.getUserMedia.mockReset();
+ voiceMocks.pipelineStart.mockReset().mockResolvedValue(true);
+ voiceMocks.realtimeAbort.mockReset();
+ voiceMocks.realtimeStart.mockReset().mockReturnValue(new Promise(() => undefined));
+ voiceMocks.getUserMedia.mockResolvedValue({
+ getTracks: () => [{ stop: vi.fn() }],
+ });
+ Object.defineProperty(navigator, 'mediaDevices', {
+ configurable: true,
+ value: { getUserMedia: voiceMocks.getUserMedia },
+ });
+ Object.defineProperty(navigator, 'platform', {
+ configurable: true,
+ value: 'Linux x86_64',
+ });
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: vi.fn().mockReturnValue({ matches: false }),
+ });
+ apiFetch.mockReset().mockResolvedValue({
+ ok: true,
+ json: async () => ({ available: true, max_file_bytes: 10_000_000 }),
+ });
+});
+
+afterEach(cleanup);
+
+describe('Composer voice shortcut', () => {
+ it('starts and finishes voice input with the configured chord and advertises it on hover', async () => {
+ renderComposer();
+ const mic = await screen.findByRole('button', { name: en.chat.compose.voice });
+ expect(mic.getAttribute('title')).toBe(
+ 'Press Alt+Z for voice input, press it again to finish, or press Esc to cancel',
+ );
+ const textbox = screen.getByRole('textbox');
+
+ await act(async () => undefined);
+ fireEvent.keyDown(textbox, { code: 'KeyZ', altKey: true });
+ await waitFor(() => expect(voiceMocks.getUserMedia).toHaveBeenCalledOnce());
+ const finish = await screen.findByRole('button', { name: en.chat.compose.stopRecording });
+ expect(finish.getAttribute('title')).toBe(mic.getAttribute('title'));
+
+ fireEvent.keyDown(textbox, { code: 'KeyZ', altKey: true });
+ expect(voiceMocks.finish).toHaveBeenCalledOnce();
+ });
+
+ it('does not handle the shortcut outside the composer', async () => {
+ renderComposer('scoped-shortcut-session');
+ const textbox = screen.getByRole('textbox');
+ await act(async () => undefined);
+
+ fireEvent.keyDown(window, { code: 'KeyZ', altKey: true });
+ expect(voiceMocks.getUserMedia).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(textbox, { code: 'KeyZ', altKey: true });
+ await waitFor(() => expect(voiceMocks.getUserMedia).toHaveBeenCalledOnce());
+ });
+
+ it('owns a configured editor chord before Lexical handles it', async () => {
+ const shortcuts = defaultActionShortcuts();
+ shortcuts.voiceInput = {
+ code: 'KeyZ',
+ altKey: false,
+ ctrlKey: true,
+ metaKey: false,
+ shiftKey: false,
+ };
+ writeActionShortcuts(shortcuts);
+ renderComposer('editor-shortcut-session', { mentions: true, initialDraft: 'Keep this draft' });
+ await screen.findByRole('button', { name: en.chat.compose.voice });
+ const textbox = screen.getByRole('textbox');
+ await waitFor(() => expect(textbox.textContent).toBe('Keep this draft'));
+ await act(async () => undefined);
+
+ fireEvent.keyDown(textbox, { code: 'KeyZ', key: 'z', ctrlKey: true });
+ await waitFor(() => expect(voiceMocks.getUserMedia).toHaveBeenCalledOnce());
+ expect(textbox.textContent).toBe('Keep this draft');
+ });
+
+ it('yields the voice shortcut while the mention picker is open', async () => {
+ renderComposer('mention-picker-shortcut-session', { mentions: true });
+ await screen.findByRole('button', { name: en.chat.compose.voice });
+ const textbox = screen.getByRole('textbox');
+ const picker = document.createElement('ul');
+ picker.dataset.mentionPicker = '';
+ textbox.parentElement?.append(picker);
+ await act(async () => undefined);
+
+ fireEvent.keyDown(textbox, { code: 'KeyZ', key: 'z', altKey: true });
+ expect(voiceMocks.getUserMedia).not.toHaveBeenCalled();
+ });
+
+ it('keeps shortcut ownership after the microphone control changes to finish', async () => {
+ renderComposer('clicked-shortcut-session');
+ const mic = await screen.findByRole('button', { name: en.chat.compose.voice });
+ await act(async () => undefined);
+ mic.focus();
+
+ fireEvent.click(mic);
+ const finish = await screen.findByRole('button', { name: en.chat.compose.stopRecording });
+ await waitFor(() => expect(document.activeElement).toBe(finish));
+
+ fireEvent.keyDown(finish, { code: 'KeyZ', altKey: true });
+ expect(voiceMocks.finish).toHaveBeenCalledOnce();
+ });
+
+ it('does not advertise or handle the shortcut when voice input is disabled', async () => {
+ renderComposer('disabled-shortcut-session', { disabled: true });
+ const mic = await screen.findByRole('button', { name: en.chat.compose.voice });
+
+ expect(mic.hasAttribute('disabled')).toBe(true);
+ expect(mic.getAttribute('title')).toBe(en.chat.compose.voice);
+ fireEvent.keyDown(screen.getByRole('textbox'), { code: 'KeyZ', altKey: true });
+ expect(voiceMocks.getUserMedia).not.toHaveBeenCalled();
+ });
+
+ it('finishes a modified Escape shortcut while plain Escape still cancels', async () => {
+ const shortcuts = defaultActionShortcuts();
+ shortcuts.voiceInput = {
+ code: 'Escape',
+ altKey: true,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ };
+ writeActionShortcuts(shortcuts);
+ renderComposer('escape-shortcut-session');
+ await screen.findByRole('button', { name: en.chat.compose.voice });
+ const textbox = screen.getByRole('textbox');
+ await act(async () => undefined);
+
+ fireEvent.keyDown(textbox, { code: 'Escape', key: 'Escape', altKey: true });
+ await waitFor(() => expect(voiceMocks.getUserMedia).toHaveBeenCalledOnce());
+ await screen.findByRole('button', { name: en.chat.compose.stopRecording });
+ fireEvent.keyDown(textbox, { code: 'Escape', key: 'Escape', altKey: true });
+ expect(voiceMocks.finish).toHaveBeenCalledOnce();
+ expect(voiceMocks.abort).not.toHaveBeenCalled();
+
+ voiceMocks.finish.mockReset();
+ fireEvent.keyDown(window, { code: 'Escape', key: 'Escape' });
+ expect(voiceMocks.abort).toHaveBeenCalledOnce();
+ });
+});
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 4a8a34919..29f502946 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -16,6 +16,12 @@ import { apiFetch } from '../../lib/apiFetch';
import { primeCloudToken } from '../../lib/avibeFetch';
import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';
import { cn, copyTextToClipboard } from '../../lib/utils';
+import {
+ actionShortcutMatches,
+ isPlainEscape,
+ useActionShortcutLabel,
+ useActionShortcuts,
+} from '../../lib/actionShortcuts';
import {
applyVoiceInsertionWithSnapshot,
voiceInsertionSnapshot,
@@ -382,6 +388,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onSearchSessions,
}, ref) {
const { t } = useTranslation();
+ const { voiceInput: voiceInputShortcut } = useActionShortcuts();
+ const voiceShortcutLabel = useActionShortcutLabel(voiceInputShortcut);
+ const voiceShortcutHint = t('chat.compose.voiceShortcutHint', { shortcut: voiceShortcutLabel });
const { showToast } = useToast();
const [value, setValue] = useState('');
// The mention editor (Lexical) OWNS its text, so we don't mirror every
@@ -418,6 +427,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const recordingSessionRef = useRef<VoiceRecordingSession | null>(null);
const recordingStartRef = useRef(false);
const pendingVoiceInsertionRef = useRef<VoiceInsertionSnapshot | null>(null);
+ const focusNextVoiceControlRef = useRef(false);
+ const finishVoiceControlRef = useRef<HTMLButtonElement | null>(null);
const recordingTickerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const unmountedRef = useRef(false);
const disabledRef = useRef(disabled);
@@ -1146,7 +1157,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
useEffect(() => {
if (!recording) return;
const onKey = (e: KeyboardEvent) => {
- if (e.key === 'Escape') {
+ if (isPlainEscape(e)) {
e.preventDefault();
abortRecording();
}
@@ -1202,8 +1213,49 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
);
const voiceCaptureActive = recording || voiceProcessing;
const voiceDiscardAvailable = recording || voiceRetainedSession !== null;
+ const voiceShortcutAvailable = (
+ (voiceControlMode === 'record' || voiceControlMode === 'finish')
+ && !isVoiceControlDisabled(
+ disabled,
+ recording,
+ voiceProcessing,
+ Boolean(voiceRetainedSession),
+ )
+ );
const [stopArmed, setStopArmed] = useState(false);
+ useLayoutEffect(() => {
+ if (!focusNextVoiceControlRef.current) return;
+ if (voiceControlMode === 'finish') {
+ finishVoiceControlRef.current?.focus({ preventScroll: true });
+ focusNextVoiceControlRef.current = false;
+ } else if (voiceControlMode !== 'loading') {
+ focusNextVoiceControlRef.current = false;
+ }
+ }, [voiceControlMode]);
+
+ const handleVoiceShortcut = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (
+ !voiceShortcutAvailable
+ || event.defaultPrevented
+ || event.repeat
+ || event.currentTarget.querySelector('[data-mention-picker]') !== null
+ || !actionShortcutMatches(event.nativeEvent, voiceInputShortcut)
+ ) {
+ return;
+ }
+ event.preventDefault();
+ if (voiceControlMode === 'finish') stopRecording();
+ else void startRecording(captureVoiceInsertion());
+ }, [
+ captureVoiceInsertion,
+ startRecording,
+ stopRecording,
+ voiceControlMode,
+ voiceInputShortcut,
+ voiceShortcutAvailable,
+ ]);
+
useEffect(() => {
if (!busyControls) {
setStopArmed(false);
@@ -1271,7 +1323,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
};
return (
- <div className={cn('mx-auto flex w-full max-w-[1080px] flex-col gap-2', className)}>
+ <div
+ className={cn('mx-auto flex w-full max-w-[1080px] flex-col gap-2', className)}
+ onKeyDownCapture={handleVoiceShortcut}
+ >
{mediaEnabled && attachments.length > 0 && (
<div className="flex flex-wrap gap-2">
{attachments.map((att) => (
@@ -1376,7 +1431,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onContextMenu={() => {
pendingVoiceInsertionRef.current = null;
}}
- onClick={(event) => toggleRecording(event.detail > 0)}
+ onClick={(event) => {
+ focusNextVoiceControlRef.current = true;
+ toggleRecording(event.detail > 0);
+ }}
disabled={isVoiceControlDisabled(
disabled,
recording,
@@ -1384,6 +1442,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
Boolean(voiceRetainedSession),
)}
aria-label={t('chat.compose.voice')}
+ title={voiceShortcutAvailable ? voiceShortcutHint : t('chat.compose.voice')}
className="size-9 shrink-0"
>
<Mic className="size-4" />
@@ -1391,11 +1450,13 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
)}
{voiceControlMode === 'finish' && (
<Button
+ ref={finishVoiceControlRef}
type="button"
variant="default"
size="icon"
onClick={stopRecording}
aria-label={t('chat.compose.stopRecording')}
+ title={voiceShortcutAvailable ? voiceShortcutHint : t('chat.compose.stopRecording')}
className="h-9 w-12 shrink-0"
>
<Check className="size-[18px]" strokeWidth={2.5} />
diff --git a/ui/src/components/workbench/MentionEditor.tsx b/ui/src/components/workbench/MentionEditor.tsx
index 5c6ab52f9..5ad24e1c5 100644
--- a/ui/src/components/workbench/MentionEditor.tsx
+++ b/ui/src/components/workbench/MentionEditor.tsx
@@ -729,6 +729,7 @@ const MentionMenu = forwardRef<HTMLUListElement, BeautifulMentionsMenuProps>(
// composer to trigger, which our 5–8 item menus effectively never hit.
<ul
ref={ref}
+ data-mention-picker
className="absolute left-0 z-50 mb-4 !bottom-full !top-auto max-h-64 min-w-[15rem] list-none overflow-y-auto overflow-x-hidden rounded-md border border-border bg-panel p-1 text-text shadow-md"
{...props}
>
diff --git a/ui/src/components/workbench/ShowPageAnnotateControl.test.tsx b/ui/src/components/workbench/ShowPageAnnotateControl.test.tsx
index a373020aa..8f6bca345 100644
--- a/ui/src/components/workbench/ShowPageAnnotateControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageAnnotateControl.test.tsx
@@ -4,6 +4,7 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';
import { describe, expect, it, vi } from 'vitest';
import en from '../../i18n/en.json';
+import { defaultActionShortcuts, formatActionShortcut } from '../../lib/actionShortcuts';
import { ShowPageAnnotateControl } from './ShowPageAnnotateControl';
const i18n = createInstance();
@@ -30,9 +31,16 @@ const renderCompact = (enabled: boolean) =>
describe('ShowPageAnnotateControl compact presentation', () => {
it.each([false, true])('keeps one title-bar button when enabled=%s', (enabled) => {
const html = renderCompact(enabled);
+ const shortcut = formatActionShortcut(
+ defaultActionShortcuts().showPageAnnotation,
+ i18n.getFixedT('en'),
+ );
expect(html.match(/<button/g)).toHaveLength(1);
expect(html).toContain('aria-label="Annotate"');
+ expect(html).toContain(enabled
+ ? 'title="Annotate"'
+ : `title="Press ${shortcut} to enter annotation mode; press Esc to exit"`);
expect(html).toContain('text-muted');
expect(html).toContain('hover:text-foreground');
});
diff --git a/ui/src/components/workbench/ShowPageAnnotateControl.tsx b/ui/src/components/workbench/ShowPageAnnotateControl.tsx
index fefb942fe..42ff9dc49 100644
--- a/ui/src/components/workbench/ShowPageAnnotateControl.tsx
+++ b/ui/src/components/workbench/ShowPageAnnotateControl.tsx
@@ -5,6 +5,7 @@ import { Camera, Check, type LucideIcon, MessageSquarePlus, MousePointerClick, X
import { Button } from '../ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
+import { useActionShortcutLabel, useActionShortcuts } from '../../lib/actionShortcuts';
import type { AnnotationMode, AnnotationState } from './useShowPageAnnotation';
// Show Page annotation control rendered in the chat header (only in Show Page
@@ -75,6 +76,11 @@ export const ShowPageAnnotateControl: React.FC<ShowPageAnnotateControlProps> = (
ownerWindowId,
}) => {
const { t } = useTranslation();
+ const { showPageAnnotation: annotationShortcut } = useActionShortcuts();
+ const annotationShortcutLabel = useActionShortcutLabel(annotationShortcut);
+ const shortcutHint = t('chat.showPage.annotate.shortcutHint', {
+ shortcut: annotationShortcutLabel,
+ });
const ready = state !== null;
const available = state?.available === true;
const enabled = state?.enabled === true;
@@ -197,7 +203,7 @@ export const ShowPageAnnotateControl: React.FC<ShowPageAnnotateControlProps> = (
className="size-7 shrink-0"
onClick={() => onEnable()}
aria-label={toggleLabel}
- title={toggleLabel}
+ title={shortcutHint}
>
<MessageSquarePlus className="size-3.5" />
</Button>
@@ -219,7 +225,7 @@ export const ShowPageAnnotateControl: React.FC<ShowPageAnnotateControlProps> = (
: 'size-7 shrink-0',
)}
aria-label={toggleLabel}
- title={toggleLabel}
+ title={enabled ? toggleLabel : shortcutHint}
>
<MessageSquarePlus className="size-3.5" />
</Button>
diff --git a/ui/src/components/workbench/ShowPageAnnotationHost.tsx b/ui/src/components/workbench/ShowPageAnnotationHost.tsx
index 6e4b87e93..d0c3ceb59 100644
--- a/ui/src/components/workbench/ShowPageAnnotationHost.tsx
+++ b/ui/src/components/workbench/ShowPageAnnotationHost.tsx
@@ -3,7 +3,10 @@ import type { ReactNode } from 'react';
import { ShowPageAnnotationHostContext } from './ShowPageAnnotationHostContext';
import { useShowPageAnnotation } from './useShowPageAnnotation';
-export const ShowPageAnnotationHost: React.FC<{ src: string | null; children: ReactNode }> = ({ src, children }) => {
+export const ShowPageAnnotationHost: React.FC<{
+ src: string | null;
+ children: ReactNode;
+}> = ({ src, children }) => {
const annotation = useShowPageAnnotation(src);
return (
<ShowPageAnnotationHostContext.Provider value={{ src, annotation }}>
diff --git a/ui/src/components/workbench/chatShortcuts.test.ts b/ui/src/components/workbench/chatShortcuts.test.ts
index 7d9dbd6a9..015365e82 100644
--- a/ui/src/components/workbench/chatShortcuts.test.ts
+++ b/ui/src/components/workbench/chatShortcuts.test.ts
@@ -7,9 +7,10 @@ import {
isArchiveSessionKeydown,
} from './chatShortcuts';
-const chord = (over: Partial<Record<'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey', boolean>> & { code?: string }) => ({
+const chord = (over: Partial<Record<'altKey' | 'ctrlKey' | 'defaultPrevented' | 'metaKey' | 'shiftKey', boolean>> & { code?: string }) => ({
altKey: false,
ctrlKey: false,
+ defaultPrevented: false,
metaKey: false,
shiftKey: false,
code: 'KeyD',
@@ -85,6 +86,10 @@ describe('isArchiveSessionKeydown', () => {
expect(isArchiveSessionKeydown(archiveChord, elWithClosest((s) => s.includes('[role="dialog"]')))).toBe(false);
});
+ it('yields a chord already consumed by a closer surface', () => {
+ expect(isArchiveSessionKeydown({ ...archiveChord, defaultPrevented: true }, null)).toBe(false);
+ });
+
it('still ignores everything that is not the chord', () => {
expect(isArchiveSessionKeydown(chord({ metaKey: true }), null)).toBe(false);
});
diff --git a/ui/src/components/workbench/chatShortcuts.ts b/ui/src/components/workbench/chatShortcuts.ts
index fbe8befba..535144e5a 100644
--- a/ui/src/components/workbench/chatShortcuts.ts
+++ b/ui/src/components/workbench/chatShortcuts.ts
@@ -4,7 +4,10 @@ import { isApplePlatform } from '../../lib/platform';
// apps/dockShortcuts.ts and apps/windowChords.ts) so the exactness of each chord
// is unit-testable without a DOM.
-type ChordEvent = Pick<KeyboardEvent, 'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey' | 'code'>;
+type ChordEvent = Pick<
+ KeyboardEvent,
+ 'altKey' | 'code' | 'ctrlKey' | 'defaultPrevented' | 'metaKey' | 'shiftKey'
+>;
/**
* ⌘⇧D / Ctrl+Shift+D — archive the session the user is reading.
@@ -44,7 +47,7 @@ export function inForegroundSurface(el: Element | null): boolean {
* a read-only or still-loading chat never consumes the browser's ⌘⇧D either.
*/
export function isArchiveSessionKeydown(event: ChordEvent, target: Element | null): boolean {
- return isArchiveSessionChord(event) && !inForegroundSurface(target);
+ return !event.defaultPrevented && isArchiveSessionChord(event) && !inForegroundSurface(target);
}
/** Display label for the archive chord, shown as the menu row's hint badge. */
diff --git a/ui/src/components/workbench/useShowPageAnnotation.test.ts b/ui/src/components/workbench/useShowPageAnnotation.test.ts
index 748b5d8b7..4e5c654ab 100644
--- a/ui/src/components/workbench/useShowPageAnnotation.test.ts
+++ b/ui/src/components/workbench/useShowPageAnnotation.test.ts
@@ -64,6 +64,118 @@ const dispatchParentKeydown = (target: EventTarget, key = 'Escape', preventDefau
act(() => target.dispatchEvent(event));
};
+const dispatchAnnotationShortcut = (target: EventTarget) => {
+ const event = new KeyboardEvent('keydown', {
+ code: 'KeyX',
+ altKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ act(() => target.dispatchEvent(event));
+ return event;
+};
+
+describe('useShowPageAnnotation shortcut', () => {
+ it('leaves the shortcut to the parent surface outside the Show Page frame', () => {
+ const { iframe } = mountBridge();
+ const postMessage = vi.spyOn(iframe.contentWindow!, 'postMessage');
+ reportState(iframe, false);
+ postMessage.mockClear();
+
+ const event = dispatchAnnotationShortcut(document.body);
+ expect(event.defaultPrevented).toBe(false);
+ expect(postMessage).not.toHaveBeenCalled();
+ });
+
+ it('enters annotation from the owning parent surface', () => {
+ const { iframe, result } = mountBridge();
+ const postMessage = vi.spyOn(iframe.contentWindow!, 'postMessage');
+ reportState(iframe, false);
+ postMessage.mockClear();
+ const nativeEvent = new KeyboardEvent('keydown', {
+ code: 'KeyX',
+ altKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+
+ act(() => result.current.handleShortcutKeyDown({
+ defaultPrevented: false,
+ repeat: false,
+ target: document.body,
+ nativeEvent,
+ preventDefault: () => nativeEvent.preventDefault(),
+ } as React.KeyboardEvent<HTMLElement>));
+
+ expect(nativeEvent.defaultPrevented).toBe(true);
+ expect(postMessage).toHaveBeenLastCalledWith(
+ { type: 'avibe:annotation:control', action: 'enable' },
+ window.location.origin,
+ );
+ });
+
+ it('binds the same shortcut inside the focused Show Page iframe', () => {
+ const { iframe } = mountBridge();
+ const postMessage = vi.spyOn(iframe.contentWindow!, 'postMessage');
+ reportState(iframe, false);
+ postMessage.mockClear();
+
+ dispatchAnnotationShortcut(iframe.contentWindow!);
+ expect(postMessage).toHaveBeenLastCalledWith(
+ { type: 'avibe:annotation:control', action: 'enable' },
+ window.location.origin,
+ );
+ });
+
+ it('leaves the iframe shortcut with its active dialog or menu overlay', () => {
+ const { iframe } = mountBridge();
+ const postMessage = vi.spyOn(iframe.contentWindow!, 'postMessage');
+ const frameDocument = iframe.contentDocument!;
+ reportState(iframe, false);
+ postMessage.mockClear();
+
+ const dialog = frameDocument.createElement('div');
+ dialog.setAttribute('role', 'dialog');
+ const dialogButton = frameDocument.createElement('button');
+ dialog.append(dialogButton);
+ frameDocument.body.append(dialog);
+ dialogButton.focus();
+ expect(dispatchAnnotationShortcut(iframe.contentWindow!).defaultPrevented).toBe(false);
+
+ dialog.remove();
+ const menu = frameDocument.createElement('div');
+ menu.setAttribute('role', 'menu');
+ menu.dataset.state = 'open';
+ const menuItem = frameDocument.createElement('button');
+ menu.append(menuItem);
+ frameDocument.body.append(menu);
+ menuItem.focus();
+ expect(dispatchAnnotationShortcut(iframe.contentWindow!).defaultPrevented).toBe(false);
+ expect(postMessage).not.toHaveBeenCalled();
+ });
+
+ it('does not mistake persistent iframe navigation for an open overlay', () => {
+ const { iframe } = mountBridge();
+ const postMessage = vi.spyOn(iframe.contentWindow!, 'postMessage');
+ const frameDocument = iframe.contentDocument!;
+ reportState(iframe, false);
+ postMessage.mockClear();
+
+ const navigation = frameDocument.createElement('div');
+ navigation.setAttribute('role', 'menu');
+ const pageButton = frameDocument.createElement('button');
+ frameDocument.body.append(navigation, pageButton);
+ pageButton.focus();
+
+ expect(dispatchAnnotationShortcut(iframe.contentWindow!).defaultPrevented).toBe(true);
+ expect(postMessage).toHaveBeenLastCalledWith(
+ { type: 'avibe:annotation:control', action: 'enable' },
+ window.location.origin,
+ );
+ });
+
+});
+
describe('useShowPageAnnotation host Escape forwarding', () => {
it('forwards parent Escape to the iframe document while annotation is enabled', () => {
const { iframe } = mountBridge();
diff --git a/ui/src/components/workbench/useShowPageAnnotation.ts b/ui/src/components/workbench/useShowPageAnnotation.ts
index fa185a8ba..0254af8a8 100644
--- a/ui/src/components/workbench/useShowPageAnnotation.ts
+++ b/ui/src/components/workbench/useShowPageAnnotation.ts
@@ -1,5 +1,9 @@
import { useCallback, useEffect, useRef, useState } from 'react';
+import { actionShortcutMatches, isPlainEscape, useActionShortcuts } from '../../lib/actionShortcuts';
+import { useLatestRef } from '../../lib/useLatestRef';
+import { bindFrameChord } from '../apps/windowChords';
+
// postMessage bridge between the chat host and the annotation overlay running
// inside the chat's Show Page iframe (plan show-page-annotation-phase1 §3).
//
@@ -24,6 +28,8 @@ export interface AnnotationBridge {
setIframe: React.RefCallback<HTMLIFrameElement>;
/** Attach to the iframe `onLoad` to re-sync after a (re)load / re-point. */
handleIframeLoad: () => void;
+ /** Attach to the owning Show Page surface for parent-document keystrokes. */
+ handleShortcutKeyDown: React.KeyboardEventHandler<HTMLElement>;
/** `enable` without a mode uses the overlay's remembered mode (§3). */
enable: (mode?: AnnotationMode) => void;
disable: () => void;
@@ -38,6 +44,19 @@ type ControlMessage =
const PARENT_ESCAPE_CLAIM_SELECTOR =
'input, textarea, [contenteditable]:not([contenteditable="false"]), [data-state="open"], [role="menu"], [aria-expanded="true"][aria-haspopup], [role="dialog"]:not([data-window-id]), dialog[open]';
+const ANNOTATION_SHORTCUT_BLOCKING_SELECTOR = [
+ '[aria-expanded="true"][aria-haspopup]',
+ '[role="menu"][data-state="open"]',
+ '[role="listbox"][data-state="open"]',
+ '[role="dialog"]:not([data-window-id])',
+ '[role="alertdialog"]',
+ 'dialog[open]',
+].join(', ');
+
+function annotationShortcutBlocked(target: Element | null): boolean {
+ return Boolean(target?.closest?.(ANNOTATION_SHORTCUT_BLOCKING_SELECTOR));
+}
+
/**
* `src` is the current iframe URL; changing it (first open, or a private↔public
* re-point, or a session switch that clears it) drops the derived state back to
@@ -46,8 +65,12 @@ const PARENT_ESCAPE_CLAIM_SELECTOR =
*/
export function useShowPageAnnotation(src: string | null): AnnotationBridge {
const iframeRef = useRef<HTMLIFrameElement | null>(null);
+ const frameShortcutCleanupRef = useRef<() => void>(() => undefined);
const [state, setState] = useState<AnnotationState | null>(null);
const [lastSrc, setLastSrc] = useState(src);
+ const { showPageAnnotation: annotationShortcut } = useActionShortcuts();
+ const stateRef = useLatestRef(state);
+ const shortcutRef = useLatestRef(annotationShortcut);
// The loaded page changed — the new overlay hasn't reported yet, so drop back
// to "unknown" until it does (and so one session's state never briefly shows
@@ -98,11 +121,9 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {
}, [startListening, stopListening]);
const onParentKeyDown = useCallback((event: KeyboardEvent) => {
- if (event.key !== 'Escape' || event.defaultPrevented) return;
+ if (!isPlainEscape(event) || event.defaultPrevented) return;
const target = event.target;
if (target instanceof Element && target.closest(PARENT_ESCAPE_CLAIM_SELECTOR)) return;
- // Custom menus render role=menu only while open, so its presence is an
- // open-state fact even when focus remains on the invoking element.
if (document.querySelector('[role="menu"]')) return;
try {
@@ -110,7 +131,12 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {
if (!frameDocument) return;
const FrameKeyboardEvent = frameDocument.defaultView?.KeyboardEvent ?? KeyboardEvent;
frameDocument.dispatchEvent(
- new FrameKeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
+ new FrameKeyboardEvent('keydown', {
+ code: 'Escape',
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ }),
);
} catch {
// The frame may be sandboxed, navigating, or already torn down.
@@ -140,18 +166,6 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {
if (win) win.postMessage(message, window.location.origin);
}, []);
- const setIframe = useCallback<React.RefCallback<HTMLIFrameElement>>(
- (iframe) => {
- if (iframeRef.current !== iframe) stopEscapeListening();
- iframeRef.current = iframe;
- if (iframe) {
- startListening();
- if (state?.enabled === true) startEscapeListening();
- }
- },
- [startEscapeListening, startListening, state?.enabled, stopEscapeListening],
- );
-
const enable = useCallback(
(mode?: AnnotationMode) =>
post(
@@ -166,9 +180,76 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {
(mode: AnnotationMode) => post({ type: 'avibe:annotation:control', action: 'set-mode', mode }),
[post],
);
+ const enableFromShortcut = useCallback(() => {
+ const current = stateRef.current;
+ if (current?.available !== true || current.enabled) return;
+ post({ type: 'avibe:annotation:control', action: 'enable' });
+ }, [post, stateRef]);
+
+ const handleShortcutKeyDown = useCallback<React.KeyboardEventHandler<HTMLElement>>((event) => {
+ if (
+ event.defaultPrevented
+ || event.repeat
+ || stateRef.current?.available !== true
+ || stateRef.current.enabled
+ || !actionShortcutMatches(event.nativeEvent, shortcutRef.current)
+ || annotationShortcutBlocked(event.target as Element | null)
+ ) {
+ return;
+ }
+ event.preventDefault();
+ enableFromShortcut();
+ }, [enableFromShortcut, shortcutRef, stateRef]);
+
+ const setIframe = useCallback<React.RefCallback<HTMLIFrameElement>>(
+ (iframe) => {
+ if (iframeRef.current !== iframe) {
+ stopEscapeListening();
+ }
+ frameShortcutCleanupRef.current();
+ frameShortcutCleanupRef.current = () => undefined;
+ iframeRef.current = iframe;
+ if (!iframe) return;
+ startListening();
+ if (stateRef.current?.enabled === true) startEscapeListening();
+ frameShortcutCleanupRef.current = bindFrameChord(
+ iframe,
+ (event, activeInFrame) => {
+ return (
+ !event.defaultPrevented
+ && !event.repeat
+ && stateRef.current?.available === true
+ && stateRef.current.enabled !== true
+ && actionShortcutMatches(event, shortcutRef.current)
+ && !annotationShortcutBlocked(activeInFrame)
+ );
+ },
+ enableFromShortcut,
+ );
+ },
+ [
+ enableFromShortcut,
+ shortcutRef,
+ startEscapeListening,
+ startListening,
+ stateRef,
+ stopEscapeListening,
+ ],
+ );
+
+ useEffect(() => () => frameShortcutCleanupRef.current(), []);
+
// On (re)load the overlay broadcasts its state on mount, but the parent
// listener is already attached, so we also query as a backstop (§3).
const handleIframeLoad = useCallback(() => post({ type: 'avibe:annotation:query' }), [post]);
- return { state, setIframe, handleIframeLoad, enable, disable, setMode };
+ return {
+ state,
+ setIframe,
+ handleIframeLoad,
+ handleShortcutKeyDown,
+ enable,
+ disable,
+ setMode,
+ };
}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index a6c907e0c..337d8f6e4 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -281,6 +281,7 @@
"platforms": "Platforms",
"platformConnections": "Platform Connections",
"remoteAccess": "Remote Access",
+ "shortcuts": "Shortcuts",
"service": "Service",
"dependencies": "Dependencies",
"diagnostics": "Diagnostics & Logs",
@@ -289,6 +290,58 @@
"navigationLabel": "Settings sections",
"backToSections": "All settings",
"close": "Close Settings",
+ "shortcuts": {
+ "title": "Shortcuts",
+ "subtitle": "Choose the keyboard commands you use most often in Chat and Show Pages.",
+ "panelTitle": "Action shortcuts",
+ "panelDescription": "Changes apply immediately in this browser.",
+ "voiceInput": {
+ "title": "Chat voice input",
+ "description": "Start dictation in the chat composer, then finish it with the same shortcut."
+ },
+ "showPageAnnotation": {
+ "title": "Show Page annotation mode",
+ "description": "Enter annotation mode on the Show Page in front."
+ },
+ "change": "Change {{action}} shortcut",
+ "pressKeys": "Press shortcut",
+ "escapeToCancel": "Esc cancels",
+ "modifierRequired": "Include Option, Alt, Command, or Control.",
+ "reserved": "This shortcut is already used by Avibe.",
+ "conflict": "Already used by {{action}}.",
+ "saveFailed": "Couldn't save the shortcut in this browser.",
+ "modifierLabels": {
+ "control": "Control",
+ "option": "Option",
+ "command": "Command",
+ "ctrl": "Ctrl",
+ "alt": "Alt",
+ "shift": "Shift",
+ "meta": "Meta"
+ },
+ "keyLabels": {
+ "backspace": "Backspace",
+ "capsLock": "Caps Lock",
+ "contextMenu": "Context Menu",
+ "delete": "Delete",
+ "end": "End",
+ "enter": "Enter",
+ "escape": "Esc",
+ "home": "Home",
+ "insert": "Insert",
+ "numLock": "Num Lock",
+ "numpad": "Numpad {{key}}",
+ "numpadEnter": "Numpad Enter",
+ "pageDown": "Page Down",
+ "pageUp": "Page Up",
+ "pause": "Pause",
+ "printScreen": "Print Screen",
+ "scrollLock": "Scroll Lock",
+ "space": "Space",
+ "tab": "Tab"
+ },
+ "reset": "Restore defaults"
+ },
"diagnosticsTab": "Diagnostics",
"logsTab": "Logs",
"diagnosticsNavigationLabel": "Diagnostics and logs",
@@ -3677,6 +3730,7 @@
"closeAnnotation": "Turn off annotation",
"modeTitle": "Annotation mode",
"rememberHint": "Remembers last choice",
+ "shortcutHint": "Press {{shortcut}} to enter annotation mode; press Esc to exit",
"unavailable": "Annotation not available yet"
},
"title": "Show Page",
@@ -3815,6 +3869,7 @@
"stop": "Stop",
"attach": "Attach files",
"voice": "Voice input",
+ "voiceShortcutHint": "Press {{shortcut}} for voice input, press it again to finish, or press Esc to cancel",
"stopRecording": "Finish recording",
"cancelRecording": "Cancel recording",
"voicePreview": "Live transcription preview",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index a616e15eb..418ae6703 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -281,6 +281,7 @@
"platforms": "通讯平台",
"platformConnections": "平台接入",
"remoteAccess": "远程访问",
+ "shortcuts": "快捷键",
"service": "服务",
"dependencies": "依赖",
"diagnostics": "诊断与日志",
@@ -289,6 +290,58 @@
"navigationLabel": "设置分区",
"backToSections": "全部设置",
"close": "关闭设置",
+ "shortcuts": {
+ "title": "快捷键",
+ "subtitle": "设置你在聊天和 Show Page 中最常用的键盘操作。",
+ "panelTitle": "操作快捷键",
+ "panelDescription": "修改后会立即在当前浏览器生效。",
+ "voiceInput": {
+ "title": "Chat 聊天框语音输入",
+ "description": "在聊天框开始语音输入,再按同一快捷键完成。"
+ },
+ "showPageAnnotation": {
+ "title": "Show Page 标注模式",
+ "description": "进入当前 Show Page 的标注模式。"
+ },
+ "change": "修改{{action}}快捷键",
+ "pressKeys": "请按快捷键",
+ "escapeToCancel": "按 Esc 取消",
+ "modifierRequired": "请包含 Option、Alt、Command 或 Control。",
+ "reserved": "这个快捷键已被 Avibe 使用。",
+ "conflict": "已被{{action}}使用。",
+ "saveFailed": "无法在当前浏览器中保存快捷键。",
+ "modifierLabels": {
+ "control": "Control",
+ "option": "Option",
+ "command": "Command",
+ "ctrl": "Ctrl",
+ "alt": "Alt",
+ "shift": "Shift",
+ "meta": "Meta"
+ },
+ "keyLabels": {
+ "backspace": "退格",
+ "capsLock": "大写锁定",
+ "contextMenu": "菜单",
+ "delete": "删除",
+ "end": "行尾",
+ "enter": "回车",
+ "escape": "Esc",
+ "home": "行首",
+ "insert": "插入",
+ "numLock": "数字锁定",
+ "numpad": "数字键盘 {{key}}",
+ "numpadEnter": "数字键盘回车",
+ "pageDown": "下一页",
+ "pageUp": "上一页",
+ "pause": "暂停",
+ "printScreen": "截屏",
+ "scrollLock": "滚动锁定",
+ "space": "空格",
+ "tab": "Tab"
+ },
+ "reset": "恢复默认"
+ },
"diagnosticsTab": "诊断",
"logsTab": "日志",
"diagnosticsNavigationLabel": "诊断与日志",
@@ -3677,6 +3730,7 @@
"closeAnnotation": "关闭标注",
"modeTitle": "标注模式",
"rememberHint": "记住上次选择",
+ "shortcutHint": "按下{{shortcut}}进入标注模式,按 ESC 退出",
"unavailable": "标注暂不可用"
},
"title": "Show Page",
@@ -3815,6 +3869,7 @@
"stop": "停止",
"attach": "添加附件",
"voice": "语音输入",
+ "voiceShortcutHint": "按下{{shortcut}}进行语音输入,再按一下完成,按 ESC 取消",
"stopRecording": "完成录音",
"cancelRecording": "取消录音",
"voicePreview": "实时转写预览",
diff --git a/ui/src/lib/actionShortcuts.test.ts b/ui/src/lib/actionShortcuts.test.ts
new file mode 100644
index 000000000..75bd65871
--- /dev/null
+++ b/ui/src/lib/actionShortcuts.test.ts
@@ -0,0 +1,130 @@
+import { createInstance } from 'i18next';
+import { describe, expect, it, vi } from 'vitest';
+
+import en from '../i18n/en.json';
+import zh from '../i18n/zh.json';
+
+import {
+ ACTION_SHORTCUTS_STORAGE_KEY,
+ actionShortcutMatches,
+ defaultActionShortcuts,
+ formatActionShortcut,
+ isPlainEscape,
+ isReservedActionShortcut,
+ readActionShortcuts,
+ shortcutFromKeyboardEvent,
+ writeActionShortcuts,
+} from './actionShortcuts';
+
+const i18n = createInstance();
+void i18n.init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en }, zh: { translation: zh } },
+ interpolation: { escapeValue: false },
+});
+const enT = i18n.getFixedT('en');
+const zhT = i18n.getFixedT('zh');
+
+const chord = (overrides: Partial<KeyboardEvent> = {}) => ({
+ code: 'KeyZ',
+ key: 'z',
+ altKey: false,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ ...overrides,
+}) as KeyboardEvent;
+
+describe('action shortcuts', () => {
+ it('ships the requested defaults with platform-specific modifier names', () => {
+ const defaults = defaultActionShortcuts();
+
+ expect(defaults.voiceInput).toMatchObject({ code: 'KeyZ', altKey: true });
+ expect(defaults.showPageAnnotation).toMatchObject({ code: 'KeyX', altKey: true });
+ expect(formatActionShortcut(defaults.voiceInput, enT, true)).toBe('Option+Z');
+ expect(formatActionShortcut(defaults.showPageAnnotation, enT, false)).toBe('Alt+X');
+ });
+
+ it('captures only modified non-modifier keys and matches the exact physical chord', () => {
+ expect(shortcutFromKeyboardEvent(chord({ code: 'KeyV', altKey: true }))).toEqual({
+ code: 'KeyV',
+ altKey: true,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ });
+ expect(shortcutFromKeyboardEvent(chord({ code: 'KeyV' }))).toBeNull();
+ expect(shortcutFromKeyboardEvent(chord({ code: 'KeyV', shiftKey: true }))).toBeNull();
+ expect(shortcutFromKeyboardEvent(chord({ code: 'AltLeft', key: 'Alt', altKey: true }))).toBeNull();
+
+ const shortcut = shortcutFromKeyboardEvent(chord({ code: 'KeyV', altKey: true }))!;
+ expect(actionShortcutMatches(chord({ code: 'KeyV', altKey: true }), shortcut)).toBe(true);
+ expect(actionShortcutMatches(chord({ code: 'KeyV', altKey: true, shiftKey: true }), shortcut)).toBe(false);
+ });
+
+ it('never captures or matches AltGraph text entry as a Ctrl+Alt action', () => {
+ const ctrlAlt = shortcutFromKeyboardEvent(chord({
+ code: 'KeyQ',
+ altKey: true,
+ ctrlKey: true,
+ }))!;
+ const altGraph = chord({
+ code: 'KeyQ',
+ key: '@',
+ altKey: true,
+ ctrlKey: true,
+ getModifierState: (modifier: string) => modifier === 'AltGraph',
+ });
+
+ expect(shortcutFromKeyboardEvent(altGraph)).toBeNull();
+ expect(actionShortcutMatches(altGraph, ctrlAlt)).toBe(false);
+ });
+
+ it('localizes generated key names without changing platform modifier names', () => {
+ const numpad = shortcutFromKeyboardEvent(chord({ code: 'Numpad1', key: '1', altKey: true }))!;
+ const pageDown = shortcutFromKeyboardEvent(chord({ code: 'PageDown', key: 'PageDown', ctrlKey: true }))!;
+
+ expect(formatActionShortcut(numpad, enT, false)).toBe('Alt+Numpad 1');
+ expect(formatActionShortcut(numpad, zhT, false)).toBe('Alt+数字键盘 1');
+ expect(formatActionShortcut(pageDown, enT, false)).toBe('Ctrl+Page Down');
+ expect(formatActionShortcut(pageDown, zhT, false)).toBe('Ctrl+下一页');
+ });
+
+ it('keeps plain Escape separate from modified user shortcuts', () => {
+ expect(isPlainEscape(chord({ code: 'Escape', key: 'Escape' }))).toBe(true);
+ expect(isPlainEscape(chord({ code: 'Escape', key: 'Escape', altKey: true }))).toBe(false);
+ });
+
+ it('reserves only chords owned by the same action surface', () => {
+ const enter = shortcutFromKeyboardEvent(chord({ code: 'Enter', key: 'Enter', ctrlKey: true }))!;
+ const windowClose = shortcutFromKeyboardEvent(chord({ code: 'KeyW', altKey: true }))!;
+ const dockLaunch = shortcutFromKeyboardEvent(chord({ code: 'Digit1', altKey: true }))!;
+ expect(isReservedActionShortcut('voiceInput', enter)).toBe(true);
+ expect(isReservedActionShortcut('showPageAnnotation', enter)).toBe(false);
+ expect(isReservedActionShortcut('showPageAnnotation', windowClose)).toBe(false);
+ expect(isReservedActionShortcut('showPageAnnotation', dockLaunch)).toBe(false);
+ expect(isReservedActionShortcut('voiceInput', windowClose)).toBe(false);
+ expect(isReservedActionShortcut('voiceInput', shortcutFromKeyboardEvent(chord({ code: 'KeyK', metaKey: true }))!)).toBe(false);
+ expect(isReservedActionShortcut('voiceInput', shortcutFromKeyboardEvent(chord({ code: 'KeyD', ctrlKey: true, shiftKey: true }))!)).toBe(false);
+ expect(isReservedActionShortcut('voiceInput', shortcutFromKeyboardEvent(chord({ code: 'KeyL', ctrlKey: true }))!)).toBe(false);
+ });
+
+ it('persists valid settings, reports write failures, and rejects malformed storage', () => {
+ const setItem = vi.fn();
+ const custom = defaultActionShortcuts();
+ custom.voiceInput.code = 'KeyV';
+
+ expect(writeActionShortcuts(custom, { setItem })).toBe(true);
+ expect(setItem).toHaveBeenCalledWith(ACTION_SHORTCUTS_STORAGE_KEY, JSON.stringify(custom));
+ expect(writeActionShortcuts(custom, { setItem: () => { throw new Error('blocked'); } })).toBe(false);
+ expect(readActionShortcuts({ getItem: () => JSON.stringify(custom) })).toEqual(custom);
+ expect(readActionShortcuts({ getItem: () => '{broken' })).toEqual(defaultActionShortcuts());
+ expect(readActionShortcuts({
+ getItem: () => JSON.stringify({
+ voiceInput: custom.showPageAnnotation,
+ showPageAnnotation: custom.showPageAnnotation,
+ }),
+ })).toEqual(defaultActionShortcuts());
+ });
+});
diff --git a/ui/src/lib/actionShortcuts.ts b/ui/src/lib/actionShortcuts.ts
new file mode 100644
index 000000000..6a12b154b
--- /dev/null
+++ b/ui/src/lib/actionShortcuts.ts
@@ -0,0 +1,312 @@
+import { useMemo, useSyncExternalStore } from 'react';
+import { useTranslation } from 'react-i18next';
+import type { TFunction } from 'i18next';
+
+import { isApplePlatform } from './platform';
+
+export type ActionShortcutId = 'voiceInput' | 'showPageAnnotation';
+
+export type ActionShortcut = {
+ code: string;
+ altKey: boolean;
+ ctrlKey: boolean;
+ metaKey: boolean;
+ shiftKey: boolean;
+};
+
+export type ActionShortcuts = Record<ActionShortcutId, ActionShortcut>;
+
+type ShortcutEvent = Pick<
+ KeyboardEvent,
+ 'altKey' | 'code' | 'ctrlKey' | 'key' | 'metaKey' | 'shiftKey'
+> & Partial<Pick<KeyboardEvent, 'getModifierState'>>;
+
+type ReadableStorage = Pick<Storage, 'getItem'>;
+type WritableStorage = Pick<Storage, 'setItem'>;
+
+export const ACTION_SHORTCUTS_STORAGE_KEY = 'avibe.action-shortcuts.v1';
+export const ACTION_SHORTCUTS_CHANGED_EVENT = 'avibe:action-shortcuts-changed';
+
+export const DEFAULT_ACTION_SHORTCUTS: Readonly<ActionShortcuts> = {
+ voiceInput: {
+ code: 'KeyZ',
+ altKey: true,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ },
+ showPageAnnotation: {
+ code: 'KeyX',
+ altKey: true,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ },
+};
+
+const MODIFIER_CODES = new Set([
+ 'AltLeft',
+ 'AltRight',
+ 'ControlLeft',
+ 'ControlRight',
+ 'MetaLeft',
+ 'MetaRight',
+ 'ShiftLeft',
+ 'ShiftRight',
+]);
+
+const cloneShortcut = (shortcut: ActionShortcut): ActionShortcut => ({
+ code: shortcut.code,
+ altKey: shortcut.altKey,
+ ctrlKey: shortcut.ctrlKey,
+ metaKey: shortcut.metaKey,
+ shiftKey: shortcut.shiftKey,
+});
+
+export const defaultActionShortcuts = (): ActionShortcuts => ({
+ voiceInput: cloneShortcut(DEFAULT_ACTION_SHORTCUTS.voiceInput),
+ showPageAnnotation: cloneShortcut(DEFAULT_ACTION_SHORTCUTS.showPageAnnotation),
+});
+
+export function actionShortcutsEqual(left: ActionShortcut, right: ActionShortcut): boolean {
+ return (
+ left.code === right.code
+ && left.altKey === right.altKey
+ && left.ctrlKey === right.ctrlKey
+ && left.metaKey === right.metaKey
+ && left.shiftKey === right.shiftKey
+ );
+}
+
+function isActionShortcut(value: unknown): value is ActionShortcut {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const shortcut = value as Partial<ActionShortcut>;
+ return (
+ typeof shortcut.code === 'string'
+ && shortcut.code.length > 0
+ && shortcut.code !== 'Unidentified'
+ && !MODIFIER_CODES.has(shortcut.code)
+ && typeof shortcut.altKey === 'boolean'
+ && typeof shortcut.ctrlKey === 'boolean'
+ && typeof shortcut.metaKey === 'boolean'
+ && typeof shortcut.shiftKey === 'boolean'
+ && (shortcut.altKey || shortcut.ctrlKey || shortcut.metaKey)
+ );
+}
+
+function normalizeActionShortcuts(value: unknown): ActionShortcuts {
+ const defaults = defaultActionShortcuts();
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return defaults;
+ const candidate = value as Partial<Record<ActionShortcutId, unknown>>;
+ const voiceInput = isActionShortcut(candidate.voiceInput)
+ && !isReservedActionShortcut('voiceInput', candidate.voiceInput)
+ ? cloneShortcut(candidate.voiceInput)
+ : defaults.voiceInput;
+ const showPageAnnotation = isActionShortcut(candidate.showPageAnnotation)
+ && !isReservedActionShortcut('showPageAnnotation', candidate.showPageAnnotation)
+ ? cloneShortcut(candidate.showPageAnnotation)
+ : defaults.showPageAnnotation;
+ if (actionShortcutsEqual(voiceInput, showPageAnnotation)) return defaults;
+ return { voiceInput, showPageAnnotation };
+}
+
+export function readActionShortcuts(storage?: ReadableStorage): ActionShortcuts {
+ try {
+ const target = storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);
+ const raw = target?.getItem(ACTION_SHORTCUTS_STORAGE_KEY);
+ return raw ? normalizeActionShortcuts(JSON.parse(raw)) : defaultActionShortcuts();
+ } catch {
+ return defaultActionShortcuts();
+ }
+}
+
+export function writeActionShortcuts(
+ shortcuts: ActionShortcuts,
+ storage?: WritableStorage,
+): boolean {
+ const normalized = normalizeActionShortcuts(shortcuts);
+ try {
+ const target = storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);
+ if (!target) return false;
+ target.setItem(ACTION_SHORTCUTS_STORAGE_KEY, JSON.stringify(normalized));
+ } catch {
+ return false;
+ }
+ if (typeof window !== 'undefined' && storage === undefined) {
+ window.dispatchEvent(new Event(ACTION_SHORTCUTS_CHANGED_EVENT));
+ }
+ return true;
+}
+
+export function isPlainEscape(
+ event: Pick<ShortcutEvent, 'altKey' | 'code' | 'ctrlKey' | 'key' | 'metaKey' | 'shiftKey'>,
+): boolean {
+ return (
+ (event.code === 'Escape' || event.key === 'Escape')
+ && !event.altKey
+ && !event.ctrlKey
+ && !event.metaKey
+ && !event.shiftKey
+ );
+}
+
+export function isAltGraphShortcutEvent(event: Pick<ShortcutEvent, 'getModifierState'>): boolean {
+ return event.getModifierState?.('AltGraph') === true;
+}
+
+export function shortcutFromKeyboardEvent(event: ShortcutEvent): ActionShortcut | null {
+ if (isAltGraphShortcutEvent(event)) return null;
+ const shortcut: ActionShortcut = {
+ code: event.code,
+ altKey: event.altKey,
+ ctrlKey: event.ctrlKey,
+ metaKey: event.metaKey,
+ shiftKey: event.shiftKey,
+ };
+ return isActionShortcut(shortcut) ? shortcut : null;
+}
+
+export function actionShortcutMatches(event: ShortcutEvent, shortcut: ActionShortcut): boolean {
+ return (
+ !isAltGraphShortcutEvent(event)
+ && event.code === shortcut.code
+ && event.altKey === shortcut.altKey
+ && event.ctrlKey === shortcut.ctrlKey
+ && event.metaKey === shortcut.metaKey
+ && event.shiftKey === shortcut.shiftKey
+ );
+}
+
+/**
+ * Chords already owned by the action's own surface cannot be assigned.
+ * Browser/OS reservations are intentionally not mirrored here: Settings can
+ * persist only keydown events the current browser actually delivers.
+ */
+export function isReservedActionShortcut(
+ id: ActionShortcutId,
+ shortcut: ActionShortcut,
+): boolean {
+ // Both Chat composer implementations submit every non-Shift Enter.
+ return (
+ id === 'voiceInput'
+ && !shortcut.shiftKey
+ && (shortcut.code === 'Enter' || shortcut.code === 'NumpadEnter')
+ );
+}
+
+const SYMBOL_KEY_LABELS: Readonly<Record<string, string>> = {
+ ArrowDown: '↓',
+ ArrowLeft: '←',
+ ArrowRight: '→',
+ ArrowUp: '↑',
+ Backquote: '`',
+ Backslash: '\\',
+ BracketLeft: '[',
+ BracketRight: ']',
+ Comma: ',',
+ Equal: '=',
+ Minus: '-',
+ Period: '.',
+ Quote: "'",
+ Semicolon: ';',
+ Slash: '/',
+};
+
+const TRANSLATED_KEY_LABELS: Readonly<Record<string, string>> = {
+ Backspace: 'backspace',
+ CapsLock: 'capsLock',
+ ContextMenu: 'contextMenu',
+ Delete: 'delete',
+ End: 'end',
+ Enter: 'enter',
+ Escape: 'escape',
+ Home: 'home',
+ Insert: 'insert',
+ NumLock: 'numLock',
+ NumpadEnter: 'numpadEnter',
+ PageDown: 'pageDown',
+ PageUp: 'pageUp',
+ Pause: 'pause',
+ PrintScreen: 'printScreen',
+ ScrollLock: 'scrollLock',
+ Space: 'space',
+ Tab: 'tab',
+};
+
+export function actionShortcutKeyLabel(code: string, t: TFunction): string {
+ if (/^Key[A-Z]$/.test(code)) return code.slice(3);
+ if (/^Digit[0-9]$/.test(code)) return code.slice(5);
+ if (/^Numpad[0-9]$/.test(code)) {
+ return t('settings.shortcuts.keyLabels.numpad', { key: code.slice(6) });
+ }
+ const numpadSymbol = ({
+ NumpadAdd: '+',
+ NumpadComma: ',',
+ NumpadDecimal: '.',
+ NumpadDivide: '/',
+ NumpadEqual: '=',
+ NumpadMultiply: '×',
+ NumpadSubtract: '-',
+ } as Readonly<Record<string, string>>)[code];
+ if (numpadSymbol) return t('settings.shortcuts.keyLabels.numpad', { key: numpadSymbol });
+ const translated = TRANSLATED_KEY_LABELS[code];
+ if (translated) return t(`settings.shortcuts.keyLabels.${translated}`);
+ return SYMBOL_KEY_LABELS[code] ?? code;
+}
+
+export function formatActionShortcut(
+ shortcut: ActionShortcut,
+ t: TFunction,
+ apple = isApplePlatform(),
+): string {
+ const key = actionShortcutKeyLabel(shortcut.code, t);
+ if (apple) {
+ return [
+ shortcut.ctrlKey ? t('settings.shortcuts.modifierLabels.control') : '',
+ shortcut.altKey ? t('settings.shortcuts.modifierLabels.option') : '',
+ shortcut.shiftKey ? t('settings.shortcuts.modifierLabels.shift') : '',
+ shortcut.metaKey ? t('settings.shortcuts.modifierLabels.command') : '',
+ key,
+ ].filter(Boolean).join('+');
+ }
+ return [
+ shortcut.ctrlKey ? t('settings.shortcuts.modifierLabels.ctrl') : '',
+ shortcut.altKey ? t('settings.shortcuts.modifierLabels.alt') : '',
+ shortcut.shiftKey ? t('settings.shortcuts.modifierLabels.shift') : '',
+ shortcut.metaKey ? t('settings.shortcuts.modifierLabels.meta') : '',
+ key,
+ ].filter(Boolean).join('+');
+}
+
+export function useActionShortcutLabel(shortcut: ActionShortcut): string {
+ const { t } = useTranslation();
+ return formatActionShortcut(shortcut, t);
+}
+
+const defaultSnapshot = JSON.stringify(defaultActionShortcuts());
+
+function shortcutSnapshot(): string {
+ return JSON.stringify(readActionShortcuts());
+}
+
+function subscribeToActionShortcuts(listener: () => void): () => void {
+ if (typeof window === 'undefined') return () => undefined;
+ const onStorage = (event: StorageEvent) => {
+ if (event.key === ACTION_SHORTCUTS_STORAGE_KEY) listener();
+ };
+ window.addEventListener('storage', onStorage);
+ window.addEventListener(ACTION_SHORTCUTS_CHANGED_EVENT, listener);
+ return () => {
+ window.removeEventListener('storage', onStorage);
+ window.removeEventListener(ACTION_SHORTCUTS_CHANGED_EVENT, listener);
+ };
+}
+
+export function useActionShortcuts(): ActionShortcuts {
+ const snapshot = useSyncExternalStore(
+ subscribeToActionShortcuts,
+ shortcutSnapshot,
+ () => defaultSnapshot,
+ );
+ return useMemo(() => normalizeActionShortcuts(JSON.parse(snapshot)), [snapshot]);
+}
diff --git a/ui/src/lib/applicationRoutes.ts b/ui/src/lib/applicationRoutes.ts
index 1cceed0dd..17aecbf22 100644
--- a/ui/src/lib/applicationRoutes.ts
+++ b/ui/src/lib/applicationRoutes.ts
@@ -46,6 +46,7 @@ export const APPLICATION_ROUTE_PATHS = [
'/settings',
'/settings/appearance',
'/settings/account',
+ '/settings/shortcuts',
'/settings/service',
'/settings/platforms',
'/settings/platforms/groups',
diff --git a/ui/src/lib/pwaRouteMemory.test.ts b/ui/src/lib/pwaRouteMemory.test.ts
index f3a3d9812..ed51a42b8 100644
--- a/ui/src/lib/pwaRouteMemory.test.ts
+++ b/ui/src/lib/pwaRouteMemory.test.ts
@@ -11,6 +11,7 @@ import {
describe('PWA route memory', () => {
it('restores canonical and dynamic app pages while dropping URL state', () => {
expect(normalizeRestorablePwaPath('/inbox')).toBe('/inbox');
+ expect(normalizeRestorablePwaPath('/settings/shortcuts')).toBe('/settings/shortcuts');
expect(normalizeRestorablePwaPath('/chat/session-123?from=push#latest')).toBe('/chat/session-123');
expect(normalizeRestorablePwaPath('/admin/settings/backends/codex')).toBe(
'/admin/settings/backends/codex',
diff --git a/ui/src/lib/pwaRouteMemory.ts b/ui/src/lib/pwaRouteMemory.ts
index f32361c79..b17a0a1af 100644
--- a/ui/src/lib/pwaRouteMemory.ts
+++ b/ui/src/lib/pwaRouteMemory.ts
@@ -19,6 +19,7 @@ const RESTORABLE_EXACT_PATHS = new Set([
'/settings',
'/settings/appearance',
'/settings/account',
+ '/settings/shortcuts',
'/settings/service',
'/settings/platforms',
'/settings/platforms/groups',