Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions apps/web/src/speech/browserPcmCapture.browser.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,64 @@
import { expect, it, vi } from "vite-plus/test";
import { createBrowserPcmCapture } from "./browserPcmCapture";
import { stubGlobal } from "../../test/render";

it("keeps streamed PCM until the owned recording is deleted", async () => {
let deliver!: (data: Float32Array | "stopped") => void;
const feed = vi.fn();
using _microphone = vi.spyOn(navigator.mediaDevices, "getUserMedia").mockResolvedValue({
getTracks: () => [{ stop() {}, addEventListener() {} }],
} as unknown as MediaStream);
using _context = stubGlobal(
"AudioContext",
class {
audioWorklet = { addModule: async () => {} };
destination = {};
createMediaStreamSource() {
return { connect() {} };
}
async resume() {}
async close() {}
},
);
using _worklet = stubGlobal(
"AudioWorkletNode",
class {
port = {
onmessage: (_event: { data: Float32Array | "stopped" }) => {},
postMessage: () => deliver("stopped"),
close() {},
};
constructor() {
deliver = (data) => this.port.onmessage({ data });
}
connect() {}
disconnect() {}
},
);
const capture = createBrowserPcmCapture(
{ getMicrophoneId: () => "", onLevel: vi.fn(), onDurationLimit: vi.fn(), onError: vi.fn() },
async () => ({
locale: "en",
transcribe: async () => "",
streaming: { feed, finish: async () => "" },
}),
);
const signal = new AbortController().signal;
await capture.transcriber.prepare({ signal });
await capture.recorder.prepareToRecordAsync(signal);
const samples = new Float32Array([0.25, -0.5]);
deliver(samples);
await capture.recorder.stop();
expect(feed).toHaveBeenCalledExactlyOnceWith(samples);
expect(capture.recorder.uri).not.toBeNull();
const uri = capture.recorder.uri!;
try {
expect(new Float32Array(await (await fetch(uri)).arrayBuffer())).toEqual(samples);
} finally {
capture.deleteRecording(uri);
}
expect(capture.recorder.uri).toBeNull();
});

