diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 5b540f48c483e..078299093f802 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1952,19 +1952,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const readComposerSnapshotStable = useStableCallback(readComposerSnapshot); - const dictationDisabled = - !canOperateThread || - environmentUnavailable !== null || + // Another surface owns the composer; a recording into it would land nowhere. + const dictationDisplaced = projectSelectionRequired || isComposerApprovalState || activePendingIsResponding || activePendingProgress?.activeQuestion?.allowCustomAnswer === false; + const dictationDisabled = + !canOperateThread || environmentUnavailable !== null || dictationDisplaced; const speechInput = useEnvironmentSpeechInput({ environmentId, projectId: activeProjectId, projectName, ownerKey: questionAttachmentTarget ?? composerDraftTargetKey, disabled: dictationDisabled, + discardsRecording: dictationDisplaced, label: activeThread?.title ?? null, presented: !hiddenThread, // A question's answer lives only in this composer, so only the thread draft outlives it. diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx index 5c918f9430086..c51952d380363 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx @@ -170,6 +170,7 @@ it.each([{ cpu: null, accelerated: 2.1 }, { cpu: 5, accelerated: null }, { accel label: prepared.label, grantId: "test", prepared, + retainOnDisconnect: true, }), async () => { const previous = getClientSettings(); @@ -303,7 +304,13 @@ it("tests the selected model after download and preserves its transcript across const transcript = "Keep this transcript."; using _scope = vi.mocked(useEnvironmentScope).mockReturnValue(true); await vi.mocked(useVoiceTranscriptionDestination).withImplementation( - () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }), + () => ({ + environmentId: target.environmentId, + label: target.label, + grantId: "test", + prepared, + retainOnDisconnect: true, + }), async () => { await vi.mocked(useEnvironmentSpeechInput).withImplementation( (input) => ({ @@ -486,6 +493,7 @@ it.each([ label: target.label, grantId: "test", prepared, + retainOnDisconnect: true, })); await using screen = await render( {}}> @@ -562,7 +570,13 @@ it("recovers from a failed download progress poll without notifying, but reports }); using notify = vi.spyOn(toastManager, "add").mockReturnValue("test"); await vi.mocked(useVoiceTranscriptionDestination).withImplementation( - () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }), + () => ({ + environmentId: target.environmentId, + label: target.label, + grantId: "test", + prepared, + retainOnDisconnect: true, + }), async () => { const panel = (key: string) => ( {}}> diff --git a/apps/web/src/speech/browserPcmCapture.ts b/apps/web/src/speech/browserPcmCapture.ts index 72b4f73dd6e69..c3d725950dcfe 100644 --- a/apps/web/src/speech/browserPcmCapture.ts +++ b/apps/web/src/speech/browserPcmCapture.ts @@ -119,8 +119,9 @@ export function createBrowserPcmCapture( input.onLevel(data); return; } - if (feed) feed(data); - else chunks.push(data); + // Kept even while streaming, so a dropped stream can still upload the recording. + chunks.push(data); + feed?.(data); }; node.onprocessorerror = () => { stopped?.reject(new Error(m(msg("Microphone processing failed.")))); @@ -166,7 +167,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); } @@ -202,7 +203,6 @@ export function createBrowserPcmCapture( streaming = prepared.streaming; feed = prepared.streaming.feed; for (const chunk of chunks) feed(chunk); - chunks = []; } return prepared; }) @@ -222,8 +222,9 @@ export function createBrowserPcmCapture( get locale() { return destination?.locale ?? "auto"; }, + // A destination drops `streaming` when its stream fails, so the recording uploads instead. get streaming() { - return streaming; + return destination?.streaming ? streaming : undefined; }, async transcribe(uri, transcriptionOptions) { const prepared = await pending; diff --git a/apps/web/src/speech/browserVoiceInput.browser.test.ts b/apps/web/src/speech/browserVoiceInput.browser.test.ts index 5f3023a635240..69e90281b429b 100644 --- a/apps/web/src/speech/browserVoiceInput.browser.test.ts +++ b/apps/web/src/speech/browserVoiceInput.browser.test.ts @@ -130,7 +130,7 @@ it("retains all PCM until stop, retries batch audio, and captures preferences be }); const onError = vi.fn(); const platform = createBrowserVoiceInputPlatform({ - prepared, + getPrepared: () => prepared, hasAudioConsent: () => true, getStreamingEnabled: () => streaming, getTranscriptionOptions: () => options, @@ -289,7 +289,7 @@ it("streams the opening audio in order when the destination becomes ready during microphone.feed(continuing); await platform.recorder.stop(); expect(feed.mock.calls).toEqual([[opening], [continuing]]); - expect(platform.recorder.uri).toBeNull(); + expect(platform.recorder.uri).not.toBeNull(); await expect(transcription.streaming?.finish({ signal: abort.signal })).resolves.toBe("hello"); }); @@ -328,7 +328,7 @@ it.each([ const abort = new AbortController(); using _abort = { [Symbol.dispose]: () => abort.abort() }; const platform = createBrowserVoiceInputPlatform({ - prepared, + getPrepared: () => prepared, hasAudioConsent: () => true, getStreamingEnabled: () => enabled, getTranscriptionOptions: () => ({ @@ -350,3 +350,135 @@ it.each([ ); }, ); + +it.each(["lost", "replaced"] as const)( + "does not open a stream with a ticket fetched before its connection was %s", + async (change) => { + const sockets: string[] = []; + using _socket = stubGlobal( + "WebSocket", + class extends EventTarget { + constructor(url: string) { + super(); + sockets.push(url); + } + close() {} + }, + ); + let currentPrepared: typeof prepared | null = prepared; + let resolveTicket!: (response: Response) => void; + const pendingTicket = new Promise((resolve) => { + resolveTicket = resolve; + }); + using _network = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const request = new Request(input, init); + if (request.url.endsWith("/api/voice/status")) return Response.json(status); + if (request.url.includes("/api/auth/websocket-ticket/")) return (await pendingTicket).clone(); + throw new Error(`Unexpected request: ${request.url}`); + }); + const abort = new AbortController(); + using _abort = { [Symbol.dispose]: () => abort.abort() }; + const platform = createBrowserVoiceInputPlatform({ + getPrepared: () => currentPrepared, + hasAudioConsent: () => true, + getStreamingEnabled: () => true, + getTranscriptionOptions: () => DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, + getMicrophoneId: () => "", + onLevel() {}, + onDurationLimit() {}, + onText() {}, + onError() {}, + }); + const preparation = platform.transcriber.prepare({ signal: abort.signal }); + await vi.waitFor(() => + expect( + _network.mock.calls.some(([input]) => String(input).includes("websocket-ticket")), + ).toBe(true), + ); + currentPrepared = + change === "lost" ? null : { ...prepared, httpBaseUrl: "https://reconnected.example.test" }; + resolveTicket(Response.json({ ticket: "stale-ticket", expiresAt: "2030-01-01T00:00:00.000Z" })); + const transcription = await preparation; + expect(transcription.streaming).toBeUndefined(); + expect(sockets).toEqual([]); + }, +); + +it("keeps a streamed recording when its stream drops and uploads it after reconnecting", async () => { + using microphone = capture(); + const sockets: EventTarget[] = []; + using _socket = stubGlobal( + "WebSocket", + class extends EventTarget { + constructor() { + super(); + sockets.push(this); + } + send() {} + close() {} + }, + ); + const uploads: Uint8Array[] = []; + const fetch = globalThis.fetch; + using _network = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const request = new Request(input, init); + if (request.url.endsWith("/api/voice/status")) return Response.json(status); + if (request.url.includes("/api/auth/websocket-ticket/")) + return Response.json({ ticket: "stream-ticket", expiresAt: "2030-01-01T00:00:00.000Z" }); + if (request.url.endsWith("/api/voice/transcribe")) { + uploads.push(decodeSpeechPcmRequest(new Uint8Array(await request.arrayBuffer())).pcm); + return Response.json({ text: "recovered" }); + } + return fetch(input, init); + }); + let currentPrepared: typeof prepared | null = prepared; + const onError = vi.fn(); + const platform = createBrowserVoiceInputPlatform({ + getPrepared: () => currentPrepared, + hasAudioConsent: () => true, + getStreamingEnabled: () => true, + getTranscriptionOptions: () => DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, + getMicrophoneId: () => "", + onLevel() {}, + onDurationLimit() {}, + onText() {}, + onError, + }); + const commitDraft = vi.fn(); + const controller = new VoiceInputController({ + recorder: platform.recorder, + retryFailedRecording: true, + getTranscriber: () => platform.transcriber, + requestPermission: async () => ({ granted: true, canAskAgain: true }), + configureRecording: async () => {}, + releaseRecording: async () => platform.cancelRecording(), + deleteRecording: platform.deleteRecording, + readDraft: () => ({ + ownerKey: "draft", + text: "", + selection: { start: 0, end: 0 }, + revision: 0, + }), + commitDraft, + onStateChange() {}, + }); + using _controller = { [Symbol.dispose]: () => controller.dispose() }; + await controller.start(); + await vi.waitFor(() => expect(sockets).toHaveLength(1)); + microphone.feed(new Float32Array([0.1])); + currentPrepared = null; + sockets[0]!.dispatchEvent(new Event("close")); + microphone.feed(new Float32Array([0.2])); + expect(controller.currentState.phase).toBe("recording"); + expect(onError).not.toHaveBeenCalled(); + + await controller.stop(); + expect(controller.currentState).toMatchObject({ phase: "error", errorAction: "retry" }); + currentPrepared = prepared; + await controller.start(); + expect(commitDraft).toHaveBeenCalledWith("recovered", expect.anything()); + expect(uploads.map((pcm) => [...new Float32Array(pcm.slice().buffer)])).toEqual([ + [Math.fround(0.1), Math.fround(0.2)], + ]); + expect(sockets).toHaveLength(1); +}); diff --git a/apps/web/src/speech/browserVoiceInput.ts b/apps/web/src/speech/browserVoiceInput.ts index 2d03019ce4ca8..c39b9f46b1a80 100644 --- a/apps/web/src/speech/browserVoiceInput.ts +++ b/apps/web/src/speech/browserVoiceInput.ts @@ -29,7 +29,8 @@ import { m } from "../i18n/messages"; const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError); export function createBrowserVoiceInputPlatform(input: { - readonly prepared: PreparedConnection; + /** The destination's current connection; null while it reconnects. */ + readonly getPrepared: () => PreparedConnection | null; readonly cloudProvider?: CloudSpeechProvider | undefined; /** The exact OpenRouter model the grant names; required with that provider. */ readonly cloudModel?: CloudSpeechModelId | undefined; @@ -43,6 +44,14 @@ export function createBrowserVoiceInputPlatform(input: { readonly onText: (text: SpeechStreamText) => void; readonly onError: (message: string, code?: VoiceInputErrorCode) => void; }) { + const requirePrepared = () => { + const prepared = input.getPrepared(); + if (prepared) return prepared; + throw new VoiceTranscriptionError({ + code: "unavailable", + message: m(msg("Voice transcription failed. Check the destination in Settings → Voice.")), + }); + }; return createBrowserPcmCapture(input, async (options, canStream) => { const onStatus = input.getStatusListener?.(); const recordingOptions = input.getTranscriptionOptions(); @@ -54,22 +63,18 @@ export function createBrowserVoiceInputPlatform(input: { try { const response = await fetch(uri, { signal: transcriptionSignal }); const pcm = new Uint8Array(await response.arrayBuffer()); + const prepared = requirePrepared(); const result = await runEnvironmentSpeech( input.cloudProvider ? transcribeCloudPcm( - input.prepared, + prepared, input.cloudProvider, pcm, recordingOptions, input.hasAudioConsent, input.cloudModel, ) - : transcribeEnvironmentPcm( - input.prepared, - pcm, - recordingOptions, - input.hasAudioConsent, - ), + : transcribeEnvironmentPcm(prepared, pcm, recordingOptions, input.hasAudioConsent), { signal: transcriptionSignal }, ); throwIfVoiceTranscriptionAborted(transcriptionSignal); @@ -91,7 +96,7 @@ export function createBrowserVoiceInputPlatform(input: { message: m(msg("Choose an OpenRouter model in Settings → Voice.")), }); await runEnvironmentSpeech( - requireCloudSpeechKey(input.prepared, input.cloudProvider), + requireCloudSpeechKey(requirePrepared(), input.cloudProvider), options, ); throwIfVoiceTranscriptionAborted(options.signal); @@ -100,7 +105,8 @@ export function createBrowserVoiceInputPlatform(input: { transcribe: transcribeRecording, }; } - const status = await runEnvironmentSpeech(getEnvironmentSpeechStatus(input.prepared), options); + const prepared = requirePrepared(); + const status = await runEnvironmentSpeech(getEnvironmentSpeechStatus(prepared), options); throwIfVoiceTranscriptionAborted(options.signal); onStatus?.(status); throwIfVoiceTranscriptionAborted(options.signal); @@ -130,20 +136,28 @@ export function createBrowserVoiceInputPlatform(input: { ) { return batch; } - const url = await runEnvironmentSpeech(getEnvironmentSpeechStreamUrl(input.prepared), options); - if (!canStream()) return batch; - return { - locale: nativeStreaming ? language : batchLocale, - transcribe: transcribeRecording, - streaming: openSpeechStream({ - url, - canSend: input.hasAudioConsent, - options: recordingOptions, - signal: options.signal, - onText: input.onText, - onError: (error) => input.onError(error.message), - }), - }; + const streamPrepared = requirePrepared(); + const url = await runEnvironmentSpeech(getEnvironmentSpeechStreamUrl(streamPrepared), options); + // A reconnect while the URL was fetched invalidates it; the recording uploads at stop instead. + if (!canStream() || input.getPrepared() !== streamPrepared) return batch; + const transcription: { + readonly locale: string; + readonly transcribe: typeof transcribeRecording; + streaming?: ReturnType; + } = { locale: nativeStreaming ? language : batchLocale, transcribe: transcribeRecording }; + transcription.streaming = openSpeechStream({ + url, + canSend: input.hasAudioConsent, + options: recordingOptions, + signal: options.signal, + onText: input.onText, + onError: (error) => { + // A dropped stream keeps recording; the controller then uploads the local recording. + if (input.hasAudioConsent()) delete transcription.streaming; + else input.onError(error.message); + }, + }); + return transcription; }); } diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx index 99cbff1c14a13..a1d3c7a817431 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx +++ b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx @@ -38,6 +38,7 @@ const mocks = vi.hoisted(() => ({ voiceCapable: new Set(), cloudVoiceCapable: new Set(), canDictate: new Set(), + scopeLookupFailed: new Set(), prepared: new Map(), primaryEnvironmentId: "primary-env", statusRequests: [] as string[], @@ -70,6 +71,8 @@ vi.mock("../components/sidebar/mainAppLocation", () => ({ })); vi.mock("../state/session", () => ({ useEnvironmentScope: (id: string) => mocks.canDictate.has(id), + useEnvironmentScopeDenied: (id: string) => + !mocks.canDictate.has(id) && !mocks.scopeLookupFailed.has(id), usePreparedConnection: (environmentId: string | null) => { if (!environmentId || !mocks.connected.has(environmentId)) return Option.none(); let prepared = mocks.prepared.get(environmentId); @@ -181,15 +184,16 @@ vi.mock("./appleSpeech", () => ({ })); vi.mock("./browserVoiceInput", () => ({ createAppleSpeechVoiceInputPlatform: ( - input: Omit[0], "prepared">, + input: Omit[0], "getPrepared">, ) => mockPlatform("apple-speech", input), createBrowserVoiceInputPlatform: (input: Parameters[0]) => - mockPlatform(input.prepared.environmentId, input), + mockPlatform(input.getPrepared()!.environmentId, input), })); function mockPlatform( environmentId: string, - input: Omit[0], "prepared">, + input: Omit[0], "getPrepared"> & + Partial[0], "getPrepared">>, ) { mocks.platforms.push(environmentId); return { @@ -207,6 +211,7 @@ function mockPlatform( return { locale: "en", transcribe: async () => { + if (input.getPrepared?.() === null) throw new Error("destination disconnected"); mocks.transcribeCalls.push( input.cloudProvider ? `${[input.cloudProvider, (input as { cloudModel?: string }).cloudModel].filter(Boolean).join(":")} via ${environmentId}` @@ -236,6 +241,7 @@ function setup(options: { readonly destination?: string | null } = {}) { mocks.voiceCapable = new Set(["primary-env", THREAD_ENV, "env-a", "env-b"]); mocks.cloudVoiceCapable.clear(); mocks.canDictate = new Set(mocks.voiceCapable); + mocks.scopeLookupFailed = new Set(); mocks.prepared.clear(); mocks.statusRequests = []; mocks.statusUnavailable = false; @@ -275,6 +281,8 @@ function Probe(props: { readonly showWizard?: boolean; readonly ownerKey?: string; readonly persistent?: boolean; + readonly disabled?: boolean; + readonly discardsRecording?: boolean; }) { const value = useEnvironmentSpeechInput({ environmentId: THREAD_ENV as EnvironmentId, @@ -282,6 +290,8 @@ function Probe(props: { projectName: props.projectName, cleanup: props.cleanup, ownerKey: props.ownerKey ?? "draft", + disabled: props.disabled, + discardsRecording: props.discardsRecording, persistentDraft: props.persistent ? { readStoredText: () => mocks.storedDraft, @@ -434,6 +444,99 @@ it("retries a failed transcription on the same chosen environment", async () => expect(mocks.committed).toHaveBeenCalledExactlyOnceWith("second try", expect.anything()); }); +it("retains an offline-first destination holder until the same destination reconnects", async () => { + setup({ destination: "env-a" }); + mocks.connected.delete("env-a"); + mocks.prepared.delete("env-a"); + await using screen = await render(); + expect(mocks.voice.state.phase).toBe("idle"); + expectNoAudioSent(); + + mocks.connected.add("env-a"); + await screen.rerender(); + await act(() => mocks.voice.start()); + expect(mocks.voice.state.phase).toBe("recording"); + await act(() => mocks.voice.stop()); + expect(mocks.transcribeCalls).toEqual(["env-a"]); +}); + +it.each([ + ["a disconnect keeps it", false, "recording"], + ["a displaced composer discards it", true, "idle"], +] as const)("when the editor is disabled mid-recording, %s", async (_name, discards, phase) => { + setup({ destination: "env-a" }); + await using screen = await render(); + await act(() => mocks.voice.start()); + if (!discards) { + mocks.connected.delete("env-a"); + mocks.prepared.delete("env-a"); + } + // The composer's props when its environment drops, or when an approval takes it over. + await screen.rerender(); + expect(mocks.voice.state.phase).toBe(phase); +}); + +it("keeps a stopped recording local while disconnected and retries it on reconnect", async () => { + setup({ destination: "env-a" }); + await using screen = await render(); + await act(() => mocks.voice.start()); + mocks.connected.delete("env-a"); + mocks.prepared.delete("env-a"); + await screen.rerender(); + // The editor keeps its stop and cancel controls while the destination is down. + expect(mocks.voice.available).toBe(true); + await act(() => mocks.voice.stop()); + expect(mocks.transcribeCalls).toEqual([]); + expect(mocks.voice.state).toMatchObject({ phase: "error", errorAction: "retry" }); + + mocks.connected.add("env-a"); + await screen.rerender(); + await act(() => mocks.voice.start()); + expect(mocks.transcribeCalls).toEqual(["env-a"]); + expect(mocks.committed).toHaveBeenCalledExactlyOnceWith("dictated", expect.anything()); +}); + +it("keeps a recording alive when its last connected holder unmounts while offline", async () => { + setup({ destination: "env-a" }); + mocks.storedDraft = ""; + const view = (editor: boolean, indicator: boolean) => ( + <> + {editor ? : null} + {indicator ? : null} + + ); + await using screen = await render(view(true, false)); + await act(() => mocks.voice.start()); + mocks.connected.delete("env-a"); + mocks.prepared.delete("env-a"); + // The indicator mounts offline, then the recording's editor unmounts. + await screen.rerender(view(true, true)); + await screen.rerender(view(false, true)); + mocks.connected.add("env-a"); + await screen.rerender(view(false, true)); + await page.getByRole("button", { name: "Finish voice input" }).click(); + await vi.waitFor(() => expect(mocks.storedDraft).toBe("dictated")); + expect(mocks.transcribeCalls).toEqual(["env-a"]); +}); + +it.each([ + ["authorization is denied", "idle"], + ["capability is lost", "idle"], + ["the session lookup fails", "recording"], +] as const)("when a connected destination's %s, the recording ends up %s", async (loss, phase) => { + setup({ destination: "env-a" }); + await using screen = await render(); + await act(() => mocks.voice.start()); + if (loss === "capability is lost") mocks.voiceCapable.delete("env-a"); + else mocks.canDictate.delete("env-a"); + if (loss === "the session lookup fails") mocks.scopeLookupFailed.add("env-a"); + await screen.rerender(); + expect(mocks.voice.state.phase).toBe(phase); + if (phase === "recording") return; + await act(() => mocks.voice.stop()); + expect(mocks.transcribeCalls).toEqual([]); +}); + it.each([ ["a stored thread draft keeps recording into it", true, false], ["an editor-only draft is abandoned", false, false], diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index c7915685727b6..5af809653dfb6 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -32,7 +32,11 @@ import { useEnvironmentSettings, } from "../hooks/useSettings"; import { useEnvironment } from "../state/environments"; -import { useEnvironmentScope, usePreparedConnection } from "../state/session"; +import { + useEnvironmentScope, + useEnvironmentScopeDenied, + usePreparedConnection, +} from "../state/session"; import { useAppleSpeechLocales } from "./appleSpeech"; import { preferredSpeechLanguages } from "./preferredSpeechLanguages"; import { runEnvironmentSpeech } from "./runEnvironmentSpeech"; @@ -85,6 +89,11 @@ type HookInput = { readonly projectName?: string | null | undefined; readonly ownerKey: string; readonly disabled?: boolean | undefined; + /** + * Whether `disabled` also abandons this editor's live recording; defaults to `disabled`. False + * keeps it through a temporary block such as a disconnected environment. + */ + readonly discardsRecording?: boolean | undefined; /** * Until a destination is chosen, voice input is offered and its first gesture opens Voice * settings. False hides it instead, for editors whose draft would not survive the navigation. @@ -115,10 +124,9 @@ type HookInput = { }; /** - * Microphone audio leaves this device only for the environment the person chose in - * Voice settings. Nothing is inferred from the primary or the draft's environment, and - * the recording is abandoned the moment that choice changes or its connection drops. - * Apple Speech ("device") keeps audio on this Mac and needs no environment. + * Audio leaves this device only for the environment chosen in Voice settings, never one inferred + * from the primary or the draft. A dropped connection keeps the recording recoverable; a new + * destination, authorization, or capability abandons it. Apple Speech stays on this Mac. */ export function useVoiceTranscriptionDestination() { const gt = useGT(); @@ -134,6 +142,7 @@ export function useVoiceTranscriptionDestination() { const environment = useEnvironment(environmentId); const connection = Option.getOrNull(usePreparedConnection(environmentId)); const canDictate = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + const scopeDenied = useEnvironmentScopeDenied(environmentId, AuthOrchestrationOperateScope); const cloud = grant?.destination.kind === "cloud" ? grant.destination : undefined; const provider = cloud?.provider; const model = cloud?.provider === "openrouter" ? cloud.model : undefined; @@ -157,6 +166,10 @@ export function useVoiceTranscriptionDestination() { }) : (environment?.label ?? null), prepared: supported && canDictate ? connection : null, + // Only an explicit denial or lost capability releases a recording; a failed lookup keeps it. + retainOnDisconnect: Boolean( + environmentId && grant && !scopeDenied && (connection === null || supported), + ), }; } @@ -168,6 +181,7 @@ export function useEnvironmentSpeechInput(input: HookInput) { const grantId = destination.grantId; const cloudProvider = destination.cloudProvider; const cloudModel = destination.cloudModel; + const retainOnDisconnect = destination.retainOnDisconnect; const draftCapabilities = useEnvironment(input.environmentId)?.serverConfig?.environment .capabilities; const originatingConnection = Option.getOrNull(usePreparedConnection(input.environmentId)); @@ -203,8 +217,10 @@ export function useEnvironmentSpeechInput(input: HookInput) { } const session = useRetainedVoiceInputSession({ + environmentId: destination.environmentId, prepared, grantId, + retainOnDisconnect, onDevice, cloudProvider, cloudModel, @@ -217,10 +233,17 @@ export function useEnvironmentSpeechInput(input: HookInput) { const busyElsewhere = !owns && voiceInputBlocksSubmission(snapshot.state); const startRequestRef = useRef(0); - const latestRef = useRef({ input, clientSettings, cleanupPrepared, projectWords, session }); + const latestRef = useRef({ + input, + clientSettings, + cleanupPrepared, + projectWords, + session, + prepared, + }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed props before an async completion can read them through the session useLayoutEffect(() => { - latestRef.current = { input, clientSettings, cleanupPrepared, projectWords, session }; + latestRef.current = { input, clientSettings, cleanupPrepared, projectWords, session, prepared }; }); const mountedRef = useRef(false); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons this editor's pending work, and a recording that cannot outlive it, on unmount or a destination change @@ -286,6 +309,7 @@ export function useEnvironmentSpeechInput(input: HookInput) { }, [prepared, setup.downloading, setup.open, setupModelId]); const previousOwnerRef = useRef(input.ownerKey); + const discardsRecording = input.discardsRecording ?? input.disabled; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons a recording that cannot outlive its editor when the draft's owner changes useEffect(() => { const previous = previousOwnerRef.current; @@ -293,8 +317,8 @@ export function useEnvironmentSpeechInput(input: HookInput) { previousOwnerRef.current = input.ownerKey; startRequestRef.current += 1; if (previous !== input.ownerKey) session?.ownerChanged(previous); - else if (session?.ownerKey === input.ownerKey) session.cancel(); - }, [input.ownerKey, input.disabled, session]); + else if (discardsRecording && session?.ownerKey === input.ownerKey) session.cancel(); + }, [input.ownerKey, input.disabled, discardsRecording, session]); const submitAfterDictation = useStableCallback((submit: (text: string) => void) => { if (latestRef.current.input.disabled || state.phase === "preparing") return; @@ -361,7 +385,7 @@ export function useEnvironmentSpeechInput(input: HookInput) { const catalog = await runEnvironmentSpeech( getEnvironmentSpeechModels(connection, true), ).catch(() => null); - if (request !== startRequestRef.current) return; + if (request !== startRequestRef.current || latestRef.current.prepared !== connection) return; const choice = chooseSetupSpeechModel(catalog?.models ?? [], { selectedModelId, intent: latestRef.current.clientSettings.speechLanguage, @@ -409,6 +433,7 @@ export function useEnvironmentSpeechInput(input: HookInput) { const stillCurrent = () => request === startRequestRef.current && latestRef.current.session === session && + latestRef.current.prepared === prepared && latestRef.current.input.ownerKey === owner && !latestRef.current.input.disabled; const handleStatus = async (latestStatus: EnvironmentSpeechStatus) => { @@ -523,12 +548,14 @@ export function useEnvironmentSpeechInput(input: HookInput) { (cloudProvider !== undefined || (status?.prepared === prepared && status.value?.supported !== false))); return { + // A recording this editor owns keeps its controls while the destination reconnects. available: - destinationReady && - !busyElsewhere && - typeof navigator !== "undefined" && - Boolean(navigator.mediaDevices?.getUserMedia) && - typeof AudioWorkletNode !== "undefined", + (owns && snapshot.state.phase !== "idle") || + (destinationReady && + !busyElsewhere && + typeof navigator !== "undefined" && + Boolean(navigator.mediaDevices?.getUserMedia) && + typeof AudioWorkletNode !== "undefined"), status: currentStatus, transcriptionEnvironmentId: destination.environmentId, transcriptionEnvironmentLabel: destination.label, diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index 577b26595efed..51fc7dee24913 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -22,7 +22,7 @@ import type { import { DEFAULT_CLIENT_SETTINGS, EnvironmentInternalError } from "@t3tools/contracts"; import { resolveSpeechVocabulary } from "@t3tools/shared/speech"; import * as Schema from "effect/Schema"; -import { useEffect, useSyncExternalStore } from "react"; +import { useEffect, useRef, useSyncExternalStore } from "react"; import { toastManager } from "../components/ui/toast"; import { chooseRecordingMicrophone } from "./browserMicrophones"; @@ -80,7 +80,7 @@ export type VoiceInputSessionActivity = { type SessionKey = { /** Null is Apple Speech, which transcribes on this Mac without an environment. */ - readonly prepared: PreparedConnection | null; + readonly environmentId: EnvironmentId | null; readonly grantId: string; readonly cloudProvider: CloudSpeechProvider | undefined; readonly cloudModel: CloudSpeechModelId | undefined; @@ -106,6 +106,7 @@ function cleanupContext({ text, selection }: DraftInput): DraftInput { */ export class VoiceInputSession { readonly key: SessionKey; + private prepared: PreparedConnection | null; private readonly controller: VoiceInputController; private target: VoiceInputTarget | null = null; private pendingSubmission: { @@ -124,8 +125,9 @@ export class VoiceInputSession { private disposed = false; private onSpeechStatus: ((status: EnvironmentSpeechStatus) => void) | undefined; - constructor(key: SessionKey) { + constructor(key: SessionKey, prepared: PreparedConnection | null) { this.key = key; + this.prepared = prepared; const hasAudioConsent = bindAudioGrant(key.grantId); let recordingPreferences: | { @@ -180,10 +182,10 @@ export class VoiceInputSession { if (!this.disposed) void this.controller.interruptRecording(message, null, code); }, }; - const platform = key.prepared + const platform = key.environmentId ? createBrowserVoiceInputPlatform({ ...platformInput, - prepared: key.prepared, + getPrepared: () => this.prepared, cloudProvider: key.cloudProvider, cloudModel: key.cloudModel, onText: (preview) => { @@ -273,6 +275,11 @@ export class VoiceInputSession { return this.controller.currentState; } + /** A reconnect to the same destination replaces the transport; null while it is down. */ + updatePrepared(prepared: PreparedConnection | null): void { + this.prepared = prepared; + } + get ownerKey(): string | null { return this.target?.ownerKey ?? null; } @@ -379,7 +386,7 @@ const registryListeners = new Set<() => void>(); function sameKey(session: VoiceInputSession, key: SessionKey): boolean { return ( - session.key.prepared === key.prepared && + session.key.environmentId === key.environmentId && session.key.grantId === key.grantId && session.key.cloudProvider === key.cloudProvider && session.key.cloudModel === key.cloudModel @@ -391,23 +398,33 @@ function findSession(key: SessionKey): VoiceInputSession | null { return null; } -/** Every holder of a destination shares one session; the last release disposes it. */ -function retainVoiceInputSession(key: SessionKey): () => void { - const session = findSession(key) ?? new VoiceInputSession(key); +/** + * Every holder of a destination shares one session; the last release disposes it. Offline, + * a holder joins an existing session but never creates one. + */ +function retainVoiceInputSession(key: SessionKey, prepared: PreparedConnection | null) { + const session = + findSession(key) ?? + (prepared || key.environmentId === null ? new VoiceInputSession(key, prepared) : null); + if (!session) return null; + session.updatePrepared(prepared); sessions.set(session, (sessions.get(session) ?? 0) + 1); for (const listener of registryListeners) listener(); let released = false; - return () => { - if (released) return; - released = true; - const count = (sessions.get(session) ?? 1) - 1; - if (count > 0) { - sessions.set(session, count); - return; - } - sessions.delete(session); - session.dispose(); - for (const listener of registryListeners) listener(); + return { + session, + release: () => { + if (released) return; + released = true; + const count = (sessions.get(session) ?? 1) - 1; + if (count > 0) { + sessions.set(session, count); + return; + } + sessions.delete(session); + session.dispose(); + for (const listener of registryListeners) listener(); + }, }; } @@ -416,24 +433,49 @@ function subscribeRegistry(listener: () => void): () => void { return () => registryListeners.delete(listener); } -/** Holds the destination's shared session while mounted; null until it is retained. */ +/** + * Holds the destination's shared session while mounted; null until it is retained. The + * session is first retained on a live connection and then survives it dropping for as long + * as `retainOnDisconnect` holds, so a reconnect resumes the same recording. + */ export function useRetainedVoiceInputSession(input: { + readonly environmentId: EnvironmentId | null; readonly prepared: PreparedConnection | null; readonly grantId: string | null; + readonly retainOnDisconnect: boolean; readonly onDevice?: boolean | undefined; readonly cloudProvider?: CloudSpeechProvider | undefined; readonly cloudModel?: CloudSpeechModelId | undefined; }): VoiceInputSession | null { const { grantId, cloudProvider, cloudModel } = input; - const prepared = input.onDevice ? null : input.prepared; - const ready = (input.onDevice === true || prepared !== null) && grantId !== null; - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- retains the shared recording session for this destination while mounted + const onDevice = input.onDevice === true; + const environmentId = onDevice ? null : input.environmentId; + const prepared = onDevice ? null : input.prepared; + const retain = onDevice || input.retainOnDisconnect; + const keyed = grantId !== null && (onDevice || environmentId !== null); + const leaseRef = useRef>(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases the shared recording session on unmount + useEffect( + () => () => { + leaseRef.current?.release(); + leaseRef.current = null; + }, + [], + ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- acquires, refreshes, or releases the shared recording session as the destination and its transport change useEffect(() => { - if (!ready || !grantId || typeof navigator === "undefined") return; - return retainVoiceInputSession({ prepared, grantId, cloudProvider, cloudModel }); - }, [ready, prepared, grantId, cloudProvider, cloudModel]); + const key = keyed && grantId ? { environmentId, grantId, cloudProvider, cloudModel } : null; + const lease = leaseRef.current; + if (lease && (!key || !retain || !sameKey(lease.session, key))) { + lease.release(); + leaseRef.current = null; + } + if (leaseRef.current) leaseRef.current.session.updatePrepared(prepared); + else if (key && retain && typeof navigator !== "undefined") + leaseRef.current = retainVoiceInputSession(key, prepared); + }, [keyed, environmentId, grantId, cloudProvider, cloudModel, prepared, retain]); return useSyncExternalStore(subscribeRegistry, () => - ready && grantId ? findSession({ prepared, grantId, cloudProvider, cloudModel }) : null, + keyed && grantId ? findSession({ environmentId, grantId, cloudProvider, cloudModel }) : null, ); } diff --git a/apps/web/src/state/session.ts b/apps/web/src/state/session.ts index 8a08e99fc6967..d7d61686833cd 100644 --- a/apps/web/src/state/session.ts +++ b/apps/web/src/state/session.ts @@ -1,5 +1,8 @@ import { useAtomValue } from "@effect/atom-react"; -import { createEnvironmentSessionAtoms } from "@t3tools/client-runtime/state/session"; +import { + createEnvironmentSessionAtoms, + sessionDeniesScope, +} from "@t3tools/client-runtime/state/session"; import { type AuthEnvironmentScope, type AuthSessionState, @@ -35,6 +38,18 @@ export function useEnvironmentScope( ); } +export function useEnvironmentScopeDenied( + environmentId: EnvironmentId | null, + scope: AuthEnvironmentScope, +): boolean { + return useAtomValue( + environmentId === null + ? EMPTY_SESSION_STATE_ATOM + : environmentSession.sessionStateAtom(environmentId), + (result) => sessionDeniesScope(result, scope), + ); +} + export function useEnvironmentCanConfigureRelay(environmentId: EnvironmentId | null): boolean { return useAtomValue( environmentId === null diff --git a/docs/user/voice-input.md b/docs/user/voice-input.md index 9831eeafd49f8..0055108d46ffc 100644 --- a/docs/user/voice-input.md +++ b/docs/user/voice-input.md @@ -22,7 +22,8 @@ on this device only, so every computer and browser you use asks for it once. Set it back to **Off** at any time; a recording in progress is discarded. If the chosen environment goes offline, voice input waits for it. T3 Code never -substitutes another environment. +substitutes another environment. A recording in progress keeps going; if you stop +before it reconnects, choose retry once it is back to transcribe what you recorded. In the desktop app on macOS 26 or later, you can instead choose **Apple Speech** under **On this Mac**. Audio stays on the Mac and macOS transcribes it. The first