From 0e882656523f1681d42a3ee196745bf1c6ddac11 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 9 Nov 2026 10:39:27 +0100 Subject: [PATCH 1/5] fix(ui-react,ui-server): end the Gemini drain on generationComplete and lock an en-US language hint Google never sends finished or turnComplete after audioStreamEnd (#3710), so every Done waited the full 3 s. End the drain on the generationComplete that follows audioStreamEnd, or after a 300 ms quiet with nothing pending (#3768). Lock languageCodes ["en-US"] in the minted token and repeat it in the client's setup, matching Deepgram's fixed en (#3769). Closes #3768 Closes #3769 Co-Authored-By: Claude Opus 5.5 --- .changeset/gemini-dictation-drain-language.md | 6 + docs/plans/selectable-dictation.md | 66 +++++++--- packages/ui-react/src/voice/asr-gemini.ts | 59 ++++++++- packages/ui-react/tests/asr-gemini.test.ts | 122 ++++++++++++++++-- .../browser/dictation-gemini.offline.tsx | 9 +- packages/ui-server/src/voice/gemini-speech.ts | 12 +- .../tests/fixtures/gemini-auth-token-wire.ts | 17 ++- .../ui-server/tests/gemini-speech.test.ts | 4 +- 8 files changed, 249 insertions(+), 46 deletions(-) create mode 100644 .changeset/gemini-dictation-drain-language.md diff --git a/.changeset/gemini-dictation-drain-language.md b/.changeset/gemini-dictation-drain-language.md new file mode 100644 index 0000000000..8a47fc9695 --- /dev/null +++ b/.changeset/gemini-dictation-drain-language.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-react": patch +"@schlessera/brain-ui-server": patch +--- + +Gemini dictation finishes Done faster and no longer guesses the language. Google never sends `finished` or `turnComplete` after `audioStreamEnd`, so Done waited its full 3 s every time. Done now ends on the `generationComplete` that follows the last words, or after 300 ms of quiet when nothing is pending (#3768). The minted token now locks `languageCodes: ["en-US"]` and the client repeats it, matching Deepgram's fixed `en`. With automatic detection, a short English segment had come back as Spanish (#3769). diff --git a/docs/plans/selectable-dictation.md b/docs/plans/selectable-dictation.md index 5693074d3a..88e7f77a91 100644 --- a/docs/plans/selectable-dictation.md +++ b/docs/plans/selectable-dictation.md @@ -75,21 +75,40 @@ dependency: both sides speak the documented wire protocol, as | A browser presents the token as an `access_token` query parameter (or `Authorization: Token …`); tokens work only with the Live API | Token guide | | `gemini-3.5-transcribe` (unary, saved files) is a separate model and endpoint | Model page | -**Divergence to resolve during qualification.** The token guide says ephemeral +**Endpoint version (resolved by #3710).** The token guide says ephemeral tokens work with `v1beta`. The installed SDK connects an `auth_tokens/…` credential to `wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained?access_token=…` -and warns that its ephemeral support is v1alpha-only. The implementation uses -the SDK-observed v1alpha `BidiGenerateContentConstrained` URL. The server mints -the full URL, so a correction is a server-only change. #3710 records which one -Google accepts. - -**Still unproven until #3710 runs:** that Google accepts the constrained token -and setup for this model; whether interim text is cumulative per segment or -per message; whether every final text is followed by `finished`, or by -`turnComplete`, after `audioStreamEnd`; the actual SMART output for corrections -and lists; latency; and physical-device behavior. No keyless test proves any of -these. Nothing here claims parity with Pixel Recorder or Rambler features, or +and warns that its ephemeral support is v1alpha-only. Measured on 2026-11-09, +Google accepts the constrained token on both the v1alpha and the v1beta +constrained endpoints, with identical output. The implementation keeps the +SDK's v1alpha URL. The server mints the full URL, so a later change is +server-only. + +**Measured by #3710's scripted check of the protocol (2026-11-09, +synthetic TTS audio, no device):** + +- Google accepts the constrained token and setup for this model. +- `uses: 1` is enforced: a second connect closes with 1011 "Token has been used + too many times". +- The locked mode overrides a client `setup` that asks for another one. +- Interim text is cumulative within a segment and stays verbatim in SMART; + only the final is cleaned. +- A final arrives on a pause, as `inputTranscription`, then + `generationComplete: true`, then `speechState: NON_SPEECH`. +- After `audioStreamEnd`, Google sends the pending final and `generationComplete` + (+253 ms measured). When nothing is pending it sends nothing at all. + `finished` and `turnComplete` never came, so Done waits for + `generationComplete` (#3768). +- A pause ends a segment, so SMART formats a spoken list only within one + segment. +- With automatic language detection, a short English segment was once + returned as Spanish. The `en-US` hint fixed it in the one session tried + (#3769). + +**Still unproven until #3710 Phase B runs:** latency and behavior with a real +microphone, a real browser and a physical device. No keyless test proves any +of these, and none of the measurements above is an accuracy claim. Nothing here claims parity with Pixel Recorder or Rambler features, or that saved files work because streaming does. ## 3. Rulings this design uses @@ -328,8 +347,11 @@ x-goog-api-key: - Vocabulary is the existing bounded keyterm list, capped at **100 terms** of at most 64 UTF-8 bytes each. No corpus, history, screen or chat context is sent. - Language uses automatic detection (`languageCodes` omitted). Adding a - language setting is out of scope for this epic; Deepgram stays `en`. + Language is a fixed `languageCodes: ["en-US"]` hint, locked in the token and + repeated in the setup, matching Deepgram's fixed `en` (#3769: automatic + detection returned a short English segment as Spanish). A hint biases + recognition; it does not restrict it. Adding a language setting is out of + scope for this epic. - The constraint locks model, modality and transcription config, and the browser's `setup` repeats them field for field. Any additional field the client sends is rejected or overridden by Google, which is the point of the @@ -368,10 +390,14 @@ x-goog-api-key: Messages are zod-parsed with the same size bounds as `gemini-conversation.ts`. `error`, `goAway` and unknown-close reasons map to `speechError` codes without exposing their text. -- **Done (`drainAndStop`).** Stop the tracks, flush the partial chunk, send - `audioStreamEnd`, then wait for the next `inputTranscription` with - `finished`, or `turnComplete`, for up to **3 s**. Close either way. Words - already heard are kept. +- **Done (`drainAndStop`).** Stop the tracks, flush the partial chunk and send + `audioStreamEnd`. If speech is pending (a `SPEECH` state or an interim that + no final or `generationComplete` has closed), wait for the + `generationComplete` that follows `audioStreamEnd`. Otherwise end after + **300 ms** of quiet, extended to `generationComplete` by any speech or + interim that arrives in it. `finished` or `turnComplete` also end it, and + **3 s** caps all of it (#3768). Close either way. Words already heard are + kept. - **Hard stop, cancel, unmount, superseded start.** Close the socket (1000), disconnect the worklet, close the AudioContext, stop the tracks, clear the timers and the queue, and ignore every later message, because the existing @@ -502,8 +528,8 @@ key-registered built-in over the legacy single selection. - Client: published `runAsrClientContract`, plus a local WebSocket double that asserts the setup frame, base64 PCM16 framing at 16 kHz from 44.1 and 48 kHz contexts in real Chrome, the pre-setup buffer bound, backpressure failure, - interim replacement, single final commit, the `audioStreamEnd` drain within - 3 s, and complete teardown (tracks ended, context closed, socket closed, no + interim replacement, single final commit, the `audioStreamEnd` drain (on + `generationComplete`, after a quiet with nothing pending, capped at 3 s), and complete teardown (tracks ended, context closed, socket closed, no late mutation). - Mutations: final mapped as partial, resampler bypassed, constraint lock removed, teardown skipping `context.close()`. Each fails its named diff --git a/packages/ui-react/src/voice/asr-gemini.ts b/packages/ui-react/src/voice/asr-gemini.ts index 41b4f8a57e..aba92e5b61 100644 --- a/packages/ui-react/src/voice/asr-gemini.ts +++ b/packages/ui-react/src/voice/asr-gemini.ts @@ -24,8 +24,14 @@ export const GEMINI_PRESETUP_FRAMES = 50; export const GEMINI_HANDSHAKE_MS = 10_000; /** Upload backlog at which the take fails rather than grow without bound. */ export const GEMINI_MAX_BUFFERED_BYTES = 256 * 1024; -/** Done waits this long for the last final after audioStreamEnd. */ +/** Done waits at most this long for the last final after audioStreamEnd. */ export const GEMINI_DRAIN_MS = 3_000; +/** + * With nothing pending at audioStreamEnd, Done ends after this much quiet. + * Google sends nothing at all after audioStreamEnd when no speech is pending + * (#3710), so without it every such Done waited the full cap (#3768). + */ +export const GEMINI_DRAIN_QUIET_MS = 300; const MAX_MESSAGE_BYTES = 262_144; const MODEL = "models/gemini-3.5-transcribe-live"; const MIME = `audio/pcm;rate=${GEMINI_SAMPLE_RATE}`; @@ -37,19 +43,22 @@ const messageSchema = z.object({ interimInputTranscription: transcript.optional(), inputTranscription: transcript.optional(), turnComplete: z.boolean().optional(), + generationComplete: z.boolean().optional(), + speechState: z.string().max(32).optional(), }).optional(), goAway: z.object({}).optional(), // Remote error text is deliberately never surfaced: it may echo request details. error: z.unknown().optional(), }); const vocabularySchema = z.array(z.string().min(1).max(64)).max(100); +const languageCodesSchema = z.array(z.string().regex(/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8}){0,3}$/)).min(1).max(4); interface GeminiAsrClientOptions { /** Constrained Live endpoint, from the server. */ url: string; /** Single-use ephemeral token (`auth_tokens/…`), from the server. */ token: string; - /** `model`, `mode` (SMART/VERBATIM) and `vocabulary` (JSON array), from the server. */ + /** `model`, `mode` (SMART/VERBATIM), `vocabulary` and `languageCodes` (JSON arrays), from the server. */ params: Record; onEvent: (event: AsrEvent) => void; onError?: (error: Error) => void; @@ -75,6 +84,11 @@ export class GeminiAsrClient implements AsrClient { /** Done has the worklet's tail and the partial frame; audioStreamEnd may follow. */ private tailFlushed = false; private inbound: Promise = Promise.resolve(); + /** Speech or an interim arrived that no final or generationComplete has closed yet. */ + private pending = false; + /** audioStreamEnd has been sent; only now can generationComplete end the drain. */ + private streamEnded = false; + private quiet: ReturnType | null = null; private readonly setup: string; constructor(private readonly opts: GeminiAsrClientOptions) { @@ -82,11 +96,15 @@ export class GeminiAsrClient implements AsrClient { const mode = params.mode === "VERBATIM" ? "VERBATIM" : "SMART"; let vocabulary: string[] = []; try { vocabulary = vocabularySchema.parse(JSON.parse(params.vocabulary ?? "[]")); } catch { vocabulary = []; } + // The token locks the language server side; a missing or malformed hint + // here only omits the repeat, it cannot unlock anything. + let languageCodes: string[] = []; + try { languageCodes = languageCodesSchema.parse(JSON.parse(params.languageCodes ?? "null")); } catch { languageCodes = []; } this.setup = JSON.stringify({ setup: { model: params.model || MODEL, generationConfig: { responseModalities: ["TEXT"] }, - inputAudioTranscription: { mode, ...(vocabulary.length ? { customVocabulary: vocabulary } : {}) }, + inputAudioTranscription: { mode, ...(languageCodes.length ? { languageCodes } : {}), ...(vocabulary.length ? { customVocabulary: vocabulary } : {}) }, }, }); } @@ -142,7 +160,8 @@ export class GeminiAsrClient implements AsrClient { /** * Done: flush the worklet's partial block, send it and audioStreamEnd, wait - * for the last final, then close; all of it within 3 s. Heard words are kept. + * for the last final (generationComplete) or, with nothing pending, a short + * quiet, then close; all of it within 3 s. Heard words are kept. */ async drainAndStop(): Promise { if (this.phase !== "live") { this.stop(); return; } @@ -214,7 +233,23 @@ export class GeminiAsrClient implements AsrClient { private endInput(): void { for (const frame of this.queue.splice(0)) if (!this.send(frame)) return; - this.send(JSON.stringify({ realtimeInput: { audioStreamEnd: true } })); + if (!this.send(JSON.stringify({ realtimeInput: { audioStreamEnd: true } }))) return; + // Google answers audioStreamEnd with the pending final and generationComplete + // (+253 ms measured in #3710), and with nothing at all when no speech is + // pending; it never sent finished or turnComplete. So: wait for + // generationComplete while speech is pending, otherwise end after a quiet. + this.streamEnded = true; + if (!this.pending) this.armQuiet(); + } + + /** (Re)start the quiet window that ends a drain with nothing pending. */ + private armQuiet(): void { + if (this.quiet) clearTimeout(this.quiet); + this.quiet = setTimeout(() => { this.quiet = null; this.finishDrain(); }, GEMINI_DRAIN_QUIET_MS); + } + + private disarmQuiet(): void { + if (this.quiet) { clearTimeout(this.quiet); this.quiet = null; } } private receive(text: string | null): void { @@ -241,12 +276,24 @@ export class GeminiAsrClient implements AsrClient { if (interim) this.opts.onEvent({ type: "partial", text: interim }); const final = content?.inputTranscription; if (final?.text) this.opts.onEvent({ type: "final", text: final.text, endsTurn: final.finished ?? true }); - if (this.phase === "draining" && (final?.finished === true || content?.turnComplete === true)) this.finishDrain(); + if (interim || content?.speechState === "SPEECH") this.pending = true; + if (final?.text || content?.generationComplete === true) this.pending = false; + if (this.phase === "draining") { + if (final?.finished === true || content?.turnComplete === true) this.finishDrain(); + else if (this.streamEnded && content?.generationComplete === true) this.finishDrain(); + else if (this.streamEnded) { + // More speech is still being transcribed: wait for generationComplete. + if (this.pending) this.disarmQuiet(); + // A final without generationComplete: end after a quiet, not the cap. + else if (final?.text) this.armQuiet(); + } + } // The session is about to end: what was heard is kept, the take ends. if (message.goAway) this.fail("Gemini session ending", "network"); } private finishDrain(): void { + this.disarmQuiet(); const settle = this.settleDrain; this.settleDrain = null; settle?.(); diff --git a/packages/ui-react/tests/asr-gemini.test.ts b/packages/ui-react/tests/asr-gemini.test.ts index f1335af0ea..f722fda500 100644 --- a/packages/ui-react/tests/asr-gemini.test.ts +++ b/packages/ui-react/tests/asr-gemini.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { runAsrClientContract } from "@schlessera/brain-ui-sdk/testing"; import type { AsrEvent, VoiceSessionResponse } from "@schlessera/brain-ui-sdk/client"; import { - GEMINI_DRAIN_MS, GEMINI_FRAME_SAMPLES, GEMINI_HANDSHAKE_MS, GEMINI_MAX_BUFFERED_BYTES, GEMINI_PRESETUP_FRAMES, GeminiAsrClient, + GEMINI_DRAIN_MS, GEMINI_DRAIN_QUIET_MS, GEMINI_FRAME_SAMPLES, GEMINI_HANDSHAKE_MS, GEMINI_MAX_BUFFERED_BYTES, GEMINI_PRESETUP_FRAMES, GeminiAsrClient, } from "../src/voice/asr-gemini"; import { createPcmResampler, PCM_CAPTURE_BLOCK } from "../src/voice/pcm-capture"; @@ -15,7 +15,7 @@ import { createPcmResampler, PCM_CAPTURE_BLOCK } from "../src/voice/pcm-capture" const URL_ = "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained"; const TOKEN = "auth_tokens/ithaca-fixture"; -const PARAMS = { model: "models/gemini-3.5-transcribe-live", mode: "SMART", sampleRate: "16000", vocabulary: JSON.stringify(["Ithaca", "Penelope"]) }; +const PARAMS = { model: "models/gemini-3.5-transcribe-live", mode: "SMART", sampleRate: "16000", vocabulary: JSON.stringify(["Ithaca", "Penelope"]), languageCodes: JSON.stringify(["en-US"]) }; const SESSION: VoiceSessionResponse = { providerId: "gemini", url: URL_, token: TOKEN, params: PARAMS, expiresAt: 1000, capabilities: { streaming: true, interimResults: true, keyterms: true, endpointing: false, smartTranscription: true, savedAudio: false } }; @@ -151,12 +151,12 @@ const tick = () => new Promise((resolve) => realSetTimeout(resolve, 0)); let cleanup: Array<() => void> = []; afterEach(() => { for (const restore of cleanup.splice(0).reverse()) restore(); }); -function harness(options: Parameters[0] = {}) { +function harness({ params = PARAMS, ...options }: Parameters[0] & { params?: Record } = {}) { const browser = scriptedBrowser(options); cleanup.push(browser.restore); const events: AsrEvent[] = [], errors: Error[] = []; let closes = 0; - const client = new GeminiAsrClient({ url: URL_, token: TOKEN, params: PARAMS, onEvent: (event) => events.push(event), onError: (error) => errors.push(error), onClose: () => { closes++; } }); + const client = new GeminiAsrClient({ url: URL_, token: TOKEN, params, onEvent: (event) => events.push(event), onError: (error) => errors.push(error), onClose: () => { closes++; } }); cleanup.push(() => client.stop()); return { ...browser, client, events, errors, closes: () => closes, socket: () => browser.sockets[0]! }; } @@ -235,8 +235,18 @@ describe("GeminiAsrClient wire behaviour", () => { expect(JSON.parse(h.socket().sent[0]!)).toEqual({ setup: { model: "models/gemini-3.5-transcribe-live", generationConfig: { responseModalities: ["TEXT"] }, - inputAudioTranscription: { mode: "SMART", customVocabulary: ["Ithaca", "Penelope"] }, - } }); + inputAudioTranscription: { mode: "SMART", languageCodes: ["en-US"], customVocabulary: ["Ithaca", "Penelope"] }, + } }, "GEMINI_SETUP_REPEATS_LANGUAGE"); + }); + + for (const [name, languageCodes] of [ + ["missing", undefined], ["not JSON", "en-US"], ["empty", "[]"], ["not a language tag", JSON.stringify(["en US"])], ["too many", JSON.stringify(["en-US", "en-GB", "de-DE", "fr-FR", "es-ES"])], + ] as const) test(`a ${name} languageCodes param omits the hint; the token still locks it server side`, async () => { + const { languageCodes: _, ...rest } = PARAMS; + const h = harness({ params: languageCodes === undefined ? rest : { ...rest, languageCodes } }); + await h.client.start(); + await tick(); + expect(JSON.parse(h.socket().sent[0]!).setup.inputAudioTranscription, "GEMINI_LANGUAGE_PARAM_VALIDATED").toEqual({ mode: "SMART", customVocabulary: ["Ithaca", "Penelope"] }); }); test("a verbatim session without vocabulary sets up verbatim with no customVocabulary", async () => { @@ -246,7 +256,7 @@ describe("GeminiAsrClient wire behaviour", () => { cleanup.push(() => client.stop()); await client.start(); await tick(); - expect(JSON.parse(browser.sockets[0]!.sent[0]!).setup.inputAudioTranscription).toEqual({ mode: "VERBATIM" }); + expect(JSON.parse(browser.sockets[0]!.sent[0]!).setup.inputAudioTranscription).toEqual({ mode: "VERBATIM", languageCodes: ["en-US"] }); }); test("streams 100 ms base64 PCM16 frames at 16 kHz from a 48 kHz context", async () => { @@ -428,12 +438,15 @@ describe("GeminiAsrClient wire behaviour", () => { expect(h.contexts[0]!.state).toBe("closed"); }); - test("Done is bounded at 3 s when no final arrives", async () => { + test("Done is bounded at 3 s when speech is pending and no final arrives", async () => { const h = harness({ timers: true }); await h.client.start(); await tick(); await tick(); + h.socket().server({ serverContent: { interimInputTranscription: { text: "Ask Nes" } } }); + await tick(); let settled = false; const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); h.advance(GEMINI_DRAIN_MS - 1); await tick(); expect(settled).toBe(false); @@ -443,6 +456,99 @@ describe("GeminiAsrClient wire behaviour", () => { expect(h.contexts[0]!.state).toBe("closed"); }); + // Measured against Google in #3710: after audioStreamEnd the pending final + // arrives with generationComplete, and nothing at all arrives when no speech + // is pending; finished and turnComplete never came. + test("with speech pending, Done resolves on the generationComplete that follows audioStreamEnd", async () => { + const h = harness({ timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + s.server({ serverContent: { speechState: "SPEECH" } }); + s.server({ serverContent: { interimInputTranscription: { text: "Odysseus leaves the island at" } } }); + await tick(); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + expect(JSON.parse(s.sent.at(-1)!)).toEqual({ realtimeInput: { audioStreamEnd: true } }); + h.advance(GEMINI_DRAIN_QUIET_MS * 2); + await tick(); + expect(settled, "pending speech is not cut off by the quiet window").toBe(false); + s.server({ serverContent: { inputTranscription: { text: "Odysseus leaves the island at dawn." } } }); + s.server({ serverContent: { generationComplete: true } }); + await tick(); + expect(settled, "GEMINI_DRAIN_ON_GENERATION_COMPLETE").toBe(true); + await draining; + expect(h.events.at(-1)).toEqual({ type: "final", text: "Odysseus leaves the island at dawn.", endsTurn: true }); + expect(h.socket().readyState).toBe(3); + expect(h.contexts[0]!.state).toBe("closed"); + }); + + test("a generationComplete before audioStreamEnd is sent does not end the drain", async () => { + // Without setupComplete the stream end waits, so audioStreamEnd is + // deterministically unsent while Google's message is handled. + const h = harness({ timers: true, answerSetup: false }); + await h.client.start(); + await tick(); + const s = h.socket(); + h.speak(GEMINI_FRAME_SAMPLES * 3); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + s.server({ serverContent: { generationComplete: true } }); + await tick(); await tick(); + expect(s.sent.some((frame) => JSON.parse(frame).realtimeInput?.audioStreamEnd), "audioStreamEnd not yet sent").toBe(false); + expect(settled, "GEMINI_DRAIN_WAITS_FOR_STREAM_END").toBe(false); + s.server({ setupComplete: {} }); + await tick(); + expect(JSON.parse(s.sent.at(-1)!)).toEqual({ realtimeInput: { audioStreamEnd: true } }); + h.advance(GEMINI_DRAIN_QUIET_MS); + await draining; + }); + + test("with nothing pending, Done resolves after the quiet window instead of the 3 s cap", async () => { + const h = harness({ timers: true }); + await h.client.start(); + await tick(); await tick(); + h.socket().server({ serverContent: { inputTranscription: { text: "Ask Nestor about the ships." } } }); + h.socket().server({ serverContent: { generationComplete: true } }); + await tick(); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + expect(JSON.parse(h.socket().sent.at(-1)!)).toEqual({ realtimeInput: { audioStreamEnd: true } }); + h.advance(GEMINI_DRAIN_QUIET_MS - 1); + await tick(); + expect(settled).toBe(false); + h.advance(1); + await tick(); + expect(settled, "GEMINI_DRAIN_QUIET_WITHOUT_PENDING").toBe(true); + await draining; + expect(h.socket().readyState).toBe(3); + }); + + for (const [name, message] of [ + ["speech", { serverContent: { speechState: "SPEECH" } }], + ["an interim", { serverContent: { interimInputTranscription: { text: "and the" } } }], + ] as const) test(`${name} inside the quiet window extends the drain to generationComplete`, async () => { + const h = harness({ timers: true }); + await h.client.start(); + await tick(); await tick(); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + h.advance(GEMINI_DRAIN_QUIET_MS - 100); + h.socket().server(message); + await tick(); + h.advance(GEMINI_DRAIN_QUIET_MS * 3); + await tick(); + expect(settled, "GEMINI_DRAIN_QUIET_EXTENDED").toBe(false); + h.socket().server({ serverContent: { inputTranscription: { text: "And the harbor." } } }); + h.socket().server({ serverContent: { generationComplete: true } }); + await draining; + expect(h.events.at(-1)).toEqual({ type: "final", text: "And the harbor.", endsTurn: true }); + }); + test("Done before setupComplete sends the waiting audio and the stream end once setup completes", async () => { const h = harness({ answerSetup: false }); await h.client.start(); diff --git a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx index 417e8a2d5a..121b7ad3b5 100644 --- a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx +++ b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx @@ -199,6 +199,10 @@ for (const rate of [44_100, 48_000]) { speech.deliver({ serverContent: { inputTranscription: { text: "Ask Nestor about the ships.", finished: true } } }); await expect.poll(() => s.ui.stores.voice.getState().finalText).toBe("Ask Nestor about the ships."); expect(s.ui.stores.voice.getState().partial, "a final clears the partial").toBe(""); + // Still speaking at Done, as Google reports it (#3710): the drain waits for + // this segment's final rather than ending after the quiet window. + speech.deliver({ serverContent: { interimInputTranscription: { text: "And the" } } }); + await expect.poll(() => s.ui.stores.voice.getState().partial).toBe("And the"); await userEvent.click([...s.host.querySelectorAll("button")].find((el) => el.textContent?.trim() === "Done")!); await expect.poll(() => json(speech).some((frame) => frame.realtimeInput?.audioStreamEnd === true), { message: "Done ends the input stream" }).toBe(true); @@ -307,6 +311,9 @@ test("Google closing with 1011 while Done drains keeps the words and explains th speech.deliver({ setupComplete: {} }); speech.deliver({ serverContent: { inputTranscription: { text: "Ask Nestor about the ships.", finished: true } } }); await expect.poll(() => s.ui.stores.voice.getState().finalText).toBe("Ask Nestor about the ships."); + // Speech still pending at Done, so the drain waits for Google. + speech.deliver({ serverContent: { interimInputTranscription: { text: "And the" } } }); + await expect.poll(() => s.ui.stores.voice.getState().partial).toBe("And the"); await userEvent.click([...s.host.querySelectorAll("button")].find((el) => el.textContent?.trim() === "Done")!); await expect.poll(() => json(speech).some((frame) => frame.realtimeInput?.audioStreamEnd === true), { message: "Done ends the input stream" }).toBe(true); expect(s.ui.stores.voice.getState().mode, "Done waits for the last final").toBe("dictate"); @@ -314,7 +321,7 @@ test("Google closing with 1011 while Done drains keeps the words and explains th // handshake (no error event), so only the code says the take failed. speech.finish(1011, "", true); await expect.poll(() => s.ui.stores.voice.getState().mode, { message: "the close settled the drain" }).toBe("idle"); - expect(s.ui.stores.voice.getState().reviewText).toBe("Ask Nestor about the ships."); + expect(s.ui.stores.voice.getState().reviewText, "the words still pending at the close are kept").toBe("Ask Nestor about the ships. And the"); expect(s.ui.stores.voice.getState().dictationNotice, "GEMINI_BROWSER_DRAIN_CLOSE_NOTICE").toEqual({ reason: "network", phase: "ended", retained: true }); await expect.poll(() => audio.contexts[0]!.state).toBe("closed"); }); diff --git a/packages/ui-server/src/voice/gemini-speech.ts b/packages/ui-server/src/voice/gemini-speech.ts index 4979465d03..7057feb114 100644 --- a/packages/ui-server/src/voice/gemini-speech.ts +++ b/packages/ui-server/src/voice/gemini-speech.ts @@ -36,6 +36,13 @@ const TOKEN_MS = 11 * 60_000; const REQUEST_TIMEOUT_MS = 10_000; const GEMINI_MAX_VOCABULARY_TERMS = 100; const GEMINI_MAX_TERM_BYTES = 64; +/** + * Fixed language hint, matching Deepgram's `language: "en"` and browser + * speech's `en-US` default. Without it Google auto-detects, and #3710 measured + * a short English segment returned as Spanish (#3769). A hint biases + * recognition; it does not restrict it. + */ +export const GEMINI_LANGUAGE_CODES: readonly string[] = ["en-US"]; // Google's token resource name; anything else is not connection material. const TOKEN_NAME = /^auth_tokens\/[\x21-\x7e]{1,1024}$/; @@ -64,9 +71,9 @@ function geminiLockedSetup(vocabulary: readonly string[], mode: "SMART" | "VERBA const setup = { model: GEMINI_TRANSCRIBE_MODEL, generationConfig: { responseModalities: ["TEXT"] }, - inputAudioTranscription: { mode, ...(vocabulary.length ? { customVocabulary: [...vocabulary] } : {}) }, + inputAudioTranscription: { mode, languageCodes: [...GEMINI_LANGUAGE_CODES], ...(vocabulary.length ? { customVocabulary: [...vocabulary] } : {}) }, }; - const fieldMask = ["model", "generationConfig.responseModalities", "inputAudioTranscription.mode", ...(vocabulary.length ? ["inputAudioTranscription.customVocabulary"] : [])].join(","); + const fieldMask = ["model", "generationConfig.responseModalities", "inputAudioTranscription.mode", "inputAudioTranscription.languageCodes", ...(vocabulary.length ? ["inputAudioTranscription.customVocabulary"] : [])].join(","); return { setup, fieldMask }; } @@ -126,6 +133,7 @@ export function createGeminiSpeechProvider(apiKey: string): SpeechProvider { mode: wireMode, sampleRate: "16000", vocabulary: JSON.stringify(vocabulary), + languageCodes: JSON.stringify(GEMINI_LANGUAGE_CODES), }, }; }, diff --git a/packages/ui-server/tests/fixtures/gemini-auth-token-wire.ts b/packages/ui-server/tests/fixtures/gemini-auth-token-wire.ts index 8d24ae493e..3f78d37e08 100644 --- a/packages/ui-server/tests/fixtures/gemini-auth-token-wire.ts +++ b/packages/ui-server/tests/fixtures/gemini-auth-token-wire.ts @@ -7,24 +7,27 @@ * with `fetch` stubbed to record the request, config * `{ uses: 1, expireTime, newSessionExpireTime, liveConnectConstraints: { model: * "gemini-3.5-transcribe-live", config: { responseModalities: [TEXT], - * inputAudioTranscription } }, lockAdditionalFields: [] }`. The SDK's + * inputAudioTranscription } }, lockAdditionalFields: [] }`, where + * `inputAudioTranscription` is `{ mode: "SMART", languageCodes: ["en-US"] }` + * plus `customVocabulary` when keyterms are present (recaptured for #3769). The SDK's * `createAuthTokenConfigToMldev` maps `liveConnectConstraints` to * `bidiGenerateContentSetup.setup`, and `convertBidiSetupToTokenSetup` unwraps * `setup` and turns `lockAdditionalFields: []` into a `fieldMask` naming exactly * the setup fields present. `liveConnectConstraints` and `lockAdditionalFields` * are SDK option names; neither is a wire field. The SDK sent these to - * `/v1alpha/auth_tokens` because it was configured for v1alpha; which version - * Google accepts is #3710's question, not this fixture's. + * `/v1alpha/auth_tokens` because it was configured for v1alpha. #3710 measured + * that Google accepts the token on both the v1alpha and v1beta constrained + * Live endpoints. */ -/** Keyterms `["Ithaca", "Penelope"]`, SMART. */ +/** Keyterms `["Ithaca", "Penelope"]`, SMART, `en-US`. */ export const AUTH_TOKEN_WITH_VOCABULARY = JSON.parse( - `{"expireTime":"2026-07-12T00:11:00.000Z","newSessionExpireTime":"2026-07-12T00:01:00.000Z","uses":1,"bidiGenerateContentSetup":{"model":"models/gemini-3.5-transcribe-live","generationConfig":{"responseModalities":["TEXT"]},"inputAudioTranscription":{"mode":"SMART","customVocabulary":["Ithaca","Penelope"]}},"fieldMask":"model,generationConfig.responseModalities,inputAudioTranscription.mode,inputAudioTranscription.customVocabulary"}`, + `{"expireTime":"2026-07-12T00:11:00.000Z","newSessionExpireTime":"2026-07-12T00:01:00.000Z","uses":1,"bidiGenerateContentSetup":{"model":"models/gemini-3.5-transcribe-live","generationConfig":{"responseModalities":["TEXT"]},"inputAudioTranscription":{"mode":"SMART","languageCodes":["en-US"],"customVocabulary":["Ithaca","Penelope"]}},"fieldMask":"model,generationConfig.responseModalities,inputAudioTranscription.mode,inputAudioTranscription.languageCodes,inputAudioTranscription.customVocabulary"}`, ); -/** No keyterms, SMART: `customVocabulary` is neither set nor masked. */ +/** No keyterms, SMART, `en-US`: `customVocabulary` is neither set nor masked. */ export const AUTH_TOKEN_WITHOUT_VOCABULARY = JSON.parse( - `{"expireTime":"2026-07-12T00:11:00.000Z","newSessionExpireTime":"2026-07-12T00:01:00.000Z","uses":1,"bidiGenerateContentSetup":{"model":"models/gemini-3.5-transcribe-live","generationConfig":{"responseModalities":["TEXT"]},"inputAudioTranscription":{"mode":"SMART"}},"fieldMask":"model,generationConfig.responseModalities,inputAudioTranscription.mode"}`, + `{"expireTime":"2026-07-12T00:11:00.000Z","newSessionExpireTime":"2026-07-12T00:01:00.000Z","uses":1,"bidiGenerateContentSetup":{"model":"models/gemini-3.5-transcribe-live","generationConfig":{"responseModalities":["TEXT"]},"inputAudioTranscription":{"mode":"SMART","languageCodes":["en-US"]}},"fieldMask":"model,generationConfig.responseModalities,inputAudioTranscription.mode,inputAudioTranscription.languageCodes"}`, ); /** Every top-level field the captured AuthToken bodies carry. */ diff --git a/packages/ui-server/tests/gemini-speech.test.ts b/packages/ui-server/tests/gemini-speech.test.ts index e01b725700..bd038f664c 100644 --- a/packages/ui-server/tests/gemini-speech.test.ts +++ b/packages/ui-server/tests/gemini-speech.test.ts @@ -82,7 +82,7 @@ describe("Gemini dictation session", () => { expect(Date.parse(expireTime)).toBeLessThanOrEqual(after + 11 * 60_000); expect(session).toEqual({ url: GEMINI_TRANSCRIBE_URL, token: TOKEN, expiresAt: Date.parse(newSessionExpireTime), - params: { model: GEMINI_TRANSCRIBE_MODEL, mode: "SMART", sampleRate: "16000", vocabulary: JSON.stringify(["Ithaca", "Penelope"]) }, + params: { model: GEMINI_TRANSCRIBE_MODEL, mode: "SMART", sampleRate: "16000", vocabulary: JSON.stringify(["Ithaca", "Penelope"]), languageCodes: JSON.stringify(["en-US"]) }, }); expect(JSON.stringify(session)).not.toContain(KEY); }); @@ -101,7 +101,7 @@ describe("Gemini dictation session", () => { const verbatim = await provider.createSession({ keyterms: [], mode: "verbatim" }); const smart = await provider.createSession({ keyterms: [], mode: "smart" }); const unset = await provider.createSession({ keyterms: [] }); - expect(d.seen.map((seen) => seen.body.bidiGenerateContentSetup.inputAudioTranscription)).toEqual([{ mode: "VERBATIM" }, { mode: "SMART" }, { mode: "SMART" }]); + expect(d.seen.map((seen) => seen.body.bidiGenerateContentSetup.inputAudioTranscription)).toEqual([{ mode: "VERBATIM", languageCodes: ["en-US"] }, { mode: "SMART", languageCodes: ["en-US"] }, { mode: "SMART", languageCodes: ["en-US"] }]); expect(d.seen.map((seen) => authTokenWireError(seen.body))).toEqual([null, null, null]); expect([verbatim, smart, unset].map((session) => [session.params!.mode, session.params!.vocabulary])).toEqual([["VERBATIM", "[]"], ["SMART", "[]"], ["SMART", "[]"]]); }); From 7e21896c2f7695094618a515c6cd4d64c0a953a8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 9 Nov 2026 10:43:26 +0100 Subject: [PATCH 2/5] test(ui-react): label the language setup assertion on expect Co-Authored-By: Claude Opus 5.5 --- packages/ui-react/tests/asr-gemini.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-react/tests/asr-gemini.test.ts b/packages/ui-react/tests/asr-gemini.test.ts index f722fda500..8b92d7543d 100644 --- a/packages/ui-react/tests/asr-gemini.test.ts +++ b/packages/ui-react/tests/asr-gemini.test.ts @@ -232,11 +232,11 @@ describe("GeminiAsrClient wire behaviour", () => { expect(url.origin + url.pathname).toBe(URL_); expect(url.searchParams.get("access_token")).toBe(TOKEN); expect(h.socket().binaryType).toBe("arraybuffer"); - expect(JSON.parse(h.socket().sent[0]!)).toEqual({ setup: { + expect(JSON.parse(h.socket().sent[0]!), "GEMINI_SETUP_REPEATS_LANGUAGE").toEqual({ setup: { model: "models/gemini-3.5-transcribe-live", generationConfig: { responseModalities: ["TEXT"] }, inputAudioTranscription: { mode: "SMART", languageCodes: ["en-US"], customVocabulary: ["Ithaca", "Penelope"] }, - } }, "GEMINI_SETUP_REPEATS_LANGUAGE"); + } }); }); for (const [name, languageCodes] of [ From fc6127fa003d2ca79ba70046c8aa7e07216ba40f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 9 Nov 2026 10:45:01 +0100 Subject: [PATCH 3/5] refactor(ui-server): keep the Gemini language hint module-private Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/voice/gemini-speech.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/src/voice/gemini-speech.ts b/packages/ui-server/src/voice/gemini-speech.ts index 7057feb114..c84c58cc4e 100644 --- a/packages/ui-server/src/voice/gemini-speech.ts +++ b/packages/ui-server/src/voice/gemini-speech.ts @@ -42,7 +42,7 @@ const GEMINI_MAX_TERM_BYTES = 64; * a short English segment returned as Spanish (#3769). A hint biases * recognition; it does not restrict it. */ -export const GEMINI_LANGUAGE_CODES: readonly string[] = ["en-US"]; +const GEMINI_LANGUAGE_CODES: readonly string[] = ["en-US"]; // Google's token resource name; anything else is not connection material. const TOKEN_NAME = /^auth_tokens\/[\x21-\x7e]{1,1024}$/; From 74a11cd620dc29c6ff40d99847188dc7350ccb0f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 9 Nov 2026 12:34:38 +0100 Subject: [PATCH 4/5] fix(ui-react): keep Done open for voice Google has not placed in a segment The first drain fix ended Done on any generationComplete after audioStreamEnd, or after 300 ms of quiet with nothing pending. Review found two ways that still lost the last words: speech captured just before Done that Google had not yet signalled, and an earlier segment's completion that was still in flight when audioStreamEnd went out. A quiet window could also lapse while an already-arrived message was still decoding. Done now tracks how far into the stream the microphone heard voice and how far Google has closed segments (ACTIVITY_END audioOffset). After audioStreamEnd it waits while a segment is open, waits up to 1.5 s while voice lies past Google's last ACTIVITY_END, and otherwise ends as soon as Google has answered, or after 300 ms with no answer. A lapsed quiet first drains the inbound queue, and anything that re-armed it wins. The 3 s cap still bounds every wait. The browser test now ends segments the way Google did in #3710 (final, generationComplete, ACTIVITY_END; never finished) and carries the language params. The plan's wire examples include languageCodes, and the changeset calls it a fixed English recognition hint. Co-Authored-By: Claude Opus 5.5 --- .changeset/gemini-dictation-drain-language.md | 2 +- docs/plans/selectable-dictation.md | 39 +++- packages/ui-react/src/voice/asr-gemini.ts | 82 ++++++-- packages/ui-react/tests/asr-gemini.test.ts | 195 +++++++++++++++++- .../browser/dictation-gemini.offline.tsx | 19 +- 5 files changed, 302 insertions(+), 35 deletions(-) diff --git a/.changeset/gemini-dictation-drain-language.md b/.changeset/gemini-dictation-drain-language.md index 8a47fc9695..4d8ffe2d15 100644 --- a/.changeset/gemini-dictation-drain-language.md +++ b/.changeset/gemini-dictation-drain-language.md @@ -3,4 +3,4 @@ "@schlessera/brain-ui-server": patch --- -Gemini dictation finishes Done faster and no longer guesses the language. Google never sends `finished` or `turnComplete` after `audioStreamEnd`, so Done waited its full 3 s every time. Done now ends on the `generationComplete` that follows the last words, or after 300 ms of quiet when nothing is pending (#3768). The minted token now locks `languageCodes: ["en-US"]` and the client repeats it, matching Deepgram's fixed `en`. With automatic detection, a short English segment had come back as Spanish (#3769). +Gemini dictation finishes Done faster and recognizes English with a fixed language hint. Google never sends `finished` or `turnComplete` after `audioStreamEnd`, so Done waited its full 3 s every time. Done now ends as soon as Google has answered for all the speech the microphone heard: on `generationComplete` and the `ACTIVITY_END` that covers the last voiced audio, or after 300 ms of quiet when nothing is pending. Voice that Google has not signalled yet keeps Done open for up to 1.5 s, so the last words are not cut off (#3768). The minted token now locks a fixed English recognition hint, `languageCodes: ["en-US"]`, and the client repeats it, matching Deepgram's fixed `en`. With automatic detection, a short English segment had come back as Spanish (#3769). diff --git a/docs/plans/selectable-dictation.md b/docs/plans/selectable-dictation.md index 88e7f77a91..c2f7fe0baa 100644 --- a/docs/plans/selectable-dictation.md +++ b/docs/plans/selectable-dictation.md @@ -95,7 +95,12 @@ synthetic TTS audio, no device):** - Interim text is cumulative within a segment and stays verbatim in SMART; only the final is cleaned. - A final arrives on a pause, as `inputTranscription`, then - `generationComplete: true`, then `speechState: NON_SPEECH`. + `generationComplete: true`, then `speechState: NON_SPEECH` with a top-level + `voiceActivity: { type: "ACTIVITY_END", audioOffset }`. Speech starts with + `speechState: SPEECH` and `ACTIVITY_START`, about 75 ms after the audio + reached Google. `audioOffset` counts from the first audio of the stream; + `ACTIVITY_END` fell 0.7–1.3 s after the last voiced audio, or at the stream + end when speech ran into it. - After `audioStreamEnd`, Google sends the pending final and `generationComplete` (+253 ms measured). When nothing is pending it sends nothing at all. `finished` and `turnComplete` never came, so Done waits for @@ -327,8 +332,9 @@ x-goog-api-key: "model": "models/gemini-3.5-transcribe-live", "generationConfig": { "responseModalities": ["TEXT"] }, "inputAudioTranscription": { "mode": "SMART", + "languageCodes": ["en-US"], "customVocabulary": ["Ithaca", "Penelope", "…"] } }, - "fieldMask": "model,generationConfig.responseModalities,inputAudioTranscription.mode,inputAudioTranscription.customVocabulary" } + "fieldMask": "model,generationConfig.responseModalities,inputAudioTranscription.mode,inputAudioTranscription.languageCodes,inputAudioTranscription.customVocabulary" } ``` This is the REST AuthToken that `@google/genai` 2.24.0 serializes from @@ -342,7 +348,8 @@ x-goog-api-key: { "url": "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained", "token": "auth_tokens/…", "expiresAt": 1783847400000, "params": { "model": "models/gemini-3.5-transcribe-live", "mode": "SMART", - "sampleRate": "16000", "vocabulary": "[\"Ithaca\",\"Penelope\"]" } } + "sampleRate": "16000", "vocabulary": "[\"Ithaca\",\"Penelope\"]", + "languageCodes": "[\"en-US\"]" } } ``` - Vocabulary is the existing bounded keyterm list, capped at **100 terms** of at @@ -355,8 +362,9 @@ x-goog-api-key: - The constraint locks model, modality and transcription config, and the browser's `setup` repeats them field for field. Any additional field the client sends is rejected or overridden by Google, which is the point of the - lock. Whether Google enforces the `fieldMask` this way, and which API version - (`v1alpha` or `v1beta`) accepts the token, is a #3710 check. + lock. #3710 measured it: a client setup asking for another mode or model + still got the locked transcription, and both `v1alpha` and `v1beta` accept + the token. - Token TTL: one use, 60 s to connect, 11 minutes overall (the 10-minute session plus margin). **No session resumption** in the first delivery: a take ends at Google's 10-minute limit through provider-ended, and its words go to @@ -391,11 +399,18 @@ x-goog-api-key: `error`, `goAway` and unknown-close reasons map to `speechError` codes without exposing their text. - **Done (`drainAndStop`).** Stop the tracks, flush the partial chunk and send - `audioStreamEnd`. If speech is pending (a `SPEECH` state or an interim that - no final or `generationComplete` has closed), wait for the - `generationComplete` that follows `audioStreamEnd`. Otherwise end after - **300 ms** of quiet, extended to `generationComplete` by any speech or - interim that arrives in it. `finished` or `turnComplete` also end it, and + `audioStreamEnd`. Then, after every message Google sends: + - While a segment is open (a `SPEECH` state or an interim that no final or + `generationComplete` has closed), wait. + - While the microphone heard voice (block RMS ≥ 0.015) past Google's last + `ACTIVITY_END` offset, wait up to **1.5 s** of quiet: Google has not yet + signalled that speech, and an earlier segment's completion may still be + arriving. If Google never calls it speech, Done ends there. + - Otherwise Google's answer is complete and Done ends at once. With no + answer at all (nothing was pending), it ends after **300 ms** of quiet. + + A lapsed quiet first processes messages that already arrived, so a final + still decoding is kept. `finished` or `turnComplete` also end Done, and **3 s** caps all of it (#3768). Close either way. Words already heard are kept. - **Hard stop, cancel, unmount, superseded start.** Close the socket (1000), @@ -529,7 +544,9 @@ key-registered built-in over the legacy single selection. asserts the setup frame, base64 PCM16 framing at 16 kHz from 44.1 and 48 kHz contexts in real Chrome, the pre-setup buffer bound, backpressure failure, interim replacement, single final commit, the `audioStreamEnd` drain (on - `generationComplete`, after a quiet with nothing pending, capped at 3 s), and complete teardown (tracks ended, context closed, socket closed, no + `generationComplete` and `ACTIVITY_END`, waiting for voice Google has not + signalled and for messages still decoding, after a quiet with nothing + pending, capped at 3 s), and complete teardown (tracks ended, context closed, socket closed, no late mutation). - Mutations: final mapped as partial, resampler bypassed, constraint lock removed, teardown skipping `context.close()`. Each fails its named diff --git a/packages/ui-react/src/voice/asr-gemini.ts b/packages/ui-react/src/voice/asr-gemini.ts index aba92e5b61..37f8a72995 100644 --- a/packages/ui-react/src/voice/asr-gemini.ts +++ b/packages/ui-react/src/voice/asr-gemini.ts @@ -32,6 +32,15 @@ export const GEMINI_DRAIN_MS = 3_000; * (#3710), so without it every such Done waited the full cap (#3768). */ export const GEMINI_DRAIN_QUIET_MS = 300; +/** + * The quiet window when the microphone heard voice that Google has not yet + * placed in a segment: its speech signal is still on the way. Google signalled + * speech about 75 ms after the audio reached it in #3710, so this leaves room + * for a slow network; if Google never calls it speech, Done ends here. + */ +export const GEMINI_DRAIN_TAIL_MS = 1_500; +/** Block RMS that counts as voice; the conversation capture uses the same bar. */ +export const GEMINI_VOICE_RMS = 0.015; const MAX_MESSAGE_BYTES = 262_144; const MODEL = "models/gemini-3.5-transcribe-live"; const MIME = `audio/pcm;rate=${GEMINI_SAMPLE_RATE}`; @@ -46,6 +55,9 @@ const messageSchema = z.object({ generationComplete: z.boolean().optional(), speechState: z.string().max(32).optional(), }).optional(), + // Google's voice activity detection; audioOffset is a Duration ("3.310s") + // from the first audio of the stream. + voiceActivity: z.object({ type: z.string().max(32).optional(), audioOffset: z.string().max(32).optional() }).optional(), goAway: z.object({}).optional(), // Remote error text is deliberately never surfaced: it may echo request details. error: z.unknown().optional(), @@ -89,6 +101,14 @@ export class GeminiAsrClient implements AsrClient { /** audioStreamEnd has been sent; only now can generationComplete end the drain. */ private streamEnded = false; private quiet: ReturnType | null = null; + /** Bumped on every (re)arm and disarm, so a stale quiet callback does nothing. */ + private quietRound = 0; + /** Samples captured for the stream so far: the stream offset of the next one. */ + private captured = 0; + /** Stream offset just past the last block the microphone heard voice in. */ + private voicedTo = 0; + /** Stream offset up to which Google has closed segments (ACTIVITY_END). */ + private heardTo = 0; private readonly setup: string; constructor(private readonly opts: GeminiAsrClientOptions) { @@ -194,6 +214,8 @@ export class GeminiAsrClient implements AsrClient { // During Done the flush still delivers the worklet's last samples. if (this.phase === "draining" ? this.tailFlushed : this.phase !== "live") return; if (this.phase === "live") this.opts.onAudioLevel?.(Math.min(1, rms * 4)); + if (rms >= GEMINI_VOICE_RMS) this.voicedTo = this.captured + pcm.length; + this.captured += pcm.length; const drain = this.settleDrain; // A failure ends the loop: it closes a live take or settles the drain. const open = () => this.phase === "live" || (this.phase === "draining" && this.settleDrain === drain); @@ -234,21 +256,48 @@ export class GeminiAsrClient implements AsrClient { private endInput(): void { for (const frame of this.queue.splice(0)) if (!this.send(frame)) return; if (!this.send(JSON.stringify({ realtimeInput: { audioStreamEnd: true } }))) return; - // Google answers audioStreamEnd with the pending final and generationComplete - // (+253 ms measured in #3710), and with nothing at all when no speech is - // pending; it never sent finished or turnComplete. So: wait for - // generationComplete while speech is pending, otherwise end after a quiet. this.streamEnded = true; - if (!this.pending) this.armQuiet(); + this.settleOrWait(false); } - /** (Re)start the quiet window that ends a drain with nothing pending. */ - private armQuiet(): void { - if (this.quiet) clearTimeout(this.quiet); - this.quiet = setTimeout(() => { this.quiet = null; this.finishDrain(); }, GEMINI_DRAIN_QUIET_MS); + /** The microphone heard voice past the last segment Google closed. */ + private unplaced(): boolean { + return this.voicedTo > this.heardTo; + } + + /** + * After audioStreamEnd, decide whether Done is complete. Google answers it + * with the pending final, generationComplete and ACTIVITY_END (+253 ms in + * #3710), and with nothing at all when no speech is pending; it never sent + * finished or turnComplete. So Done waits while a segment is open; waits a + * long quiet while the microphone heard voice past Google's last ACTIVITY_END, + * since an earlier segment's completion can arrive before the new speech is + * signalled; and otherwise ends after a short quiet (at audioStreamEnd) or + * at once (after Google's answer). The 3 s cap bounds every wait. + */ + private settleOrWait(answered: boolean): void { + if (this.pending) this.disarmQuiet(); + else if (this.unplaced()) this.armQuiet(GEMINI_DRAIN_TAIL_MS); + else if (answered) this.finishDrain(); + else this.armQuiet(GEMINI_DRAIN_QUIET_MS); + } + + /** + * (Re)start a quiet window. When it lapses, messages that already arrived + * are processed first (a Blob decodes asynchronously), and any of them that + * re-armed or disarmed the window wins. + */ + private armQuiet(ms: number): void { + this.disarmQuiet(); + const round = this.quietRound; + this.quiet = setTimeout(() => { + this.quiet = null; + void this.inbound.then(() => { if (this.quietRound === round) this.finishDrain(); }); + }, ms); } private disarmQuiet(): void { + this.quietRound++; if (this.quiet) { clearTimeout(this.quiet); this.quiet = null; } } @@ -263,6 +312,7 @@ export class GeminiAsrClient implements AsrClient { return; } if (message.error !== undefined) { this.fail("Gemini reported an error", "unknown"); return; } + const endedBefore = this.streamEnded; if (message.setupComplete && !this.setupDone) { this.setupDone = true; if (this.handshake) { clearTimeout(this.handshake); this.handshake = null; } @@ -276,17 +326,17 @@ export class GeminiAsrClient implements AsrClient { if (interim) this.opts.onEvent({ type: "partial", text: interim }); const final = content?.inputTranscription; if (final?.text) this.opts.onEvent({ type: "final", text: final.text, endsTurn: final.finished ?? true }); + const activity = message.voiceActivity; if (interim || content?.speechState === "SPEECH") this.pending = true; if (final?.text || content?.generationComplete === true) this.pending = false; + if (activity?.type === "ACTIVITY_END") { + const seconds = /^(\d{1,6}(?:\.\d{1,9})?)s$/.exec(activity.audioOffset ?? "")?.[1]; + if (seconds !== undefined) this.heardTo = Math.max(this.heardTo, Math.ceil(Number(seconds) * GEMINI_SAMPLE_RATE)); + } if (this.phase === "draining") { if (final?.finished === true || content?.turnComplete === true) this.finishDrain(); - else if (this.streamEnded && content?.generationComplete === true) this.finishDrain(); - else if (this.streamEnded) { - // More speech is still being transcribed: wait for generationComplete. - if (this.pending) this.disarmQuiet(); - // A final without generationComplete: end after a quiet, not the cap. - else if (final?.text) this.armQuiet(); - } + // A setupComplete that just sent audioStreamEnd has already decided. + else if (endedBefore) this.settleOrWait(true); } // The session is about to end: what was heard is kept, the take ends. if (message.goAway) this.fail("Gemini session ending", "network"); diff --git a/packages/ui-react/tests/asr-gemini.test.ts b/packages/ui-react/tests/asr-gemini.test.ts index 8b92d7543d..7733b36894 100644 --- a/packages/ui-react/tests/asr-gemini.test.ts +++ b/packages/ui-react/tests/asr-gemini.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { runAsrClientContract } from "@schlessera/brain-ui-sdk/testing"; import type { AsrEvent, VoiceSessionResponse } from "@schlessera/brain-ui-sdk/client"; import { - GEMINI_DRAIN_MS, GEMINI_DRAIN_QUIET_MS, GEMINI_FRAME_SAMPLES, GEMINI_HANDSHAKE_MS, GEMINI_MAX_BUFFERED_BYTES, GEMINI_PRESETUP_FRAMES, GeminiAsrClient, + GEMINI_DRAIN_MS, GEMINI_DRAIN_QUIET_MS, GEMINI_DRAIN_TAIL_MS, GEMINI_FRAME_SAMPLES, GEMINI_HANDSHAKE_MS, GEMINI_MAX_BUFFERED_BYTES, GEMINI_PRESETUP_FRAMES, GeminiAsrClient, } from "../src/voice/asr-gemini"; import { createPcmResampler, PCM_CAPTURE_BLOCK } from "../src/voice/pcm-capture"; @@ -502,7 +502,8 @@ describe("GeminiAsrClient wire behaviour", () => { s.server({ setupComplete: {} }); await tick(); expect(JSON.parse(s.sent.at(-1)!)).toEqual({ realtimeInput: { audioStreamEnd: true } }); - h.advance(GEMINI_DRAIN_QUIET_MS); + // The voiced audio was never placed in a segment, so the tail window applies. + h.advance(GEMINI_DRAIN_TAIL_MS); await draining; }); @@ -549,6 +550,196 @@ describe("GeminiAsrClient wire behaviour", () => { expect(h.events.at(-1)).toEqual({ type: "final", text: "And the harbor.", endsTurn: true }); }); + // Offsets below are in 16 kHz samples: a 16 kHz context passes them through. + const offset = (samples: number) => `${(samples / 16_000).toFixed(3)}s`; + + test("voice the microphone heard but Google has not yet signalled keeps Done open past the short quiet", async () => { + const h = harness({ rate: 16_000, timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + // The last word, right before Done: Google has not answered it yet. + h.speak(GEMINI_FRAME_SAMPLES * 2); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + expect(JSON.parse(s.sent.at(-1)!)).toEqual({ realtimeInput: { audioStreamEnd: true } }); + h.advance(GEMINI_DRAIN_QUIET_MS * 2); + await tick(); + expect(settled, "GEMINI_DRAIN_WAITS_FOR_UNSIGNALLED_VOICE").toBe(false); + s.server({ serverContent: { speechState: "SPEECH" }, voiceActivity: { type: "ACTIVITY_START", audioOffset: offset(0) } }); + await tick(); + h.advance(GEMINI_DRAIN_TAIL_MS); + await tick(); + expect(settled, "an open segment waits for its completion").toBe(false); + s.server({ serverContent: { inputTranscription: { text: "Ithaca." } } }); + s.server({ serverContent: { generationComplete: true } }); + s.server({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: offset(GEMINI_FRAME_SAMPLES * 2) } }); + await tick(); + expect(settled, "GEMINI_DRAIN_ENDS_ON_ACTIVITY_END").toBe(true); + await draining; + expect(h.events, "GEMINI_DRAIN_WAITS_FOR_UNSIGNALLED_VOICE").toEqual([{ type: "final", text: "Ithaca.", endsTurn: true }]); + }); + + test("an earlier segment's completion arriving after audioStreamEnd does not end Done before the new speech", async () => { + const h = harness({ rate: 16_000, timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + const first = GEMINI_FRAME_SAMPLES * 4; + h.speak(first); + h.speak(GEMINI_FRAME_SAMPLES * 3, 440, 0); + s.server({ serverContent: { speechState: "SPEECH" }, voiceActivity: { type: "ACTIVITY_START", audioOffset: offset(0) } }); + await tick(); + // The second sentence starts; Google is still finishing the first. + h.speak(GEMINI_FRAME_SAMPLES * 2); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + // The first segment's answer was already in flight. + s.server({ serverContent: { inputTranscription: { text: "Ask Nestor." } } }); + s.server({ serverContent: { generationComplete: true } }); + s.server({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: offset(first + GEMINI_FRAME_SAMPLES) } }); + await tick(); + h.advance(GEMINI_DRAIN_QUIET_MS * 2); + await tick(); + expect(settled, "GEMINI_DRAIN_IGNORES_EARLIER_COMPLETION").toBe(false); + s.server({ serverContent: { speechState: "SPEECH" }, voiceActivity: { type: "ACTIVITY_START", audioOffset: offset(first + GEMINI_FRAME_SAMPLES * 3) } }); + s.server({ serverContent: { inputTranscription: { text: "Then the ships." } } }); + s.server({ serverContent: { generationComplete: true } }); + s.server({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: offset(first + GEMINI_FRAME_SAMPLES * 5) } }); + await tick(); + expect(settled, "GEMINI_DRAIN_ENDS_ON_ACTIVITY_END").toBe(true); + await draining; + expect(h.events.map((event) => event.text), "GEMINI_DRAIN_IGNORES_EARLIER_COMPLETION").toEqual(["Ask Nestor.", "Then the ships."]); + }); + + test("silence after the last segment Google closed ends Done after the short quiet", async () => { + const h = harness({ rate: 16_000, timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + h.speak(GEMINI_FRAME_SAMPLES * 2); + s.server({ serverContent: { speechState: "SPEECH" } }); + s.server({ serverContent: { inputTranscription: { text: "Ithaca." } } }); + s.server({ serverContent: { generationComplete: true } }); + s.server({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: offset(GEMINI_FRAME_SAMPLES * 2) } }); + await tick(); + h.speak(GEMINI_FRAME_SAMPLES * 4, 440, 0.005); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + h.advance(GEMINI_DRAIN_QUIET_MS); + await tick(); + expect(settled, "GEMINI_DRAIN_SILENCE_IS_NOT_VOICE").toBe(true); + await draining; + }); + + test("voice Google never calls speech ends Done at the tail window, not the 3 s cap", async () => { + const h = harness({ rate: 16_000, timers: true }); + await h.client.start(); + await tick(); await tick(); + h.speak(GEMINI_FRAME_SAMPLES); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + h.advance(GEMINI_DRAIN_TAIL_MS - 1); + await tick(); + expect(settled).toBe(false); + h.advance(1); + await tick(); + expect(settled, "GEMINI_DRAIN_TAIL_BOUNDED").toBe(true); + await draining; + }); + + test("a final that arrived before the quiet lapsed but is still decoding reaches review", async () => { + const h = harness({ timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + let release!: () => void; + const decoded = new Promise((resolve) => { release = resolve; }); + class SlowBlob extends Blob { override async text() { await decoded; return super.text(); } } + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + h.advance(GEMINI_DRAIN_QUIET_MS - 50); + s.onmessage?.({ data: new SlowBlob([JSON.stringify({ serverContent: { inputTranscription: { text: "Penelope waits." } } })]) }); + h.advance(50); + await tick(); + expect(settled, "the quiet waits for messages that already arrived").toBe(false); + release(); + await draining; + expect(h.events, "GEMINI_DRAIN_WAITS_FOR_INBOUND").toEqual([{ type: "final", text: "Penelope waits.", endsTurn: true }]); + }); + + test("speech still decoding when the quiet lapses keeps Done open for its completion", async () => { + const h = harness({ timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + let release!: () => void; + const decoded = new Promise((resolve) => { release = resolve; }); + class SlowBlob extends Blob { override async text() { await decoded; return super.text(); } } + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + h.advance(GEMINI_DRAIN_QUIET_MS - 50); + s.onmessage?.({ data: new SlowBlob([JSON.stringify({ serverContent: { interimInputTranscription: { text: "Penelope" } } })]) }); + h.advance(50); + release(); + await tick(); await tick(); + expect(settled, "GEMINI_DRAIN_LAPSED_QUIET_YIELDS").toBe(false); + s.server({ serverContent: { inputTranscription: { text: "Penelope waits." }, generationComplete: true } }); + await draining; + expect(h.events.at(-1)).toEqual({ type: "final", text: "Penelope waits.", endsTurn: true }); + }); + + test("a final and its completion in one message end Done at once", async () => { + const h = harness({ timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + s.server({ serverContent: { speechState: "SPEECH" } }); + await tick(); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + s.server({ serverContent: { inputTranscription: { text: "Sail at dawn." }, generationComplete: true } }); + await tick(); + expect(settled, "GEMINI_DRAIN_COMBINED_COMPLETION").toBe(true); + await draining; + expect(h.events).toEqual([{ type: "final", text: "Sail at dawn.", endsTurn: true }]); + }); + + test("a final without generationComplete after audioStreamEnd ends Done once nothing is left unplaced", async () => { + const h = harness({ timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + s.server({ serverContent: { interimInputTranscription: { text: "Sail at" } } }); + await tick(); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + s.server({ serverContent: { inputTranscription: { text: "Sail at dawn." } } }); + await tick(); + expect(settled, "GEMINI_DRAIN_FINAL_WITHOUT_COMPLETION").toBe(true); + await draining; + }); + + test("hard stop during the quiet window leaves no timer behind", async () => { + const h = harness({ timers: true }); + await h.client.start(); + await tick(); await tick(); + const draining = h.client.drainAndStop(); + await tick(); await tick(); + expect(h.pending.length, "the cap and the quiet window are armed").toBe(2); + h.client.stop(); + await draining; + expect(h.pending, "GEMINI_DRAIN_STOP_CLEARS_QUIET").toHaveLength(0); + }); + test("Done before setupComplete sends the waiting audio and the stream end once setup completes", async () => { const h = harness({ answerSetup: false }); await h.client.start(); diff --git a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx index 121b7ad3b5..ee4834f81b 100644 --- a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx +++ b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx @@ -35,7 +35,7 @@ const HELLO = [ const SESSION: VoiceSessionResponse = { providerId: "gemini", url: SPEECH, token: TOKEN, expiresAt: Date.now() + 60 * 60_000, - params: { model: "models/gemini-3.5-transcribe-live", mode: "SMART", sampleRate: "16000", vocabulary: JSON.stringify(["Ithaca", "Penelope"]) }, + params: { model: "models/gemini-3.5-transcribe-live", mode: "SMART", sampleRate: "16000", vocabulary: JSON.stringify(["Ithaca", "Penelope"]), languageCodes: JSON.stringify(["en-US"]) }, capabilities: { streaming: true, interimResults: true, keyterms: true, endpointing: false, smartTranscription: true, savedAudio: false }, }; @@ -177,7 +177,7 @@ for (const rate of [44_100, 48_000]) { expect(json(speech)[0], "the setup the token locks").toEqual({ setup: { model: "models/gemini-3.5-transcribe-live", generationConfig: { responseModalities: ["TEXT"] }, - inputAudioTranscription: { mode: "SMART", customVocabulary: ["Ithaca", "Penelope"] }, + inputAudioTranscription: { mode: "SMART", languageCodes: ["en-US"], customVocabulary: ["Ithaca", "Penelope"] }, } }); expect(audio.contexts[0]?.sampleRate, "the client's context runs at the hardware rate").toBe(rate); speech.deliver({ setupComplete: {} }); @@ -196,9 +196,13 @@ for (const rate of [44_100, 48_000]) { await expect.poll(() => s.ui.stores.voice.getState().partial).toBe("Ask Nes"); speech.deliver({ serverContent: { interimInputTranscription: { text: "Ask Nestor about" } } }); await expect.poll(() => s.ui.stores.voice.getState().partial, { message: "interim text replaces, never appends" }).toBe("Ask Nestor about"); - speech.deliver({ serverContent: { inputTranscription: { text: "Ask Nestor about the ships.", finished: true } } }); + // Each segment ends as Google ended it in #3710: the final, then + // generationComplete, then NON_SPEECH; never finished or turnComplete. + speech.deliver({ serverContent: { inputTranscription: { text: "Ask Nestor about the ships." } } }); + speech.deliver({ serverContent: { generationComplete: true } }); await expect.poll(() => s.ui.stores.voice.getState().finalText).toBe("Ask Nestor about the ships."); expect(s.ui.stores.voice.getState().partial, "a final clears the partial").toBe(""); + speech.deliver({ serverContent: { speechState: "SPEECH" }, voiceActivity: { type: "ACTIVITY_START", audioOffset: "1.000s" } }); // Still speaking at Done, as Google reports it (#3710): the drain waits for // this segment's final rather than ending after the quiet window. speech.deliver({ serverContent: { interimInputTranscription: { text: "And the" } } }); @@ -208,8 +212,13 @@ for (const rate of [44_100, 48_000]) { await expect.poll(() => json(speech).some((frame) => frame.realtimeInput?.audioStreamEnd === true), { message: "Done ends the input stream" }).toBe(true); expect(audio.streams[0]!.getTracks().map((track) => track.readyState), "Done closes the microphone first").toEqual(["ended"]); expect(s.ui.stores.voice.getState().mode, "Done waits for the last final").toBe("dictate"); - speech.deliver({ serverContent: { inputTranscription: { text: "And the harbor.", finished: true } } }); - await expect.poll(() => s.ui.stores.voice.getState().mode, { message: "the drain ended the dictation" }).toBe("idle"); + // The tone never stops, so Google's ACTIVITY_END places the whole stream. + const streamed = audioFrames(speech).reduce((samples, frame) => samples + atob(frame.data).length / 2, 0); + speech.deliver({ serverContent: { inputTranscription: { text: "And the harbor." } } }); + speech.deliver({ serverContent: { generationComplete: true } }); + speech.deliver({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: `${(streamed / 16_000).toFixed(3)}s` } }); + // Well inside the 1.5 s tail window and the 3 s cap: Google's answer ended it. + await expect.poll(() => s.ui.stores.voice.getState().mode, { message: "GEMINI_BROWSER_DRAIN_ON_ANSWER", timeout: 1_000 }).toBe("idle"); expect(s.ui.stores.voice.getState().reviewText, "each final commits exactly once").toBe("Ask Nestor about the ships. And the harbor."); await expect.poll(() => audio.contexts[0]!.state, { message: "GEMINI_BROWSER_TEARDOWN_CONTEXT_CLOSED" }).toBe("closed"); expect(speech.readyState).toBe(3); From 3426a5644bcab2c331182561221004d5f426db31 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 9 Nov 2026 12:47:08 +0100 Subject: [PATCH 5/5] fix(ui-react): end Gemini Done only on an answer that reaches the stream end A second review of the drain found that an earlier segment's answer could still close Done early. Its generationComplete or finished, or an unrelated message, ended Done whenever no loud voice lay past Google's last ACTIVITY_END, so speech too quiet for the RMS bar was dropped. Google also reports audioOffset in 10 ms steps, so an ACTIVITY_END at the stream end could land a few samples short and wait the 1.5 s tail window for nothing. Done now ends at once only when an ACTIVITY_END reaches the stream end, within one frame. An answer that stops short waits the 300 ms quiet. finished and turnComplete close a segment like generationComplete and no longer end Done by themselves. Only messages about speech are considered, and a running tail window is not restarted. The voice threshold stays module-private. Co-Authored-By: Claude Opus 5.5 --- .changeset/gemini-dictation-drain-language.md | 2 +- docs/plans/selectable-dictation.md | 39 +++--- packages/ui-react/src/voice/asr-gemini.ts | 52 +++++--- packages/ui-react/tests/asr-gemini.test.ts | 114 +++++++++++++++++- .../browser/dictation-gemini.offline.tsx | 8 +- 5 files changed, 177 insertions(+), 38 deletions(-) diff --git a/.changeset/gemini-dictation-drain-language.md b/.changeset/gemini-dictation-drain-language.md index 4d8ffe2d15..0228eafb4b 100644 --- a/.changeset/gemini-dictation-drain-language.md +++ b/.changeset/gemini-dictation-drain-language.md @@ -3,4 +3,4 @@ "@schlessera/brain-ui-server": patch --- -Gemini dictation finishes Done faster and recognizes English with a fixed language hint. Google never sends `finished` or `turnComplete` after `audioStreamEnd`, so Done waited its full 3 s every time. Done now ends as soon as Google has answered for all the speech the microphone heard: on `generationComplete` and the `ACTIVITY_END` that covers the last voiced audio, or after 300 ms of quiet when nothing is pending. Voice that Google has not signalled yet keeps Done open for up to 1.5 s, so the last words are not cut off (#3768). The minted token now locks a fixed English recognition hint, `languageCodes: ["en-US"]`, and the client repeats it, matching Deepgram's fixed `en`. With automatic detection, a short English segment had come back as Spanish (#3769). +Gemini dictation finishes Done faster and recognizes English with a fixed language hint. Google never sends `finished` or `turnComplete` after `audioStreamEnd`, so Done waited its full 3 s every time. Done now ends as soon as Google's answer reaches the end of the stream, and otherwise after 300 ms of quiet. Voice the microphone heard that Google has not yet signalled holds Done in a 1.5 s window, so words spoken just before Done are less likely to be cut off. The 3 s cap still bounds every wait (#3768). The minted token now locks a fixed English recognition hint, `languageCodes: ["en-US"]`, and the client repeats it, matching Deepgram's fixed `en`. With automatic detection, a short English segment had come back as Spanish (#3769). diff --git a/docs/plans/selectable-dictation.md b/docs/plans/selectable-dictation.md index c2f7fe0baa..10dcd9e39f 100644 --- a/docs/plans/selectable-dictation.md +++ b/docs/plans/selectable-dictation.md @@ -103,8 +103,8 @@ synthetic TTS audio, no device):** end when speech ran into it. - After `audioStreamEnd`, Google sends the pending final and `generationComplete` (+253 ms measured). When nothing is pending it sends nothing at all. - `finished` and `turnComplete` never came, so Done waits for - `generationComplete` (#3768). + `finished` and `turnComplete` never came, so Done ends on Google's answer + rather than on those flags (#3768). - A pause ends a segment, so SMART formats a spoken list only within one segment. - With automatic language detection, a short English segment was once @@ -399,20 +399,27 @@ x-goog-api-key: `error`, `goAway` and unknown-close reasons map to `speechError` codes without exposing their text. - **Done (`drainAndStop`).** Stop the tracks, flush the partial chunk and send - `audioStreamEnd`. Then, after every message Google sends: - - While a segment is open (a `SPEECH` state or an interim that no final or - `generationComplete` has closed), wait. - - While the microphone heard voice (block RMS ≥ 0.015) past Google's last - `ACTIVITY_END` offset, wait up to **1.5 s** of quiet: Google has not yet - signalled that speech, and an earlier segment's completion may still be - arriving. If Google never calls it speech, Done ends there. - - Otherwise Google's answer is complete and Done ends at once. With no - answer at all (nothing was pending), it ends after **300 ms** of quiet. - - A lapsed quiet first processes messages that already arrived, so a final - still decoding is kept. `finished` or `turnComplete` also end Done, and - **3 s** caps all of it (#3768). Close either way. Words already heard are - kept. + `audioStreamEnd`. Then, at the stream end and after every later message + about speech (an interim, a final, `speechState`, `generationComplete`, + `turnComplete` or `voiceActivity`; any other message is ignored): + - While a segment is open (a `SPEECH` state or an interim that no final, + `generationComplete`, `finished` or `turnComplete` has closed), wait. + - While the microphone heard voice (block RMS ≥ 0.015) more than one frame + past Google's last `ACTIVITY_END` offset, wait a **1.5 s** tail window: + Google has not yet signalled that speech, and an earlier segment's answer + may still be arriving. Later messages do not restart a running window; if + Google never calls the voice speech, Done ends when it lapses. + - When a message's `ACTIVITY_END` reaches the stream end (within one frame, + since Google reports 10 ms steps), Done ends at once. + - Otherwise wait **300 ms** of quiet, restarted by each such message. This + covers the stream end with nothing pending, and an earlier segment's + answer that stops short of the stream end, where speech too quiet for the + RMS bar may still be signalled. + + A lapsed window first processes messages that already arrived, so a final + still decoding is kept, and one that reopened a segment wins. The RMS bar + is a heuristic: speech it misses gets only the 300 ms window. **3 s** caps + all of it (#3768). Close either way. Words already heard are kept. - **Hard stop, cancel, unmount, superseded start.** Close the socket (1000), disconnect the worklet, close the AudioContext, stop the tracks, clear the timers and the queue, and ignore every later message, because the existing diff --git a/packages/ui-react/src/voice/asr-gemini.ts b/packages/ui-react/src/voice/asr-gemini.ts index 37f8a72995..0eab1b4889 100644 --- a/packages/ui-react/src/voice/asr-gemini.ts +++ b/packages/ui-react/src/voice/asr-gemini.ts @@ -40,7 +40,9 @@ export const GEMINI_DRAIN_QUIET_MS = 300; */ export const GEMINI_DRAIN_TAIL_MS = 1_500; /** Block RMS that counts as voice; the conversation capture uses the same bar. */ -export const GEMINI_VOICE_RMS = 0.015; +const GEMINI_VOICE_RMS = 0.015; +/** Google reports audioOffset in 10 ms steps; one frame absorbs its rounding. */ +const OFFSET_SLACK = GEMINI_FRAME_SAMPLES; const MAX_MESSAGE_BYTES = 262_144; const MODEL = "models/gemini-3.5-transcribe-live"; const MIME = `audio/pcm;rate=${GEMINI_SAMPLE_RATE}`; @@ -103,6 +105,8 @@ export class GeminiAsrClient implements AsrClient { private quiet: ReturnType | null = null; /** Bumped on every (re)arm and disarm, so a stale quiet callback does nothing. */ private quietRound = 0; + /** Length of the window now armed, or 0. */ + private quietMs = 0; /** Samples captured for the stream so far: the stream offset of the next one. */ private captured = 0; /** Stream offset just past the last block the microphone heard voice in. */ @@ -262,23 +266,33 @@ export class GeminiAsrClient implements AsrClient { /** The microphone heard voice past the last segment Google closed. */ private unplaced(): boolean { - return this.voicedTo > this.heardTo; + return this.voicedTo > this.heardTo + OFFSET_SLACK; + } + + /** Google's last ACTIVITY_END reaches the end of the stream. */ + private covered(): boolean { + return this.heardTo + OFFSET_SLACK >= this.captured; } /** * After audioStreamEnd, decide whether Done is complete. Google answers it - * with the pending final, generationComplete and ACTIVITY_END (+253 ms in - * #3710), and with nothing at all when no speech is pending; it never sent - * finished or turnComplete. So Done waits while a segment is open; waits a - * long quiet while the microphone heard voice past Google's last ACTIVITY_END, - * since an earlier segment's completion can arrive before the new speech is - * signalled; and otherwise ends after a short quiet (at audioStreamEnd) or - * at once (after Google's answer). The 3 s cap bounds every wait. + * with the pending final, generationComplete and an ACTIVITY_END at the + * stream end (+253 ms in #3710), and with nothing at all when no speech is + * pending; it never sent finished or turnComplete. So Done: + * - waits while a segment is open; + * - waits the tail window while the microphone heard voice past Google's + * last ACTIVITY_END, since an earlier segment's answer can arrive before + * the new speech is signalled (a window already running is not extended); + * - ends at once when Google's answer has an ACTIVITY_END reaching the + * stream end; + * - otherwise ends after the short quiet, restarted by each speech message, + * because voice too quiet for the RMS bar may still be signalled. + * The 3 s cap bounds every wait. */ private settleOrWait(answered: boolean): void { if (this.pending) this.disarmQuiet(); - else if (this.unplaced()) this.armQuiet(GEMINI_DRAIN_TAIL_MS); - else if (answered) this.finishDrain(); + else if (this.unplaced()) { if (this.quietMs !== GEMINI_DRAIN_TAIL_MS) this.armQuiet(GEMINI_DRAIN_TAIL_MS); } + else if (answered && this.covered()) this.finishDrain(); else this.armQuiet(GEMINI_DRAIN_QUIET_MS); } @@ -290,6 +304,7 @@ export class GeminiAsrClient implements AsrClient { private armQuiet(ms: number): void { this.disarmQuiet(); const round = this.quietRound; + this.quietMs = ms; this.quiet = setTimeout(() => { this.quiet = null; void this.inbound.then(() => { if (this.quietRound === round) this.finishDrain(); }); @@ -298,6 +313,7 @@ export class GeminiAsrClient implements AsrClient { private disarmQuiet(): void { this.quietRound++; + this.quietMs = 0; if (this.quiet) { clearTimeout(this.quiet); this.quiet = null; } } @@ -327,17 +343,19 @@ export class GeminiAsrClient implements AsrClient { const final = content?.inputTranscription; if (final?.text) this.opts.onEvent({ type: "final", text: final.text, endsTurn: final.finished ?? true }); const activity = message.voiceActivity; + const turnEnded = final?.finished === true || content?.turnComplete === true; if (interim || content?.speechState === "SPEECH") this.pending = true; - if (final?.text || content?.generationComplete === true) this.pending = false; + if (final?.text || content?.generationComplete === true || turnEnded) this.pending = false; if (activity?.type === "ACTIVITY_END") { const seconds = /^(\d{1,6}(?:\.\d{1,9})?)s$/.exec(activity.audioOffset ?? "")?.[1]; if (seconds !== undefined) this.heardTo = Math.max(this.heardTo, Math.ceil(Number(seconds) * GEMINI_SAMPLE_RATE)); } - if (this.phase === "draining") { - if (final?.finished === true || content?.turnComplete === true) this.finishDrain(); - // A setupComplete that just sent audioStreamEnd has already decided. - else if (endedBefore) this.settleOrWait(true); - } + // Only speech messages bear on Done; a setupComplete that just sent + // audioStreamEnd has already decided. finished and turnComplete close the + // segment like generationComplete, and nothing more. + const speech = interim || final !== undefined || content?.speechState !== undefined + || content?.generationComplete !== undefined || content?.turnComplete !== undefined || activity !== undefined; + if (this.phase === "draining" && endedBefore && speech) this.settleOrWait(true); // The session is about to end: what was heard is kept, the take ends. if (message.goAway) this.fail("Gemini session ending", "network"); } diff --git a/packages/ui-react/tests/asr-gemini.test.ts b/packages/ui-react/tests/asr-gemini.test.ts index 7733b36894..633510d67f 100644 --- a/packages/ui-react/tests/asr-gemini.test.ts +++ b/packages/ui-react/tests/asr-gemini.test.ts @@ -635,11 +635,123 @@ describe("GeminiAsrClient wire behaviour", () => { await draining; }); + test("an earlier segment's answer that ends short of the stream end waits the short quiet for quieter speech", async () => { + const h = harness({ rate: 16_000, timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + const first = GEMINI_FRAME_SAMPLES * 2; + h.speak(first); + s.server({ serverContent: { speechState: "SPEECH" } }); + await tick(); + h.speak(GEMINI_FRAME_SAMPLES * 6, 440, 0); + // Speech below the voice bar: the microphone cannot tell it from silence. + h.speak(GEMINI_FRAME_SAMPLES * 2, 440, 0.012); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + s.server({ serverContent: { inputTranscription: { text: "Ask Nestor." } } }); + s.server({ serverContent: { generationComplete: true } }); + s.server({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: offset(first + GEMINI_FRAME_SAMPLES * 4) } }); + await tick(); + expect(settled, "GEMINI_DRAIN_QUIET_AFTER_PARTIAL_ANSWER").toBe(false); + h.advance(75); + s.server({ serverContent: { speechState: "SPEECH" } }); + await tick(); + h.advance(GEMINI_DRAIN_QUIET_MS); + await tick(); + expect(settled, "the quieter speech is now an open segment").toBe(false); + s.server({ serverContent: { inputTranscription: { text: "Quietly." } } }); + s.server({ serverContent: { generationComplete: true } }); + s.server({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: offset(first + GEMINI_FRAME_SAMPLES * 8) } }); + await tick(); + expect(settled, "GEMINI_DRAIN_ENDS_ON_ACTIVITY_END").toBe(true); + await draining; + expect(h.events.map((event) => event.text)).toEqual(["Ask Nestor.", "Quietly."]); + }); + + test("a message that says nothing about speech does not end Done", async () => { + const h = harness({ timers: true }); + await h.client.start(); + await tick(); await tick(); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + h.socket().server({ serverContent: {} }); + await tick(); + expect(settled, "GEMINI_DRAIN_IGNORES_UNRELATED").toBe(false); + h.advance(GEMINI_DRAIN_QUIET_MS); + await tick(); + expect(settled).toBe(true); + await draining; + }); + + for (const [name, message] of [ + ["finished", { serverContent: { inputTranscription: { text: "Ask Nestor.", finished: true } } }], + ["turnComplete", { serverContent: { turnComplete: true } }], + ] as const) test(`an earlier segment's ${name} does not end Done before voice Google has not placed`, async () => { + const h = harness({ rate: 16_000, timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + h.speak(GEMINI_FRAME_SAMPLES * 2); + h.speak(GEMINI_FRAME_SAMPLES * 6, 440, 0); + h.speak(GEMINI_FRAME_SAMPLES * 2); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + s.server(message); + s.server({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: offset(GEMINI_FRAME_SAMPLES * 4) } }); + await tick(); + expect(settled, "GEMINI_DRAIN_FLAGGED_COMPLETION").toBe(false); + s.server({ serverContent: { speechState: "SPEECH" } }); + s.server({ serverContent: { inputTranscription: { text: "Then the ships." }, generationComplete: true } }); + s.server({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: offset(GEMINI_FRAME_SAMPLES * 10) } }); + await draining; + expect(h.events.at(-1)).toEqual({ type: "final", text: "Then the ships.", endsTurn: true }); + }); + + test("an ACTIVITY_END Google rounded down to 10 ms still reaches the stream end", async () => { + const h = harness({ rate: 16_000, timers: true }); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + const streamed = GEMINI_FRAME_SAMPLES * 3 + 37; + h.speak(streamed); + s.server({ serverContent: { speechState: "SPEECH" } }); + await tick(); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + s.server({ serverContent: { inputTranscription: { text: "Ithaca." }, generationComplete: true } }); + s.server({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: `${(Math.floor(streamed / 160) / 100).toFixed(2)}s` } }); + await tick(); + expect(settled, "GEMINI_DRAIN_OFFSET_ROUNDING").toBe(true); + await draining; + }); + + test("speech messages do not extend a running tail window", async () => { + const h = harness({ rate: 16_000, timers: true }); + await h.client.start(); + await tick(); await tick(); + h.speak(GEMINI_FRAME_SAMPLES * 2); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); await tick(); + h.advance(GEMINI_DRAIN_TAIL_MS - 500); + h.socket().server({ serverContent: { speechState: "NON_SPEECH" } }); + await tick(); + h.advance(500); + await tick(); + expect(settled, "GEMINI_DRAIN_TAIL_NOT_EXTENDED").toBe(true); + await draining; + }); + test("voice Google never calls speech ends Done at the tail window, not the 3 s cap", async () => { const h = harness({ rate: 16_000, timers: true }); await h.client.start(); await tick(); await tick(); - h.speak(GEMINI_FRAME_SAMPLES); + h.speak(GEMINI_FRAME_SAMPLES * 2); let settled = false; const draining = h.client.drainAndStop().then(() => { settled = true; }); await tick(); await tick(); diff --git a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx index ee4834f81b..db9a7c3b2d 100644 --- a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx +++ b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx @@ -212,11 +212,12 @@ for (const rate of [44_100, 48_000]) { await expect.poll(() => json(speech).some((frame) => frame.realtimeInput?.audioStreamEnd === true), { message: "Done ends the input stream" }).toBe(true); expect(audio.streams[0]!.getTracks().map((track) => track.readyState), "Done closes the microphone first").toEqual(["ended"]); expect(s.ui.stores.voice.getState().mode, "Done waits for the last final").toBe("dictate"); - // The tone never stops, so Google's ACTIVITY_END places the whole stream. + // The tone never stops, so Google's ACTIVITY_END places the whole stream, + // in the 10 ms steps Google reports. const streamed = audioFrames(speech).reduce((samples, frame) => samples + atob(frame.data).length / 2, 0); speech.deliver({ serverContent: { inputTranscription: { text: "And the harbor." } } }); speech.deliver({ serverContent: { generationComplete: true } }); - speech.deliver({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: `${(streamed / 16_000).toFixed(3)}s` } }); + speech.deliver({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: `${(Math.floor(streamed / 160) / 100).toFixed(2)}s` } }); // Well inside the 1.5 s tail window and the 3 s cap: Google's answer ended it. await expect.poll(() => s.ui.stores.voice.getState().mode, { message: "GEMINI_BROWSER_DRAIN_ON_ANSWER", timeout: 1_000 }).toBe("idle"); expect(s.ui.stores.voice.getState().reviewText, "each final commits exactly once").toBe("Ask Nestor about the ships. And the harbor."); @@ -309,7 +310,8 @@ test("Done keeps the worklet's partial block: every captured sample reaches Goog expect(received.length, "GEMINI_BROWSER_DONE_KEEPS_TAIL sample count").toBe(expected.length); expect([...received], "GEMINI_BROWSER_DONE_KEEPS_TAIL samples").toEqual(expected); expect(audio.streams[0]!.getTracks().map((track) => track.readyState), "the microphone closes once the tail is in").toEqual(["ended"]); - speech.deliver({ serverContent: { turnComplete: true } }); + speech.deliver({ serverContent: { generationComplete: true } }); + speech.deliver({ serverContent: { speechState: "NON_SPEECH" }, voiceActivity: { type: "ACTIVITY_END", audioOffset: `${(Math.floor(received.length / 160) / 100).toFixed(2)}s` } }); await expect.poll(() => s.ui.stores.voice.getState().mode, { message: "the drain ended the dictation" }).toBe("idle"); });