Skip to content

Commit 5ef056b

Browse files
committed
fix(ui): preserve dictation draft ownership through preview and cancel
1 parent a868258 commit 5ef056b

8 files changed

Lines changed: 253 additions & 83 deletions

‎ui/src/e2e/browser-dictation-status.e2e.test.ts‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,135 @@ const suite = createControlUiE2eSuite({
1515
});
1616

1717
suite.define(() => {
18+
it.each([
19+
{ name: "caret insertion", start: 5, end: 5, expected: "ship please it", cancel: false },
20+
{ name: "selection replacement", start: 5, end: 7, expected: "ship please", cancel: false },
21+
{ name: "cancel after blur", start: 7, end: 7, expected: "ship it please", cancel: true },
22+
])("preserves the draft through $name", async ({ name, start, end, expected, cancel }) => {
23+
await suite.withPage({ permissions: ["microphone"] }, async ({ page }) => {
24+
const gateway = await installMockGateway(page, {
25+
deferredMethods: ["talk.session.create"],
26+
methodResponses: {
27+
"talk.catalog": {
28+
transcription: { ready: true, providers: [] },
29+
realtime: { providers: [] },
30+
speech: { providers: [] },
31+
modes: [],
32+
transports: [],
33+
brains: [],
34+
},
35+
"talk.session.create": {
36+
sessionId: "dictation-preview-proof",
37+
transcriptionSessionId: "dictation-preview-proof",
38+
audio: { inputEncoding: "g711_ulaw", inputSampleRateHz: 8000 },
39+
},
40+
},
41+
});
42+
await installTalkBrowserFixtures(page);
43+
await page.goto(`${suite.server.baseUrl}chat`);
44+
const textarea = page.locator(".agent-chat__composer-combobox textarea");
45+
await textarea.fill("ship it");
46+
await textarea.evaluate(
47+
(element: HTMLTextAreaElement, selection) =>
48+
element.setSelectionRange(selection.start, selection.end),
49+
{ start, end },
50+
);
51+
await page.getByRole("button", { name: "Start voice input" }).hover();
52+
await page.mouse.down();
53+
await gateway.waitForRequest("talk.session.create");
54+
await gateway.resolveDeferred("talk.session.create");
55+
await page.mouse.up();
56+
await gateway.emitGatewayEvent("talk.event", {
57+
transcriptionSessionId: "dictation-preview-proof",
58+
type: "partial",
59+
text: "please",
60+
});
61+
await expect.poll(() => textarea.inputValue()).toBe(expected);
62+
if (cancel) {
63+
await page.getByRole("button", { name: "Collapse sidebar", exact: true }).click();
64+
await page.keyboard.press("Escape");
65+
} else {
66+
await page.getByRole("button", { name: "Stop and keep text" }).click();
67+
}
68+
await gateway.waitForRequest("talk.session.close");
69+
const committedDraft = cancel ? "ship it" : expected;
70+
expect(await textarea.inputValue()).toBe(committedDraft);
71+
expect(await gateway.getRequests("chat.send")).toHaveLength(0);
72+
await captureComposerProof(page, `dictation-${name.replaceAll(" ", "-")}-committed.png`);
73+
expect(await textarea.inputValue()).toBe(committedDraft);
74+
});
75+
});
76+
77+
it("keeps recognized speech visible until Escape cancels new-session dictation", async () => {
78+
await suite.withPage({ permissions: ["microphone"] }, async ({ page }) => {
79+
const gateway = await installMockGateway(page, {
80+
deferredMethods: ["talk.session.create"],
81+
featureMethods: ["chat.metadata", "chat.startup", "sessions.create", "sessions.dispatch"],
82+
methodResponses: {
83+
"talk.catalog": {
84+
transcription: { ready: true, providers: [] },
85+
realtime: { providers: [] },
86+
speech: { providers: [] },
87+
modes: [],
88+
transports: [],
89+
brains: [],
90+
},
91+
"talk.session.create": {
92+
sessionId: "dictation-direct-proof",
93+
transcriptionSessionId: "dictation-direct-proof",
94+
audio: { inputEncoding: "g711_ulaw", inputSampleRateHz: 8000 },
95+
},
96+
},
97+
});
98+
await installTalkBrowserFixtures(page);
99+
await page.goto(`${suite.server.baseUrl}new`);
100+
const textarea = page.locator(".new-session-page__message");
101+
await textarea.fill("keep this draft");
102+
await page.getByRole("button", { name: "Dictate", exact: true }).click();
103+
await gateway.waitForRequest("talk.session.create");
104+
await gateway.resolveDeferred("talk.session.create");
105+
await gateway.emitGatewayEvent("talk.event", {
106+
transcriptionSessionId: "dictation-direct-proof",
107+
type: "partial",
108+
text: "discard this speech",
109+
});
110+
await expect.poll(() => textarea.inputValue()).toContain("discard this speech");
111+
await gateway.emitGatewayEvent("talk.event", {
112+
transcriptionSessionId: "dictation-direct-proof",
113+
type: "transcript",
114+
text: "discard this speech",
115+
final: true,
116+
});
117+
await expect.poll(() => textarea.inputValue()).toBe("keep this draft discard this speech");
118+
await gateway.emitGatewayEvent("talk.event", {
119+
transcriptionSessionId: "dictation-direct-proof",
120+
type: "partial",
121+
text: "too",
122+
});
123+
await expect
124+
.poll(() => textarea.inputValue())
125+
.toBe("keep this draft discard this speech too");
126+
await gateway.emitGatewayEvent("talk.event", {
127+
transcriptionSessionId: "dictation-direct-proof",
128+
type: "transcript",
129+
text: "",
130+
final: true,
131+
});
132+
await expect
133+
.poll(() => textarea.inputValue())
134+
.toBe("keep this draft discard this speech too");
135+
await captureComposerProof(page, "dictation-new-session-recognized-preview.png");
136+
await page.keyboard.press("Escape");
137+
await expect.poll(() => textarea.inputValue()).toBe("keep this draft");
138+
await gateway.waitForRequest("talk.session.close");
139+
expect(await page.getByRole("button", { name: "Dictate", exact: true }).isVisible()).toBe(
140+
true,
141+
);
142+
expect(await gateway.getRequests("sessions.create")).toHaveLength(0);
143+
await captureComposerProof(page, "dictation-new-session-cancelled.png");
144+
});
145+
});
146+
18147
it("keeps the hold-to-dictate switch interactive without closing the microphone picker", async () => {
19148
await suite.withPage({ permissions: ["microphone"] }, async ({ page }) => {
20149
await installMockGateway(page, {

‎ui/src/pages/chat/components/chat-composer-types.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,5 +174,5 @@ export type ChatComposerState = SkillMenuState &
174174
dictation: ComposerDictationController | null;
175175
dictationDraftKey: string | null;
176176
dictationError: string | null;
177-
dictationSelection: { start: number; end: number } | null;
177+
dictationSelection: { start: number; end: number; value: string } | null;
178178
};

‎ui/src/pages/chat/components/chat-composer-view.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -242,15 +242,14 @@ export function renderChatComposerView(context: ChatComposerViewContext) {
242242
: nothing;
243243
// Dictation previews at the captured selection. The textarea remains
244244
// read-only until stop commits the same insertion into the real draft.
245-
const dictationPreviewDraft =
246-
dictation?.active && dictation.partial
247-
? insertComposerDictation(
248-
visibleDraft,
249-
dictation.partial,
250-
state.dictationSelection?.start ?? visibleDraft.length,
251-
state.dictationSelection?.end ?? visibleDraft.length,
252-
).value
253-
: visibleDraft;
245+
const dictationPreviewDraft = dictation?.active
246+
? insertComposerDictation(
247+
state.dictationSelection?.value ?? visibleDraft,
248+
dictation.transcript,
249+
state.dictationSelection?.start ?? visibleDraft.length,
250+
state.dictationSelection?.end ?? visibleDraft.length,
251+
).value
252+
: visibleDraft;
254253
const draftDirection = detectTextDirection(dictationPreviewDraft);
255254
const interruptedStatus = props.runError
256255
? nothing

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

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -384,12 +384,15 @@ export function renderChatComposer(props: ChatComposerProps) {
384384
if (state.composingDraft?.key === draftKey) {
385385
state.composingDraft = null;
386386
}
387-
const normalizedDraft = normalizeChatComposerDraft(target.value);
388-
if (target.value !== normalizedDraft) {
389-
target.value = normalizedDraft;
390-
adjustTextareaHeight(target);
387+
// Dictation owns the read-only preview; blur must not commit discarded speech.
388+
if (!state.dictation?.locksComposer) {
389+
const normalizedDraft = normalizeChatComposerDraft(target.value);
390+
if (target.value !== normalizedDraft) {
391+
target.value = normalizedDraft;
392+
adjustTextareaHeight(target);
393+
}
394+
commitComposerDraft(props, normalizedDraft);
391395
}
392-
commitComposerDraft(props, normalizedDraft);
393396
props.onTypingChange?.(false);
394397
};
395398
const handleSend = (submissionAction?: Event) => {
@@ -467,10 +470,10 @@ export function renderChatComposer(props: ChatComposerProps) {
467470
const selection = state.dictationSelection ?? {
468471
start: target?.selectionStart ?? visibleDraft.length,
469472
end: target?.selectionEnd ?? visibleDraft.length,
473+
value: props.getDraft?.() ?? props.draft,
470474
};
471-
const currentDraft = target?.value ?? props.getDraft?.() ?? props.draft;
472475
const insertion = insertComposerDictation(
473-
currentDraft,
476+
selection.value,
474477
transcript,
475478
selection.start,
476479
selection.end,
@@ -525,12 +528,17 @@ export function renderChatComposer(props: ChatComposerProps) {
525528
requestUpdate();
526529
}
527530
const target = state.composerTextarea;
528-
state.dictationSelection = {
531+
const selection = {
529532
start: target?.selectionStart ?? visibleDraft.length,
530533
end: target?.selectionEnd ?? visibleDraft.length,
534+
value: target?.value ?? visibleDraft,
531535
};
532-
if (dictation?.handlePointerDown(event) && target) {
533-
target.readOnly = true;
536+
if (dictation?.handlePointerDown(event)) {
537+
// Stop also emits pointerdown; only a new gesture owns a draft snapshot.
538+
state.dictationSelection = selection;
539+
if (target) {
540+
target.readOnly = true;
541+
}
534542
}
535543
};
536544
const runControlsProps: ChatRunControlsProps = {

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

Lines changed: 65 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -190,29 +190,52 @@ afterEach(() => {
190190
});
191191

192192
describe("ComposerDictationController", () => {
193-
it("starts the canonical session immediately for a direct-dictation surface", async () => {
194-
const { controller } = createHarness();
195-
196-
expect(controller.startDirect()).toBe(true);
197-
await waitForFast(() =>
198-
expect(request).toHaveBeenCalledWith("talk.session.create", expect.anything()),
199-
);
193+
it.each(["Escape", "blur", "hidden"])("cancels direct dictation on %s", async (action) => {
194+
const { controller, onCommit } = createHarness();
195+
const stopTrack = vi.fn();
196+
getUserMedia.mockResolvedValue({ getTracks: () => [{ stop: stopTrack }] });
197+
198+
try {
199+
expect(controller.startDirect()).toBe(true);
200+
await waitForFast(() =>
201+
expect(request).toHaveBeenCalledWith("talk.session.create", expect.anything()),
202+
);
203+
expect(getUserMedia).toHaveBeenCalledOnce();
204+
expect(controller.active).toBe(true);
205+
emit({ transcriptionSessionId: "dictation-1", type: "partial", text: "discard me" });
206+
207+
if (action === "Escape") {
208+
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
209+
} else if (action === "blur") {
210+
window.dispatchEvent(new Event("blur"));
211+
} else {
212+
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
213+
document.dispatchEvent(new Event("visibilitychange"));
214+
}
200215

201-
expect(getUserMedia).toHaveBeenCalledOnce();
202-
expect(controller.active).toBe(true);
203-
controller.dispose();
216+
expect(controller.active).toBe(false);
217+
expect(stopTrack).toHaveBeenCalledOnce();
218+
expect(onCommit).not.toHaveBeenCalled();
219+
await waitForFast(() =>
220+
expect(request).toHaveBeenCalledWith("talk.session.close", { sessionId: "dictation-1" }),
221+
);
222+
} finally {
223+
controller.dispose();
224+
}
204225
});
205226

206227
it("commits and unlocks immediately while remote close finishes in background", async () => {
207228
let resolveClose: () => void = () => {};
208229
const close = new Promise<void>((resolve) => {
209230
resolveClose = resolve;
210231
});
232+
let sessionsCreated = 0;
211233
request = vi.fn(async (method: string) => {
212234
if (method === "talk.session.create") {
235+
const sessionId = `dictation-${++sessionsCreated}`;
213236
return {
214-
sessionId: "dictation-1",
215-
transcriptionSessionId: "dictation-1",
237+
sessionId,
238+
transcriptionSessionId: sessionId,
216239
audio: { inputEncoding: "g711_ulaw", inputSampleRateHz: 8000 },
217240
};
218241
}
@@ -232,9 +255,26 @@ describe("ComposerDictationController", () => {
232255
expect(onCommit).toHaveBeenCalledWith("keep this now");
233256
await expect(committed).resolves.toBe(true);
234257
expect(request).toHaveBeenCalledWith("talk.session.close", { sessionId: "dictation-1" });
235-
resolveClose();
236-
await Promise.resolve();
237-
controller.dispose();
258+
try {
259+
expect(controller.startDirect()).toBe(true);
260+
await waitForFast(() => expect(sessionsCreated).toBe(2));
261+
emit({ transcriptionSessionId: "dictation-2", type: "partial", text: "new preview" });
262+
expect(controller.transcript).toBe("new preview");
263+
emit({ transcriptionSessionId: "dictation-1", type: "partial", text: "stale preview" });
264+
expect(controller.transcript).toBe("new preview");
265+
emit({
266+
transcriptionSessionId: "dictation-1",
267+
type: "transcript",
268+
text: "late final",
269+
final: true,
270+
});
271+
expect(controller.transcript).toBe("new preview");
272+
expect(onCommit).toHaveBeenCalledExactlyOnceWith("keep this now");
273+
} finally {
274+
resolveClose();
275+
controller.dispose();
276+
await Promise.resolve();
277+
}
238278
});
239279

240280
it("consumes the click tail when a hold falls back to unavailable dictation", async () => {
@@ -397,7 +437,7 @@ describe("ComposerDictationController", () => {
397437
type: "partial",
398438
text: "hello wor",
399439
});
400-
expect(controller.partial).toBe("hello wor");
440+
expect(controller.transcript).toBe("hello wor");
401441
emit({
402442
transcriptionSessionId: "dictation-1",
403443
type: "transcript",
@@ -431,7 +471,7 @@ describe("ComposerDictationController", () => {
431471
controller.dispose();
432472
});
433473

434-
it("previews non-final transcript frames without committing them", async () => {
474+
it("previews the complete transcript without committing until Stop", async () => {
435475
const { controller, onCommit, target } = createHarness();
436476
await startHold(target);
437477
emit({
@@ -440,19 +480,25 @@ describe("ComposerDictationController", () => {
440480
text: "hello",
441481
final: false,
442482
});
443-
expect(controller.partial).toBe("hello");
483+
expect(controller.transcript).toBe("hello");
444484
emit({
445485
transcriptionSessionId: "dictation-1",
446486
type: "transcript",
447487
text: "hello world",
448488
final: true,
449489
});
490+
expect(controller.transcript).toBe("hello world");
491+
emit({ transcriptionSessionId: "dictation-1", type: "partial", text: "again" });
492+
expect(controller.transcript).toBe("hello world again");
493+
emit({ transcriptionSessionId: "dictation-1", type: "transcript", text: "", final: true });
494+
expect(controller.transcript).toBe("hello world again");
495+
expect(onCommit).not.toHaveBeenCalled();
450496

451497
await commitLatched(controller, target);
452498
await waitForFast(() =>
453499
expect(request).toHaveBeenCalledWith("talk.session.close", { sessionId: "dictation-1" }),
454500
);
455-
expect(onCommit).toHaveBeenCalledWith("hello world");
501+
expect(onCommit).toHaveBeenCalledWith("hello world again");
456502
controller.dispose();
457503
});
458504

0 commit comments

Comments
 (0)