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.

fix(ui): scope voice shortcut to chat page (#1758)

Call White14c5274c9f1a
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 79c955d66..7bcd06524 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -359,6 +359,19 @@ export const ChatPage: React.FC = () => {
// the chat surface still hidden and the iframe already gone — a blank chat.
const showPageAccessDenied = showPageRestoreAccess === 'deny';
const showPageActive = isShowPageActive(readOnly, showPageMode, showPageAccessDenied);
+ // The voice chord belongs to the active Chat page, not to whichever child
+ // happens to hold focus. Capture lets it win before the rich editor handles a
+ // user-configured chord such as Ctrl+Z. Starting remains limited to a writable,
+ // visible Chat surface; once recording, Composer still accepts the chord as
+ // Finish after focus moves elsewhere in this document.
+ const voiceShortcutCanStart = pageActive && writable && !showPageActive;
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ composerRef.current?.handleVoiceShortcut(event, voiceShortcutCanStart);
+ };
+ window.addEventListener('keydown', onKeyDown, true);
+ return () => window.removeEventListener('keydown', onKeyDown, true);
+ }, [voiceShortcutCanStart]);
// True while the share popover is open. The popover floats over the Show Page
// iframe; making the iframe inert lets an outside tap there reach the parent
// document so the (non-modal) popover dismisses, without modal-blocking the
diff --git a/ui/src/components/workbench/Composer.shortcut.test.tsx b/ui/src/components/workbench/Composer.shortcut.test.tsx
index 8e0c10357..c7b2143da 100644
--- a/ui/src/components/workbench/Composer.shortcut.test.tsx
+++ b/ui/src/components/workbench/Composer.shortcut.test.tsx
@@ -1,6 +1,7 @@
/* @vitest-environment jsdom */
import { createInstance } from 'i18next';
+import { useEffect, useRef } from 'react';
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';
@@ -59,7 +60,7 @@ import {
defaultActionShortcuts,
writeActionShortcuts,
} from '../../lib/actionShortcuts';
-import { Composer } from './Composer';
+import { Composer, type ComposerHandle } from './Composer';
const i18n = createInstance();
void i18n.use(initReactI18next).init({
@@ -69,13 +70,39 @@ void i18n.use(initReactI18next).init({
interpolation: { escapeValue: false },
});
-const renderComposer = (
- sessionId = 'shortcut-session',
- state: { disabled?: boolean; initialDraft?: string; mentions?: boolean } = {},
-) => render(
- <I18nextProvider i18n={i18n}>
- <ToastProvider>
+type ComposerTestState = {
+ disabled?: boolean;
+ initialDraft?: string;
+ mentions?: boolean;
+ shortcutStartEnabled?: boolean;
+};
+
+const ComposerShortcutHarness = ({
+ sessionId,
+ state,
+}: {
+ sessionId: string;
+ state: ComposerTestState;
+}) => {
+ const composerRef = useRef<ComposerHandle>(null);
+ const shortcutStartEnabled = state.shortcutStartEnabled ?? true;
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ composerRef.current?.handleVoiceShortcut(event, shortcutStartEnabled);
+ };
+ window.addEventListener('keydown', onKeyDown, true);
+ return () => window.removeEventListener('keydown', onKeyDown, true);
+ }, [shortcutStartEnabled]);
+
+ return (
+ <>
+ <button type="button">Outside composer</button>
+ <div role="dialog" aria-label="Foreground surface">
+ <button type="button">Foreground control</button>
+ </div>
<Composer
+ ref={composerRef}
sessionId={sessionId}
onSend={() => undefined}
disabled={state.disabled}
@@ -83,10 +110,26 @@ const renderComposer = (
onSearchAgents={state.mentions ? async () => [] : undefined}
onSearchSessions={state.mentions ? async () => [] : undefined}
/>
+ </>
+ );
+};
+
+const composerView = (
+ sessionId = 'shortcut-session',
+ state: ComposerTestState = {},
+) => (
+ <I18nextProvider i18n={i18n}>
+ <ToastProvider>
+ <ComposerShortcutHarness sessionId={sessionId} state={state} />
</ToastProvider>
- </I18nextProvider>,
+ </I18nextProvider>
);
+const renderComposer = (
+ sessionId = 'shortcut-session',
+ state: ComposerTestState = {},
+) => render(composerView(sessionId, state));
+
beforeEach(() => {
window.localStorage.clear();
voiceMocks.abort.mockReset();
@@ -138,16 +181,47 @@ describe('Composer voice shortcut', () => {
expect(voiceMocks.finish).toHaveBeenCalledOnce();
});
- it('does not handle the shortcut outside the composer', async () => {
+ it('starts and finishes from anywhere in the Chat page without taking foreign focus', async () => {
renderComposer('scoped-shortcut-session');
- const textbox = screen.getByRole('textbox');
+ const outside = screen.getByRole('button', { name: 'Outside composer' });
+ await act(async () => undefined);
+ outside.focus();
+
+ fireEvent.keyDown(outside, { code: 'KeyZ', altKey: true });
+ await waitFor(() => expect(voiceMocks.getUserMedia).toHaveBeenCalledOnce());
+ expect(document.activeElement).toBe(outside);
+
+ fireEvent.keyDown(outside, { code: 'KeyZ', altKey: true });
+ expect(voiceMocks.finish).toHaveBeenCalledOnce();
+ });
+
+ it('does not start behind a foreground surface but always finishes an active recording', async () => {
+ const view = renderComposer('gated-shortcut-session');
+ const outside = screen.getByRole('button', { name: 'Outside composer' });
+ const foreground = screen.getByRole('button', { name: 'Foreground control' });
await act(async () => undefined);
- fireEvent.keyDown(window, { code: 'KeyZ', altKey: true });
+ fireEvent.keyDown(foreground, { code: 'KeyZ', altKey: true });
expect(voiceMocks.getUserMedia).not.toHaveBeenCalled();
- fireEvent.keyDown(textbox, { code: 'KeyZ', altKey: true });
+ fireEvent.keyDown(outside, { code: 'KeyZ', altKey: true });
await waitFor(() => expect(voiceMocks.getUserMedia).toHaveBeenCalledOnce());
+ view.rerender(composerView('gated-shortcut-session', { shortcutStartEnabled: false }));
+
+ fireEvent.keyDown(foreground, { code: 'KeyZ', altKey: true });
+ expect(voiceMocks.finish).toHaveBeenCalledOnce();
+ });
+
+ it('does not start when the Chat page is not eligible', async () => {
+ renderComposer('inactive-shortcut-session', { shortcutStartEnabled: false });
+ await screen.findByRole('button', { name: en.chat.compose.voice });
+ await act(async () => undefined);
+
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Outside composer' }), {
+ code: 'KeyZ',
+ altKey: true,
+ });
+ expect(voiceMocks.getUserMedia).not.toHaveBeenCalled();
});
it('keeps a configured editor chord through the complete voice flow', async () => {
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index a34c846c6..56060f3ea 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -56,6 +56,7 @@ import {
workbenchUploadErrorTranslationKey,
} from '../../lib/workbenchUpload';
import { Button } from '../ui/button';
+import { inForegroundSurface } from './chatShortcuts';
import {
MentionEditor,
type AgentSearchResult,
@@ -366,6 +367,9 @@ export interface ComposerHandle {
* with a separating space when the composer is non-empty. No-op when the
* mention editor isn't active (the plain-textarea home composer). */
appendText: (text: string) => void;
+ /** Handle the Chat page's configured voice chord. Starting may be gated by
+ * the page, while an active recording can always be completed. */
+ handleVoiceShortcut: (event: KeyboardEvent, allowStart: boolean) => boolean;
}
// The chat-style input row: an auto-growing textarea + a Send/Stop icon button,
@@ -401,6 +405,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// box is non-empty (``hasText``) for the Send button; ``value`` still backs the
// plain-textarea (home) path. See onChange below.
const [hasText, setHasText] = useState(false);
+ const composerRootRef = useRef<HTMLDivElement | null>(null);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const valueRef = useRef('');
// Seed once from a saved draft, but only while the box is untouched so a
@@ -654,19 +659,6 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
&& voiceSessionLocksDraft(voiceSessionsById.get(sessionId))
)
);
- useImperativeHandle(ref, () => ({
- addFiles: (files: File[]) => void uploadFiles(files),
- insertSessionReference: (refSessionId: string, title?: string | null) => {
- if (voiceDraftLocked()) return;
- // Same node a typed `#` pick yields: trigger `#`, label = title||id, data
- // carries the stable sessionId → serializes to `#<id>` + a session ref.
- mentionRef.current?.insertMention('#', title?.trim() || refSessionId, { sessionId: refSessionId });
- },
- appendText: (text: string) => {
- if (!voiceDraftLocked()) mentionRef.current?.append(text);
- },
- }));
-
const captureVoiceInsertion = useCallback((): VoiceInsertionSnapshot => {
if (useMentions) {
return mentionRef.current?.captureSelection()
@@ -1248,31 +1240,40 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
}
}, [voiceDraftReadOnly]);
- const handleVoiceShortcut = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
+ const handleVoiceShortcut = useCallback((event: KeyboardEvent, allowStart: boolean): boolean => {
if (
!voiceShortcutAvailable
|| event.defaultPrevented
|| event.repeat
- || event.currentTarget.querySelector('[data-mention-picker]') !== null
- || !actionShortcutMatches(event.nativeEvent, voiceInputShortcut)
+ || Boolean(composerRootRef.current?.querySelector('[data-mention-picker]'))
+ || !actionShortcutMatches(event, voiceInputShortcut)
) {
- return;
+ return false;
}
+ if (
+ voiceControlMode === 'record'
+ && (!allowStart || inForegroundSurface(event.target as Element | null))
+ ) return false;
+
event.preventDefault();
if (voiceControlMode === 'finish') stopRecording();
else {
const activeElement = document.activeElement;
- voiceEditorFocusReturnRef.current = (
+ const editorFocus = (
activeElement === textareaRef.current
|| (
activeElement instanceof HTMLElement
&& activeElement.getAttribute('contenteditable') === 'true'
- && event.currentTarget.contains(activeElement)
+ && composerRootRef.current?.contains(activeElement)
)
) ? activeElement as HTMLElement : null;
- focusNextVoiceControlRef.current = true;
+ voiceEditorFocusReturnRef.current = editorFocus;
+ // Keep the page's current focus when the shortcut started outside the
+ // editor. Editor starts still move to Finish, then restore the caret.
+ focusNextVoiceControlRef.current = editorFocus !== null;
void startRecording(captureVoiceInsertion());
}
+ return true;
}, [
captureVoiceInsertion,
startRecording,
@@ -1282,6 +1283,23 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
voiceShortcutAvailable,
]);
+ // ChatPage owns the window listener because the shortcut applies across that
+ // page, while the composer remains the sole owner of voice state and actions.
+ // No deps array keeps every exposed operation on the latest render state.
+ useImperativeHandle(ref, () => ({
+ addFiles: (files: File[]) => void uploadFiles(files),
+ insertSessionReference: (refSessionId: string, title?: string | null) => {
+ if (voiceDraftLocked()) return;
+ // Same node a typed `#` pick yields: trigger `#`, label = title||id, data
+ // carries the stable sessionId → serializes to `#<id>` + a session ref.
+ mentionRef.current?.insertMention('#', title?.trim() || refSessionId, { sessionId: refSessionId });
+ },
+ appendText: (text: string) => {
+ if (!voiceDraftLocked()) mentionRef.current?.append(text);
+ },
+ handleVoiceShortcut,
+ }));
+
useEffect(() => {
if (!busyControls) {
setStopArmed(false);
@@ -1350,8 +1368,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
return (
<div
+ ref={composerRootRef}
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">