diff --git a/apps/web/src/speech/browserPcmCapture.browser.test.ts b/apps/web/src/speech/browserPcmCapture.browser.test.ts index 892f6d640691d..a53f59f62f2c0 100644 --- a/apps/web/src/speech/browserPcmCapture.browser.test.ts +++ b/apps/web/src/speech/browserPcmCapture.browser.test.ts @@ -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; diff --git a/apps/web/src/speech/browserPcmCapture.ts b/apps/web/src/speech/browserPcmCapture.ts index f38d616d95441..a1d78d1fa2b10 100644 --- a/apps/web/src/speech/browserPcmCapture.ts +++ b/apps/web/src/speech/browserPcmCapture.ts @@ -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.")); @@ -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); } diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx index 58f11d581c457..b81bf7a74ca6f 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx +++ b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx @@ -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[], @@ -196,7 +197,9 @@ vi.mock("./browserVoiceInput", () => ({ }, }, cancelRecording() {}, - deleteRecording() {}, + deleteRecording(uri: string) { + mocks.deletedRecordings.push(uri); + }, }; }, })); @@ -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 = []; @@ -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 = { "thread-a": "Fix", "thread-b": "" }; - await using screen = await render(); - await act(() => mocks.voice.start()); - await screen.rerender(); - await vi.waitFor(() => - expect(toastManager.add).toHaveBeenCalledWith(expect.objectContaining({ type: "error" })), - ); - await screen.rerender(); - 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 = { "thread-a": "Fix", "thread-b": "" }; + await using screen = await render(); + await act(() => mocks.voice.start()); + const finishing = mocks.voice.stop(); + await act(() => mocks.voice.submitAfterDictation(submit)); + await screen.rerender( + action === "unmount-before-failure" ? ( +
+ ) : ( + + ), + ); + 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(
); + } else if (action === "consent") { + setDestination("env-b"); + await screen.rerender(); + } else { + await screen.rerender(); + expect(mocks.voice.state.phase).toBe("error"); + await screen.rerender(); + expect(mocks.deletedRecordings).toEqual([]); + await screen.rerender(); + 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" }); diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index 456b15917465a..cfa251bd8e894 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -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() }; @@ -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; @@ -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)) ) @@ -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; } diff --git a/docs/user/voice-input.md b/docs/user/voice-input.md index a20e22028527c..b7314e9d7d905 100644 --- a/docs/user/voice-input.md +++ b/docs/user/voice-input.md @@ -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 diff --git a/packages/client-runtime/src/voice-input/controller.test.ts b/packages/client-runtime/src/voice-input/controller.test.ts index 41e56933ce104..2f8375d8ad1c6 100644 --- a/packages/client-runtime/src/voice-input/controller.test.ts +++ b/packages/client-runtime/src/voice-input/controller.test.ts @@ -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() - .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() + .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({ diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index 668705546a489..52f250b248aa5 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -259,6 +259,10 @@ export class VoiceInputController { return this.state; } + get canRetryRecording(): boolean { + return this.retryRecording !== null; + } + async start(): Promise { if (this.state.phase !== "idle" && this.state.phase !== "error") return; const initiatingDraft = this.dependencies.readDraft(); @@ -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");