Skip to content
Open
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
8 changes: 5 additions & 3 deletions apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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) => ({
Expand Down Expand Up @@ -486,6 +493,7 @@ it.each([
label: target.label,
grantId: "test",
prepared,
retainOnDisconnect: true,
}));
await using screen = await render(
<SettingsScopeProvider search={{}} onChange={() => {}}>
Expand Down Expand Up @@ -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) => (
<SettingsScopeProvider search={{}} onChange={() => {}}>
Expand Down
11 changes: 6 additions & 5 deletions apps/web/src/speech/browserPcmCapture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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."))));
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -202,7 +203,6 @@ export function createBrowserPcmCapture(
streaming = prepared.streaming;
feed = prepared.streaming.feed;
for (const chunk of chunks) feed(chunk);
chunks = [];
}
return prepared;
})
Expand All @@ -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;
Expand Down
138 changes: 135 additions & 3 deletions apps/web/src/speech/browserVoiceInput.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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");
});

Expand Down Expand Up @@ -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: () => ({
Expand All @@ -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<Response>((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);
});
62 changes: 38 additions & 24 deletions apps/web/src/speech/browserVoiceInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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<typeof openSpeechStream>;
} = { 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;
});
}

Expand Down
Loading
Loading