it("cancels an unanswered permission prompt and stops a late microphone stream", async () => {
let grantPermission!: (media: MediaStream) => void;
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/speech/browserPcmCapture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export function createBrowserPcmCapture(
return;
}
if (feed) feed(data);
else chunks.push(data);
chunks.push(data);
};
node.onprocessorerror = () => {
stopped?.reject(new Error("Microphone processing failed."));
Expand Down Expand Up @@ -149,7 +149,7 @@ export function createBrowserPcmCapture(
worklet.port.postMessage("stop");
try {
await pending;
if (!feed && chunks.length) {
if (chunks.length) {
const blob = new Blob(chunks, { type: "application/octet-stream" });
recordingUri = URL.createObjectURL(blob);
}
Expand Down
76 changes: 60 additions & 16 deletions apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const mocks = vi.hoisted(() => ({
platforms: [] as string[],
microphoneRequests: [] as string[],
transcribeCalls: [] as string[],
deletedRecordings: [] as string[],
cleanupCalls: [] as string[],
cleanupDraft: vi.fn(),
cleanupOptions: [] as SpeechPostProcessingOptions[],
Expand Down Expand Up @@ -196,7 +197,9 @@ vi.mock("./browserVoiceInput", () => ({
},
},
cancelRecording() {},
deleteRecording() {},
deleteRecording(uri: string) {
mocks.deletedRecordings.push(uri);
},
};
},
}));
Expand Down Expand Up @@ -226,6 +229,7 @@ function setup(options: { readonly destination?: string | null } = {}) {
mocks.platforms = [];
mocks.microphoneRequests = [];
mocks.transcribeCalls = [];
mocks.deletedRecordings = [];
mocks.cleanupCalls = [];
mocks.cleanupDraft.mockClear();
mocks.cleanupOptions = [];
Expand Down Expand Up @@ -450,21 +454,61 @@ it("still abandons a detachable recording when the destination changes", async (
expect(drafts["thread-a"]).toBe("Fix dictated");
});

it("drops a detached recording whose transcription failed and leaves its thread idle", async () => {
setup({ destination: "env-a" });
vi.mocked(toastManager.add).mockClear();
mocks.transcripts = [new Error("inference failed")];
const drafts: Record<string, string> = { "thread-a": "Fix", "thread-b": "" };
await using screen = await render(<ThreadProbe owner="thread-a" drafts={drafts} />);
await act(() => mocks.voice.start());
await screen.rerender(<ThreadProbe owner="thread-b" drafts={drafts} />);
await vi.waitFor(() =>
expect(toastManager.add).toHaveBeenCalledWith(expect.objectContaining({ type: "error" })),
);
await screen.rerender(<ThreadProbe owner="thread-a" drafts={drafts} />);
expect(mocks.voice.state.phase).toBe("idle");
expect(drafts["thread-a"]).toBe("Fix");
});
it.each(["retry", "cancel", "unmount", "consent", "unmount-before-failure"] as const)(
"keeps failed detached audio for its original owner until %s",
async (action) => {
setup({ destination: "env-a" });
vi.mocked(toastManager.add).mockClear();
mocks.transcripts = [new Error("inference failed"), "recovered"];
const submit = vi.fn();
const drafts: Record<string, string> = { "thread-a": "Fix", "thread-b": "" };
await using screen = await render(<ThreadProbe owner="thread-a" drafts={drafts} />);
await act(() => mocks.voice.start());
const finishing = mocks.voice.stop();
await act(() => mocks.voice.submitAfterDictation(submit));
await screen.rerender(
action === "unmount-before-failure" ? (
<div />
) : (
<ThreadProbe owner="thread-b" drafts={drafts} />
),
);
await act(() => finishing);
if (action === "unmount-before-failure") {
expect(mocks.deletedRecordings).toEqual(["blob:env-a"]);
expect(drafts["thread-a"]).toBe("Fix");
return;
}
expect(mocks.voice.state.phase).toBe("idle");
expect(mocks.deletedRecordings).toEqual([]);
await act(() => mocks.voice.start());
await act(() => mocks.voice.cancel());
expect(mocks.microphoneRequests).toEqual(["env-a"]);
expect(mocks.deletedRecordings).toEqual([]);
if (action === "unmount") {
await screen.rerender(<div />);
} else if (action === "consent") {
setDestination("env-b");
await screen.rerender(<ThreadProbe owner="thread-b" drafts={drafts} />);
} else {
await screen.rerender(<ThreadProbe owner="thread-a" drafts={drafts} />);
expect(mocks.voice.state.phase).toBe("error");
await screen.rerender(<ThreadProbe owner="thread-b" drafts={drafts} />);
expect(mocks.deletedRecordings).toEqual([]);
await screen.rerender(<ThreadProbe owner="thread-a" drafts={drafts} />);
if (action === "retry") {
drafts["thread-a"] = "Edited";
await act(() => mocks.voice.start());
expect(mocks.transcribeCalls).toEqual(["env-a", "env-a"]);
expect(mocks.microphoneRequests).toEqual(["env-a"]);
expect(drafts["thread-a"]).toBe("Edited recovered");
} else await act(() => mocks.voice.cancel());
}
expect(drafts["thread-b"]).toBe("");
expect(submit).not.toHaveBeenCalled();
expect(mocks.deletedRecordings).toEqual(["blob:env-a"]);
},
);

it("does not start or cancel from another thread while the previous one finishes", async () => {
setup({ destination: "env-a" });
Expand Down
22 changes: 18 additions & 4 deletions apps/web/src/speech/useEnvironmentSpeechInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,10 @@ function detachRecording(
if (
!detachDraft ||
snapshot?.ownerKey !== ownerKey ||
(phase !== "recording" && phase !== "transcribing" && phase !== "post-processing")
(phase !== "recording" &&
phase !== "transcribing" &&
phase !== "post-processing" &&
!(phase === "error" && controller.canRetryRecording))
)
return false;
detachedRef.current = { snapshot, access: detachDraft() };
Expand Down Expand Up @@ -437,10 +440,15 @@ export function useEnvironmentSpeechInput(input: HookInput) {
const detached = detachedRef.current;
if (detached) {
if (value.phase !== "idle" && value.phase !== "error") return;
if (value.phase === "error" && !disposed && controller.canRetryRecording) {
failDetached(
`${value.error} Return to the original thread to retry or discard the recording.`,
);
return;
}
detachedRef.current = null;
if (value.phase === "error") {
failDetached(value.error);
// Drops the audio kept for Retry; no editor shows this recording to offer it.
controller.cancel();
}
return;
Expand All @@ -461,6 +469,7 @@ export function useEnvironmentSpeechInput(input: HookInput) {
const last = latestRef.current.input;
if (
unmountingRef.current &&
controller.currentState.phase !== "error" &&
(detachedRef.current ||
detachRecording(controller, detachedRef, lastSnapshotRef.current, last))
)
Expand Down Expand Up @@ -590,10 +599,15 @@ export function useEnvironmentSpeechInput(input: HookInput) {
const start = useStableCallback(async () => {
if (latestRef.current.input.disabled || (setup.open && setup.downloading)) return;
if (detachedRef.current) {
const retained = controllerRef.current?.canRetryRecording;
toastManager.add({
type: "info",
title: "Finishing dictation for the previous thread",
description: "Try again in a moment.",
title: retained
? "A recording is waiting for retry in the previous thread"
: "Finishing dictation for the previous thread",
description: retained
? "Return to that thread to retry or discard the recording."
: "Try again in a moment.",
});
return;
}
Expand Down
8 changes: 5 additions & 3 deletions docs/user/voice-input.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,11 @@ five minutes. Text is inserted at the cursor or replaces the selection you had
when recording started, and the editor is read-only while dictation runs.
Switching threads while dictating in the composer finishes the recording into
the draft of the thread you started in; dictation in another thread can start
once it is done. If that transcript cannot be added, a notification says why and
the recording is discarded. A spoken answer to an agent's question is discarded
instead.
once it is done. If transcription fails while the composer remains open, return
to the original thread to retry or discard its recording before starting another.
Closing the composer or changing the voice destination discards retained audio.
Other failures show a notification and discard the recording. A spoken answer
to an agent's question is discarded instead.

Pressing Send while dictating finishes the recording and sends the draft once
the transcript has been inserted. Cancelling also cancels that queued send. In
Expand Down
56 changes: 33 additions & 23 deletions packages/client-runtime/src/voice-input/controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,30 +88,40 @@ function createHarness(
describe("environment voice input", () => {
beforeEach(() => resetVoiceInputGlobalsForTests());

it("retries failed batch audio without recording again, then deletes it", async () => {
const transcribe = vi
.fn<PreparedVoiceTranscription["transcribe"]>()
.mockRejectedValueOnce(new Error("inference failed"))
.mockResolvedValueOnce("recovered text");
const harness = createHarness({
retryFailedRecording: true,
getTranscriber: () => ({ prepare: async () => preparedTranscription(transcribe) }),
});
await harness.controller.start();
await harness.controller.stop();
expect(harness.controller.currentState.phase).toBe("error");
expect(harness.deleted).toEqual([]);
it.each([false, true])(
"retries failed audio (streaming: %s) without recording again, then deletes it",
async (streaming) => {
const transcribe = vi
.fn<PreparedVoiceTranscription["transcribe"]>()
.mockRejectedValueOnce(new Error("inference failed"))
.mockResolvedValueOnce("recovered text");
const harness = createHarness({
retryFailedRecording: true,
getTranscriber: () => ({
prepare: async () => ({
...preparedTranscription(transcribe),
...(streaming
? { streaming: { finish: (options) => transcribe("file:///voice.m4a", options) } }
: {}),
}),
}),
});
await harness.controller.start();
await harness.controller.stop();
expect(harness.controller.currentState.phase).toBe("error");
expect(harness.deleted).toEqual([]);

harness.setDraft(draft({ text: "updated ", revision: 2, selection: { start: 8, end: 8 } }));
await harness.controller.start();
expect(transcribe.mock.calls.map(([uri]) => uri)).toEqual([
"file:///voice.m4a",
"file:///voice.m4a",
]);
expect(harness.recorder.record).toHaveBeenCalledOnce();
expect(harness.commits[0]?.text).toBe("updated recovered text");
expect(harness.deleted).toEqual(["file:///voice.m4a"]);
});
harness.setDraft(draft({ text: "updated ", revision: 2, selection: { start: 8, end: 8 } }));
await harness.controller.start();
expect(transcribe.mock.calls.map(([uri]) => uri)).toEqual([
"file:///voice.m4a",
"file:///voice.m4a",
]);
expect(harness.recorder.record).toHaveBeenCalledOnce();
expect(harness.commits[0]?.text).toBe("updated recovered text");
expect(harness.deleted).toEqual(["file:///voice.m4a"]);
},
);

it("deletes retained failed audio when the user cancels instead of retrying", async () => {
const harness = createHarness({
Expand Down
13 changes: 6 additions & 7 deletions packages/client-runtime/src/voice-input/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,10 @@ export class VoiceInputController {
return this.state;
}

get canRetryRecording(): boolean {
return this.retryRecording !== null;
}

async start(): Promise<void> {
if (this.state.phase !== "idle" && this.state.phase !== "error") return;
const initiatingDraft = this.dependencies.readDraft();
Expand Down Expand Up @@ -515,16 +519,11 @@ export class VoiceInputController {
));
} catch (error) {
if (this.isCurrent(operationToken)) {
if (
this.dependencies.retryFailedRecording &&
!this.liveTranscription &&
!transcription.streaming &&
recordingUri
) {
if (this.dependencies.retryFailedRecording && !this.liveTranscription && recordingUri) {
this.retryRecording = {
uri: recordingUri,
ownerKey: capturedDraft.ownerKey,
transcription,
transcription: { locale: transcription.locale, transcribe: transcription.transcribe },
};
}
this.setError(transcriptionErrorMessage(error), "retry");
Expand Down