Skip to content

Commit aae5b0f

Browse files
authored
feat(ui): hold-to-record dictation on the composer mic button (#111114)
* feat(ui): add hold-to-record dictation * chore: drop changelog edit (release generation owns CHANGELOG.md) * fix(ui): preserve composer controls after rebase * fix(ui): preserve dictation pointer capture * fix(ui): finish dictation on cancellation * docs(ui): note transcription-relay event envelope contract at the dictation parser * test(ui): complete realtime-talk-input mock factory for shared-registry workers * test(ui): isolate composer mocks across workers * test(ui): isolate shared chat module mocks * test(ui): type shared chat spies
1 parent aaacee8 commit aae5b0f

17 files changed

Lines changed: 1980 additions & 158 deletions

‎ui/src/app/settings.node.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,28 @@ describe("loadSettings default gateway URL derivation", () => {
639639
);
640640
});
641641

642+
it("defaults composer hold-to-record on and persists only the opt-out", () => {
643+
setTestLocation({
644+
protocol: "https:",
645+
host: "gateway.example:8443",
646+
pathname: "/",
647+
});
648+
649+
const gwUrl = expectedGatewayUrl("");
650+
const scopedKey = `openclaw.control.settings.v1:${gwUrl}`;
651+
expect(loadSettings().composerHoldToRecord).toBe(true);
652+
653+
saveSettings({ ...loadSettings(), composerHoldToRecord: false });
654+
expect(JSON.parse(localStorage.getItem(scopedKey) ?? "{}").composerHoldToRecord).toBe(false);
655+
expect(loadSettings().composerHoldToRecord).toBe(false);
656+
657+
saveSettings({ ...loadSettings(), composerHoldToRecord: true });
658+
expect(JSON.parse(localStorage.getItem(scopedKey) ?? "{}")).not.toHaveProperty(
659+
"composerHoldToRecord",
660+
);
661+
expect(loadSettings().composerHoldToRecord).toBe(true);
662+
});
663+
642664
it("normalizes and persists the device-local talk camera preference", () => {
643665
setTestLocation({
644666
protocol: "https:",

‎ui/src/app/settings.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ export type UiSettings = {
115115
catalogOpenTarget?: CatalogOpenTarget;
116116
realtimeTalkInputDeviceId?: string;
117117
realtimeTalkVideoDeviceId?: string;
118+
composerHoldToRecord?: boolean;
118119
// Camera intent is device-local, not per-agent or synced through config ui.prefs.
119120
talkCameraAutoEnable?: boolean;
120121
splitRatio: number; // Sidebar split ratio (0.4 to 0.7, default 0.6)
@@ -358,6 +359,7 @@ export function loadSettings(): UiSettings {
358359
sidebarEntries: [...DEFAULT_SIDEBAR_ENTRIES],
359360
pinnedAgentIds: [],
360361
textScale: 100,
362+
composerHoldToRecord: true,
361363
};
362364

363365
try {
@@ -425,6 +427,10 @@ export function loadSettings(): UiSettings {
425427
catalogOpenTarget: normalizeCatalogOpenTarget(parsed.catalogOpenTarget),
426428
realtimeTalkInputDeviceId: normalizeOptionalString(parsed.realtimeTalkInputDeviceId),
427429
realtimeTalkVideoDeviceId: normalizeOptionalString(parsed.realtimeTalkVideoDeviceId),
430+
composerHoldToRecord:
431+
typeof parsed.composerHoldToRecord === "boolean"
432+
? parsed.composerHoldToRecord
433+
: defaults.composerHoldToRecord,
428434
talkCameraAutoEnable:
429435
typeof parsed.talkCameraAutoEnable === "boolean" ? parsed.talkCameraAutoEnable : undefined,
430436
splitRatio:
@@ -572,6 +578,7 @@ function persistSettings(next: UiSettings, options: { selectGateway?: boolean }
572578
...(normalizeOptionalString(next.realtimeTalkVideoDeviceId)
573579
? { realtimeTalkVideoDeviceId: normalizeOptionalString(next.realtimeTalkVideoDeviceId) }
574580
: {}),
581+
...(next.composerHoldToRecord === false ? { composerHoldToRecord: false } : {}),
575582
...(typeof next.talkCameraAutoEnable === "boolean"
576583
? { talkCameraAutoEnable: next.talkCameraAutoEnable }
577584
: {}),

‎ui/src/i18n/locales/en.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3908,6 +3908,20 @@ export const en: TranslationMap = {
39083908
microphonePageInactive: "Microphone inputs are unavailable while this page is inactive.",
39093909
microphonePermissionBlocked:
39103910
"Microphone access is blocked. Allow it in browser site settings to list inputs.",
3911+
holdToRecordSetting: "Hold microphone button to dictate",
3912+
holdToRecordSettingDescription:
3913+
"Hold the composer microphone button, speak, then release to insert text without sending.",
3914+
dictationAudioUnsupported: "The Gateway returned an unsupported dictation audio format.",
3915+
dictationBrowserAudioUnsupported: "This browser cannot capture dictation audio at 8 kHz.",
3916+
dictationConnecting: "Starting dictation…",
3917+
dictationDisconnected: "Dictation stopped because the Gateway disconnected.",
3918+
dictationFailed: "Dictation failed.",
3919+
dictationFinalizing: "Finishing dictation…",
3920+
dictationFinalizationTimedOut:
3921+
"Dictation stopped before the last partial transcript could be finalized.",
3922+
dictationProviderUnavailable: "No transcription provider is configured for dictation.",
3923+
dictationRecording: "Recording {elapsed}",
3924+
dictationReleaseToInsert: "Release to insert dictation",
39113925
realtimeTalkRequiresMicrophone: "Realtime voice input requires browser microphone access.",
39123926
selectedMicrophoneUnavailable:
39133927
"The selected microphone is unavailable. Choose another input or System default.",

‎ui/src/pages/chat/chat-composer.test.ts‎

Lines changed: 134 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,26 @@
11
/* @vitest-environment jsdom */
22

33
import { html, render } from "lit";
4-
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import type { GatewayBrowserClient } from "../../api/gateway.ts";
56
import type { QuestionPrompt } from "../../app/question-prompt.ts";
67
import { loadSettings, patchSettings } from "../../app/settings.ts";
8+
import { icons } from "../../components/icons.ts";
79
import { i18n, t } from "../../i18n/index.ts";
810
import { renderChatComposer, resetChatComposerState } from "./components/chat-composer.ts";
11+
import * as realtimeTalkInput from "./realtime-talk-input.ts";
912

10-
const discoverRealtimeTalkInputsMock = vi.hoisted(() => vi.fn());
11-
12-
vi.mock("./realtime-talk-input.ts", () => ({
13-
discoverRealtimeTalkInputs: discoverRealtimeTalkInputsMock,
14-
}));
15-
16-
vi.mock("../../components/icons.ts", async () => {
17-
const { html: litHtml } = await import("lit");
18-
return {
19-
icons: {
20-
camera: litHtml`<svg data-icon="camera"></svg>`,
21-
cameraOff: litHtml`<svg data-icon="camera-off"></svg>`,
22-
switchCamera: litHtml`<svg data-icon="switch-camera"></svg>`,
23-
check: litHtml`<svg data-icon="check"></svg>`,
24-
chevronDown: litHtml`<svg data-icon="chevron-down"></svg>`,
25-
},
26-
};
27-
});
13+
const discoverRealtimeTalkInputsMock = vi.fn();
14+
const openRealtimeTalkInputMock = vi.fn();
2815

2916
type ComposerProps = Parameters<typeof renderChatComposer>[0];
3017

18+
function iconMarkup(icon: unknown): string | undefined {
19+
const container = document.createElement("div");
20+
render(icon, container);
21+
return container.querySelector("svg")?.innerHTML;
22+
}
23+
3124
function props(overrides: Partial<ComposerProps> = {}): ComposerProps {
3225
return {
3326
paneId: crypto.randomUUID(),
@@ -92,11 +85,59 @@ function button(container: Element, label: string): HTMLButtonElement {
9285
return result;
9386
}
9487

88+
class DictationAudioContext {
89+
readonly destination = {};
90+
readonly sampleRate = 8000;
91+
readonly close = vi.fn(async () => undefined);
92+
93+
createMediaStreamSource() {
94+
return { connect: vi.fn(), disconnect: vi.fn() };
95+
}
96+
97+
createScriptProcessor() {
98+
return { connect: vi.fn(), disconnect: vi.fn(), onaudioprocess: null };
99+
}
100+
101+
createGain() {
102+
return { connect: vi.fn(), disconnect: vi.fn(), gain: { value: 1 } };
103+
}
104+
105+
createAnalyser() {
106+
return {
107+
fftSize: 0,
108+
smoothingTimeConstant: 0,
109+
connect: vi.fn(),
110+
disconnect: vi.fn(),
111+
getFloatTimeDomainData: (samples: Float32Array) => samples.fill(0),
112+
};
113+
}
114+
}
115+
116+
function dictationPointerDown(pointerId: number): PointerEvent {
117+
const event = new MouseEvent("pointerdown", { bubbles: true, cancelable: true, button: 0 });
118+
Object.defineProperty(event, "pointerId", { value: pointerId });
119+
return event as PointerEvent;
120+
}
121+
122+
beforeEach(() => {
123+
// ESM imports remain live when the composer was cached by another test file.
124+
// Patch the shared dependencies instead of clearing isolate:false's registry.
125+
vi.spyOn(realtimeTalkInput, "discoverRealtimeTalkInputs").mockImplementation(
126+
discoverRealtimeTalkInputsMock,
127+
);
128+
vi.spyOn(realtimeTalkInput, "openRealtimeTalkInput").mockImplementation(
129+
openRealtimeTalkInputMock,
130+
);
131+
});
132+
95133
afterEach(async () => {
96134
resetChatComposerState();
97135
discoverRealtimeTalkInputsMock.mockReset();
136+
openRealtimeTalkInputMock.mockReset();
98137
localStorage.clear();
99138
document.body.replaceChildren();
139+
vi.useRealTimers();
140+
vi.unstubAllGlobals();
100141
await i18n.setLocale("en");
101142
vi.restoreAllMocks();
102143
});
@@ -151,6 +192,15 @@ describe("renderChatComposer controls", () => {
151192
});
152193
expect(button(view.container, t("chat.runControls.queueMessage")).disabled).toBe(false);
153194

195+
const onToggleWithDraft = vi.fn();
196+
view = renderComposer({
197+
draft: "Keep this text",
198+
onToggleRealtimeTalk: onToggleWithDraft,
199+
});
200+
button(view.container, t("chat.composer.startVoiceInput")).click();
201+
expect(onToggleWithDraft).toHaveBeenCalledOnce();
202+
expect(button(view.container, t("chat.runControls.sendMessage"))).toBeTruthy();
203+
154204
view = renderComposer({
155205
canAbort: true,
156206
draft: "Replace the current run",
@@ -206,9 +256,9 @@ describe("renderChatComposer controls", () => {
206256
expect(items.find((item) => item.value === "studio-mic")?.getAttribute("aria-checked")).toBe(
207257
"true",
208258
);
209-
expect(
210-
items.find((item) => item.value === "studio-mic")?.querySelector('[data-icon="check"]'),
211-
).not.toBeNull();
259+
expect(items.find((item) => item.value === "studio-mic")?.querySelector("svg")?.innerHTML).toBe(
260+
iconMarkup(icons.check),
261+
);
212262

213263
items.find((item) => item.value === "headset")?.click();
214264
await dropdown?.updateComplete;
@@ -299,8 +349,8 @@ describe("renderChatComposer controls", () => {
299349
});
300350

301351
const cameraToggle = button(container, t("chat.composer.turnCameraOff"));
302-
expect(cameraToggle.querySelector('[data-icon="camera-off"]')).not.toBeNull();
303-
expect(cameraToggle.querySelector('[data-icon="camera"]')).toBeNull();
352+
expect(cameraToggle.querySelector("svg")?.innerHTML).toBe(iconMarkup(icons.cameraOff));
353+
expect(cameraToggle.querySelector("svg")?.innerHTML).not.toBe(iconMarkup(icons.camera));
304354
});
305355

306356
it("offers camera switching only for a live preview with multiple cameras", () => {
@@ -354,7 +404,7 @@ describe("renderChatComposer controls", () => {
354404
);
355405
});
356406

357-
it("sends attachment-only drafts instead of starting voice", () => {
407+
it("keeps send and dictation distinct for attachment-only drafts", () => {
358408
const onSend = vi.fn();
359409
const onToggleRealtimeTalk = vi.fn();
360410
const { container } = renderComposer({
@@ -368,7 +418,65 @@ describe("renderChatComposer controls", () => {
368418
expect(onToggleRealtimeTalk).not.toHaveBeenCalled();
369419
expect(
370420
container.querySelector(`button[aria-label="${t("chat.composer.startVoiceInput")}"]`),
371-
).toBeNull();
421+
).not.toBeNull();
422+
});
423+
424+
it("keeps the captured dictation button through the hold-start rerender", async () => {
425+
vi.useFakeTimers();
426+
openRealtimeTalkInputMock.mockResolvedValue({ getTracks: () => [{ stop: vi.fn() }] });
427+
vi.stubGlobal("AudioContext", DictationAudioContext);
428+
const request = vi.fn(async (method: string) => {
429+
if (method === "talk.catalog") {
430+
return { transcription: { ready: true } };
431+
}
432+
if (method === "talk.session.create") {
433+
return {
434+
sessionId: "dictation-1",
435+
transcriptionSessionId: "dictation-1",
436+
audio: { inputEncoding: "g711_ulaw", inputSampleRateHz: 8000 },
437+
};
438+
}
439+
return { ok: true };
440+
});
441+
const gatewayClient = {
442+
addEventListener: vi.fn(() => () => undefined),
443+
request,
444+
} as unknown as GatewayBrowserClient;
445+
const container = document.createElement("div");
446+
document.body.append(container);
447+
const composerProps = props({
448+
draft: "Keep this text",
449+
gatewayClient,
450+
onToggleRealtimeTalk: vi.fn(),
451+
});
452+
const draw = () => render(renderChatComposer(composerProps), container);
453+
composerProps.onRequestUpdate = draw;
454+
draw();
455+
456+
const capturedButton = container.querySelector<HTMLButtonElement>(
457+
".chat-talk-control > openclaw-tooltip > button",
458+
);
459+
expect(capturedButton).not.toBeNull();
460+
const captures = new Set<number>();
461+
Object.defineProperties(capturedButton!, {
462+
setPointerCapture: { value: (pointerId: number) => captures.add(pointerId) },
463+
hasPointerCapture: { value: (pointerId: number) => captures.has(pointerId) },
464+
releasePointerCapture: { value: (pointerId: number) => captures.delete(pointerId) },
465+
});
466+
467+
capturedButton!.dispatchEvent(dictationPointerDown(9));
468+
expect(capturedButton!.hasPointerCapture(9)).toBe(true);
469+
await vi.advanceTimersByTimeAsync(250);
470+
await Promise.resolve();
471+
await Promise.resolve();
472+
await Promise.resolve();
473+
474+
const rerenderedButton = container.querySelector<HTMLButtonElement>(
475+
".chat-talk-control > openclaw-tooltip > button",
476+
);
477+
expect(request).toHaveBeenCalledWith("talk.session.create", expect.anything());
478+
expect(rerenderedButton).toBe(capturedButton);
479+
expect(rerenderedButton?.hasPointerCapture(9)).toBe(true);
372480
});
373481

374482
it("keeps voice and generation stop controls distinct when both are active", () => {

‎ui/src/pages/chat/chat-pane.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2852,6 +2852,8 @@ class ChatPane extends OpenClawLightDomElement {
28522852
realtimeTalkVideoPending: state.realtimeTalkVideoPending,
28532853
realtimeTalkCameraError: state.realtimeTalkCameraError,
28542854
connected: state.connected,
2855+
gatewayClient: state.client,
2856+
composerHoldToRecord: state.settings.composerHoldToRecord,
28552857
canSend: catalogKey ? this.catalogSession?.canContinue === true : !selectedSessionArchived,
28562858
disabledReason: catalogDisabledReason ?? disabledReason,
28572859
disabledActionLabel:
@@ -2984,6 +2986,11 @@ class ChatPane extends OpenClawLightDomElement {
29842986
dismissRealtimeTalkError(state as never);
29852987
state.requestUpdate?.();
29862988
},
2989+
onDictationError: (message) => {
2990+
state.lastError = message;
2991+
state.chatError = message;
2992+
state.requestUpdate?.();
2993+
},
29872994
onAbort: () => void state.handleAbortChat({ preserveDraft: true }),
29882995
onQueueRemove: state.removeQueuedMessage,
29892996
onQueueRetry: (id) => void state.retryQueuedChatMessage(id),

0 commit comments

Comments
 (0)