From 391c5f373121c96fbde44609b3e1376994b56f7e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 12:55:02 +0100 Subject: [PATCH 1/9] CONTRACT: feat(ui-server): register selectable dictation providers (WIP) Co-Authored-By: Claude Opus 5.5 --- .changeset/selectable-dictation.md | 11 + api-report/ui-react.txt | 10 +- api-report/ui-sdk.txt | 45 ++++ api-report/ui-server.txt | 2 + docs/extending/speech.md | 27 +- docs/http-api-coverage.md | 3 + docs/http-api.md | 52 +++- docs/integration-contract/http.md | 15 ++ docs/integration-contract/package-api.md | 27 +- packages/ui-react/src/lib/api-client.ts | 13 +- packages/ui-react/src/lib/recordings.ts | 2 +- packages/ui-react/tests/api-client.test.ts | 15 ++ packages/ui-sdk/src/protocol.ts | 27 ++ packages/ui-sdk/src/server/speech.ts | 4 +- packages/ui-server/README.md | 4 +- packages/ui-server/src/app.ts | 10 +- packages/ui-server/src/config/env.ts | 4 +- packages/ui-server/src/db/settings-writes.ts | 2 + packages/ui-server/src/db/settings.ts | 24 ++ .../ui-server/src/routes/transcriptions.ts | 15 +- packages/ui-server/src/routes/voice.ts | 67 ++++- .../ui-server/src/voice/speech-providers.ts | 118 ++++++--- .../src/voice/transcription-store.ts | 1 + .../tests/drafts-settings-offloop.test.ts | 3 +- .../ui-server/tests/external-speech.test.ts | 20 +- .../tests/helpers/http-contract-app.ts | 4 + .../tests/helpers/http-mount-lifetimes.ts | 3 + .../tests/http-discovery-voice.test.ts | 2 +- .../tests/http-supported-mounts.test.ts | 3 + .../tests/saved-transcription.test.ts | 4 +- .../tests/selectable-dictation.test.ts | 248 ++++++++++++++++++ 31 files changed, 697 insertions(+), 88 deletions(-) create mode 100644 .changeset/selectable-dictation.md create mode 100644 packages/ui-server/tests/selectable-dictation.test.ts diff --git a/.changeset/selectable-dictation.md b/.changeset/selectable-dictation.md new file mode 100644 index 0000000000..eb1fda9e82 --- /dev/null +++ b/.changeset/selectable-dictation.md @@ -0,0 +1,11 @@ +--- +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-react": minor +--- + +Register multiple dictation providers, discover their destinations and capabilities, +and persist an owner-controlled default with revision checks. Bind session minting +and saved-audio uploads to the explicitly disclosed provider, and reject retries +that change a receipt's provider. Preserve bodyless clients and legacy by-value +registration while exposing additive protocol types and client helpers. diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index 0e6079c480..e01ed418f9 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -1107,6 +1107,7 @@ signatures (every public export and the types it is made of) success: boolean; }>; checkWorkerHost: () => Promise; + dictationSettings: () => Promise; fileResolve: (path: string) => Promise<{ ancestors: string[]; exists: boolean; @@ -1228,6 +1229,7 @@ signatures (every public export and the types it is made of) timeZone: null | string; }>; refreshModels: () => Promise; + saveDictationSettings: (settings: DictationSettings) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; @@ -1333,7 +1335,8 @@ signatures (every public export and the types it is made of) voiceOverrides: (signal?: AbortSignal) => Promise<{ overrides: PronunciationOverride[]; }>; - voiceSession: (signal?: AbortSignal) => Promise; + voiceProviders: () => Promise; + voiceSession: (signal?: AbortSignal, selection?: VoiceSessionRequest) => Promise; voiceToken: () => Promise; vpnCheck: () => Promise<{ vpn: boolean; @@ -1601,6 +1604,7 @@ signatures (every public export and the types it is made of) success: boolean; }>; checkWorkerHost: () => Promise; + dictationSettings: () => Promise; fileResolve: (path: string) => Promise<{ ancestors: string[]; exists: boolean; @@ -1722,6 +1726,7 @@ signatures (every public export and the types it is made of) timeZone: null | string; }>; refreshModels: () => Promise; + saveDictationSettings: (settings: import("@schlessera/brain-ui-sdk").DictationSettings) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; @@ -1827,7 +1832,8 @@ signatures (every public export and the types it is made of) voiceOverrides: (signal?: AbortSignal) => Promise<{ overrides: import("@schlessera/brain-ui-sdk").PronunciationOverride[]; }>; - voiceSession: (signal?: AbortSignal) => Promise; + voiceProviders: () => Promise; + voiceSession: (signal?: AbortSignal, selection?: import("@schlessera/brain-ui-sdk").VoiceSessionRequest) => Promise; voiceToken: () => Promise; vpnCheck: () => Promise<{ vpn: boolean; diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 4815058a91..994f391eb5 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -168,6 +168,7 @@ export "." (./src/index.ts) type DialogueEvidence type DialoguePage type DialogueRecord + type DictationSettings type Draft type DraftAttachment type DraftAttachmentResponse @@ -468,6 +469,8 @@ export "." (./src/index.ts) type VoiceCapabilitiesResponse type VoiceKeytermsResponse type VoiceMode + type VoiceProvidersResponse + type VoiceSessionRequest type VoiceSessionResponse type VoiceTokenResponse type WikilinkMapResponse @@ -742,6 +745,7 @@ export "./client" (./src/client/index.ts) type DialogueEvidence type DialoguePage type DialogueRecord + type DictationSettings type Draft type DraftAttachment type DraftAttachmentResponse @@ -1133,6 +1137,8 @@ export "./client" (./src/client/index.ts) type VoiceCapabilitiesResponse type VoiceKeytermsResponse type VoiceMode + type VoiceProvidersResponse + type VoiceSessionRequest type VoiceSessionResponse type VoiceTokenResponse type WebSocketClose @@ -1602,6 +1608,7 @@ export "./protocol" (./src/protocol.ts) type DialogueEvidence type DialoguePage type DialogueRecord + type DictationSettings type Draft type DraftAttachment type DraftAttachmentResponse @@ -1896,6 +1903,8 @@ export "./protocol" (./src/protocol.ts) type VoiceCapabilitiesResponse type VoiceKeytermsResponse type VoiceMode + type VoiceProvidersResponse + type VoiceSessionRequest type VoiceSessionResponse type VoiceTokenResponse type WikilinkMapResponse @@ -2408,6 +2417,7 @@ export "./server" (./src/server/index.ts) type DialogueEvidence type DialoguePage type DialogueRecord + type DictationSettings type Draft type DraftAttachment type DraftAttachmentResponse @@ -2845,6 +2855,8 @@ export "./server" (./src/server/index.ts) type VoiceCapabilitiesResponse type VoiceKeytermsResponse type VoiceMode + type VoiceProvidersResponse + type VoiceSessionRequest type VoiceSessionResponse type VoiceTokenResponse type WebSearchBrief @@ -7297,6 +7309,12 @@ signatures (every public export and the types it is made of) identity: string; evidence: DialogueEvidence; } + DictationSettings (packages/ui-sdk/src/protocol.ts) + export interface DictationSettings { + defaultProvider: string | null; + smart: boolean; + revision: string; + } Draft (packages/ui-sdk/src/protocol.ts) export interface Draft { draftId: string; @@ -11391,13 +11409,17 @@ signatures (every public export and the types it is made of) keyterms: boolean; endpointing: boolean; savedAudio?: boolean; + smartTranscription?: boolean; } SpeechProvider (packages/ui-sdk/src/server/speech.ts) export interface SpeechProvider { id: string; + label?: string; + destination?: string; capabilities: SpeechCapabilities; createSession(opts: { keyterms: string[]; + mode?: "smart" | "verbatim"; }): Promise; transcribeRecording?(input: { audio: Uint8Array; @@ -12444,6 +12466,29 @@ signatures (every public export and the types it is made of) } VoiceMode (packages/ui-sdk/src/protocol.ts) export type VoiceMode = "idle" | "dictate" | "conversation"; + VoiceProvidersResponse (packages/ui-sdk/src/protocol.ts) + export interface VoiceProvidersResponse { + providers: Array<{ + id: string; + label: string; + destination?: string; + capabilities: SpeechCapabilities; + }>; + dictation: { + saved: string | null; + savedUsable: boolean; + host: string | null; + effective: string | null; + source: "saved" | "host" | "only" | "none" | "unavailable"; + smart: boolean; + revision: string; + }; + } + VoiceSessionRequest (packages/ui-sdk/src/protocol.ts) + export interface VoiceSessionRequest { + providerId?: string; + smart?: boolean; + } VoiceSessionResponse (packages/ui-sdk/src/protocol.ts) export interface VoiceSessionResponse { providerId: string; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 1d59be16b5..b10d44d741 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -511,6 +511,8 @@ signatures (every public export and the types it is made of) dbPath?: string; renderer?: AppRenderer; speechProvider?: SpeechProvider; + speechProviders?: SpeechProvider[]; + defaultSpeechProviderId?: string; conversationProvider?: LiveConversationProvider; labeller?: LabellerOptions; turnTimeoutMs?: number; diff --git a/docs/extending/speech.md b/docs/extending/speech.md index f2cf310530..fb7c08ccb8 100644 --- a/docs/extending/speech.md +++ b/docs/extending/speech.md @@ -40,10 +40,29 @@ A supplied value takes precedence over automatic Deepgram key detection. If `config.voice.provider` is set (including by `VOICE_PROVIDER`), it must equal the supplied id. Ids are nonempty, trimmed and lowercase. Without a value, `deepgram`/`webspeech` keep their existing selection rules; absent credentials -never select browser speech. A mismatch or provider failure returns 500 -`{ error }` from the existing protected `POST /api/voice/session`, without -trying another service. Validation occurs on that request, before calling an -invalid provider or publishing an invalid session. +never select browser speech. A mismatch or invalid registration fails construction. Session validation and +legacy provider failures return 500 `{ error }` from the protected +`POST /api/voice/session`, without trying another service. + +To offer several services, pass `createApp({ speechProviders: [first, second], +defaultSpeechProviderId: first.id })`. The list adds to configured built-ins; +duplicate ids (including built-in collisions), supplying both registration options, +and unregistered host defaults fail construction. Browser speech remains opt-in. +The legacy single value replaces built-ins. A saved dictation choice overrides +the host default; a removed saved choice blocks dictation until explicitly changed. +Registration snapshots metadata, capabilities and bound methods; changing a supplied +object afterward does not alter the registered set or running operations. + +Optional `label` and `destination` describe the service to users. Keep credentials +out of both. Declare `smartTranscription: true` only if `createSession` honors +`mode: "smart" | "verbatim"`; the server passes mode only for that capability. +The saved switch starts true. Existing implementations need no new fields. +Use `voiceProviders()` for discovery (no mint), then send the disclosed id in +`voiceSession(signal, { providerId, smart })`. Saved recordings send +`Speech-Provider` with the confirmed id; a retry must retain the receipt's provider. +See the [HTTP specification](../http-api.md#selectable-dictation-providers) for +settings revisions, exact selection errors and the no-fallback rule. Gemini's +built-in factory is implemented separately in #3708; no placeholder is registered. The four streaming capabilities are boolean. Optional `savedAudio` is derived from a callable `transcribeRecording`; a contradictory explicit declaration is rejected. `streaming` describes streaming recognition, `interimResults` controls partial display, `keyterms` controls domain-term diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index 25b1fed554..d88a21b646 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -142,6 +142,9 @@ row's real mounting check. They do not establish mounting by themselves. | `POST /api/status/worker-host` | `mounted supported handler: POST /api/status/worker-host` | T | | `GET /api/voice/keyterms` | `mounted supported handler: GET /api/voice/keyterms` | N | | `GET /api/voice/overrides` | `mounted supported handler: GET /api/voice/overrides` | N | +| `GET /api/voice/providers` | `mounted supported handler: GET /api/voice/providers` | R | +| `GET /api/voice/dictation/settings` | `mounted supported handler: GET /api/voice/dictation/settings` | R | +| `PUT /api/voice/dictation/settings` | `mounted supported handler: PUT /api/voice/dictation/settings` | R | | `GET /api/voice/capabilities` | `mounted supported handler: GET /api/voice/capabilities` | R | | `GET /api/voice/recordings/:recordingId/transcription` | `mounted supported handler: GET /api/voice/recordings/:recordingId/transcription` | R | | `PUT /api/voice/recordings/:recordingId/transcription` | `mounted supported handler: PUT /api/voice/recordings/:recordingId/transcription` | R | diff --git a/docs/http-api.md b/docs/http-api.md index fdac577570..c7d129231c 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -184,6 +184,9 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/tracks` | I | Resolve canonical imported-track evidence | Paired React track-block/export transport; no independent retrieval API selected. | | GET | `/api/tool-permissions` | I | List remembered always-allow grants | React approval settings; paired administrative transport. Permission behavior remains governed by its own contract. | | DELETE | `/api/tool-permissions/:tool` | I | Revoke one remembered grant | React approval settings; paired administrative transport. Permission behavior remains governed by its own contract. | +| GET | `/api/voice/providers` | S | Read registered dictation providers and effective selection; never mint | Authenticated discovery, no-store. | +| GET | `/api/voice/dictation/settings` | S | Read brain-wide dictation choice, SMART mode and revision | Independent of live conversation settings. | +| PUT | `/api/voice/dictation/settings` | S | Save dictation choice with If-Match revision | Human owner/ambient only; stale writes never overwrite. | | GET | `/api/voice/capabilities` | S | Read active-provider capabilities without minting a credential | Saved-audio discovery and independent clients; additive #1021 contract. | | GET | `/api/voice/recordings/:recordingId/transcription` | S | Read an account-owned durable transcription receipt | Saved-audio status recovery; never dispatches a provider. | | PUT | `/api/voice/recordings/:recordingId/transcription` | S | Explicitly upload or retry saved audio | Account ownership, verified hash, bounded body and durable claim protect idempotency. | @@ -845,7 +848,7 @@ SDK speech-session payloads rather than exposing long-lived provider keys: | Supported operation | Inputs/defaults | Success | Errors and behavior | | --- | --- | --- | --- | -| POST `/api/voice/session` | No inputs; configured active speech provider, including `createApp({ speechProvider })` | `VoiceSessionResponse`: providerId, connection url, optional token/params, expiresAt and capabilities (streaming, interimResults, keyterms, endpointing, derived savedAudio) | 500 `{ error }` for unavailable provider/minting, invalid provider/session, or explicit provider/value mismatch; no fallback. Keyterms are included only when supported by the provider; browser/local sessions can omit token and use empty URL/zero expiry. | +| POST `/api/voice/session` | Optional JSON `VoiceSessionRequest` `{ providerId?, smart? }`; absent body uses the effective provider | `VoiceSessionResponse`: providerId, connection url, optional token/params, expiresAt and capabilities (streaming, interimResults, keyterms, endpointing, derived savedAudio) | An explicit unregistered provider gives 409 `speech_provider_unavailable` before minting; malformed/non-object JSON or wrong field types give 400 `voice_session_invalid`. No effective provider or mint/session validation failure gives 500 `{ error }`; no fallback. Keyterms are included only when supported by the provider; browser/local sessions can omit token and use empty URL/zero expiry. | | POST `/api/voice/token` | No inputs | `{ token, expiresAt }` | Deprecated Deepgram-specific alias retained for client migration; mints directly with 60-second requested TTL, 500 `{ error }` on failure. | | GET `/api/voice/keyterms` | `rebuild=1` forces cache rebuild; all other values read normal cache | `{ keyterms: string[], generatedAt, count }` | 500 `{ error }` on read/build failure, including a missing, corrupt, locked or unreadable index. Without a usable optional `@schlessera/brain` peer, or with an index version core cannot read, 200 with an empty vocabulary that is never cached ([optional core peer](integration-contract/package-api.md#ui-server-optional-core-peer-breaking-host-migration-697)). | | GET `/api/voice/overrides` | No inputs | `{ overrides: [{ match, replacement }] }` | Configured pronunciation replacements; 500 `{ error }` on cache read/build failure. | @@ -1357,6 +1360,44 @@ authority and disclosure rules are security properties and are pinned by records whose file it can currently read. Only the owner's rows and details carry `markedBy: { label, you }`; other principals' responses omit the field. +## Selectable dictation providers + +`GET /api/voice/providers` returns `VoiceProvidersResponse`: `providers[]` +contains `{ id, label, destination?, capabilities }`; `dictation` contains +`{ saved, savedUsable, host, effective, source, smart, revision }`. Ids absent +from selection are `null`, `savedUsable` is false when nothing is saved, and +`source` is `saved | host | only | none | unavailable`. Discovery is authenticated, +`no-store`, and never mints credentials or probes providers. Labels default to +ids; saved-audio support comes from the optional provider method. + +The registered set is fixed at construction. The saved choice wins if registered; +if removed, it blocks dictation without fallback. With no saved choice, use the +host default, otherwise the sole registered provider, otherwise none. Multiple +providers without a default require a deliberate choice. `/voice/capabilities` +keeps its response shape and reports this effective provider. + +`GET /api/voice/dictation/settings` returns `DictationSettings` +`{ defaultProvider: string | null, smart: boolean, revision: string }` and a quoted +revision `ETag`. Defaults are `{ defaultProvider: null, smart: true, revision: "0" }`. +Corrupt/invalid operational KV `voice.dictation` rows use those defaults; storage +uses a numeric revision. `PUT` accepts `{ defaultProvider, smart? }` (`smart` +defaults true); `null` clears the saved choice. Send `If-Match: ""` +(the unquoted revision is also accepted). Only human `owner`/`ambient` principals +may write; others receive 403 `{ error: "owner_required" }`. Unknown providers +return 400 `speech_provider_unknown`, invalid bodies 400 `dictation_settings_invalid`, +missing If-Match 428 `dictation_settings_stale`, and stale writes 409 +`dictation_settings_stale` with `current`. A successful write returns 200 with the +new settings/revision and ETag. Reads and writes are `no-store`; neither mints a +session, changes a running take, nor touches conversation settings or history. + +`POST /api/voice/session` resolves a supplied `providerId` exactly, before minting, +regardless of current defaults. It snapshots identity/capabilities for the response. +`smart` overrides the saved mode for this request; only a provider declaring +`smartTranscription` receives `mode: "smart" | "verbatim"`. Omitted mode uses the +saved switch (initially true). A failed exact mint returns generic 500 +`{ error: "Voice session failed" }` without provider diagnostics or credentials. +Bodyless legacy requests retain their previous response/error shape. + ## Saved-audio transcription The protected `GET /api/voice/capabilities` returns `VoiceCapabilitiesResponse` @@ -1390,7 +1431,14 @@ specifies the receipt fields, errors, retry decision and permanent retention. `PUT` responds 200 with the stored receipt, including provider failures; a failed plain replay gives 409. `?retry=` is the only retry request, with at most three user retries and no automatic provider calls. -Unsupported providers return 501 `saved_audio_unsupported`. +`Speech-Provider: ` binds upload admission to exactly the disclosed provider, +before reading the audio and before claiming a receipt. An unknown id returns +409 `speech_provider_unavailable`; a streaming-only provider returns 501 +`saved_audio_unsupported`. Neither claims or dispatches. Without this header, +legacy uploads resolve the effective provider at request admission. A retry +naming a different provider returns 409 `transcription_provider_mismatch` with +its original receipt and never dispatches. Plain repeats, tombstones, unknown +outcomes and the retry ceiling retain their existing semantics. `DELETE ?disposition=accepted|discarded` returns 200 with a `consumed` receipt; an invalid disposition gives 400. It removes text, retains the immutable id and hash, and inserts a hashless tombstone if no upload has claimed yet. diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index d8a097c00d..6f8a293b40 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -1050,3 +1050,18 @@ expiry are rechecked at delivery after settlement. `snapshotComplete` and detector completeness are separate; neither omitted details nor a review receipt replace the aggregate. Route absence and refused reads are explicitly unavailable. Existing history visibility and mutation authority remain intact. + + +### Selectable dictation providers (additive, #3707) + +The [dictation routes](../http-api.md#selectable-dictation-providers) add +read-only `/api/voice/providers` discovery and revisioned +`/api/voice/dictation/settings` GET/PUT. The registered set is fixed; a removed +saved choice blocks dictation. Only human owners/ambient accounts write settings. +`POST /api/voice/session` accepts optional `{ providerId, smart }`; an explicit +id is exact or 409 `speech_provider_unavailable`, never a fallback. Bodyless +clients and `/voice/capabilities` retain their shapes. Discovery never mints. +Saved-audio PUT binds `Speech-Provider` before claim/body consumption; absent +headers preserve effective-provider resolution. Retry provider changes return +409 `transcription_provider_mismatch` with the receipt. Settings revisions, +error codes, response schemas and operation binding are supported HTTP promises. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index fa42f0ecdd..2a9db44a0f 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1502,10 +1502,33 @@ the supplied implementation. It validates a nonempty trimmed lowercase id, four boolean capabilities and callable `createSession` before invoking it. The returned `SpeechSession` has a string URL, finite nonnegative expiry, optional string token and optional string-record params. Empty URL/zero expiry -remain supported for browser/local sessions. Validation, mismatch and provider -failures return the existing 500 `{ error }` envelope without fallback. +remain supported for browser/local sessions. Invalid registrations and host-default mismatches fail construction. Session +validation and legacy provider failures retain the 500 `{ error }` envelope without fallback. The deprecated token route remains Deepgram-specific. +`CreateAppOptions.speechProviders?: SpeechProvider[]` adds implementations to +configured built-ins. Supplying it together with legacy `speechProvider`, duplicate +ids, invalid implementations or an unregistered host default fails construction. +Legacy `speechProvider` replaces all built-ins and must match `VOICE_PROVIDER`. +`defaultSpeechProviderId?: string` sets the host default ahead of `VOICE_PROVIDER`, +then registered Deepgram; a legacy supplied value is its own default. Deepgram +registers when its key is configured; browser speech registers only through +`VOICE_PROVIDER=webspeech`. The Gemini built-in registration point is reserved for +#3708's factory; this change does not advertise a placeholder Gemini implementation. +A saved brain-wide choice overrides the host default. Removed saved choices block +selection; with neither saved nor host choice only a sole provider is selected. + +`SpeechProvider` adds optional `label?: string`, `destination?: string` and +`createSession` option `mode?: "smart" | "verbatim"`; `SpeechCapabilities` adds +`smartTranscription?: boolean`. Mode is passed only to providers declaring it. +Identity, capabilities, metadata and executor references are fixed at registration. +`VoiceProvidersResponse`, `DictationSettings`, `VoiceSessionRequest` are exported +protocol types for the [HTTP shapes](../http-api.md#selectable-dictation-providers). +`createBrainApi` adds `voiceProviders()`, `dictationSettings()` and +`saveDictationSettings(settings: DictationSettings)` (sends the revision as +If-Match). `voiceSession(signal?, selection?: VoiceSessionRequest)` sends no body +when selection is omitted. Explicit selection never substitutes another provider. + The route builds keyterms only when supported, snapshots provider identity and capabilities, and publishes `VoiceSessionResponse` with connection material. The client's matching `AsrClientFactory` receives that whole session through diff --git a/packages/ui-react/src/lib/api-client.ts b/packages/ui-react/src/lib/api-client.ts index d5392ab175..109c0268f5 100644 --- a/packages/ui-react/src/lib/api-client.ts +++ b/packages/ui-react/src/lib/api-client.ts @@ -16,6 +16,9 @@ import type { VoiceKeytermsResponse, VoiceTokenResponse, VoiceSessionResponse, + VoiceSessionRequest, + VoiceProvidersResponse, + DictationSettings, PronunciationOverride, ProviderInfo, UnavailableProfileInfo, @@ -505,8 +508,14 @@ export function createBrainApi( ), /** Mint a dictation session for the active speech provider. */ - voiceSession: (signal?: AbortSignal) => - fetchJson("/voice/session", { method: "POST", signal }), + voiceSession: (signal?: AbortSignal, selection?: VoiceSessionRequest) => + fetchJson("/voice/session", { method: "POST", signal, ...(selection !== undefined ? { body: JSON.stringify(selection) } : {}) }), + + voiceProviders: () => fetchJson("/voice/providers"), + dictationSettings: () => fetchJson("/voice/dictation/settings"), + saveDictationSettings: (settings: DictationSettings) => + fetchJson("/voice/dictation/settings", { method: "PUT", headers: { "If-Match": `"${settings.revision}"` }, + body: JSON.stringify({ defaultProvider: settings.defaultProvider, smart: settings.smart }) }), /** @deprecated use voiceSession(); kept during client transition. */ voiceToken: () => diff --git a/packages/ui-react/src/lib/recordings.ts b/packages/ui-react/src/lib/recordings.ts index ad7f77aeca..1606b40f70 100644 --- a/packages/ui-react/src/lib/recordings.ts +++ b/packages/ui-react/src/lib/recordings.ts @@ -784,7 +784,7 @@ export function createRecordingStore(options: RecordingStoreOptions): RecordingS if (response.ok) await applyReceipt(partition, id, result); else if (result.receipt) await applyReceipt(partition, id, result.receipt); else { - const preclaim: Record = { recording_id_invalid: 400, recording_hash_invalid: 400, recording_empty: 400, recording_too_large: 413, recording_media_unsupported: 415, saved_audio_unsupported: 501, transcription_not_found: 404, transcription_retry_stale: 409 }; + const preclaim: Record = { recording_id_invalid: 400, recording_hash_invalid: 400, recording_empty: 400, recording_too_large: 413, recording_media_unsupported: 415, saved_audio_unsupported: 501, speech_provider_unavailable: 409, transcription_not_found: 404, transcription_retry_stale: 409 }; if (preclaim[result.error] === response.status) definitiveRejection = typeof result.message === "string" ? result.message : "The recording was rejected before transcription. The recording is kept."; throw new Error(result.message ?? "Could not transcribe. The recording is kept."); } diff --git a/packages/ui-react/tests/api-client.test.ts b/packages/ui-react/tests/api-client.test.ts index 8ec33c5cb7..7a549670d1 100644 --- a/packages/ui-react/tests/api-client.test.ts +++ b/packages/ui-react/tests/api-client.test.ts @@ -241,3 +241,18 @@ test("retained session listing opts in and encodes its exclusive cursor without expect(cap.urls).toEqual(["/api/sessions?includeRetainedConversations=true&retainedAfter=ithaca%20%2F%3F%26"]); expect(response).toEqual(fixture); }); + + +test("dictation selection client preserves legacy requests and sends exact provider and revision", async () => { + const cap = captureUrl({}); + const signal = new AbortController().signal; + await api.voiceSession(signal); + expect(cap.inits[0]?.body).toBeUndefined(); expect(cap.inits[0]?.signal).toBe(signal); + await api.voiceSession(signal, { providerId: "beta", smart: false }); + expect(JSON.parse(String(cap.inits[1]?.body))).toEqual({ providerId: "beta", smart: false }); + await api.voiceProviders(); await api.dictationSettings(); + await api.saveDictationSettings({ defaultProvider: "alpha", smart: true, revision: "4" }); + expect(cap.urls).toEqual(["/api/voice/session", "/api/voice/session", "/api/voice/providers", "/api/voice/dictation/settings", "/api/voice/dictation/settings"]); + expect(new Headers(cap.inits[4]?.headers).get("If-Match")).toBe('"4"'); + expect(JSON.parse(String(cap.inits[4]?.body))).toEqual({ defaultProvider: "alpha", smart: true }); +}); diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index b274e74714..77ed4e4e15 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -1990,6 +1990,31 @@ export interface TranscriptionErrorResponse { receipt?: RecordingTranscription; } +/** An explicit provider is exact; omitted selection retains legacy resolution. */ +export interface VoiceSessionRequest { + providerId?: string; + smart?: boolean; +} + +export interface DictationSettings { + defaultProvider: string | null; + smart: boolean; + revision: string; +} + +export interface VoiceProvidersResponse { + providers: Array<{ id: string; label: string; destination?: string; capabilities: SpeechCapabilities }>; + dictation: { + saved: string | null; + savedUsable: boolean; + host: string | null; + effective: string | null; + source: "saved" | "host" | "only" | "none" | "unavailable"; + smart: boolean; + revision: string; + }; +} + export interface SpeechCapabilities { streaming: boolean; interimResults: boolean; @@ -1997,6 +2022,8 @@ export interface SpeechCapabilities { endpointing: boolean; /** Absent/false means saved recordings cannot be transcribed. Derived from the optional server method. */ savedAudio?: boolean; + /** Supports SMART cleanup of the current unsent dictation. */ + smartTranscription?: boolean; } /** @deprecated superseded by VoiceSessionResponse; kept for client migration. */ diff --git a/packages/ui-sdk/src/server/speech.ts b/packages/ui-sdk/src/server/speech.ts index 54b23fe5d8..72ba876cf4 100644 --- a/packages/ui-sdk/src/server/speech.ts +++ b/packages/ui-sdk/src/server/speech.ts @@ -25,13 +25,15 @@ export interface SpeechSession { */ export interface SpeechProvider { id: string; + label?: string; + destination?: string; capabilities: SpeechCapabilities; /** * Mint one dictation session. `keyterms` are domain terms from the brain's * keyterm builder — providers without keyterm support ignore them * (capabilities.keyterms = false). */ - createSession(opts: { keyterms: string[] }): Promise; + createSession(opts: { keyterms: string[]; mode?: "smart" | "verbatim" }): Promise; /** Optional saved-audio path. Call only the provider from the server with its * server-held credential; forward bytes unchanged. Reject on failure. No * automatic retries. Untyped errors are terminal unknown outcomes. */ diff --git a/packages/ui-server/README.md b/packages/ui-server/README.md index bf9203fa97..d8ce5680cd 100644 --- a/packages/ui-server/README.md +++ b/packages/ui-server/README.md @@ -414,7 +414,7 @@ under the [service terms](../geo/README.md#configuration). | `COASTLINE_CACHE_DIR` | Directory holding fetched map geometry. Cached forever; coastlines do not move. | $BRAIN_PATH/.brain-ui/geo | | `COOKIE_SECRET` | Secret signing the session cookie. | **required** — AUTH_MODE=password | | `DB_PATH` | SQLite file for the UI's own database (sessions, passkeys, settings). The turn journal keeps its own database beside it, DB_PATH.journal.db, with the same permissions. Must resolve outside the brain; an in-brain operational-state layout refuses boot with migration guidance. The server factory defaults to ./brain-ui.db; brain-ui-cron defaults to the container path /data/db/brain-ui.db. | ./brain-ui.db (server); /data/db/brain-ui.db (brain-ui-cron) | -| `DEEPGRAM_API_KEY` | Deepgram API key for streaming ASR (short-lived tokens are minted from it). | **required** — VOICE_PROVIDER=deepgram (or any voice use without VOICE_PROVIDER=webspeech) | +| `DEEPGRAM_API_KEY` | Deepgram API key for streaming ASR (short-lived tokens are minted from it). | **required** — When registering built-in Deepgram dictation | | `GITHUB_TOKEN` | Generic GitHub token fallback. Used for skill installs when BRAIN_UI_SKILLS_GITHUB_TOKEN is unset; the host sync mirror transport falls back to it when BRAIN_UI_SYNC_GITHUB_TOKEN is unset. These GitHub tokens never reach brain maintenance workers. | — | | `HOME` | Fallback anchor for the BRAIN_PATH default and the pi config dir (~/.pi). | /root | | `HOST` | Bind host; consulted by the auth validation to decide whether AUTH_MODE=none is loopback-safe. | (empty) | @@ -431,7 +431,7 @@ under the [service terms](../geo/README.md#configuration). | `TYPESAFE_API_KEY` | TypeSafe AI key for the classification pass that draws markdown the model typed as kit blocks (D42). Absent = pass disabled; the answer renders as markdown either way. | — | | `VOICE_CACHE_DIR` | Directory holding the keyterm cache JSON. | $BRAIN_PATH/.brain-ui | | `VOICE_KEYTERM_LIMIT` | Maximum custom-vocabulary terms built from the brain database. | 500 | -| `VOICE_PROVIDER` | Speech provider: "deepgram", "webspeech" (opt-in only — Chromium streams audio to Google), or the id supplied through createApp({ speechProvider }). An explicit name must match a supplied value. Unset prefers that value, otherwise auto-detects deepgram when its key is present. | (auto-detect) | +| `VOICE_PROVIDER` | Host default dictation provider: "deepgram", "webspeech" (explicit opt-in; Chromium streams audio to Google), or a registered by-value id. createApp({ defaultSpeechProviderId }) takes precedence. A legacy speechProvider replaces built-ins and must match this name. Unset prefers that value, otherwise registered deepgram. A saved dictation choice overrides the host default; an unavailable saved choice never falls back. | (auto-detect) | | `WEBAUTHN_ORIGINS` | Comma-separated extra origins allowed for WebAuthn ceremonies. | (empty) | | `WEBAUTHN_RP_ID` | Relying-party id override for proxies that rewrite Host. | (derived from the request origin) | | `WEBAUTHN_RP_NAME` | Relying-party display name shown by authenticators. | Brain UI | diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 12c3f5a92d..5668a65534 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -72,6 +72,7 @@ import { createGovernanceRoutes } from "./routes/governance.js"; import { createTranscriptionRoutes } from "./routes/transcriptions.js"; import { createTranscriptionWrites } from "./voice/transcription-writes.js"; import { createSettingsWrites } from "./db/settings-writes.js"; +import { createSpeechProviderRegistry } from "./voice/speech-providers.js"; import { createVoiceRoutes } from "./routes/voice.js"; import { createFilesRoutes, HTML_PREVIEW_CSP, HTML_PREVIEW_PATH } from "./routes/files.js"; import { createInboxIntake } from "./inbox/intake.js"; @@ -238,6 +239,10 @@ export interface CreateAppOptions { * @experimental Part of the SpeechProvider seam until 1.0. */ speechProvider?: SpeechProvider; + /** Additional by-value dictation providers, fixed at construction. */ + speechProviders?: SpeechProvider[]; + /** Must name a registered dictation provider. */ + defaultSpeechProviderId?: string; /** * Live-conversation provider (#957), registered separately from dictation. * Absent: the host does not advertise `liveConversation` and refuses the @@ -341,6 +346,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise settings.saveDictationSettings(db, expected, value), setSetting: (key: string, value: unknown) => settings.setSetting(db, key, value), setHiddenModelIds: (ids: string[]) => settings.setHiddenModelIds(db, ids), setDefaultModelId: (id: string | null) => settings.setDefaultModelId(db, id), @@ -55,6 +56,7 @@ export function createSettingsWrites(db: Database, writer?: SqliteWriter, log?: return result.value; }); return { + saveDictationSettings: (...args) => invoke("saveDictationSettings", args), setSetting: (...args) => invoke("setSetting", args), setHiddenModelIds: (...args) => invoke("setHiddenModelIds", args), setDefaultModelId: (...args) => invoke("setDefaultModelId", args), diff --git a/packages/ui-server/src/db/settings.ts b/packages/ui-server/src/db/settings.ts index a5d54716e3..9b051d7178 100644 --- a/packages/ui-server/src/db/settings.ts +++ b/packages/ui-server/src/db/settings.ts @@ -12,6 +12,7 @@ import { isBillingMode, isThinkingLevel, type BillingMode, + type DictationSettings, type ThinkingLevel, } from "@schlessera/brain-ui-sdk/protocol"; @@ -189,3 +190,26 @@ export function getDetailRetentionDays(db: Database, log?: Logger): number { export function setDetailRetentionDays(db: Database, days: number): void { setSetting(db, DETAIL_RETENTION_KEY, days); } + +const DICTATION_KEY = "voice.dictation"; +/** Invalid rows are discarded as a whole; removed provider ids stay saved. */ +export function getDictationSettings(db: Database): DictationSettings { + const fallback = { defaultProvider: null, smart: true, revision: "0" }; + const value = getSetting(db, DICTATION_KEY, null); + if (!value || typeof value !== "object" || Array.isArray(value)) return fallback; + const row = value as Record; + if (!(row.defaultProvider === null || typeof row.defaultProvider === "string" && row.defaultProvider.length > 0 && row.defaultProvider === row.defaultProvider.trim().toLowerCase()) || + typeof row.smart !== "boolean" || typeof row.revision !== "number" || !Number.isSafeInteger(row.revision) || row.revision < 0) return fallback; + return { defaultProvider: row.defaultProvider, smart: row.smart, revision: String(row.revision) }; +} + +/** The revision comparison and write run in the same writer transaction. */ +export function saveDictationSettings(db: Database, expected: string, value: { defaultProvider: string | null; smart: boolean }) { + return db.transaction(() => { + const current = getDictationSettings(db); + if (expected !== current.revision || Number(current.revision) >= Number.MAX_SAFE_INTEGER) return { saved: false, current }; + const revision = Number(current.revision) + 1; + setSetting(db, DICTATION_KEY, { ...value, revision }); + return { saved: true, current: { ...value, revision: String(revision) } }; + }).immediate(); +} diff --git a/packages/ui-server/src/routes/transcriptions.ts b/packages/ui-server/src/routes/transcriptions.ts index b991a5ff38..16ccb74be8 100644 --- a/packages/ui-server/src/routes/transcriptions.ts +++ b/packages/ui-server/src/routes/transcriptions.ts @@ -1,11 +1,12 @@ +import type { Database } from "bun:sqlite"; +import { getDictationSettings } from "../db/settings.js"; import { createHash } from "node:crypto"; import { Hono, type Context } from "hono"; -import { SpeechTranscriptionError, type SpeechProvider } from "@schlessera/brain-ui-sdk/server"; +import { SpeechTranscriptionError } from "@schlessera/brain-ui-sdk/server"; import type { TranscriptionFailure } from "@schlessera/brain-ui-sdk/protocol"; import type { AppEnv } from "../app-env.js"; -import type { VoiceConfig } from "../config/env.js"; import { getKeyterms, type KeytermSettings } from "../voice/keyterm-builder.js"; -import { pickSpeechProvider, speechCapabilities } from "../voice/speech-providers.js"; +import { speechCapabilities, type SpeechProviderRegistry } from "../voice/speech-providers.js"; import { refuse, TranscriptionError } from "../voice/transcription-store.js"; import type { AwaitableTranscriptionStore } from "../voice/transcription-writes.js"; @@ -54,7 +55,8 @@ async function readAudio(c: Context): Promise { return new Uint8Array(Buffer.concat(chunks, bytes)); } export function createTranscriptionRoutes(deps: { - store: AwaitableTranscriptionStore; voice: VoiceConfig; keyterms: KeytermSettings; speechProvider?: SpeechProvider; + store: AwaitableTranscriptionStore; keyterms: KeytermSettings; + speechProviders: SpeechProviderRegistry; db: Database; }): Hono { const app = new Hono(); const run = (handler: (c: Context, principalId: string, id: string) => Promise) => async (c: Context) => { @@ -80,7 +82,10 @@ export function createTranscriptionRoutes(deps: { return c.json(await deps.store.remove(principalId, id, disposition)); })); app.put(path, run(async (c, principalId, id) => { - const provider = pickSpeechProvider(deps.voice, deps.speechProvider); + const selected = c.req.header("Speech-Provider"); + const provider = selected !== undefined ? deps.speechProviders.get(selected) + : deps.speechProviders.effective(getDictationSettings(deps.db)); + if (!provider) return refuse(409, "speech_provider_unavailable", "That dictation service isn't available on this host."); if (!speechCapabilities(provider).savedAudio) return refuse(501, "saved_audio_unsupported", "Saved-audio transcription is unavailable."); const contentType = c.req.header("content-type") ?? ""; if (!MEDIA.test(contentType)) return refuse(415, "recording_media_unsupported", "Upload a WebM, Ogg or MP4 audio container."); diff --git a/packages/ui-server/src/routes/voice.ts b/packages/ui-server/src/routes/voice.ts index 413c12ad19..ac6ab9d300 100644 --- a/packages/ui-server/src/routes/voice.ts +++ b/packages/ui-server/src/routes/voice.ts @@ -1,44 +1,91 @@ +import type { Database } from "bun:sqlite"; +import type { AppEnv } from "../app-env.js"; +import { getDictationSettings } from "../db/settings.js"; +import type { SettingsWrites } from "../db/settings-writes.js"; import { Hono } from "hono"; import type { VoiceKeytermsResponse, VoiceTokenResponse, VoiceSessionResponse, + VoiceSessionRequest, } from "@schlessera/brain-ui-sdk/protocol"; import type { VoiceConfig } from "../config/env.js"; -import type { SpeechProvider, SpeechSession } from "@schlessera/brain-ui-sdk/server"; +import type { SpeechSession } from "@schlessera/brain-ui-sdk/server"; import { mintDeepgramToken } from "../voice/deepgram-token.js"; import { getKeyterms, type KeytermSettings } from "../voice/keyterm-builder.js"; -import { pickSpeechProvider, speechCapabilities } from "../voice/speech-providers.js"; +import { type SpeechProviderRegistry, speechCapabilities } from "../voice/speech-providers.js"; interface VoiceRoutesDeps { voice: VoiceConfig; keyterms: KeytermSettings; - speechProvider?: SpeechProvider; + speechProviders: SpeechProviderRegistry; + db: Database; + settingsWrites: SettingsWrites; } -export function createVoiceRoutes(deps: VoiceRoutesDeps): Hono { - const { voice, keyterms, speechProvider } = deps; +export function createVoiceRoutes(deps: VoiceRoutesDeps): Hono { + const { voice, keyterms, speechProviders, db, settingsWrites } = deps; - return new Hono() + return new Hono() + .get("/voice/providers", (c) => { + c.header("Cache-Control", "no-store"); + return c.json(speechProviders.discovery(getDictationSettings(db))); + }) + .get("/voice/dictation/settings", (c) => { + c.header("Cache-Control", "no-store"); + const settings = getDictationSettings(db); + c.header("ETag", `"${settings.revision}"`); + return c.json(settings); + }) + .put("/voice/dictation/settings", async (c) => { + c.header("Cache-Control", "no-store"); + const principal = c.get("principal"); + if (principal?.kind !== "owner" && principal?.kind !== "ambient") return c.json({ error: "owner_required" }, 403); + const match = c.req.header("If-Match"); + if (match === undefined) return c.json({ error: "dictation_settings_stale", message: "If-Match is required.", current: getDictationSettings(db) }, 428); + const body = await c.req.json().catch(() => null); + if (!body || typeof body !== "object" || Array.isArray(body) || + !(body.defaultProvider === null || typeof body.defaultProvider === "string") || + (body.smart !== undefined && typeof body.smart !== "boolean")) return c.json({ error: "dictation_settings_invalid" }, 400); + if (body.defaultProvider !== null && !speechProviders.has(body.defaultProvider)) return c.json({ error: "speech_provider_unknown", message: "That dictation service isn't available on this host." }, 400); + const expected = /^"[0-9]+"$/.test(match) ? match.slice(1, -1) : match; + const result = await settingsWrites.saveDictationSettings(expected, { defaultProvider: body.defaultProvider, smart: body.smart ?? true }); + if (!result.saved) return c.json({ error: "dictation_settings_stale", message: "Changed on another device.", current: result.current }, 409); + c.header("ETag", `"${result.current.revision}"`); + return c.json(result.current); + }) .get("/voice/capabilities", (c) => { c.header("Cache-Control", "no-store"); try { - const provider = pickSpeechProvider(voice, speechProvider); + const provider = speechProviders.effective(getDictationSettings(db)); return c.json({ providerId: provider.id, capabilities: speechCapabilities(provider) }); } catch (err) { return c.json({ error: err instanceof Error ? err.message : "Voice capabilities failed" }, 500); } }) .post("/voice/session", async (c) => { + let request: VoiceSessionRequest = {}; + try { + const raw = await c.req.text(); + if (raw) { + const body = JSON.parse(raw); + if (!body || typeof body !== "object" || Array.isArray(body) || + (body.providerId !== undefined && typeof body.providerId !== "string") || + (body.smart !== undefined && typeof body.smart !== "boolean")) return c.json({ error: "voice_session_invalid" }, 400); + request = body; + } + } catch { return c.json({ error: "voice_session_invalid" }, 400); } try { - const provider = pickSpeechProvider(voice, speechProvider); + const settings = getDictationSettings(db); + const provider = request.providerId !== undefined ? speechProviders.get(request.providerId) : speechProviders.effective(settings); + if (!provider) return c.json({ error: "speech_provider_unavailable", message: "That dictation service isn't available on this host." }, 409); const providerId = provider.id; const capabilities = speechCapabilities(provider); // Only fetch domain keyterms when the provider can use them. const terms = capabilities.keyterms ? getKeyterms(keyterms, false).keyterms : []; - const session = await provider.createSession({ keyterms: terms }); + const session = await provider.createSession({ keyterms: terms, ...(capabilities.smartTranscription ? { mode: (request.smart ?? settings.smart) ? "smart" : "verbatim" } as const : {}) }); assertSpeechSession(session); const body: VoiceSessionResponse = { providerId, @@ -51,7 +98,7 @@ export function createVoiceRoutes(deps: VoiceRoutesDeps): Hono { return c.json(body); } catch (err) { return c.json( - { error: err instanceof Error ? err.message : "Voice session failed" }, + { error: request.providerId !== undefined ? "Voice session failed" : err instanceof Error ? err.message : "Voice session failed" }, 500 ); } diff --git a/packages/ui-server/src/voice/speech-providers.ts b/packages/ui-server/src/voice/speech-providers.ts index 94029344db..ba541d752e 100644 --- a/packages/ui-server/src/voice/speech-providers.ts +++ b/packages/ui-server/src/voice/speech-providers.ts @@ -7,13 +7,14 @@ * - `webspeech` — no server session; the browser's SpeechRecognition does the * work, so it returns empty url/token. * - * VOICE_PROVIDER selects the provider; default is deepgram when - * DEEPGRAM_API_KEY is set, otherwise selection fails. An external value takes - * precedence over auto-detection and must match an explicit VOICE_PROVIDER. + * Registration is fixed at construction. VOICE_PROVIDER selects a host default; + * saved settings choose among registered providers without automatic fallback. + * A legacy external value replaces built-ins and must match VOICE_PROVIDER. * Both arrive here as the resolved * {@link VoiceConfig} — this module reads no environment. */ +import type { DictationSettings, VoiceProvidersResponse } from "@schlessera/brain-ui-sdk/protocol"; import type { SpeechProvider } from "@schlessera/brain-ui-sdk/server"; import { defineSpeechProvider, SpeechTranscriptionError } from "@schlessera/brain-ui-sdk/server"; import type { VoiceConfig } from "../config/env.js"; @@ -116,43 +117,9 @@ export const webspeechSpeechProvider: SpeechProvider = defineSpeechProvider({ }, }); -/** - * Select the active speech provider from the resolved voice config. - * - * webspeech is OPT-IN ONLY (`VOICE_PROVIDER=webspeech`): on Chromium it streams - * microphone audio to Google, so it must never be a silent fallback when the - * Deepgram key goes missing. Every other unresolved case throws so the caller - * 500s loudly instead of quietly degrading to third-party egress. - */ -export function pickSpeechProvider(voice: VoiceConfig, supplied?: SpeechProvider): SpeechProvider { - const configured = voice.provider; - if (supplied !== undefined) { - assertSpeechProvider(supplied); - if (configured && configured !== supplied.id) { - throw new Error(`VOICE_PROVIDER="${configured}" does not match supplied SpeechProvider "${supplied.id}".`); - } - return supplied; - } - if (configured === "webspeech") return webspeechSpeechProvider; - if (configured === "deepgram") { - if (!voice.deepgramApiKey) { - throw new Error("VOICE_PROVIDER=deepgram but DEEPGRAM_API_KEY is not set."); - } - return createDeepgramSpeechProvider(voice.deepgramApiKey); - } - if (configured) { - throw new Error( - `Unknown VOICE_PROVIDER="${configured}" (expected "deepgram" or "webspeech").` - ); - } - // Auto-detect: Deepgram when its key is present; otherwise fail loudly. - if (voice.deepgramApiKey) return createDeepgramSpeechProvider(voice.deepgramApiKey); - throw new Error( - 'No speech provider configured. Set DEEPGRAM_API_KEY, or set ' + - 'VOICE_PROVIDER=webspeech to explicitly opt into the browser speech API ' + - "(which streams audio to Google on Chromium)." - ); -} +const NO_SPEECH_PROVIDER = 'No speech provider configured. Set DEEPGRAM_API_KEY, or set ' + + 'VOICE_PROVIDER=webspeech to explicitly opt into the browser speech API ' + + '(which streams audio to Google on Chromium).'; /** Validate a by-value implementation before invoking it or building keyterms. */ function assertSpeechProvider(provider: SpeechProvider): void { @@ -160,6 +127,12 @@ function assertSpeechProvider(provider: SpeechProvider): void { !provider.id || provider.id !== provider.id.trim().toLowerCase()) { throw new Error("Invalid SpeechProvider: id must be a nonempty, trimmed, lowercase string."); } + for (const field of ["label", "destination"] as const) { + if (provider[field] !== undefined && typeof provider[field] !== "string") throw new Error(`Invalid SpeechProvider: ${field} must be a string.`); + } + if (provider.capabilities?.smartTranscription !== undefined && typeof provider.capabilities.smartTranscription !== "boolean") { + throw new Error("Invalid SpeechProvider: smartTranscription must be boolean."); + } for (const capability of ["streaming", "interimResults", "keyterms", "endpointing"] as const) { if (typeof provider.capabilities?.[capability] !== "boolean") { throw new Error(`Invalid SpeechProvider "${provider.id}": capabilities.${capability} must be boolean.`); @@ -180,3 +153,68 @@ function assertSpeechProvider(provider: SpeechProvider): void { export function speechCapabilities(provider: SpeechProvider) { return { ...provider.capabilities, savedAudio: typeof provider.transcribeRecording === "function" }; } + +/** Built-in registration point: add createGeminiSpeechProvider(voice.geminiApiKey) + * here when #3708 supplies that factory. No placeholder provider is advertised. */ +function configuredSpeechProviders(voice: VoiceConfig): SpeechProvider[] { + const providers: SpeechProvider[] = []; + if (voice.deepgramApiKey) providers.push(createDeepgramSpeechProvider(voice.deepgramApiKey)); + if (voice.provider === "webspeech") providers.push(webspeechSpeechProvider); + return providers; +} + +/** Construction fixes identities, metadata, capabilities and executors. Settings + * only choose among these values; they never construct or probe a provider. */ +export function createSpeechProviderRegistry(voice: VoiceConfig, options: { + speechProvider?: SpeechProvider; + speechProviders?: SpeechProvider[]; + defaultSpeechProviderId?: string; +} = {}) { + if (options.speechProvider !== undefined && options.speechProviders !== undefined) { + throw new Error("Supply either speechProvider or speechProviders, not both."); + } + const supplied = options.speechProvider; + const values = supplied !== undefined ? [supplied] : [...configuredSpeechProviders(voice), ...(options.speechProviders ?? [])]; + const providers = new Map(); + for (const value of values) { + assertSpeechProvider(value); + if (providers.has(value.id)) throw new Error(`Duplicate SpeechProvider id "${value.id}".`); + providers.set(value.id, Object.freeze({ + id: value.id, + ...(value.label !== undefined ? { label: value.label } : {}), + ...(value.destination !== undefined ? { destination: value.destination } : {}), + capabilities: Object.freeze(speechCapabilities(value)), + createSession: value.createSession.bind(value), + ...(value.transcribeRecording ? { transcribeRecording: value.transcribeRecording.bind(value) } : {}), + })); + } + if (supplied && voice.provider && supplied.id !== voice.provider) { + throw new Error(`VOICE_PROVIDER="${voice.provider}" does not match supplied SpeechProvider "${supplied.id}".`); + } + const host = options.defaultSpeechProviderId ?? (supplied?.id ?? voice.provider ?? (providers.has("deepgram") ? "deepgram" : null)); + if (host !== null && !providers.has(host)) throw new Error("The host default speech provider is not registered."); + const discovery = (settings: DictationSettings): VoiceProvidersResponse => { + const saved = settings.defaultProvider; + const savedUsable = saved !== null && providers.has(saved); + const effective = saved !== null ? savedUsable ? saved : null : host ?? (providers.size === 1 ? providers.keys().next().value! : null); + const source = saved !== null ? savedUsable ? "saved" : "unavailable" : host !== null ? "host" : effective !== null ? "only" : "none"; + return { + providers: [...providers.values()].map(provider => ({ id: provider.id, label: provider.label ?? provider.id, + ...(provider.destination !== undefined ? { destination: provider.destination } : {}), capabilities: { ...provider.capabilities } })), + dictation: { saved, savedUsable, host, effective, source, smart: settings.smart, revision: settings.revision }, + }; + }; + return { + has: (id: string) => providers.has(id), + get: (id: string) => providers.get(id), + discovery, + effective(settings: DictationSettings): SpeechProvider { + const id = discovery(settings).dictation.effective; + if (id !== null) return providers.get(id)!; + // Preserve the original unconfigured-client error text. + if (!providers.size && settings.defaultProvider === null) throw new Error(NO_SPEECH_PROVIDER); + throw new Error("No effective speech provider. Choose an available dictation service in Settings."); + }, + }; +} +export type SpeechProviderRegistry = ReturnType; diff --git a/packages/ui-server/src/voice/transcription-store.ts b/packages/ui-server/src/voice/transcription-store.ts index be370b6a62..d36b2d1158 100644 --- a/packages/ui-server/src/voice/transcription-store.ts +++ b/packages/ui-server/src/voice/transcription-store.ts @@ -72,6 +72,7 @@ export function transcriptionOperations(db: Database, accountKey: (principal: Pr if (row.status === "transcribing") return refuse(409, "transcription_in_progress", "Transcription is already in progress.", stored); if (row.status === "outcome_unknown") return refuse(409, "transcription_outcome_unknown", "The provider may have processed this audio. It cannot be retried.", stored); if (!retry) return refuse(409, "transcription_failed", "Review the failed transcription before choosing a retry.", stored); + if (providerId !== row.provider_id) return refuse(409, "transcription_provider_mismatch", "Retry with the original transcription service.", stored); if (retry !== row.attempt_id) return refuse(409, "transcription_retry_stale", "This retry names an older attempt.", stored); if (!stored.failure?.retryable) return refuse(409, "transcription_not_retryable", "This provider rejection cannot be retried.", stored); if (row.retry_count >= 3) return refuse(409, "transcription_retry_limit", "All three retries have been used. The recording is kept.", stored); diff --git a/packages/ui-server/tests/drafts-settings-offloop.test.ts b/packages/ui-server/tests/drafts-settings-offloop.test.ts index fb1b8e57c3..e9628757ed 100644 --- a/packages/ui-server/tests/drafts-settings-offloop.test.ts +++ b/packages/ui-server/tests/drafts-settings-offloop.test.ts @@ -1,3 +1,4 @@ +import { createSpeechProviderRegistry } from "../src/voice/speech-providers"; import { expect, test } from "bun:test"; import { createHash, randomUUID } from "node:crypto"; import { mkdtempSync, rmSync } from "node:fs"; @@ -129,7 +130,7 @@ test("a transcription claim commits at FULL before provider dispatch; duplicates }; const app = new Hono(); app.use("*", async (c, next) => { c.set("principal", f.owner); await next(); }); - app.route("/", createTranscriptionRoutes({ store, speechProvider, voice: { provider: speechProvider.id, deepgramApiKey: null, keytermLimit: 0, cacheDir: f.root }, keyterms: { brainPath: f.root, cacheDir: f.root, limit: 0 } })); + app.route("/", createTranscriptionRoutes({ store, db: f.db, speechProviders: createSpeechProviderRegistry({ provider: speechProvider.id, deepgramApiKey: null, keytermLimit: 0, cacheDir: f.root }, { speechProvider }), keyterms: { brainPath: f.root, cacheDir: f.root, limit: 0 } })); const id = randomUUID(), audio = new Uint8Array([1, 2, 3]); const hash = createHash("sha256").update(audio).digest("hex"); const path = `/voice/recordings/${id}/transcription`; diff --git a/packages/ui-server/tests/external-speech.test.ts b/packages/ui-server/tests/external-speech.test.ts index 43a968d3e7..e00db4385f 100644 --- a/packages/ui-server/tests/external-speech.test.ts +++ b/packages/ui-server/tests/external-speech.test.ts @@ -43,6 +43,11 @@ test("a supplied provider wins over automatic Deepgram discovery but never an ex const provider = externalProvider({ createSession: async () => { calls++; return localSession; } }); for (const selection of ["", "fixture-speech", "deepgram", "webspeech", "unknown"]) { const before = calls; + if (selection && selection !== provider.id) { + await expect(httpContractApp({ env: { VOICE_PROVIDER: selection, DEEPGRAM_API_KEY: "unused-fixture-key" }, speechProvider: provider })).rejects.toThrow(`VOICE_PROVIDER="${selection}" does not match supplied SpeechProvider "fixture-speech".`); + expect(calls).toBe(before); + continue; + } const t = await httpContractApp({ env: { VOICE_PROVIDER: selection, DEEPGRAM_API_KEY: "unused-fixture-key" }, speechProvider: provider }); try { const response = await t.fetch("/api/voice/session", { method: "POST" }); @@ -89,6 +94,10 @@ test("a provider failure stays a session error even when a built-in key is confi test("selection without an external value preserves opt-in browser speech and fails closed otherwise", async () => { for (const selection of ["", "deepgram", "unknown", "webspeech"]) { + if (selection === "deepgram" || selection === "unknown") { + await expect(httpContractApp({ env: { VOICE_PROVIDER: selection, DEEPGRAM_API_KEY: "" } })).rejects.toThrow("host default speech provider is not registered"); + continue; + } const t = await httpContractApp({ env: { VOICE_PROVIDER: selection, DEEPGRAM_API_KEY: "" } }); try { const response = await t.fetch("/api/voice/session", { method: "POST" }); @@ -109,16 +118,11 @@ for (const [field, value] of [ ["id", ""], ["id", " Fixture "], ["capabilities", {}], ["capabilities", { streaming: "true", interimResults: false, keyterms: false, endpointing: false }], ["createSession", null], ] as const) { - test(`the mounted route rejects invalid provider ${field}: ${JSON.stringify(value)}`, async () => { + test(`construction rejects invalid provider ${field}: ${JSON.stringify(value)}`, async () => { let called = false; const provider = externalProvider({ createSession: async () => { called = true; return localSession; }, [field]: value } as unknown as Partial); - const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProvider: provider }); - try { - const response = await t.fetch("/api/voice/session", { method: "POST" }); - expect(response.status).toBe(500); - expect(await response.json()).toEqual({ error: expect.stringContaining("Invalid SpeechProvider") }); - expect(called).toBe(false); - } finally { await t.close(); } + await expect(httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProvider: provider })).rejects.toThrow("Invalid SpeechProvider"); + expect(called).toBe(false); }); } diff --git a/packages/ui-server/tests/helpers/http-contract-app.ts b/packages/ui-server/tests/helpers/http-contract-app.ts index 00fc4ceec2..fb07a77ae3 100644 --- a/packages/ui-server/tests/helpers/http-contract-app.ts +++ b/packages/ui-server/tests/helpers/http-contract-app.ts @@ -27,6 +27,8 @@ export async function httpContractApp(options: { renderer?: CreateAppOptions["renderer"]; registry?: CreateAppOptions["registry"]; speechProvider?: SpeechProvider; + speechProviders?: SpeechProvider[]; + defaultSpeechProviderId?: string; } = {}) { const root = mkdtempSync(join(tmpdir(), "brain-http-contract-")); const brainPath = join(root, "brain"); @@ -81,6 +83,8 @@ else if (args[0] === "sync") console.log("Fixture sync complete"); try { const appOptions: CreateAppOptions & { speechProvider?: SpeechProvider } = { config, observability, + speechProviders: options.speechProviders, + defaultSpeechProviderId: options.defaultSpeechProviderId, registry: options.registry ?? createStaticBackendRegistry([backend]), ...(options.speechProvider ? { speechProvider: options.speechProvider } : {}), ...(options.staticRoot ? { staticRoot } : {}), diff --git a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts index 83d8e004f2..9acb8c595b 100644 --- a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts +++ b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts @@ -111,6 +111,9 @@ export const mountLifetimes: Record = { "POST /share-target": { init: { method: "POST" }, status: 303, verify: async (r) => { expect(r.headers.get("location")).toBe("/?share_error=no_worker"); } }, "POST /api/render": { init: json("POST", { content: "# Arrival", contentType: "markdown", format: "png" }), status: 501, body: { error: "render_unavailable" } }, "GET /api/geo/coastline": { path: "/api/geo/coastline?bbox=15.6,38.2,15.8,38.32", body: { coastline: [], attribution: "© OpenStreetMap contributors" } }, + "GET /api/voice/providers": { body: { dictation: { effective: "webspeech", source: "host" } } }, + "GET /api/voice/dictation/settings": { body: { defaultProvider: null, smart: true, revision: "0" } }, + "PUT /api/voice/dictation/settings": { init: { method: "PUT", headers: { "If-Match": '"0"' }, body: JSON.stringify({ defaultProvider: "webspeech", smart: false }) }, body: { defaultProvider: "webspeech", smart: false, revision: "1" } }, "GET /api/voice/capabilities": { body: { providerId: "webspeech", capabilities: { savedAudio: false } } }, "GET /api/voice/recordings/:recordingId/transcription": { path: "/api/voice/recordings/00000000-0000-4000-8000-000000000001/transcription", status: 404, body: { error: "transcription_not_found" } }, "PUT /api/voice/recordings/:recordingId/transcription": { path: "/api/voice/recordings/00000000-0000-4000-8000-000000000001/transcription", init: { method: "PUT" }, status: 501, body: { error: "saved_audio_unsupported" } }, diff --git a/packages/ui-server/tests/saved-transcription.test.ts b/packages/ui-server/tests/saved-transcription.test.ts index d5f8c1efd3..5ba21e39e6 100644 --- a/packages/ui-server/tests/saved-transcription.test.ts +++ b/packages/ui-server/tests/saved-transcription.test.ts @@ -206,9 +206,7 @@ test("optional capability declarations must match the method and Web Speech refu const provider = fake(async () => ({ text: "Ithaca" })); provider.capabilities.savedAudio = !withMethod; if (!withMethod) delete provider.transcribeRecording; - const t = await httpContractApp({ env: { VOICE_PROVIDER: "fixture-speech" }, speechProvider: provider }); - try { expect((await t.fetch("/api/voice/capabilities")).status).toBe(500); expect((await t.fetch(path(randomUUID()), put())).status).toBe(500); } - finally { await t.close(); } + await expect(httpContractApp({ env: { VOICE_PROVIDER: "fixture-speech" }, speechProvider: provider })).rejects.toThrow("savedAudio contradicts transcribeRecording"); } const webspeech = await httpContractApp(); try { diff --git a/packages/ui-server/tests/selectable-dictation.test.ts b/packages/ui-server/tests/selectable-dictation.test.ts new file mode 100644 index 0000000000..df9b8cd4e0 --- /dev/null +++ b/packages/ui-server/tests/selectable-dictation.test.ts @@ -0,0 +1,248 @@ +import { expect, test } from "bun:test"; +import { createHash, randomUUID } from "node:crypto"; +import type { SpeechProvider } from "@schlessera/brain-ui-sdk/server"; +import { SpeechTranscriptionError } from "@schlessera/brain-ui-sdk/server"; +import { httpContractApp, type HttpContractApp } from "./helpers/http-contract-app"; +import { createSettingsWrites } from "../src/db/settings-writes"; +import { getDictationSettings } from "../src/db/settings"; +import { generateSignedCookie } from "hono/cookie"; +import { createPrincipal } from "../src/db/principals"; +import { Database } from "bun:sqlite"; + +function doubles() { + const calls = { alpha: [] as unknown[], beta: [] as unknown[], audio: [] as Uint8Array[] }; + const alpha: SpeechProvider = { id: "alpha", label: "Ithaca dictation", destination: "Audio goes to the Ithaca fixture.", + capabilities: { streaming: true, interimResults: true, keyterms: false, endpointing: true }, + async createSession(options) { calls.alpha.push(options); return { url: "", expiresAt: 0 }; }, + async transcribeRecording({ audio }) { calls.audio.push(audio); return { text: "Odysseus reaches Ithaca." }; }, + }; + const beta: SpeechProvider = { id: "beta", capabilities: { streaming: true, interimResults: true, keyterms: false, endpointing: false, smartTranscription: true }, + async createSession(options) { calls.beta.push(options); return { url: "", expiresAt: 0 }; }, + }; + return { alpha, beta, calls }; +} +const settingsPath = "/api/voice/dictation/settings"; +const audio = new Uint8Array([1, 2, 3]); +const path = (id: string) => `/api/voice/recordings/${id}/transcription`; +const upload = (provider?: string): RequestInit => ({ method: "PUT", body: audio, + headers: { "Content-Type": "audio/webm", "Content-SHA256": createHash("sha256").update(audio).digest("hex"), ...(provider !== undefined ? { "Speech-Provider": provider } : {}) } }); +const mint = (providerId?: string, smart?: boolean): RequestInit => ({ method: "POST", ...(providerId !== undefined ? { body: JSON.stringify({ providerId, smart }) } : {}) }); +const save = (t: HttpContractApp, defaultProvider: string | null, revision = "0", smart = true, headers = {}) => t.fetch(settingsPath, { + method: "PUT", headers: { "Content-Type": "application/json", "If-Match": `"${revision}"`, ...headers }, body: JSON.stringify({ defaultProvider, smart }), +}); +function gate() { + let release!: () => void; + const promise = new Promise(resolve => { release = resolve; }); + return { promise, release }; +} + +// The plan's Deepgram/Gemini rows use the same alpha/beta executors by value. +for (const row of [ + { name: "zero", ids: [], saved: null, host: undefined, effective: null, source: "none" }, + { name: "zero with saved", ids: [], saved: "removed", host: undefined, effective: null, source: "unavailable" }, + { name: "one with host", ids: ["alpha"], saved: null, host: "alpha", effective: "alpha", source: "host" }, + { name: "one without host", ids: ["beta"], saved: null, host: undefined, effective: "beta", source: "only" }, + { name: "two with host", ids: ["alpha", "beta"], saved: null, host: "alpha", effective: "alpha", source: "host" }, + { name: "saved overrides host", ids: ["alpha", "beta"], saved: "beta", host: "alpha", effective: "beta", source: "saved" }, + { name: "removed blocks host", ids: ["alpha", "beta"], saved: "removed", host: "alpha", effective: null, source: "unavailable" }, + { name: "two require choice", ids: ["alpha", "beta"], saved: null, host: undefined, effective: null, source: "none" }, + { name: "legacy supplied", ids: ["alpha"], saved: "alpha", host: "alpha", effective: "alpha", source: "saved", legacy: true }, +]) test(`selection matrix: ${row.name}; legacy bodyless session and upload use the effective provider`, async () => { + const { alpha, beta, calls } = doubles(); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, defaultSpeechProviderId: row.host, + ...("legacy" in row ? { speechProvider: alpha } : { speechProviders: row.ids.map(id => id === "alpha" ? alpha : beta) }) }); + try { + if (row.saved) { + // Model persisted settings from another startup, including a removed id. + const writer = new Database(t.app.config.dbPath); + try { await createSettingsWrites(writer).setSetting("voice.dictation", { defaultProvider: row.saved, smart: false, revision: 3 }); } + finally { writer.close(); } + } + const discovery = await t.fetch("/api/voice/providers"); + expect(discovery.status).toBe(200); expect(discovery.headers.get("cache-control")).toBe("no-store"); + const body = await discovery.json(); + expect(body.providers.map((p: { id: string }) => p.id)).toEqual(row.ids); + expect(body.dictation).toEqual({ saved: row.saved, savedUsable: row.saved !== null && row.ids.includes(row.saved), host: row.host ?? null, + effective: row.effective, source: row.source, smart: !row.saved, revision: row.saved ? "3" : "0" }); + expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); + const capabilities = await t.fetch("/api/voice/capabilities"); + const session = await t.fetch("/api/voice/session", mint()); + expect(session.status).toBe(row.effective ? 200 : 500); + expect(capabilities.status).toBe(session.status); + if (row.effective) { + const expected = row.effective === "alpha" ? alpha : beta; + expect(await capabilities.text()).toBe(JSON.stringify({ providerId: expected.id, capabilities: { ...expected.capabilities, savedAudio: expected.id === "alpha" } })); + expect(await session.text()).toBe(JSON.stringify({ providerId: expected.id, url: "", expiresAt: 0, capabilities: { ...expected.capabilities, savedAudio: expected.id === "alpha" } })); + } + expect(calls.alpha).toEqual(row.effective === "alpha" ? [{ keyterms: [] }] : []); + expect(calls.beta).toEqual(row.effective === "beta" ? [{ keyterms: [], mode: row.saved ? "verbatim" : "smart" }] : []); + const result = await t.fetch(path(randomUUID()), upload()); + expect(result.status).toBe(row.effective === "alpha" ? 200 : row.effective === "beta" ? 501 : 500); + expect(calls.audio).toEqual(row.effective === "alpha" ? [audio] : []); + } finally { await t.close(); } +}); + +test("held mint keeps the requested provider across a default save", async () => { + const { alpha, beta, calls } = doubles(); const entered = gate(), held = gate(); + const original = beta.createSession; + beta.createSession = async opts => { const result = await original(opts); entered.release(); await held.promise; return result; }; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "alpha" }); + let pending: Promise | undefined; + try { + pending = t.fetch("/api/voice/session", mint("beta", false)); + // Race-safe even under the mutation: a wrong provider resolves immediately. + await Promise.race([entered.promise, pending]); + expect(calls.beta, "the disclosed beta provider must mint, even while alpha is the default").toEqual([{ keyterms: [], mode: "verbatim" }]); + expect((await save(t, "beta")).status).toBe(200); + expect((await save(t, "alpha", "1")).status).toBe(200); + held.release(); const result = await (await pending).json(); + expect(result.providerId).toBe("beta"); expect(result.capabilities.smartTranscription).toBe(true); + expect(calls.alpha).toEqual([]); expect(calls.audio).toEqual([]); + } finally { held.release(); await pending; await t.close(); } +}); + +test("held upload keeps the header provider across a default save", async () => { + const { alpha, beta, calls } = doubles(); const entered = gate(), held = gate(); + const original = alpha.transcribeRecording!; + alpha.transcribeRecording = async opts => { const result = await original(opts); entered.release(); await held.promise; return result; }; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "beta" }); + let pending: Promise | undefined; + try { + const id = randomUUID(); pending = t.fetch(path(id), upload("alpha")); + await Promise.race([entered.promise, pending]); + expect(calls.audio, "the disclosed alpha provider must receive the audio despite the streaming-only default").toEqual([audio]); + expect((await save(t, "alpha")).status).toBe(200); + expect((await save(t, "beta", "1")).status).toBe(200); + held.release(); const receipt = await (await pending).json(); + expect(receipt.providerId).toBe("alpha"); expect(receipt.status).toBe("done"); + expect(await (await t.fetch(path(id), upload("alpha"))).json()).toEqual(receipt); + expect(calls.audio).toHaveLength(1); expect(calls.alpha).toEqual([]); expect(calls.beta).toEqual([]); + } finally { held.release(); await pending; await t.close(); } +}); + +test("upload admission freezes the header before the request body finishes", async () => { + const { alpha, beta, calls } = doubles(); const reading = gate(); let finish!: () => void; + const body = new ReadableStream({ start(c) { c.enqueue(audio); finish = () => { finish = () => {}; c.close(); }; }, pull() { reading.release(); } }, { highWaterMark: 0 }); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "alpha" }); + let pending: Promise | undefined; + try { + pending = t.fetch(path(randomUUID()), { ...upload("alpha"), body, duplex: "half" } as RequestInit); + await reading.promise; + expect((await save(t, "beta")).status).toBe(200); + finish(); const result = await (await pending).json(); + expect(result.providerId).toBe("alpha"); expect(calls.audio).toEqual([audio]); expect(calls.beta).toEqual([]); + } finally { finish(); await pending; await t.close(); } +}); + +test("exact selections refuse unknown providers and streaming-only uploads before claims; failures never fall back", async () => { + const { alpha, beta, calls } = doubles(); + beta.createSession = async options => { calls.beta.push(options); throw new Error("fixture-secret-not-for-client"); }; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "alpha" }); + try { + for (const id of ["removed", ""]) { + const response = await t.fetch("/api/voice/session", mint(id)); + expect(response.status).toBe(409); expect((await response.json()).error).toBe("speech_provider_unavailable"); + } + for (const provider of ["removed", "beta"]) { + const id = randomUUID(), response = await t.fetch(path(id), upload(provider)); + expect(response.status).toBe(provider === "beta" ? 501 : 409); + expect((await t.fetch(path(id))).status).toBe(404); + } + const failure = await t.fetch("/api/voice/session", mint("beta")); + expect(failure.status).toBe(500); expect(await failure.text()).not.toContain("fixture-secret"); + expect(calls.beta).toEqual([{ keyterms: [], mode: "smart" }]); expect(calls.alpha).toEqual([]); expect(calls.audio).toEqual([]); + } finally { await t.close(); } +}); + +test("retry cannot change the provider of a durable receipt", async () => { + const { alpha, beta, calls } = doubles(); let otherCalls = 0; + alpha.transcribeRecording = async ({ audio }) => { calls.audio.push(audio); throw new SpeechTranscriptionError("provider_error", 503); }; + // A second saved-audio implementation is needed to reach the receipt check. + const other: SpeechProvider = { ...alpha, id: "other", async transcribeRecording() { otherCalls++; return { text: "Ithaca" }; } }; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta, other], defaultSpeechProviderId: "alpha" }); + try { + const id = randomUUID(), receipt = await (await t.fetch(path(id), upload("alpha"))).json(); + expect(receipt.status).toBe("failed"); + expect((await save(t, "other")).status).toBe(200); + const response = await t.fetch(`${path(id)}?retry=${receipt.attemptId}`, upload("other")); + expect(response.status).toBe(409); expect(await response.json()).toEqual({ error: "transcription_provider_mismatch", message: "Retry with the original transcription service.", receipt }); + expect(calls.audio).toHaveLength(1); expect(otherCalls).toBe(0); expect(calls.beta).toEqual([]); + expect((await t.fetch(`${path(id)}?retry=${receipt.attemptId}`, upload("alpha"))).status).toBe(200); + expect(calls.audio).toHaveLength(2); + } finally { await t.close(); } +}); + +test("settings enforce owner authority and atomic revisions without minting", async () => { + const { alpha, beta, calls } = doubles(); const secret = "odysseus-dictation-cookie-secret"; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "", AUTH_MODE: "password", COOKIE_SECRET: secret, BRAIN_UI_PASSWORD_HASH: "fixture" }, speechProviders: [alpha, beta] }); + try { + const owner = createPrincipal(t.app.db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const agent = createPrincipal(t.app.db, { authMethod: "delegated", label: "Eurylochus", createdBy: owner.id, ttlSeconds: 3600 }); + const cookie = async (id: string) => ({ cookie: (await generateSignedCookie("brain_ui_session", id, secret)).split(";")[0]! }); + const ownerHeaders = await cookie(owner.id); + expect((await t.fetch(settingsPath)).status).toBe(401); + expect((await t.fetch("/api/voice/providers")).status).toBe(401); + expect((await save(t, "alpha", "0", true, await cookie(agent.id))).status).toBe(403); + const initial = await t.fetch(settingsPath, { headers: ownerHeaders }); + expect(await initial.json()).toEqual({ defaultProvider: null, smart: true, revision: "0" }); + expect(initial.headers.get("etag")).toBe('"0"'); + expect((await t.fetch(settingsPath, { method: "PUT", headers: ownerHeaders, body: JSON.stringify({ defaultProvider: "alpha" }) })).status).toBe(428); + const unknown = await save(t, "removed", "0", true, ownerHeaders); + expect(unknown.status).toBe(400); expect((await unknown.json()).error).toBe("speech_provider_unknown"); + const concurrent = await Promise.all([save(t, "alpha", "0", false, ownerHeaders), save(t, "beta", "0", false, ownerHeaders)]); + expect(concurrent.map(r => r.status).sort()).toEqual([200, 409]); + const current = await concurrent.find(r => r.status === 200)!.json(); + expect(current.revision).toBe("1"); expect(current.smart).toBe(false); + expect(await concurrent.find(r => r.status === 409)!.json()).toEqual({ error: "dictation_settings_stale", message: "Changed on another device.", current }); + expect((await save(t, null, "1", true, ownerHeaders)).status).toBe(200); + expect(getDictationSettings(t.app.db)).toEqual({ defaultProvider: null, smart: true, revision: "2" }); + const reader = new Database(t.app.config.dbPath); + try { expect(getDictationSettings(reader)).toEqual(getDictationSettings(t.app.db)); } finally { reader.close(); } + expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); + } finally { await t.close(); } +}); + +test("invalid settings are total and malformed requests do not change them", async () => { + const { alpha, beta, calls } = doubles(); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta] }); + const writer = new Database(t.app.config.dbPath); + try { + for (const value of ["{", "null", "[]", '{"defaultProvider":"alpha","smart":true,"revision":-1}', '{"defaultProvider":"alpha","smart":"yes","revision":1}']) { + writer.query("INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES ('voice.dictation', ?, 0)").run(value); + expect(await (await t.fetch(settingsPath)).json()).toEqual({ defaultProvider: null, smart: true, revision: "0" }); + } + for (const body of ["{", "null", "[]", '{}', '{"defaultProvider":"alpha","smart":1}']) { + expect((await t.fetch(settingsPath, { method: "PUT", headers: { "If-Match": '"0"' }, body })).status).toBe(400); + } + for (const body of ["{", "null", "[]", '{"providerId":42}', '{"smart":1}']) { + expect((await t.fetch("/api/voice/session", { method: "POST", body })).status).toBe(400); + } + expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); + } finally { writer.close(); await t.close(); } +}); + +test("registration validates duplicate ids, mutually exclusive options and unregistered defaults at construction", async () => { + const { alpha, beta } = doubles(); + for (const options of [{ speechProviders: [alpha, alpha] }, { speechProvider: alpha, speechProviders: [beta] }, + { speechProviders: [alpha], defaultSpeechProviderId: "removed" }, { speechProviders: [{ ...alpha, id: " Alpha " }] }, + { speechProviders: [{ ...alpha, capabilities: { ...alpha.capabilities, savedAudio: false } }] }]) { + await expect(httpContractApp({ env: { VOICE_PROVIDER: "" }, ...options })).rejects.toThrow(); + } + await expect(httpContractApp({ env: { VOICE_PROVIDER: "", DEEPGRAM_API_KEY: "fixture" }, speechProviders: [{ ...alpha, id: "deepgram" }] })).rejects.toThrow("Duplicate"); +}); + +test("built-ins register by key and browser speech remains opt-in; options precede environment defaults", async () => { + const { alpha, beta, calls } = doubles(); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "", DEEPGRAM_API_KEY: "fixture-private-key" }, speechProviders: [alpha, beta] }); + try { + const response = await t.fetch("/api/voice/providers"), raw = await response.text(), body = JSON.parse(raw); + expect(raw).not.toContain("fixture-private-key"); expect(body.providers.map((p: { id: string }) => p.id)).toEqual(["deepgram", "alpha", "beta"]); + expect(body.dictation.host).toBe("deepgram"); expect(body.dictation.effective).toBe("deepgram"); + expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); + } finally { await t.close(); } + const browser = await httpContractApp({ env: { VOICE_PROVIDER: "webspeech" }, speechProviders: [alpha], defaultSpeechProviderId: "alpha" }); + try { + const body = await (await browser.fetch("/api/voice/providers")).json(); + expect(body.providers.map((p: { id: string }) => p.id)).toEqual(["webspeech", "alpha"]); expect(body.dictation.host).toBe("alpha"); + } finally { await browser.close(); } +}); From 9a9ce76428936bdf6abd2ba3dd9c69d7bfe772f3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 13:00:13 +0100 Subject: [PATCH 2/9] CONTRACT: feat(ui-server): complete selectable dictation provider proof Co-Authored-By: Claude Opus 5.5 --- docs/decisions/dictation-speech.md | 17 +++++++++-------- docs/http-api-coverage.md | 2 +- docs/http-api.md | 4 ++-- .../tests/recording-transcription.test.ts | 2 +- .../tests/selectable-dictation.test.ts | 8 ++++---- 5 files changed, 17 insertions(+), 16 deletions(-) diff --git a/docs/decisions/dictation-speech.md b/docs/decisions/dictation-speech.md index 1decf9d9e0..96af9518dc 100644 --- a/docs/decisions/dictation-speech.md +++ b/docs/decisions/dictation-speech.md @@ -33,21 +33,22 @@ or bypass the host's permission and turn machinery. `createApp({ speechProvider })` supplies an implementation by value. It wins over automatic Deepgram discovery. An explicit `config.voice.provider` must match its id; a mismatch fails instead of choosing either implementation -(`pickSpeechProvider`, `packages/ui-server/src/voice/speech-providers.ts:127-155`). +(`createSpeechProviderRegistry`, `packages/ui-server/src/voice/speech-providers.ts:168-195`). Without the value, existing selection remains: explicit built-ins, automatic Deepgram only when its key is present, otherwise failure. Browser speech is an explicit opt-in; it never becomes a fallback after a missing key or provider failure. -Provider validation and session validation happen inside the mounted session -route's existing error boundary. A provider id is nonempty, trimmed and +The approved #3707 registration rules move provider validation and host-default +mismatch errors to construction; session validation stays inside the mounted +session route's error boundary. A provider id is nonempty, trimmed and lowercase, matching environment resolution. All four capabilities are boolean; `createSession` is callable. Sessions carry a string URL, finite nonnegative expiry and optional string token/string-record params. Empty URL and zero -expiry remain valid for browser/local implementations. Unknown configuration, -mismatch, invalid implementations/results and minting failures return the -existing 500 `{ error }` envelope. Authentication and the deprecated -Deepgram-specific token route keep their existing meanings. +expiry remain valid for browser/local implementations. Invalid session results +and legacy minting failures retain the existing 500 `{ error }` envelope. +Authentication and the deprecated Deepgram-specific token route keep their +existing meanings. Keyterms are built only for a provider declaring support. The route snapshots identity/capabilities before minting; the matching client receives the minted @@ -127,7 +128,7 @@ external providers may omit the optional method on the existing seam (`transcribeRecording?`, `packages/ui-sdk/src/server/speech.ts:38-43`). The server derives the advertised capability from that method, rather than trusting a flag disconnected from its executor -(`speechCapabilities`, `packages/ui-server/src/voice/speech-providers.ts:180-182`). +(`speechCapabilities`, `packages/ui-server/src/voice/speech-providers.ts:153-155`). An absent capability keeps playback, typing and retention available, with the tray's explicit unavailable explanation. diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index d88a21b646..dee3dbcdf9 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -510,7 +510,7 @@ track measurements and unchanged original bytes; the composer transport creates no inbox thread. Detailed parser/intake/containment checks live in [track-intake.test.ts](../packages/ui-server/tests/track-intake.test.ts). -**R** — [saved-transcription.test.ts](../packages/ui-server/tests/saved-transcription.test.ts): concurrent real-route claims/retries, server hashes, body caps, account access, terminal outcomes, tombstones and keyless provider transport. +**R** — [selectable-dictation.test.ts](../packages/ui-server/tests/selectable-dictation.test.ts) covers exact provider selection, settings revisions/authority and held mint/upload binding; [saved-transcription.test.ts](../packages/ui-server/tests/saved-transcription.test.ts): concurrent real-route claims/retries, server hashes, body caps, account access, terminal outcomes, tombstones and keyless provider transport. **RV — User history restoration.** `turn-revert.test.ts` exercises raw restoration, Undo, partial conflicts, operation identity, authorization, original voice and diff --git a/docs/http-api.md b/docs/http-api.md index c7d129231c..6e0ea26018 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion and individual safety-review routes mounted by `createApp`: 176 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion and individual safety-review routes mounted by `createApp`: 179 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -212,7 +212,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 176 declared endpoints are mounted regardless of backend, renderer or +All 179 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. diff --git a/packages/ui-react/tests/recording-transcription.test.ts b/packages/ui-react/tests/recording-transcription.test.ts index 2e88ec4efa..f7319ddac9 100644 --- a/packages/ui-react/tests/recording-transcription.test.ts +++ b/packages/ui-react/tests/recording-transcription.test.ts @@ -161,7 +161,7 @@ test("an ambiguous upload stays recoverable while the host has not claimed its b }); -for (const [status, error] of [[413, "recording_too_large"], [415, "recording_media_unsupported"], [400, "recording_hash_invalid"], [501, "saved_audio_unsupported"]] as const) test(`definitive pre-claim ${status} rejection leaves audio reviewable`, async () => { +for (const [status, error] of [[413, "recording_too_large"], [415, "recording_media_unsupported"], [400, "recording_hash_invalid"], [501, "saved_audio_unsupported"], [409, "speech_provider_unavailable"]] as const) test(`definitive pre-claim ${status} rejection leaves audio reviewable`, async () => { const f = fixture(); await f.seed("saved"); let uploads = 0; f.root.request = async (url, init) => { if (url.endsWith("capabilities")) return Response.json({ capabilities: { savedAudio: true } }); if (init?.method === "PUT") { uploads++; return Response.json({ error, message: "Recording rejected before provider dispatch." }, { status }); } return new Response("{}", { status: 404 }); }; const s = f.make(); await expect(s.transcribe("account:odysseus", f.id, () => {})).rejects.toThrow(); await s.syncTranscriptions(); diff --git a/packages/ui-server/tests/selectable-dictation.test.ts b/packages/ui-server/tests/selectable-dictation.test.ts index df9b8cd4e0..d1d73340f2 100644 --- a/packages/ui-server/tests/selectable-dictation.test.ts +++ b/packages/ui-server/tests/selectable-dictation.test.ts @@ -62,7 +62,7 @@ for (const row of [ expect(discovery.status).toBe(200); expect(discovery.headers.get("cache-control")).toBe("no-store"); const body = await discovery.json(); expect(body.providers.map((p: { id: string }) => p.id)).toEqual(row.ids); - expect(body.dictation).toEqual({ saved: row.saved, savedUsable: row.saved !== null && row.ids.includes(row.saved), host: row.host ?? null, + expect(body.dictation).toEqual({ saved: row.saved, savedUsable: row.saved !== null && row.ids.some(id => id === row.saved), host: row.host ?? null, effective: row.effective, source: row.source, smart: !row.saved, revision: row.saved ? "3" : "0" }); expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); const capabilities = await t.fetch("/api/voice/capabilities"); @@ -89,7 +89,7 @@ test("held mint keeps the requested provider across a default save", async () => const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "alpha" }); let pending: Promise | undefined; try { - pending = t.fetch("/api/voice/session", mint("beta", false)); + pending = Promise.resolve(t.fetch("/api/voice/session", mint("beta", false))); // Race-safe even under the mutation: a wrong provider resolves immediately. await Promise.race([entered.promise, pending]); expect(calls.beta, "the disclosed beta provider must mint, even while alpha is the default").toEqual([{ keyterms: [], mode: "verbatim" }]); @@ -108,7 +108,7 @@ test("held upload keeps the header provider across a default save", async () => const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "beta" }); let pending: Promise | undefined; try { - const id = randomUUID(); pending = t.fetch(path(id), upload("alpha")); + const id = randomUUID(); pending = Promise.resolve(t.fetch(path(id), upload("alpha"))); await Promise.race([entered.promise, pending]); expect(calls.audio, "the disclosed alpha provider must receive the audio despite the streaming-only default").toEqual([audio]); expect((await save(t, "alpha")).status).toBe(200); @@ -126,7 +126,7 @@ test("upload admission freezes the header before the request body finishes", asy const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "alpha" }); let pending: Promise | undefined; try { - pending = t.fetch(path(randomUUID()), { ...upload("alpha"), body, duplex: "half" } as RequestInit); + pending = Promise.resolve(t.fetch(path(randomUUID()), { ...upload("alpha"), body, duplex: "half" } as RequestInit)); await reading.promise; expect((await save(t, "beta")).status).toBe(200); finish(); const result = await (await pending).json(); From 9c08f9b912e8b2c308cd7e39d9848bbc659279a9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 13:03:12 +0100 Subject: [PATCH 3/9] CONTRACT: fix(ui-server): allow bound dictation uploads across origins Co-Authored-By: Claude Opus 5.5 --- docs/http-api.md | 2 +- packages/ui-server/src/app.ts | 2 +- packages/ui-server/tests/http-inventory.test.ts | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/http-api.md b/docs/http-api.md index 6e0ea26018..198306bf38 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -227,7 +227,7 @@ Range. WebSocket upgrade requires an actual GET. `ALL /api/*` installs origin policy, configured CORS and authentication. With nonempty `ALLOWED_ORIGINS`, CORS middleware answers allowed **OPTIONS /api/** preflights with 204 before authentication, advertising GET, POST, PUT, -DELETE, the `Content-Type`, `If-Match` and `Idempotency-Key` and `Content-SHA256` headers, and credentials. Origin policy runs first; a rejected +DELETE, the `Content-Type`, `If-Match`, `Idempotency-Key`, `Content-SHA256` and `Speech-Provider` headers, and credentials. Origin policy runs first; a rejected origin gets 403. Without that configured middleware there is no universal OPTIONS endpoint: authentication/routing decide the response. These are transport behaviors, not independently supported OPTIONS resource operations. diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 5668a65534..bc264f5e39 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -999,7 +999,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise Date: Sun, 8 Nov 2026 13:06:26 +0100 Subject: [PATCH 4/9] CONTRACT: feat(ui-server,ui-react): add Gemini 3.5 Transcribe Live dictation Add Google's dedicated streaming transcription model as the built-in `gemini` dictation provider and its browser client (#3708, epic #3705). Server: createGeminiSpeechProvider mints one single-use ephemeral token per take through POST /v1beta/auth_tokens with liveConnectConstraints locking models/gemini-3.5-transcribe-live, the TEXT modality and the transcription config (SMART unless verbatim is requested, keyterms as customVocabulary, at most 100 terms of 64 UTF-8 bytes). GEMINI_API_KEY is read into VoiceConfig and documented in the env descriptor; VOICE_PROVIDER=gemini selects it, and auto-detection uses it only when DEEPGRAM_API_KEY is unset. Every mint failure is the fixed "Gemini dictation session failed" error; neither the key nor Google's text is reflected. Client: GeminiAsrClient, registered as `gemini`, streams 16 kHz mono PCM16 LE in 100 ms base64 frames resampled from the hardware rate through the AudioWorklet now shared with live conversation (pcm-capture.ts). Bounds: 5 s pre-setup buffer, 10 s handshake, 256 KiB upload backlog, 3 s Done drain after audioStreamEnd. Interim text replaces the partial; each final transcription commits once. SDK (additive): SpeechProvider.label/destination, createSession mode "smart" | "verbatim", SpeechCapabilities.smartTranscription; validated by the server and the published provider conformance suite. Co-Authored-By: Claude Opus 5.5 --- .../gemini-transcribe-live-dictation.md | 9 + api-report/ui-sdk.txt | 4 + api-report/ui-server.txt | 1 + docs/extending/speech.md | 65 ++- docs/http-api.md | 2 +- docs/integration-contract/package-api.md | 41 ++ docs/supported-inputs.md | 2 +- .../src/components/voice/dictation-sheet.tsx | 2 + packages/ui-react/src/voice/asr-clients.ts | 16 + packages/ui-react/src/voice/asr-gemini.ts | 274 ++++++++++++ .../ui-react/src/voice/conversation-pcm.ts | 63 +-- packages/ui-react/src/voice/pcm-capture.ts | 107 +++++ packages/ui-react/tests/asr-gemini.test.ts | 411 ++++++++++++++++++ .../browser/dictation-gemini.offline.tsx | 245 +++++++++++ .../tests/registration-on-mount-harness.ts | 1 + .../tests/registration-on-mount.test.tsx | 5 +- packages/ui-sdk/src/protocol.ts | 3 + packages/ui-sdk/src/server/speech.ts | 10 +- .../ui-sdk/src/testing/speech-contract.ts | 18 + packages/ui-server/README.md | 5 +- packages/ui-server/src/config/env.ts | 17 +- packages/ui-server/src/voice/gemini-speech.ts | 126 ++++++ .../ui-server/src/voice/speech-providers.ts | 30 +- .../ui-server/tests/gemini-speech.test.ts | 230 ++++++++++ 24 files changed, 1612 insertions(+), 75 deletions(-) create mode 100644 .changeset/gemini-transcribe-live-dictation.md create mode 100644 packages/ui-react/src/voice/asr-gemini.ts create mode 100644 packages/ui-react/src/voice/pcm-capture.ts create mode 100644 packages/ui-react/tests/asr-gemini.test.ts create mode 100644 packages/ui-react/tests/browser/dictation-gemini.offline.tsx create mode 100644 packages/ui-server/src/voice/gemini-speech.ts create mode 100644 packages/ui-server/tests/gemini-speech.test.ts diff --git a/.changeset/gemini-transcribe-live-dictation.md b/.changeset/gemini-transcribe-live-dictation.md new file mode 100644 index 0000000000..c92078d0ad --- /dev/null +++ b/.changeset/gemini-transcribe-live-dictation.md @@ -0,0 +1,9 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": minor +--- + +Add Google Gemini 3.5 Transcribe Live as a built-in dictation provider (#3708). `GEMINI_API_KEY` registers it as `gemini`; `VOICE_PROVIDER=gemini` selects it, and without `VOICE_PROVIDER` it is used only when `DEEPGRAM_API_KEY` is unset, so Deepgram keeps precedence. The key stays on the server: each take mints a single-use ephemeral token whose constraints lock `gemini-3.5-transcribe-live`, text output and the transcription config (SMART by default, the brain's keyterms as vocabulary, at most 100 terms of 64 bytes). Any mint failure is the session route's 500 `{ error: "Gemini dictation session failed" }`, with neither the key nor Google's text. The browser's `gemini` client streams 16 kHz mono PCM16 in 100 ms frames, resampled from the hardware rate, with bounded pre-setup buffering, handshake, upload backlog and Done drain; interim text replaces the partial and each final commits once. Gemini cannot transcribe saved recordings. Live conversation's microphone capture now shares the same worklet and resampler, unchanged byte for byte. + +SDK additions: optional `SpeechProvider.label` and `destination`, `createSession({ mode?: "smart" | "verbatim" })`, and `SpeechCapabilities.smartTranscription`. The server validates the new optional fields, and `runSpeechProviderContract` checks their types and that a SMART provider mints for both modes. Keyless tests prove protocol and resource behaviour only; acceptance by Google, accuracy and latency are qualified separately. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 4815058a91..e4db2732df 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -11391,13 +11391,17 @@ signatures (every public export and the types it is made of) keyterms: boolean; endpointing: boolean; savedAudio?: boolean; + smartTranscription?: boolean; } SpeechProvider (packages/ui-sdk/src/server/speech.ts) export interface SpeechProvider { id: string; + label?: string; + destination?: string; capabilities: SpeechCapabilities; createSession(opts: { keyterms: string[]; + mode?: "smart" | "verbatim"; }): Promise; transcribeRecording?(input: { audio: Uint8Array; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 1d59be16b5..c69b8e71e3 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -2185,6 +2185,7 @@ signatures (every public export and the types it is made of) export interface VoiceConfig { provider: string | null; deepgramApiKey: string | null; + geminiApiKey?: string | null; keytermLimit: number; cacheDir: string; } diff --git a/docs/extending/speech.md b/docs/extending/speech.md index f2cf310530..4d78587bf1 100644 --- a/docs/extending/speech.md +++ b/docs/extending/speech.md @@ -45,7 +45,13 @@ never select browser speech. A mismatch or provider failure returns 500 trying another service. Validation occurs on that request, before calling an invalid provider or publishing an invalid session. -The four streaming capabilities are boolean. Optional `savedAudio` is derived from a callable `transcribeRecording`; a contradictory explicit declaration is rejected. `streaming` describes streaming recognition, +The four streaming capabilities are boolean. Optional `savedAudio` is derived from a callable `transcribeRecording`; a contradictory explicit declaration is rejected. +Optional `smartTranscription` is boolean when supplied: it declares that +`createSession` honours its optional `mode` option, `"smart"` for cleaned-up +text or `"verbatim"` for text as spoken. Absent `mode` means the provider's +default; providers without the capability ignore it. Optional `label` and +`destination` are nonempty strings naming the service and saying where +microphone audio goes. `streaming` describes streaming recognition, `interimResults` controls partial display, `keyterms` controls domain-term building, and `endpointing` distinguishes automatic utterance-end evidence from manual Done. Capabilities do not confer permissions or confidence/provenance @@ -228,6 +234,63 @@ bytes, content type, keyterms and returned text; it is required when this method is implemented. The [saved-audio tests](../../packages/ui-server/tests/saved-transcription.test.ts) exercise a fake provider through the real mounted routes without service keys. +## Built-in Gemini 3.5 Transcribe Live dictation + +Setting `GEMINI_API_KEY` registers Google's dedicated streaming transcription +model, `gemini-3.5-transcribe-live`, as the built-in `gemini` dictation +provider. `VOICE_PROVIDER=gemini` selects it explicitly. Without +`VOICE_PROVIDER` it is used only when `DEEPGRAM_API_KEY` is unset, so a host +that already has a Gemini key for chat models keeps dictating to Deepgram. +Microphone audio then streams from the browser straight to Google, and the +dictation sheet says so. + +The key stays on the server. For each take the server sends one +`POST https://generativelanguage.googleapis.com/v1beta/auth_tokens` with the +key in `x-goog-api-key` and receives a single-use ephemeral token: `uses: 1`, +60 seconds to connect (`newSessionExpireTime`, also the session's +`expiresAt`), 11 minutes overall (`expireTime`). Its `liveConnectConstraints` +lock the model, the `TEXT` response modality and the transcription config, so +the token cannot open any other Live session. The transcription config is +`mode: "SMART"` unless `createSession` receives `mode: "verbatim"`, plus the +brain's existing keyterms as `customVocabulary`: at most 100 terms of at most +64 UTF-8 bytes, in order. No chat, history, screen or corpus context is sent. +Language is detected automatically. Every mint failure returns the session +route's 500 `{ "error": "Gemini dictation session failed" }`; neither the key +nor Google's response text appears in a response, log or error, and no other +provider is tried. Capabilities are `streaming`, `interimResults`, `keyterms` +and `smartTranscription`; `endpointing` is false, so the sheet keeps a manual +Done. There is no saved-recording transcription, so `savedAudio` is false. + +The session URL is Google's constrained Live endpoint +(`…v1alpha.GenerativeService.BidiGenerateContentConstrained`, the path the +installed `@google/genai` 2.24.0 uses; Google's token guide says `v1beta`, and +[#3710](https://github.com/schlessera/brain-kit/issues/3710) qualifies which +one Google accepts). The browser client `GeminiAsrClient`, registered as +`gemini` by `registerAsrClients`, appends `?access_token=`, sends the +same model and transcription config as its setup, and streams mono PCM16 LE at +16 kHz in 100 ms frames (3,200 bytes) as base64 `realtimeInput.audio`. Its +AudioWorklet captures at the hardware rate and resamples; it never assumes a +16 kHz context. Up to 5 seconds of audio wait for `setupComplete`; more than +that, a 10-second handshake, a socket error or an upload backlog above +256 KiB ends the take with a connection failure rather than dropping audio. +`interimInputTranscription` text replaces the partial; each +`inputTranscription` text is one final (`endsTurn` from `finished`, true when +absent). Done stops the microphone, sends the last partial frame and +`audioStreamEnd`, and waits up to 3 seconds for a `finished` final or +`turnComplete`. A hard stop, cancel or unmount releases the tracks, +AudioContext, worklet, timers, queue and socket. There is no session +resumption: Google ends a session after 10 minutes, and the take then ends as +provider-ended, with the words heard kept for review. + +The keyless [server proof](../../packages/ui-server/tests/gemini-speech.test.ts) +runs the published provider conformance and the mounted routes against a +loopback `auth_tokens` double. The [client proof](../../packages/ui-react/tests/asr-gemini.test.ts) +runs the published client conformance and the wire bounds, and the +[Chromium proof](../../packages/ui-react/tests/browser/dictation-gemini.offline.tsx) +dictates through the real ChatPage, worklet and 44.1/48 kHz contexts against +an offline socket. They show protocol and resource behaviour, not that Google +accepts the token or how accurate or fast it is; that is #3710. + ## Live conversation with Gemini Conversation is separate from dictation. Register the fixed Gemini adapter diff --git a/docs/http-api.md b/docs/http-api.md index fdac577570..9d46618b31 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -845,7 +845,7 @@ SDK speech-session payloads rather than exposing long-lived provider keys: | Supported operation | Inputs/defaults | Success | Errors and behavior | | --- | --- | --- | --- | -| POST `/api/voice/session` | No inputs; configured active speech provider, including `createApp({ speechProvider })` | `VoiceSessionResponse`: providerId, connection url, optional token/params, expiresAt and capabilities (streaming, interimResults, keyterms, endpointing, derived savedAudio) | 500 `{ error }` for unavailable provider/minting, invalid provider/session, or explicit provider/value mismatch; no fallback. Keyterms are included only when supported by the provider; browser/local sessions can omit token and use empty URL/zero expiry. | +| POST `/api/voice/session` | No inputs; configured active speech provider, including `createApp({ speechProvider })` and the built-in `gemini` | `VoiceSessionResponse`: providerId, connection url, optional token/params, expiresAt and capabilities (streaming, interimResults, keyterms, endpointing, derived savedAudio, optional smartTranscription) | 500 `{ error }` for unavailable provider/minting, invalid provider/session, or explicit provider/value mismatch; no fallback. Gemini mint failures are always `{ error: "Gemini dictation session failed" }`, never Google's text. Keyterms are included only when supported by the provider; browser/local sessions can omit token and use empty URL/zero expiry. | | POST `/api/voice/token` | No inputs | `{ token, expiresAt }` | Deprecated Deepgram-specific alias retained for client migration; mints directly with 60-second requested TTL, 500 `{ error }` on failure. | | GET `/api/voice/keyterms` | `rebuild=1` forces cache rebuild; all other values read normal cache | `{ keyterms: string[], generatedAt, count }` | 500 `{ error }` on read/build failure, including a missing, corrupt, locked or unreadable index. Without a usable optional `@schlessera/brain` peer, or with an index version core cannot read, 200 with an empty vocabulary that is never cached ([optional core peer](integration-contract/package-api.md#ui-server-optional-core-peer-breaking-host-migration-697)). | | GET `/api/voice/overrides` | No inputs | `{ overrides: [{ match, replacement }] }` | Configured pronunciation replacements; 500 `{ error }` on cache read/build failure. | diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index fa42f0ecdd..34745dd4df 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1528,6 +1528,47 @@ its protocol-specific authentication, capture and failure behavior. The [authoring guide](../extending/speech.md) supplies complete public server/client examples and points to executable harnesses and real route/Chrome integration. +Additive (#3708): `SpeechProvider` gains optional `label?: string` and +`destination?: string`, and `createSession` options gain optional +`mode?: "smart" | "verbatim"`. `SpeechCapabilities` gains optional +`smartTranscription?: boolean`, which declares that the provider honours +`mode`; providers without it ignore the option, and an absent mode means the +provider's default. The server rejects a supplied label or destination that is +not a nonempty string, and a non-boolean `smartTranscription`, with the +existing 500 envelope. The published provider suite checks the same types and, +for a SMART provider, that both modes mint a serializable session. The mounted +session route sends no mode yet, so SMART providers use their default. + +The built-in `gemini` provider (`gemini-3.5-transcribe-live`) is selected by +`VOICE_PROVIDER=gemini` and, without `VOICE_PROVIDER`, only when +`GEMINI_API_KEY` is set and `DEEPGRAM_API_KEY` is not. `VOICE_PROVIDER=gemini` +without the key is a selection error. Its capabilities are `streaming`, +`interimResults`, `keyterms` and `smartTranscription` true, `endpointing` +false, and `savedAudio` false. Each session is one +`POST https://generativelanguage.googleapis.com/v1beta/auth_tokens` +(`x-goog-api-key`) minting a single-use token (`uses: 1`, connect within 60 s, +expire after 11 min) whose `liveConnectConstraints` lock +`models/gemini-3.5-transcribe-live`, `responseModalities: ["TEXT"]` and +`inputAudioTranscription` (`mode` `SMART` unless `verbatim` is requested; +`customVocabulary` from the keyterms, at most 100 terms of at most 64 UTF-8 +bytes, omitted when empty), with `lockAdditionalFields: []`. The session is +`{ url: , token: "auth_tokens/…", +expiresAt: , params: { model, mode, sampleRate: "16000", +vocabulary: } }`. Any mint failure is 500 +`{ error: "Gemini dictation session failed" }` without the key or Google's +text, and no other provider is tried. There is no session resumption: Google's +10-minute session limit ends the take through the client's provider-ended +path. The root-registered `gemini` `AsrClient` appends `access_token`, repeats +the locked setup, and streams mono PCM16 LE at 16 kHz in 100 ms base64 +`realtimeInput.audio` frames, resampled from the hardware rate. Its bounds are +5 s of audio before `setupComplete`, a 10 s handshake, a 256 KiB upload +backlog (each failing the take as a network error), and a 3 s wait for the +final after `audioStreamEnd` on Done. Interim text is a replacing partial; +each final transcription is one final, `endsTurn` from `finished` (true when +absent). Keyless proofs establish protocol and resource behaviour, not +Google's acceptance, accuracy or latency +([#3710](https://github.com/schlessera/brain-kit/issues/3710)). + ### Saved-audio transcription (additive, #1021) diff --git a/docs/supported-inputs.md b/docs/supported-inputs.md index ff35942f17..5697d6392b 100644 --- a/docs/supported-inputs.md +++ b/docs/supported-inputs.md @@ -551,7 +551,7 @@ promote ambient SDK variables to supported inputs. | [ui-backend-claude](../packages/ui-backend-claude/README.md#environment) | `BRAIN_UI_EXEC_WRAPPER`, `BRAIN_UI_EXEC_KILLER`, `BRAIN_UI_SUBPROCESS_ENV_EXTRA`, `ANTHROPIC_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN`, `ANTHROPIC_BASE_URL`, `BRAIN_UI_REVERSE_GEOCODE`, `NOMINATIM_PUBLIC_SERVICE_ELIGIBLE`, `NOMINATIM_URL`, `NOMINATIM_USER_AGENT` | | [ui-backend-pi](../packages/ui-backend-pi/README.md#environment) | `BRAIN_UI_EXEC_WRAPPER`, `BRAIN_UI_EXEC_KILLER`, `BRAIN_UI_SUBPROCESS_ENV_EXTRA`, `GEMINI_API_KEY`, `BRAIN_UI_REVERSE_GEOCODE`, `NOMINATIM_PUBLIC_SERVICE_ELIGIBLE`, `NOMINATIM_URL`, `NOMINATIM_USER_AGENT` | | [ui-render-puppeteer](../packages/ui-render-puppeteer/README.md#environment) | `PUPPETEER_EXECUTABLE_PATH`, `BRAIN_UI_CHROME_PATH` | -| [ui-server](../packages/ui-server/README.md#environment) | `BRAIN_UI_AUTONOMOUS_SPEND_USD_PER_DAY`, `BRAIN_UI_AUTONOMOUS_TURNS_PER_DAY`, `BRAIN_UI_AUTONOMOUS_EMERGENCY_SPEND_USD`, `BRAIN_UI_AUTONOMOUS_EMERGENCY_TURNS`, `BRAIN_UI_AUTONOMOUS_TIMEZONE`, `BRAIN_UI_AUTONOMOUS_UNPRICED_USD_PER_TOKEN`, `BRAIN_UI_ASK_USER_FORM_MAX_DEPTH`, `BRAIN_UI_ASK_USER_FORM_MAX_NODES`, `BRAIN_UI_ASK_USER_FORM_MAX_OPTIONS`, `BRAIN_UI_EXEC_KILLER`, `BRAIN_UI_EXEC_WRAPPER`, `BRAIN_PATH`, `HOME`, `BRAIN_UI_CRON_HYGIENE`, `BRAIN_UI_SUBPROCESS_ENV_EXTRA`, `PI_CODING_AGENT_DIR`, `XDG_CONFIG_HOME`, `BRAIN_UI_SKILLS_GITHUB_TOKEN`, `GITHUB_TOKEN`, `DB_PATH`, `HOST`, `BRAIN_UI_INBOX_POKE_TOKEN_FILE`, `MAX_AUTONOMOUS_RUNS`, `BRAIN_UI_AUTONOMOUS_YIELD_AFTER_MS`, `BRAIN_UI_CONFIRM_BASH`, `BRAIN_UI_WS_MAX_CONNECTIONS`, `BRAIN_UI_WS_RATE`, `BRAIN_UI_WS_BURST`, `BRAIN_UI_LOG_LEVEL`, `SOURCE_COMMIT`, `ALLOWED_ORIGINS`, `MAX_CONCURRENT_SESSIONS`, `BRAIN_UI_ATTACHMENT_POOL_BYTES`, `BRAIN_UI_WORKER_STATE_BYTES`, `BRAIN_UI_WORKER_STATE_BUDGET_BYTES`, `BRAIN_UI_TURN_TEMP_BYTES`, `BRAIN_UI_TURN_TEMP_BUDGET_BYTES`, `BRAIN_UI_MAINTENANCE_TEMP_BYTES`, `BRAIN_UI_MAINTENANCE_TEMP_BUDGET_BYTES`, `BRAIN_UI_TURN_TIMEOUT_MS`, `AUTH_MODE`, `BRAIN_UI_PASSWORD_HASH`, `COOKIE_SECRET`, `TRUST_PROXY`, `TRUST_PROXY_HOPS`, `PROXY_AUTH_HEADER`, `BRAIN_UI_DANGEROUSLY_DISABLE_AUTH`, `BRAIN_UI_ALLOW_PASSWORD`, `WEBAUTHN_RP_NAME`, `WEBAUTHN_USER_NAME`, `WEBAUTHN_USER_ID`, `WEBAUTHN_RP_ID`, `WEBAUTHN_ORIGINS`, `BRAIN_UI_ALLOW_LOOPBACK_ORIGIN`, `AGENT_BACKEND`, `TYPESAFE_API_KEY`, `CLAUDE_CODE_PATH`, `BRAIN_UI_CLAUDE_DEFAULT_MODEL`, `BRAIN_UI_CLAUDE_DEFAULT_THINKING_LEVEL`, `BRAIN_UI_CLAUDE_PROFILES`, `BRAIN_UI_PI_PROFILES`, `CLAUDE_CODE_OAUTH_TOKEN`, `BRAIN_UI_CLAUDE_TOKEN_MINTED_AT`, `ANTHROPIC_API_KEY`, `BRAIN_UI_MODEL_DISCOVERY`, `BRAIN_UI_MODEL_TTL_HOURS`, `BRAIN_UI_PRICING_DISCOVERY`, `BRAIN_UI_PRICING_TTL_HOURS`, `NODE_ENV`, `APIFY_TOKEN`, `BRAIN_APIFY_LEDGER`, `DEEPGRAM_API_KEY`, `VOICE_PROVIDER`, `VOICE_KEYTERM_LIMIT`, `VOICE_CACHE_DIR`, `BRAIN_UI_COASTLINE`, `OVERPASS_URL`, `OVERPASS_USER_AGENT`, `COASTLINE_CACHE_DIR`, `BRAIN_GEO_CONFIG_JSON` | +| [ui-server](../packages/ui-server/README.md#environment) | `BRAIN_UI_AUTONOMOUS_SPEND_USD_PER_DAY`, `BRAIN_UI_AUTONOMOUS_TURNS_PER_DAY`, `BRAIN_UI_AUTONOMOUS_EMERGENCY_SPEND_USD`, `BRAIN_UI_AUTONOMOUS_EMERGENCY_TURNS`, `BRAIN_UI_AUTONOMOUS_TIMEZONE`, `BRAIN_UI_AUTONOMOUS_UNPRICED_USD_PER_TOKEN`, `BRAIN_UI_ASK_USER_FORM_MAX_DEPTH`, `BRAIN_UI_ASK_USER_FORM_MAX_NODES`, `BRAIN_UI_ASK_USER_FORM_MAX_OPTIONS`, `BRAIN_UI_EXEC_KILLER`, `BRAIN_UI_EXEC_WRAPPER`, `BRAIN_PATH`, `HOME`, `BRAIN_UI_CRON_HYGIENE`, `BRAIN_UI_SUBPROCESS_ENV_EXTRA`, `PI_CODING_AGENT_DIR`, `XDG_CONFIG_HOME`, `BRAIN_UI_SKILLS_GITHUB_TOKEN`, `GITHUB_TOKEN`, `DB_PATH`, `HOST`, `BRAIN_UI_INBOX_POKE_TOKEN_FILE`, `MAX_AUTONOMOUS_RUNS`, `BRAIN_UI_AUTONOMOUS_YIELD_AFTER_MS`, `BRAIN_UI_CONFIRM_BASH`, `BRAIN_UI_WS_MAX_CONNECTIONS`, `BRAIN_UI_WS_RATE`, `BRAIN_UI_WS_BURST`, `BRAIN_UI_LOG_LEVEL`, `SOURCE_COMMIT`, `ALLOWED_ORIGINS`, `MAX_CONCURRENT_SESSIONS`, `BRAIN_UI_ATTACHMENT_POOL_BYTES`, `BRAIN_UI_WORKER_STATE_BYTES`, `BRAIN_UI_WORKER_STATE_BUDGET_BYTES`, `BRAIN_UI_TURN_TEMP_BYTES`, `BRAIN_UI_TURN_TEMP_BUDGET_BYTES`, `BRAIN_UI_MAINTENANCE_TEMP_BYTES`, `BRAIN_UI_MAINTENANCE_TEMP_BUDGET_BYTES`, `BRAIN_UI_TURN_TIMEOUT_MS`, `AUTH_MODE`, `BRAIN_UI_PASSWORD_HASH`, `COOKIE_SECRET`, `TRUST_PROXY`, `TRUST_PROXY_HOPS`, `PROXY_AUTH_HEADER`, `BRAIN_UI_DANGEROUSLY_DISABLE_AUTH`, `BRAIN_UI_ALLOW_PASSWORD`, `WEBAUTHN_RP_NAME`, `WEBAUTHN_USER_NAME`, `WEBAUTHN_USER_ID`, `WEBAUTHN_RP_ID`, `WEBAUTHN_ORIGINS`, `BRAIN_UI_ALLOW_LOOPBACK_ORIGIN`, `AGENT_BACKEND`, `TYPESAFE_API_KEY`, `CLAUDE_CODE_PATH`, `BRAIN_UI_CLAUDE_DEFAULT_MODEL`, `BRAIN_UI_CLAUDE_DEFAULT_THINKING_LEVEL`, `BRAIN_UI_CLAUDE_PROFILES`, `BRAIN_UI_PI_PROFILES`, `CLAUDE_CODE_OAUTH_TOKEN`, `BRAIN_UI_CLAUDE_TOKEN_MINTED_AT`, `ANTHROPIC_API_KEY`, `BRAIN_UI_MODEL_DISCOVERY`, `BRAIN_UI_MODEL_TTL_HOURS`, `BRAIN_UI_PRICING_DISCOVERY`, `BRAIN_UI_PRICING_TTL_HOURS`, `NODE_ENV`, `APIFY_TOKEN`, `BRAIN_APIFY_LEDGER`, `DEEPGRAM_API_KEY`, `GEMINI_API_KEY`, `VOICE_PROVIDER`, `VOICE_KEYTERM_LIMIT`, `VOICE_CACHE_DIR`, `BRAIN_UI_COASTLINE`, `OVERPASS_URL`, `OVERPASS_USER_AGENT`, `COASTLINE_CACHE_DIR`, `BRAIN_GEO_CONFIG_JSON` | Static secrets and names selected by config are read when needed. Server factory configuration is resolved when the app is created; it is not a promise of live diff --git a/packages/ui-react/src/components/voice/dictation-sheet.tsx b/packages/ui-react/src/components/voice/dictation-sheet.tsx index 318ff352f7..5fd997dae6 100644 --- a/packages/ui-react/src/components/voice/dictation-sheet.tsx +++ b/packages/ui-react/src/components/voice/dictation-sheet.tsx @@ -186,6 +186,8 @@ function providerNoteFor( switch (providerId) { case "deepgram": return { text: "via Deepgram", warn: false }; + case "gemini": + return { text: "via Google Gemini · audio goes to Google", warn: true }; case "webspeech": // Browser speech (Chrome) streams mic audio to Google — call it out. return { text: "via browser speech · audio goes to Google", warn: true }; diff --git a/packages/ui-react/src/voice/asr-clients.ts b/packages/ui-react/src/voice/asr-clients.ts index bafc43f1b6..d916656ea5 100644 --- a/packages/ui-react/src/voice/asr-clients.ts +++ b/packages/ui-react/src/voice/asr-clients.ts @@ -10,6 +10,7 @@ import type { BrainUiRoot } from "../root.js"; import { defaultRoot } from "../default-root.js"; import { DeepgramClient } from "./asr-deepgram.js"; +import { GeminiAsrClient } from "./asr-gemini.js"; import { WebSpeechClient } from "./asr-webspeech.js"; import { providerEnded } from "./dictation-capture.js"; @@ -28,6 +29,21 @@ export function registerAsrClients(root: BrainUiRoot = defaultRoot): void { return client; }); + root.asr.register("gemini", (opts) => { + const client: GeminiAsrClient = new GeminiAsrClient({ + url: opts.session.url, + token: opts.session.token ?? "", + params: opts.session.params ?? {}, + onEvent: opts.onEvent, + onError: opts.onError, + onAudioLevel: (level) => root.stores.voice.getState().setAudioLevel(level), + // The session ended without a stop(): Google's session limit, an + // expired token, an error or a drop. What was heard goes to review. + onClose: () => providerEnded(root.stores, client), + }); + return client; + }); + root.asr.register("webspeech", (opts) => { const client: WebSpeechClient = new WebSpeechClient({ onEvent: opts.onEvent, diff --git a/packages/ui-react/src/voice/asr-gemini.ts b/packages/ui-react/src/voice/asr-gemini.ts new file mode 100644 index 0000000000..77ca334501 --- /dev/null +++ b/packages/ui-react/src/voice/asr-gemini.ts @@ -0,0 +1,274 @@ +// Gemini 3.5 Transcribe Live dictation client (#3708). +// The server mints a single-use constrained token and the constrained Live +// endpoint; this client opens the socket with it, sends the setup the token +// locks, streams 16 kHz mono PCM16 LE in 100 ms frames and reports interim +// text as partials and finalized segments as finals. Wire shapes follow the +// Live Transcribe guide; design: docs/plans/selectable-dictation.md §6. +// +// Every bound is explicit: 5 s of audio may wait for setupComplete, the +// handshake has 10 s, and an upload backlog over 256 KiB fails the take with +// a network error. Audio is never dropped silently. Provider text (errors, +// goAway, close reasons) never reaches the user or a log. + +import { z } from "zod"; +import type { AsrClient } from "@schlessera/brain-ui-sdk/client"; +import { CONVERSATION_LIMITS, type AsrEvent } from "@schlessera/brain-ui-sdk/protocol"; +import { speechError } from "./dictation-failure.js"; +import { openPcmMicrophone, pcm16Bytes, type PcmMicrophone } from "./pcm-capture.js"; + +const GEMINI_SAMPLE_RATE = 16_000; +/** 100 ms of 16 kHz mono PCM16: 1,600 samples, 3,200 bytes. */ +export const GEMINI_FRAME_SAMPLES = 1_600; +/** Frames that may wait for setupComplete: 5 s of audio. */ +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. */ +export const GEMINI_DRAIN_MS = 3_000; +const MAX_MESSAGE_BYTES = 262_144; +const MODEL = "models/gemini-3.5-transcribe-live"; +const MIME = `audio/pcm;rate=${GEMINI_SAMPLE_RATE}`; + +const transcript = z.object({ text: z.string().max(CONVERSATION_LIMITS.maxFragmentChars).optional(), finished: z.boolean().optional() }); +const messageSchema = z.object({ + setupComplete: z.object({}).optional(), + serverContent: z.object({ + interimInputTranscription: transcript.optional(), + inputTranscription: transcript.optional(), + turnComplete: z.boolean().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); + +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. */ + params: Record; + onEvent: (event: AsrEvent) => void; + onError?: (error: Error) => void; + onAudioLevel?: (level: number) => void; + /** The provider ended the take without a stop(): close, expiry, error. */ + onClose?: () => void; +} + +type Phase = "idle" | "live" | "draining" | "closed"; + +export class GeminiAsrClient implements AsrClient { + private phase: Phase = "idle"; + private socket: WebSocket | null = null; + private microphone: PcmMicrophone | null = null; + private setupDone = false; + private handshake: ReturnType | null = null; + /** Frames waiting for setupComplete, oldest first. */ + private queue: string[] = []; + private frame = new Int16Array(GEMINI_FRAME_SAMPLES); + private filled = 0; + private reported = false; + private settleDrain: (() => void) | null = null; + private inbound: Promise = Promise.resolve(); + private readonly setup: string; + + constructor(private readonly opts: GeminiAsrClientOptions) { + const params = opts.params ?? {}; + const mode = params.mode === "VERBATIM" ? "VERBATIM" : "SMART"; + let vocabulary: string[] = []; + try { vocabulary = vocabularySchema.parse(JSON.parse(params.vocabulary ?? "[]")); } catch { vocabulary = []; } + this.setup = JSON.stringify({ + setup: { + model: params.model || MODEL, + generationConfig: { responseModalities: ["TEXT"] }, + inputAudioTranscription: { mode, ...(vocabulary.length ? { customVocabulary: vocabulary } : {}) }, + }, + }); + } + + async start(): Promise { + if (this.phase !== "idle") return; + let url: URL; + try { url = new URL(this.opts.url); } catch { this.phase = "closed"; throw speechError("Gemini session material is invalid", "network"); } + url.searchParams.set("access_token", this.opts.token); + this.phase = "live"; + const socket = new WebSocket(url.toString()); + socket.binaryType = "arraybuffer"; + this.socket = socket; + this.handshake = setTimeout(() => this.fail("Gemini handshake timed out", "network"), GEMINI_HANDSHAKE_MS); + socket.onopen = () => { if (this.socket === socket) socket.send(this.setup); }; + socket.onmessage = (event: MessageEvent) => { + if (this.socket !== socket) return; + const data: unknown = event.data; + // Keep arrival order even for a Blob, whose text resolves later. + this.inbound = this.inbound.then(async () => { + const text = typeof data === "string" ? data + : data instanceof ArrayBuffer ? new TextDecoder().decode(data) + : typeof Blob !== "undefined" && data instanceof Blob ? await data.text() : null; + if (this.socket === socket) this.receive(text); + }); + }; + socket.onerror = () => { if (this.socket === socket) this.fail("Gemini socket error", "network"); }; + socket.onclose = (event: CloseEvent) => { + if (this.socket !== socket) return; + if (this.phase === "draining") { this.finishDrain(); return; } + // A clean close (Google's session limit, an expired token) ends the + // take; anything else is also a connection failure. + if (event.code !== 1000) this.report("Gemini session closed", "network"); + this.end(); + }; + + this.microphone = openPcmMicrophone(GEMINI_SAMPLE_RATE, (pcm, rms) => this.capture(pcm, rms), () => {}, () => this.fail("Microphone ended", "audio-capture")); + try { + await this.microphone.ready; + } catch (error) { + this.phase = "closed"; + this.teardown(); + throw error; + } + } + + /** Hard stop: release everything now and ignore whatever arrives later. */ + stop(): void { + this.phase = "closed"; + this.teardown(); + } + + /** Done: end the input, wait up to 3 s for the last final, then close. Heard words are kept. */ + async drainAndStop(): Promise { + if (this.phase !== "live") { this.stop(); return; } + this.phase = "draining"; + this.microphone?.stop(); + this.opts.onAudioLevel?.(0); + await new Promise((resolve) => { + const timer = setTimeout(() => this.finishDrain(), GEMINI_DRAIN_MS); + this.settleDrain = () => { clearTimeout(timer); resolve(); }; + if (this.filled) { + this.enqueue(this.frame.slice(0, this.filled)); + this.filled = 0; + } + // Before setupComplete the stream end waits with the queued audio. + if (this.setupDone) this.endInput(); + }); + this.stop(); + } + + private capture(pcm: Int16Array, rms: number): void { + if (this.phase !== "live") return; + this.opts.onAudioLevel?.(Math.min(1, rms * 4)); + let offset = 0; + while (offset < pcm.length && this.phase === "live") { + const take = Math.min(GEMINI_FRAME_SAMPLES - this.filled, pcm.length - offset); + this.frame.set(pcm.subarray(offset, offset + take), this.filled); + this.filled += take; + offset += take; + if (this.filled === GEMINI_FRAME_SAMPLES) { + this.filled = 0; + this.enqueue(this.frame.slice()); + } + } + } + + private enqueue(samples: Int16Array): void { + const bytes = pcm16Bytes(samples); + let binary = ""; + for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]!); + const frame = JSON.stringify({ realtimeInput: { audio: { data: btoa(binary), mimeType: MIME } } }); + if (!this.setupDone) { + if (this.queue.length >= GEMINI_PRESETUP_FRAMES) { this.fail("Gemini setup did not complete in time", "network"); return; } + this.queue.push(frame); + return; + } + this.send(frame); + } + + private send(frame: string): boolean { + const socket = this.socket; + if (!socket || socket.readyState !== WebSocket.OPEN) { this.fail("Gemini socket is not open", "network"); return false; } + if (socket.bufferedAmount > GEMINI_MAX_BUFFERED_BYTES) { this.fail("Gemini upload stalled", "network"); return false; } + socket.send(frame); + return true; + } + + private endInput(): void { + for (const frame of this.queue.splice(0)) if (!this.send(frame)) return; + this.send(JSON.stringify({ realtimeInput: { audioStreamEnd: true } })); + } + + private receive(text: string | null): void { + if (this.phase === "closed" || this.phase === "idle") return; + let message: z.infer; + try { + if (text === null || text.length > MAX_MESSAGE_BYTES) throw new Error("oversized"); + message = messageSchema.parse(JSON.parse(text)); + } catch { + this.fail("Gemini message rejected", "unknown"); + return; + } + if (message.error !== undefined) { this.fail("Gemini reported an error", "unknown"); return; } + if (message.setupComplete && !this.setupDone) { + this.setupDone = true; + if (this.handshake) { clearTimeout(this.handshake); this.handshake = null; } + if (this.phase === "draining") this.endInput(); + else for (const frame of this.queue.splice(0)) if (!this.send(frame)) return; + } + const content = message.serverContent; + const interim = content?.interimInputTranscription?.text; + // Interim text replaces the current partial, during Done too: if no final + // follows within the drain bound, what was last heard still reaches review. + 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(); + // 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 { + const settle = this.settleDrain; + this.settleDrain = null; + settle?.(); + } + + /** One error per take, by category only. */ + private report(message: string, code: string): void { + if (this.reported) return; + this.reported = true; + this.opts.onError?.(speechError(message, code)); + } + + private fail(message: string, code: string): void { + if (this.phase === "closed" || this.phase === "idle") return; + this.report(message, code); + if (this.phase === "draining") { this.finishDrain(); return; } + this.end(); + } + + /** The provider side ended a live take: release, then hand the words to review once. */ + private end(): void { + if (this.phase !== "live") return; + this.phase = "closed"; + this.teardown(); + this.opts.onClose?.(); + } + + private teardown(): void { + if (this.handshake) { clearTimeout(this.handshake); this.handshake = null; } + this.microphone?.stop(); + this.microphone = null; + this.queue = []; + this.filled = 0; + const socket = this.socket; + this.socket = null; + if (socket) { + socket.onopen = null; socket.onmessage = null; socket.onerror = null; socket.onclose = null; + if (socket.readyState === WebSocket.CONNECTING || socket.readyState === WebSocket.OPEN) { + try { socket.close(1000); } catch {} + } + } + this.finishDrain(); + } +} diff --git a/packages/ui-react/src/voice/conversation-pcm.ts b/packages/ui-react/src/voice/conversation-pcm.ts index df20ac7b01..de4da868e5 100644 --- a/packages/ui-react/src/voice/conversation-pcm.ts +++ b/packages/ui-react/src/voice/conversation-pcm.ts @@ -1,68 +1,9 @@ import type { ConversationAudioFormat, ConversationPlayback } from "@schlessera/brain-ui-sdk/protocol"; +import { openPcmMicrophone, pcm16Bytes } from "./pcm-capture.js"; /** Concrete browser PCM transport. No recorder codec or independent speech service. */ export function openConversationMicrophone(rate: number, receive: (pcm: Uint8Array, speaking: boolean) => void, opened: () => void, interrupted: () => void) { - let stopped = false; - let stream: MediaStream | undefined; - let context: AudioContext | undefined; - let node: AudioWorkletNode | undefined; - let source: MediaStreamAudioSourceNode | undefined; - const stop = () => { - stopped = true; - if (node) { node.port.onmessage = null; node.disconnect(); } - source?.disconnect(); - stream?.getTracks().forEach((track) => track.stop()); - if (context && context.state !== "closed") void context.close(); - }; - const ready = (async () => { - try { - stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true }, video: false }); - if (stopped) { stop(); return; } - for (const track of stream.getAudioTracks()) track.addEventListener("ended", () => { if (!stopped) { stop(); interrupted(); } }, { once: true }); - context = new AudioContext(); - const code = `class Capture extends AudioWorkletProcessor { - constructor() { super(); this.samples = new Float32Array(4096); this.used = 0; } - process(inputs) { - const input = inputs[0]?.[0]; - if (input) for (const sample of input) { - this.samples[this.used++] = sample; - if (this.used === this.samples.length) { - this.port.postMessage(this.samples.slice()); this.used = 0; - } - } - return true; - } - } registerProcessor("brain-conversation-capture", Capture);`; - const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" })); - try { await context.audioWorklet.addModule(url); } finally { URL.revokeObjectURL(url); } - if (stopped) { stop(); return; } - source = context.createMediaStreamSource(stream); - node = new AudioWorkletNode(context, "brain-conversation-capture", { numberOfInputs: 1, numberOfOutputs: 0 }); - const ratio = context.sampleRate / rate; - let cursor = 0; - node.port.onmessage = ({ data }: MessageEvent) => { - if (stopped) return; - const samples: number[] = []; - let energy = 0; - for (const value of data) energy += value * value; - for (; cursor < data.length; cursor += ratio) { - const at = Math.floor(cursor); - const value = data[at]! + ((data[Math.min(at + 1, data.length - 1)] ?? 0) - data[at]!) * (cursor - at); - samples.push(Math.round(Math.max(-1, Math.min(1, value)) * (value < 0 ? 32768 : 32767))); - } - cursor -= data.length; - const bytes = new Uint8Array(samples.length * 2); - const view = new DataView(bytes.buffer); - samples.forEach((sample, index) => view.setInt16(index * 2, sample, true)); - receive(bytes, Math.sqrt(energy / data.length) > 0.015); - }; - source.connect(node); - await context.resume(); - if (stopped) { stop(); return; } - opened(); - } catch (error) { stop(); throw error; } - })(); - return { ready, stop }; + return openPcmMicrophone(rate, (pcm, rms) => receive(pcm16Bytes(pcm), rms > 0.015), opened, interrupted); } /** One queue owns all local output, including chunks waiting for a quiet boundary. */ diff --git a/packages/ui-react/src/voice/pcm-capture.ts b/packages/ui-react/src/voice/pcm-capture.ts new file mode 100644 index 0000000000..546dca2743 --- /dev/null +++ b/packages/ui-react/src/voice/pcm-capture.ts @@ -0,0 +1,107 @@ +/** + * Browser microphone → mono PCM16 LE at a requested rate, through an + * AudioWorklet. Shared by live conversation and Gemini dictation (#3708); it + * holds no state of either. The AudioContext runs at the hardware rate + * (never assumed to be the target rate) and every block is resampled here. + */ + +/** + * Streaming linear resampler, Float32 at `from` Hz → Int16 at `to` Hz. The + * fractional position carries across blocks. Byte-for-byte the algorithm live + * conversation has always used (its PCM witness tests depend on that): the + * last output position of a block interpolates toward that block's own last + * sample rather than the next block's first. + */ +export function createPcmResampler(from: number, to: number): (block: Float32Array) => Int16Array { + if (!(from > 0) || !(to > 0)) throw new Error("PCM resampler rates must be positive."); + const step = from / to; + let cursor = 0; + return (block) => { + const out: number[] = []; + for (; cursor < block.length; cursor += step) { + const at = Math.floor(cursor); + const value = block[at]! + ((block[Math.min(at + 1, block.length - 1)] ?? 0) - block[at]!) * (cursor - at); + out.push(Math.round(Math.max(-1, Math.min(1, value)) * (value < 0 ? 32768 : 32767))); + } + cursor -= block.length; + return Int16Array.from(out); + }; +} + +export interface PcmMicrophone { + /** Resolves once audio flows; rejects when the microphone or worklet cannot open. */ + ready: Promise; + /** Idempotent hard stop: worklet, source, tracks and AudioContext. */ + stop(): void; +} + +/** + * Open the microphone and deliver resampled PCM16 LE blocks with their RMS + * level. `interrupted` reports a track the browser ended (device unplugged, + * permission revoked) after capture opened. + */ +export function openPcmMicrophone( + rate: number, + receive: (pcm: Int16Array, rms: number) => void, + opened: () => void, + interrupted: () => void, +): PcmMicrophone { + let stopped = false; + let stream: MediaStream | undefined; + let context: AudioContext | undefined; + let node: AudioWorkletNode | undefined; + let source: MediaStreamAudioSourceNode | undefined; + const stop = () => { + stopped = true; + if (node) { node.port.onmessage = null; node.disconnect(); node = undefined; } + source?.disconnect(); source = undefined; + stream?.getTracks().forEach((track) => track.stop()); + if (context && context.state !== "closed") void context.close().catch(() => {}); + }; + const ready = (async () => { + try { + stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true }, video: false }); + if (stopped) { stop(); return; } + for (const track of stream.getAudioTracks()) track.addEventListener("ended", () => { if (!stopped) { stop(); interrupted(); } }, { once: true }); + context = new AudioContext(); + const code = `class Capture extends AudioWorkletProcessor { + constructor() { super(); this.samples = new Float32Array(4096); this.used = 0; } + process(inputs) { + const input = inputs[0]?.[0]; + if (input) for (const sample of input) { + this.samples[this.used++] = sample; + if (this.used === this.samples.length) { + this.port.postMessage(this.samples.slice()); this.used = 0; + } + } + return true; + } + } registerProcessor("brain-pcm-capture", Capture);`; + const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" })); + try { await context.audioWorklet.addModule(url); } finally { URL.revokeObjectURL(url); } + if (stopped) { stop(); return; } + source = context.createMediaStreamSource(stream); + node = new AudioWorkletNode(context, "brain-pcm-capture", { numberOfInputs: 1, numberOfOutputs: 0 }); + const resample = createPcmResampler(context.sampleRate, rate); + node.port.onmessage = ({ data }: MessageEvent) => { + if (stopped) return; + let energy = 0; + for (const value of data) energy += value * value; + receive(resample(data), data.length ? Math.sqrt(energy / data.length) : 0); + }; + source.connect(node); + await context.resume(); + if (stopped) { stop(); return; } + opened(); + } catch (error) { stop(); throw error; } + })(); + return { ready, stop }; +} + +/** Little-endian bytes of PCM16 samples, independent of platform endianness. */ +export function pcm16Bytes(samples: Int16Array): Uint8Array { + const bytes = new Uint8Array(samples.length * 2); + const view = new DataView(bytes.buffer); + for (let i = 0; i < samples.length; i++) view.setInt16(i * 2, samples[i]!, true); + return bytes; +} diff --git a/packages/ui-react/tests/asr-gemini.test.ts b/packages/ui-react/tests/asr-gemini.test.ts new file mode 100644 index 0000000000..5c353cfb81 --- /dev/null +++ b/packages/ui-react/tests/asr-gemini.test.ts @@ -0,0 +1,411 @@ +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, +} from "../src/voice/asr-gemini"; +import { createPcmResampler } from "../src/voice/pcm-capture"; + +/** + * GeminiAsrClient against a scripted microphone, AudioContext/worklet and + * socket. Wire shapes follow the Live Transcribe guide. Real-Chrome capture + * (actual worklet, 44.1/48 kHz contexts, mounted ChatPage) is + * tests/browser/dictation-gemini.offline.tsx. + */ + +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 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 } }; + +function replaceGlobals(values: Record): () => void { + const originals = Object.keys(values).map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const); + for (const [name, value] of Object.entries(values)) Object.defineProperty(globalThis, name, { configurable: true, writable: true, value }); + return () => { for (const [name, original] of originals) { if (original) Object.defineProperty(globalThis, name, original); else Reflect.deleteProperty(globalThis, name); } }; +} + +interface Timer { id: number; at: number; run: () => void } + +/** A scripted browser: microphone, AudioContext + worklet, WebSocket and (optionally) timers. */ +function scriptedBrowser({ rate = 48_000, timers = false, answerSetup = true } = {}) { + const tracks: Array<{ readyState: string; stop(): void; ended?: () => void }> = []; + const contexts: FakeContext[] = []; + const nodes: FakeNode[] = []; + const sockets: FakeSocket[] = []; + class FakeNode { + port: { onmessage: ((event: { data: Float32Array }) => void) | null } = { onmessage: null }; + connected = true; + constructor() { nodes.push(this); } + disconnect() { this.connected = false; } + } + class FakeContext { + sampleRate = rate; + state = "running"; + closes = 0; + audioWorklet = { addModule: async () => {} }; + constructor() { contexts.push(this); } + createMediaStreamSource() { return { connect() {}, disconnect() {} }; } + async resume() {} + async close() { this.closes++; this.state = "closed"; } + } + class FakeSocket { + static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3; + readyState = 0; + bufferedAmount = 0; + binaryType = "blob"; + closeCode: number | undefined; + sent: string[] = []; + onopen: (() => void) | null = null; + onmessage: ((event: { data: unknown }) => void) | null = null; + onerror: (() => void) | null = null; + onclose: ((event: { code: number }) => void) | null = null; + constructor(readonly url: string) { + sockets.push(this); + queueMicrotask(() => { if (this.readyState !== 0) return; this.readyState = 1; this.onopen?.(); }); + } + send(data: string) { + if (this.readyState !== 1) throw new Error("not open"); + this.sent.push(data); + if (answerSetup && JSON.parse(data).setup) queueMicrotask(() => this.server({ setupComplete: {} })); + } + close(code = 1000) { this.closeCode = code; this.readyState = 3; } + /** Google speaks. */ + server(message: unknown) { this.onmessage?.({ data: JSON.stringify(message) }); } + /** Google or the network ends the socket. */ + end(code: number) { this.readyState = 3; this.onclose?.({ code }); } + audio() { return this.sent.map((frame) => JSON.parse(frame)).filter((frame) => frame.realtimeInput?.audio).map((frame) => frame.realtimeInput.audio); } + } + const pending: Timer[] = []; + let now = 0, nextId = 1; + const timerGlobals = timers ? { + setTimeout: (run: () => void, delay = 0) => { const timer = { id: nextId++, at: now + delay, run }; pending.push(timer); return timer.id; }, + clearTimeout: (id: number) => { const index = pending.findIndex((timer) => timer.id === id); if (index >= 0) pending.splice(index, 1); }, + } : {}; + const restore = replaceGlobals({ + WebSocket: FakeSocket, AudioContext: FakeContext, AudioWorkletNode: FakeNode, ...timerGlobals, + navigator: { mediaDevices: { async getUserMedia() { + const track = { readyState: "live", stop() { this.readyState = "ended"; }, addEventListener(_: string, listener: () => void) { this.ended = listener; } } as (typeof tracks)[number] & { addEventListener(type: string, listener: () => void): void }; + tracks.push(track); + return { getTracks: () => [track], getAudioTracks: () => [track] }; + } } }, + }); + return { + tracks, contexts, nodes, sockets, restore, pending, + /** Advance scripted time, running due timers in order. */ + advance(ms: number) { now += ms; for (const timer of [...pending].sort((a, b) => a.at - b.at)) if (timer.at <= now && pending.includes(timer)) { pending.splice(pending.indexOf(timer), 1); timer.run(); } }, + /** One block of hardware-rate microphone audio, as the worklet posts it. */ + speak(samples: number, frequency = 440, amplitude = 0.3) { + const block = new Float32Array(samples); + for (let i = 0; i < samples; i++) block[i] = Math.sin((2 * Math.PI * frequency * i) / rate) * amplitude; + nodes.at(-1)!.port.onmessage?.({ data: block }); + }, + }; +} + +// Captured before any test scripts timers, so a tick is always real. +const realSetTimeout = globalThis.setTimeout; +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] = {}) { + 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++; } }); + cleanup.push(() => client.stop()); + return { ...browser, client, events, errors, closes: () => closes, socket: () => browser.sockets[0]! }; +} + +runAsrClientContract({ + name: "GeminiAsrClient with scripted microphone, worklet and Live socket", + session: SESSION, + create(options) { + const browser = scriptedBrowser(); + const client = new GeminiAsrClient({ url: options.session.url, token: options.session.token!, params: options.session.params!, onEvent: options.onEvent, onError: options.onError }); + const socket = () => browser.sockets[0]!; + const deliver = async (event: AsrEvent) => { + await tick(); + socket().server(event.type === "partial" ? { serverContent: { interimInputTranscription: { text: event.text } } } + : { serverContent: { inputTranscription: { text: event.text, finished: event.endsTurn } } }); + await tick(); + }; + return { + client, + captureActive: () => browser.tracks.some((track) => track.readyState === "live"), + connectionActive: () => browser.sockets.some((s) => s.readyState < 2), + deliver, + async fail() { await tick(); socket().onerror?.(); }, + async finishDrain(event) { + expect(JSON.parse(socket().sent.at(-1)!)).toEqual({ realtimeInput: { audioStreamEnd: true } }); + await deliver(event); + socket().server({ serverContent: { turnComplete: true } }); + await tick(); + }, + dispose: browser.restore, + }; + }, +}, { describe, test, expect }); + +/** Dominant frequency of PCM16 by zero crossings. */ +function frequency(samples: Int16Array, rate: number): number { + let crossings = 0; + for (let i = 1; i < samples.length; i++) if ((samples[i - 1]! < 0) !== (samples[i]! < 0)) crossings++; + return (crossings / 2) * (rate / samples.length); +} + +function decode(frames: Array<{ data: string }>): Int16Array { + const bytes = frames.flatMap((frame) => [...Uint8Array.from(atob(frame.data), (char) => char.charCodeAt(0))]); + const view = new DataView(new Uint8Array(bytes).buffer); + return Int16Array.from({ length: bytes.length / 2 }, (_, i) => view.getInt16(i * 2, true)); +} + +describe("PCM resampling", () => { + for (const rate of [44_100, 48_000, 16_000]) test(`a ${rate} Hz hardware context becomes 16 kHz PCM16 with the same pitch`, () => { + const resample = createPcmResampler(rate, 16_000); + const out: number[] = []; + // Two seconds in uneven worklet-sized blocks: boundaries must not drift. + let produced = 0; + for (const size of [4096, 4096, 1000, 4096, 333]) { + for (let k = 0; k < Math.ceil((rate * 2) / 13_621); k++) { + const block = Float32Array.from({ length: size }, (_, i) => Math.sin((2 * Math.PI * 440 * (produced + i)) / rate) * 0.5); + produced += size; + out.push(...resample(block)); + } + } + const samples = Int16Array.from(out); + expect(Math.abs(samples.length - produced * (16_000 / rate)), "GEMINI_RESAMPLED_16K sample count").toBeLessThanOrEqual(2); + expect(Math.abs(frequency(samples, 16_000) - 440), "GEMINI_RESAMPLED_16K pitch").toBeLessThan(5); + }); +}); + +describe("GeminiAsrClient wire behaviour", () => { + test("connects with the token as access_token and sends the locked setup first", async () => { + const h = harness(); + await h.client.start(); + await tick(); + const url = new URL(h.socket().url); + 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: { + model: "models/gemini-3.5-transcribe-live", + generationConfig: { responseModalities: ["TEXT"] }, + inputAudioTranscription: { mode: "SMART", customVocabulary: ["Ithaca", "Penelope"] }, + } }); + }); + + test("a verbatim session without vocabulary sets up verbatim with no customVocabulary", async () => { + const browser = scriptedBrowser(); + cleanup.push(browser.restore); + const client = new GeminiAsrClient({ url: URL_, token: TOKEN, params: { ...PARAMS, mode: "VERBATIM", vocabulary: "[]" }, onEvent() {} }); + cleanup.push(() => client.stop()); + await client.start(); + await tick(); + expect(JSON.parse(browser.sockets[0]!.sent[0]!).setup.inputAudioTranscription).toEqual({ mode: "VERBATIM" }); + }); + + test("streams 100 ms base64 PCM16 frames at 16 kHz from a 48 kHz context", async () => { + const h = harness(); + await h.client.start(); + await tick(); await tick(); + for (let i = 0; i < 10; i++) h.speak(4096); + const frames = h.socket().audio(); + // Hardware-rate samples labelled 16 kHz would carry the tone at 1,320 Hz. + expect(Math.abs(frequency(decode(frames.slice(0, 8)), 16_000) - 440), "GEMINI_RESAMPLED_16K").toBeLessThan(10); + expect(frames.length, "GEMINI_RESAMPLED_16K frame count").toBe(Math.floor(Math.floor((10 * 4096) / 3) / GEMINI_FRAME_SAMPLES)); + for (const frame of frames) { + expect(frame.mimeType).toBe("audio/pcm;rate=16000"); + expect(atob(frame.data).length).toBe(3200); + } + }); + + test("audio before setupComplete waits, in order, up to 5 s; then it is sent", async () => { + const h = harness({ answerSetup: false }); + await h.client.start(); + await tick(); + for (let i = 0; i < GEMINI_PRESETUP_FRAMES; i++) h.speak(GEMINI_FRAME_SAMPLES * 3); + expect(h.socket().audio()).toHaveLength(0); + expect(h.errors).toHaveLength(0); + h.socket().server({ setupComplete: {} }); + await tick(); + expect(h.socket().audio()).toHaveLength(GEMINI_PRESETUP_FRAMES); + }); + + test("more than 5 s before setupComplete fails the take with a network error instead of dropping audio", async () => { + const h = harness({ answerSetup: false }); + await h.client.start(); + await tick(); + for (let i = 0; i <= GEMINI_PRESETUP_FRAMES; i++) h.speak(GEMINI_FRAME_SAMPLES * 3); + expect(h.errors.map((error) => (error as Error & { code?: string }).code)).toEqual(["network"]); + expect(h.closes()).toBe(1); + expect(h.tracks.every((track) => track.readyState === "ended")).toBe(true); + expect(h.socket().readyState).toBe(3); + }); + + test("the handshake is bounded at 10 s", async () => { + const h = harness({ answerSetup: false, timers: true }); + await h.client.start(); + h.advance(GEMINI_HANDSHAKE_MS - 1); + expect(h.errors).toHaveLength(0); + h.advance(1); + expect(h.errors.map((error) => (error as Error & { code?: string }).code)).toEqual(["network"]); + expect(h.closes()).toBe(1); + expect(h.contexts[0]!.state).toBe("closed"); + }); + + test("an upload backlog over 256 KiB fails the take with a network error", async () => { + const h = harness(); + await h.client.start(); + await tick(); await tick(); + h.speak(GEMINI_FRAME_SAMPLES * 3); + expect(h.socket().audio()).toHaveLength(1); + h.socket().bufferedAmount = GEMINI_MAX_BUFFERED_BYTES + 1; + h.speak(GEMINI_FRAME_SAMPLES * 3); + expect(h.socket().audio()).toHaveLength(1); + expect(h.errors.map((error) => (error as Error & { code?: string }).code)).toEqual(["network"]); + expect(h.closes()).toBe(1); + expect(h.tracks[0]!.readyState).toBe("ended"); + }); + + test("interim text replaces the partial and each finalized segment commits exactly once", async () => { + const h = harness(); + await h.client.start(); + await tick(); await tick(); + const s = h.socket(); + s.server({ serverContent: { interimInputTranscription: { text: "Ask Nes" } } }); + s.server({ serverContent: { interimInputTranscription: { text: "Ask Nestor about" } } }); + s.server({ serverContent: { inputTranscription: { text: "Ask Nestor about the ships.", finished: true } } }); + s.server({ serverContent: { interimInputTranscription: { text: "and the" } } }); + s.server({ serverContent: { inputTranscription: { text: "And the harbor.", finished: false } } }); + s.server({ serverContent: { turnComplete: true } }); + await tick(); + expect(h.events, "GEMINI_FINAL_COMMITS_ONCE").toEqual([ + { type: "partial", text: "Ask Nes" }, + { type: "partial", text: "Ask Nestor about" }, + { type: "final", text: "Ask Nestor about the ships.", endsTurn: true }, + { type: "partial", text: "and the" }, + { type: "final", text: "And the harbor.", endsTurn: false }, + ]); + }); + + test("a final without finished ends the turn", async () => { + const h = harness(); + await h.client.start(); + await tick(); await tick(); + h.socket().server({ serverContent: { inputTranscription: { text: "Ithaca at dawn." } } }); + await tick(); + expect(h.events).toEqual([{ type: "final", text: "Ithaca at dawn.", endsTurn: true }]); + }); + + test("Done flushes the partial frame, sends audioStreamEnd and waits for the final", async () => { + const h = harness(); + await h.client.start(); + await tick(); await tick(); + h.speak(GEMINI_FRAME_SAMPLES * 3 + 300); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + const audio = h.socket().audio(); + expect(audio.map((frame) => atob(frame.data).length)).toEqual([3200, 200]); + expect(JSON.parse(h.socket().sent.at(-1)!)).toEqual({ realtimeInput: { audioStreamEnd: true } }); + expect(h.tracks[0]!.readyState, "the microphone closes at Done").toBe("ended"); + await tick(); + expect(settled).toBe(false); + h.socket().server({ serverContent: { inputTranscription: { text: "Departure tomorrow.", finished: true } } }); + await draining; + expect(h.events).toEqual([{ type: "final", text: "Departure tomorrow.", endsTurn: true }]); + expect(h.socket().readyState).toBe(3); + expect(h.closes(), "Done is not a provider end").toBe(0); + }); + + test("Done is bounded at 3 s when no final arrives", 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; }); + h.advance(GEMINI_DRAIN_MS - 1); + await tick(); + expect(settled).toBe(false); + h.advance(1); + await draining; + expect(h.socket().readyState).toBe(3); + expect(h.contexts[0]!.state).toBe("closed"); + }); + + 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(); + await tick(); + h.speak(GEMINI_FRAME_SAMPLES * 3 * 2); + const draining = h.client.drainAndStop(); + expect(h.socket().audio()).toHaveLength(0); + h.socket().server({ setupComplete: {} }); + await tick(); + expect(h.socket().audio()).toHaveLength(2); + expect(JSON.parse(h.socket().sent.at(-1)!)).toEqual({ realtimeInput: { audioStreamEnd: true } }); + h.socket().server({ serverContent: { turnComplete: true } }); + await draining; + }); + + test("hard stop releases tracks, worklet, context, timers, queue and socket; late messages mutate nothing", async () => { + const h = harness({ answerSetup: false, timers: true }); + await h.client.start(); + await tick(); + h.speak(GEMINI_FRAME_SAMPLES * 3); + const socket = h.socket(); + const handler = socket.onmessage!; + h.client.stop(); + expect(h.tracks[0]!.readyState).toBe("ended"); + expect(h.nodes[0]!.connected).toBe(false); + expect(h.nodes[0]!.port.onmessage).toBe(null); + expect(h.contexts[0]!.closes, "GEMINI_TEARDOWN_CONTEXT_CLOSED").toBe(1); + expect(h.contexts[0]!.state, "GEMINI_TEARDOWN_CONTEXT_CLOSED").toBe("closed"); + expect(socket.readyState).toBe(3); + expect(socket.closeCode).toBe(1000); + expect(h.pending, "no timer outlives the take").toHaveLength(0); + handler({ data: JSON.stringify({ setupComplete: {} }) }); + handler({ data: JSON.stringify({ serverContent: { inputTranscription: { text: "Late words", finished: true } } }) }); + await tick(); + expect(socket.audio(), "the queue was discarded").toHaveLength(0); + expect(h.events).toEqual([]); + expect(h.errors).toEqual([]); + expect(h.closes()).toBe(0); + }); + + test("a stop while the microphone opens releases the stream it was granted", async () => { + const h = harness(); + const starting = h.client.start(); + h.client.stop(); + await starting; + expect(h.tracks.every((track) => track.readyState === "ended")).toBe(true); + expect(h.sockets.every((socket) => socket.readyState === 3)).toBe(true); + }); + + for (const [name, end, code] of [ + ["Google's clean close at the session limit", (s: ReturnType) => s.socket().end(1000), null], + ["an abnormal close", (s: ReturnType) => s.socket().end(1011), "network"], + ["goAway", (s: ReturnType) => s.socket().server({ goAway: { timeLeft: "5s" } }), "network"], + ["a model error", (s: ReturnType) => s.socket().server({ error: { message: `Token ${TOKEN} rejected` } }), "unknown"], + ["a malformed message", (s: ReturnType) => s.socket().onmessage?.({ data: "{not json" }), "unknown"], + ["the microphone track ending", (s: ReturnType) => s.tracks[0]!.ended?.(), "audio-capture"], + ] as const) test(`${name} ends the take once, keeping what was heard`, async () => { + const h = harness(); + await h.client.start(); + await tick(); await tick(); + h.socket().server({ serverContent: { inputTranscription: { text: "Ask Nestor", finished: false } } }); + await tick(); + end(h); + await tick(); + expect(h.errors.map((error) => (error as Error & { code?: string }).code)).toEqual(code ? [code] : []); + for (const error of h.errors) expect(error.message).not.toContain(TOKEN); + expect(h.closes()).toBe(1); + expect(h.events).toEqual([{ type: "final", text: "Ask Nestor", endsTurn: false }]); + expect(h.tracks[0]!.readyState).toBe("ended"); + expect(h.contexts[0]!.state).toBe("closed"); + h.socket().onclose?.({ code: 1006 }); + expect(h.closes(), "ends once").toBe(1); + }); +}); diff --git a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx new file mode 100644 index 0000000000..ba2ba1778f --- /dev/null +++ b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx @@ -0,0 +1,245 @@ +/// +/** + * Gemini 3.5 Transcribe Live dictation in real Chromium (#3708). + * + * The real ChatPage dictates through the shipped GeminiAsrClient: the real + * AudioWorklet captures an oscillator "microphone" from an AudioContext + * forced to a 44.1 or 48 kHz hardware rate, and #1016's fault network stands + * in for both the host and Google's Live socket. Nothing leaves the page. + * This proves framing, resampling, event mapping and teardown against the + * documented protocol; it is not evidence that Google accepts it (#3710). + */ +import { afterAll, beforeAll, expect, test, type TestContext } from "vitest"; +import { commands, userEvent } from "vitest/browser"; +import { flushSync } from "react-dom"; +import { createRoot } from "react-dom/client"; +import type { VoiceSessionResponse } from "@schlessera/brain-ui-sdk/client"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { createBrainUiRoot, type BrainUiRoot } from "../../src/root.js"; +import { ChatPage } from "../../src/components/chat/chat-page.js"; +import { installFaultNetwork, type FaultNetwork, type FaultSocket } from "./offline/fault-network.ts"; + +const ITHACA = "odysseus-ithaca"; +const SPEECH = "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained"; +const TOKEN = "auth_tokens/ithaca-fixture-ephemeral"; +const TONE_HZ = 440; + +const HELLO = [ + { type: "server_hello", protocolRev: 5, capabilities: { chatRequestAck: true } }, + { type: "session_info", sessionId: ITHACA, isNew: false }, + { type: "session_history", sessionId: ITHACA, messages: [] }, + { type: "status", sessionId: ITHACA, status: "idle" }, +]; + +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"]) }, + capabilities: { streaming: true, interimResults: true, keyterms: true, endpointing: false, smartTranscription: true, savedAudio: false }, +}; + +let styles: HTMLStyleElement | undefined; +beforeAll(async () => { + styles = document.createElement("style"); + styles.textContent = await commands.formConsumerStyles(); + document.head.append(styles); +}); +afterAll(() => styles?.remove()); + +type Scene = { ui: BrainUiRoot; host: HTMLDivElement; net: FaultNetwork; unmount: () => void }; + +async function mount(ctx: TestContext): Promise { + const net = installFaultNetwork({ + routes: (url) => { + if (url.pathname.endsWith("/voice/session")) return Response.json(SESSION); + if (url.pathname.endsWith("/voice/overrides")) return Response.json({ overrides: [] }); + if (url.pathname.endsWith("/sessions")) return Response.json({ sessions: [] }); + return undefined; + }, + // Google's socket stays silent until the test answers the setup. + onOpen: (socket) => { if (!socket.url.startsWith(SPEECH)) for (const frame of HELLO) socket.deliver(frame); }, + }); + ctx.onTestFinished(() => net.restore()); + const host = document.createElement("div"); + host.style.cssText = "position:fixed;inset:0;width:390px;height:780px"; + document.body.append(host); + const ui = createBrainUiRoot({ storage: null, request: net.request }); + const renderer = createRoot(host); + let mounted = true; + const unmount = () => { if (mounted) { mounted = false; flushSync(() => renderer.unmount()); } }; + ctx.onTestFinished(() => { unmount(); ui.dispose(); host.remove(); }); + ui.stores.chat.getState().setActiveSession(ITHACA); + flushSync(() => renderer.render()); + ui.connection.connect(); + await expect.poll(() => ui.stores.connection.getState().wsStatus, { message: "the app reached the host" }).toBe("connected"); + return { ui, host, net, unmount }; +} + +/** + * The client's AudioContext runs at `rate`, as on hardware that is not + * 16 kHz; the microphone is a steady tone from a context at the same rate. + * Every context the client creates is recorded, so teardown is observable. + */ +function hardware(ctx: TestContext, rate: number) { + const Original = window.AudioContext; + const descriptor = Object.getOwnPropertyDescriptor(window, "AudioContext"); + const source = new Original({ sampleRate: rate }); + const oscillator = source.createOscillator(); + oscillator.frequency.value = TONE_HZ; + const gain = source.createGain(); gain.gain.value = 0.3; + const destination = source.createMediaStreamDestination(); + oscillator.connect(gain); gain.connect(destination); oscillator.start(); void source.resume(); + const contexts: AudioContext[] = []; + class HardwareContext extends Original { + constructor(options?: AudioContextOptions) { super({ ...options, sampleRate: options?.sampleRate ?? rate }); contexts.push(this); } + } + Object.defineProperty(window, "AudioContext", { configurable: true, writable: true, value: HardwareContext }); + const media = navigator.mediaDevices; + const gum = Object.getOwnPropertyDescriptor(media, "getUserMedia"); + const streams: MediaStream[] = []; + Object.defineProperty(media, "getUserMedia", { configurable: true, writable: true, value: async () => { const stream = destination.stream.clone(); streams.push(stream); return stream; } }); + ctx.onTestFinished(() => { + if (descriptor) Object.defineProperty(window, "AudioContext", descriptor); else Reflect.deleteProperty(window, "AudioContext"); + if (gum) Object.defineProperty(media, "getUserMedia", gum); else Reflect.deleteProperty(media, "getUserMedia"); + oscillator.stop(); + streams.forEach((stream) => stream.getTracks().forEach((track) => track.stop())); + destination.stream.getTracks().forEach((track) => track.stop()); + void source.close(); + }); + return { contexts, streams }; +} + +const dictate = (s: Scene) => s.host.querySelector('[data-composer] [role="button"][aria-label="Dictate"]'); + +async function startDictating(s: Scene): Promise { + await expect.poll(() => dictate(s), { message: "the composer has a mic" }).not.toBe(null); + await userEvent.click(dictate(s)!); + await expect.poll(() => s.ui.stores.voice.getState().connecting, { message: "the microphone is live", timeout: 5_000 }).toBe(false); + await expect.poll(() => s.net.socket(SPEECH)?.readyState, { message: "Google's socket is open", timeout: 5_000 }).toBe(1); + return s.net.socket(SPEECH)!; +} + +function json(socket: FaultSocket): Array> { + return socket.sent.filter((frame) => typeof frame.data === "string").map((frame) => JSON.parse(frame.data as string)); +} +const audioFrames = (socket: FaultSocket) => json(socket).filter((frame) => frame.realtimeInput?.audio).map((frame) => frame.realtimeInput.audio as { data: string; mimeType: string }); + +function decode(frames: Array<{ data: string }>): Float32Array { + const bytes = Uint8Array.from(frames.map((frame) => atob(frame.data)).join(""), (char) => char.charCodeAt(0)); + const view = new DataView(bytes.buffer); + return Float32Array.from({ length: bytes.length / 2 }, (_, i) => view.getInt16(i * 2, true) / 32768); +} + +/** Strongest frequency between 100 Hz and 4 kHz (Goertzel, 10 Hz steps). */ +function dominant(samples: Float32Array, rate: number): number { + let best = 0, bestPower = -1; + for (let hz = 100; hz <= 4000; hz += 10) { + const coefficient = 2 * Math.cos((2 * Math.PI * hz) / rate); + let s1 = 0, s2 = 0; + for (const sample of samples) { const s0 = sample + coefficient * s1 - s2; s2 = s1; s1 = s0; } + const power = s1 * s1 + s2 * s2 - coefficient * s1 * s2; + if (power > bestPower) { bestPower = power; best = hz; } + } + return best; +} + +for (const rate of [44_100, 48_000]) { + test(`a ${rate} Hz context streams 100 ms PCM16 at 16 kHz, maps interim and final text, and Done drains into review`, { timeout: 30_000 }, async (ctx) => { + const audio = hardware(ctx, rate); + const s = await mount(ctx); + const speech = await startDictating(s); + const url = new URL(speech.url); + expect(url.searchParams.get("access_token"), "the ephemeral token is the only credential").toBe(TOKEN); + 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"] }, + } }); + expect(audio.contexts[0]?.sampleRate, "the client's context runs at the hardware rate").toBe(rate); + speech.deliver({ setupComplete: {} }); + await expect.poll(() => audioFrames(speech).length, { message: "two seconds of audio reached the socket", timeout: 10_000 }).toBeGreaterThanOrEqual(20); + const frames = audioFrames(speech).slice(0, 20); + for (const frame of frames) { + expect(frame.mimeType).toBe("audio/pcm;rate=16000"); + expect(atob(frame.data).length, "100 ms of 16 kHz PCM16").toBe(3200); + } + // Two seconds at 16 kHz carry the tone at its own pitch. Hardware-rate + // samples labelled 16 kHz would put it at 440 × rate / 16 000. + expect(Math.abs(dominant(decode(frames).subarray(1600), 16_000) - TONE_HZ), "GEMINI_BROWSER_RESAMPLED_16K").toBeLessThanOrEqual(10); + expect(json(speech).some((frame) => frame.realtimeInput?.mediaChunks || frame.realtimeInput?.audio?.mimeType !== undefined && !frame.realtimeInput.audio.mimeType.startsWith("audio/pcm")), "no encoded container is labelled PCM").toBe(false); + + speech.deliver({ serverContent: { interimInputTranscription: { text: "Ask Nes" } } }); + 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 } } }); + 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(""); + + 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(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"); + 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); + }); +} + +test("audio waits for setupComplete, then flows in order", { timeout: 30_000 }, async (ctx) => { + hardware(ctx, 48_000); + const s = await mount(ctx); + const speech = await startDictating(s); + await new Promise((resolve) => setTimeout(resolve, 1_200)); + expect(audioFrames(speech), "nothing is sent before setup completes").toHaveLength(0); + expect(s.ui.stores.voice.getState().mode).toBe("dictate"); + speech.deliver({ setupComplete: {} }); + await expect.poll(() => audioFrames(speech).length, { message: "the buffered head of the take is delivered" }).toBeGreaterThanOrEqual(10); +}); + +test("a stalled upload fails the take with a connection notice and keeps the words heard", { timeout: 30_000 }, async (ctx) => { + const audio = hardware(ctx, 48_000); + const s = await mount(ctx); + const speech = await startDictating(s); + 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."); + Object.defineProperty(speech, "bufferedAmount", { configurable: true, value: 256 * 1024 + 1 }); + await expect.poll(() => s.ui.stores.voice.getState().mode, { message: "the backlog ended the take", timeout: 5_000 }).toBe("idle"); + expect(s.ui.stores.voice.getState().reviewText).toBe("Ask Nestor about the ships."); + expect(s.ui.stores.voice.getState().dictationNotice).toEqual({ reason: "network", phase: "ended", retained: true }); + await expect.poll(() => audio.contexts[0]!.state).toBe("closed"); + expect(audio.streams[0]!.getTracks().map((track) => track.readyState)).toEqual(["ended"]); +}); + +test("Google ending the session hands what was heard to review once", { timeout: 30_000 }, async (ctx) => { + const audio = hardware(ctx, 44_100); + const s = await mount(ctx); + const speech = await startDictating(s); + speech.deliver({ setupComplete: {} }); + speech.deliver({ serverContent: { inputTranscription: { text: "Ask Nestor", finished: false } } }); + speech.deliver({ serverContent: { interimInputTranscription: { text: "about the ships" } } }); + await expect.poll(() => s.ui.stores.voice.getState().partial).toBe("about the ships"); + speech.finish(1000, "", true); + await expect.poll(() => s.ui.stores.voice.getState().mode, { message: "the provider ended the dictation" }).toBe("idle"); + expect(s.ui.stores.voice.getState().reviewText).toBe("Ask Nestor about the ships"); + expect(s.ui.stores.voice.getState().finalText).toBe(""); + await expect.poll(() => audio.contexts[0]!.state).toBe("closed"); +}); + +test("unmount hard-stops capture: tracks, AudioContext and socket are released and nothing more is sent", { timeout: 30_000 }, async (ctx) => { + const audio = hardware(ctx, 48_000); + const s = await mount(ctx); + const speech = await startDictating(s); + speech.deliver({ setupComplete: {} }); + await expect.poll(() => audioFrames(speech).length, { timeout: 10_000 }).toBeGreaterThanOrEqual(3); + s.unmount(); + expect(audio.streams[0]!.getTracks().map((track) => track.readyState)).toEqual(["ended"]); + await expect.poll(() => audio.contexts[0]!.state, { message: "GEMINI_BROWSER_TEARDOWN_CONTEXT_CLOSED" }).toBe("closed"); + expect(speech.readyState).toBeGreaterThanOrEqual(2); + const sent = speech.sent.length; + await new Promise((resolve) => setTimeout(resolve, 500)); + expect(speech.sent.length, "no audio after teardown").toBe(sent); + expect(json(speech).some((frame) => frame.realtimeInput?.audioStreamEnd), "a hard stop sends no graceful end").toBe(false); +}); diff --git a/packages/ui-react/tests/registration-on-mount-harness.ts b/packages/ui-react/tests/registration-on-mount-harness.ts index 9e3c473d3b..391f2bee24 100644 --- a/packages/ui-react/tests/registration-on-mount-harness.ts +++ b/packages/ui-react/tests/registration-on-mount-harness.ts @@ -9,5 +9,6 @@ export { piToolPack } from "../src/components/chat/renderers/pi-tools.js"; export { useDictation } from "../src/voice/use-dictation.js"; export { registerAsrClients } from "../src/voice/asr-clients.js"; export { DeepgramClient } from "../src/voice/asr-deepgram.js"; +export { GeminiAsrClient } from "../src/voice/asr-gemini.js"; export { WebSpeechClient } from "../src/voice/asr-webspeech.js"; export { useChatStore } from "../src/stores/chat-store.js"; diff --git a/packages/ui-react/tests/registration-on-mount.test.tsx b/packages/ui-react/tests/registration-on-mount.test.tsx index 7d534a8e2b..3b8ef69da0 100644 --- a/packages/ui-react/tests/registration-on-mount.test.tsx +++ b/packages/ui-react/tests/registration-on-mount.test.tsx @@ -130,6 +130,9 @@ if (!childMode) { expect(harness.createAsrClient(asrOptions("deepgram"))).toBeInstanceOf( harness.DeepgramClient ); + expect(harness.createAsrClient(asrOptions("gemini"))).toBeInstanceOf( + harness.GeminiAsrClient + ); expect(harness.createAsrClient(asrOptions("webspeech"))).toBeInstanceOf( harness.WebSpeechClient ); @@ -212,7 +215,7 @@ if (!childMode) { const providers = registerAsrClient.mock.calls.map( ([providerId]: [string, AsrClientFactory]) => providerId ); - expect([...new Set(providers)]).toEqual(["deepgram", "webspeech"]); + expect([...new Set(providers)]).toEqual(["deepgram", "gemini", "webspeech"]); strictDictation.unmount(); strictTimeline.unmount(); diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index b274e74714..d686e13f14 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -1997,6 +1997,9 @@ export interface SpeechCapabilities { endpointing: boolean; /** Absent/false means saved recordings cannot be transcribed. Derived from the optional server method. */ savedAudio?: boolean; + /** True when the provider honours `createSession({ mode })`: "smart" cleans up fillers, self-corrections + * and formatting, "verbatim" transcribes as spoken. Absent/false means the mode option is ignored. */ + smartTranscription?: boolean; } /** @deprecated superseded by VoiceSessionResponse; kept for client migration. */ diff --git a/packages/ui-sdk/src/server/speech.ts b/packages/ui-sdk/src/server/speech.ts index 54b23fe5d8..69ee358b55 100644 --- a/packages/ui-sdk/src/server/speech.ts +++ b/packages/ui-sdk/src/server/speech.ts @@ -25,13 +25,19 @@ export interface SpeechSession { */ export interface SpeechProvider { id: string; + /** Optional human-readable service name, e.g. for a settings row or the dictation sheet. */ + label?: string; + /** Optional plain-language disclosure of where microphone audio goes while dictating. */ + destination?: string; capabilities: SpeechCapabilities; /** * Mint one dictation session. `keyterms` are domain terms from the brain's * keyterm builder — providers without keyterm support ignore them - * (capabilities.keyterms = false). + * (capabilities.keyterms = false). `mode` selects SMART (cleaned-up) or + * verbatim transcription; providers ignore it unless they declare + * `capabilities.smartTranscription`, and an absent mode means their default. */ - createSession(opts: { keyterms: string[] }): Promise; + createSession(opts: { keyterms: string[]; mode?: "smart" | "verbatim" }): Promise; /** Optional saved-audio path. Call only the provider from the server with its * server-held credential; forward bytes unchanged. Reject on failure. No * automatic retries. Untyped errors are terminal unknown outcomes. */ diff --git a/packages/ui-sdk/src/testing/speech-contract.ts b/packages/ui-sdk/src/testing/speech-contract.ts index 54615f333f..e66be92160 100644 --- a/packages/ui-sdk/src/testing/speech-contract.ts +++ b/packages/ui-sdk/src/testing/speech-contract.ts @@ -37,6 +37,24 @@ export function runSpeechProviderContract( expect(typeof provider.capabilities[name]).toBe("boolean"); } expect(typeof provider.createSession).toBe("function"); + for (const name of ["label", "destination"] as const) { + if (provider[name] === undefined) continue; + expect(typeof provider[name]).toBe("string"); + expect(provider[name]!.trim().length).toBeGreaterThan(0); + } + if (provider.capabilities.smartTranscription !== undefined) expect(typeof provider.capabilities.smartTranscription).toBe("boolean"); + } finally { await probe.dispose(); } + }); + + test("a provider declaring SMART transcription mints a serializable session for each mode", async () => { + const probe = harness.create(); + try { + if (probe.provider.capabilities.smartTranscription !== true) return; + for (const mode of ["smart", "verbatim"] as const) { + const session = await probe.provider.createSession({ keyterms: [], mode }); + expect(typeof session.url).toBe("string"); + expect(JSON.parse(JSON.stringify(session))).toEqual(session); + } } finally { await probe.dispose(); } }); diff --git a/packages/ui-server/README.md b/packages/ui-server/README.md index bf9203fa97..00e7853ec5 100644 --- a/packages/ui-server/README.md +++ b/packages/ui-server/README.md @@ -414,7 +414,8 @@ under the [service terms](../geo/README.md#configuration). | `COASTLINE_CACHE_DIR` | Directory holding fetched map geometry. Cached forever; coastlines do not move. | $BRAIN_PATH/.brain-ui/geo | | `COOKIE_SECRET` | Secret signing the session cookie. | **required** — AUTH_MODE=password | | `DB_PATH` | SQLite file for the UI's own database (sessions, passkeys, settings). The turn journal keeps its own database beside it, DB_PATH.journal.db, with the same permissions. Must resolve outside the brain; an in-brain operational-state layout refuses boot with migration guidance. The server factory defaults to ./brain-ui.db; brain-ui-cron defaults to the container path /data/db/brain-ui.db. | ./brain-ui.db (server); /data/db/brain-ui.db (brain-ui-cron) | -| `DEEPGRAM_API_KEY` | Deepgram API key for streaming ASR (short-lived tokens are minted from it). | **required** — VOICE_PROVIDER=deepgram (or any voice use without VOICE_PROVIDER=webspeech) | +| `DEEPGRAM_API_KEY` | Deepgram API key for streaming ASR (short-lived tokens are minted from it). | **required** — VOICE_PROVIDER=deepgram (or voice use with neither VOICE_PROVIDER nor GEMINI_API_KEY set) | +| `GEMINI_API_KEY` | Google Gemini API key. For dictation it registers the gemini-3.5-transcribe-live provider (id gemini): the server mints a single-use constrained token from it per take, so the key itself never reaches the browser. Dictation uses it when VOICE_PROVIDER=gemini, or without VOICE_PROVIDER only when DEEPGRAM_API_KEY is unset. | **required** — VOICE_PROVIDER=gemini | | `GITHUB_TOKEN` | Generic GitHub token fallback. Used for skill installs when BRAIN_UI_SKILLS_GITHUB_TOKEN is unset; the host sync mirror transport falls back to it when BRAIN_UI_SYNC_GITHUB_TOKEN is unset. These GitHub tokens never reach brain maintenance workers. | — | | `HOME` | Fallback anchor for the BRAIN_PATH default and the pi config dir (~/.pi). | /root | | `HOST` | Bind host; consulted by the auth validation to decide whether AUTH_MODE=none is loopback-safe. | (empty) | @@ -431,7 +432,7 @@ under the [service terms](../geo/README.md#configuration). | `TYPESAFE_API_KEY` | TypeSafe AI key for the classification pass that draws markdown the model typed as kit blocks (D42). Absent = pass disabled; the answer renders as markdown either way. | — | | `VOICE_CACHE_DIR` | Directory holding the keyterm cache JSON. | $BRAIN_PATH/.brain-ui | | `VOICE_KEYTERM_LIMIT` | Maximum custom-vocabulary terms built from the brain database. | 500 | -| `VOICE_PROVIDER` | Speech provider: "deepgram", "webspeech" (opt-in only — Chromium streams audio to Google), or the id supplied through createApp({ speechProvider }). An explicit name must match a supplied value. Unset prefers that value, otherwise auto-detects deepgram when its key is present. | (auto-detect) | +| `VOICE_PROVIDER` | Speech provider: "deepgram", "gemini", "webspeech" (opt-in only — Chromium streams audio to Google), or the id supplied through createApp({ speechProvider }). An explicit name must match a supplied value. Unset prefers that value, otherwise auto-detects deepgram when its key is present, then gemini when only GEMINI_API_KEY is present. | (auto-detect) | | `WEBAUTHN_ORIGINS` | Comma-separated extra origins allowed for WebAuthn ceremonies. | (empty) | | `WEBAUTHN_RP_ID` | Relying-party id override for proxies that rewrite Host. | (derived from the request origin) | | `WEBAUTHN_RP_NAME` | Relying-party display name shown by authenticators. | Brain UI | diff --git a/packages/ui-server/src/config/env.ts b/packages/ui-server/src/config/env.ts index 6f6f72110a..0d8167a6e3 100644 --- a/packages/ui-server/src/config/env.ts +++ b/packages/ui-server/src/config/env.ts @@ -697,12 +697,21 @@ export const ENV_VARS: readonly EnvVarDescriptor[] = [ name: "DEEPGRAM_API_KEY", description: "Deepgram API key for streaming ASR (short-lived tokens are minted from it).", default: null, - required: "VOICE_PROVIDER=deepgram (or any voice use without VOICE_PROVIDER=webspeech)", + required: "VOICE_PROVIDER=deepgram (or voice use with neither VOICE_PROVIDER nor GEMINI_API_KEY set)", + }, + { + name: "GEMINI_API_KEY", + description: + "Google Gemini API key. For dictation it registers the gemini-3.5-transcribe-live provider (id gemini): the server " + + "mints a single-use constrained token from it per take, so the key itself never reaches the browser. Dictation uses " + + "it when VOICE_PROVIDER=gemini, or without VOICE_PROVIDER only when DEEPGRAM_API_KEY is unset.", + default: null, + required: "VOICE_PROVIDER=gemini", }, { name: "VOICE_PROVIDER", description: - 'Speech provider: "deepgram", "webspeech" (opt-in only — Chromium streams audio to Google), or the id supplied through createApp({ speechProvider }). An explicit name must match a supplied value. Unset prefers that value, otherwise auto-detects deepgram when its key is present.', + 'Speech provider: "deepgram", "gemini", "webspeech" (opt-in only — Chromium streams audio to Google), or the id supplied through createApp({ speechProvider }). An explicit name must match a supplied value. Unset prefers that value, otherwise auto-detects deepgram when its key is present, then gemini when only GEMINI_API_KEY is present.', default: "(auto-detect)", required: false, }, @@ -835,6 +844,9 @@ export interface VoiceConfig { /** Trimmed, lowercased VOICE_PROVIDER; null when unset (auto-detect). */ provider: string | null; deepgramApiKey: string | null; + /** GEMINI_API_KEY; registers the Gemini Transcribe Live dictation provider. Optional so + * hand-built configs stay valid; absent means unset. */ + geminiApiKey?: string | null; keytermLimit: number; /** Resolved keyterm cache directory. */ cacheDir: string; @@ -1211,6 +1223,7 @@ export function resolveServerConfig(env: EnvRecord = process.env): ServerConfig voice: { provider: env.VOICE_PROVIDER?.trim().toLowerCase() || null, deepgramApiKey: env.DEEPGRAM_API_KEY || null, + geminiApiKey: env.GEMINI_API_KEY || null, keytermLimit: Number(env.VOICE_KEYTERM_LIMIT || 500), cacheDir: env.VOICE_CACHE_DIR || join(brainPath, ".brain-ui"), }, diff --git a/packages/ui-server/src/voice/gemini-speech.ts b/packages/ui-server/src/voice/gemini-speech.ts new file mode 100644 index 0000000000..b5c9a6ce90 --- /dev/null +++ b/packages/ui-server/src/voice/gemini-speech.ts @@ -0,0 +1,126 @@ +/** + * Gemini 3.5 Transcribe Live dictation, server side (#3708). + * + * The long-lived GEMINI_API_KEY never leaves this closure. Each take mints one + * single-use ephemeral token through the documented REST endpoint, with + * `liveConnectConstraints` locking the model, the TEXT modality and the + * transcription configuration, so a browser holding the token cannot open any + * other Live session with it. No SDK dependency: the request is the wire shape + * Google documents, as `gemini-conversation.ts` speaks the Live wire directly. + * + * Errors never carry the key or Google's response text: every failure is the + * one message below, which the session route returns in its 500 envelope. + * No session resumption: a take ends at Google's 10-minute session limit + * through the client's provider-ended path. Design: + * docs/plans/selectable-dictation.md §6. + */ + +import type { SpeechProvider, SpeechSession } from "@schlessera/brain-ui-sdk/server"; +import { defineSpeechProvider } from "@schlessera/brain-ui-sdk/server"; + +export const GEMINI_AUTH_TOKENS_URL = "https://generativelanguage.googleapis.com/v1beta/auth_tokens"; +// The installed @google/genai 2.24.0 connects ephemeral tokens to this v1alpha +// constrained endpoint; Google's token guide says v1beta. #3710 qualifies which +// one Google accepts. The server mints the URL, so a correction is server-only. +export const GEMINI_TRANSCRIBE_URL = + "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained"; +export const GEMINI_TRANSCRIBE_MODEL = "models/gemini-3.5-transcribe-live"; +export const GEMINI_SESSION_FAILED = "Gemini dictation session failed"; + +/** Connect window for the token (`newSessionExpireTime`), also the session's `expiresAt`. */ +const NEW_SESSION_MS = 60_000; +/** Overall token lifetime (`expireTime`): Google's 10-minute session plus margin. */ +const TOKEN_MS = 11 * 60_000; +const REQUEST_TIMEOUT_MS = 10_000; +const GEMINI_MAX_VOCABULARY_TERMS = 100; +const GEMINI_MAX_TERM_BYTES = 64; +// Google's token resource name; anything else is not connection material. +const TOKEN_NAME = /^auth_tokens\/[\x21-\x7e]{1,1024}$/; + +const encoder = new TextEncoder(); + +/** The existing bounded keyterms: at most 100 nonempty terms of at most 64 UTF-8 bytes each, in order. */ +function geminiVocabulary(keyterms: readonly string[]): string[] { + const terms: string[] = []; + const seen = new Set(); + for (const raw of keyterms) { + if (terms.length >= GEMINI_MAX_VOCABULARY_TERMS) break; + const term = typeof raw === "string" ? raw.trim() : ""; + if (!term || seen.has(term) || encoder.encode(term).byteLength > GEMINI_MAX_TERM_BYTES) continue; + seen.add(term); + terms.push(term); + } + return terms; +} + +/** The transcription config the token locks and the browser's setup repeats. */ +function geminiTranscriptionConfig(vocabulary: readonly string[], mode: "SMART" | "VERBATIM") { + return { mode, ...(vocabulary.length ? { customVocabulary: [...vocabulary] } : {}) }; +} + +export function createGeminiSpeechProvider(apiKey: string): SpeechProvider { + if (typeof apiKey !== "string" || !apiKey.trim()) throw new Error("Gemini dictation requires GEMINI_API_KEY."); + return defineSpeechProvider({ + id: "gemini", + label: "Google Gemini 3.5 Transcribe Live", + destination: "Microphone audio streams from this browser to Google (gemini-3.5-transcribe-live).", + capabilities: { + streaming: true, + interimResults: true, + keyterms: true, + // Manual Done: pauses still commit finals, but the take does not end on one. + endpointing: false, + smartTranscription: true, + }, + async createSession({ keyterms, mode }): Promise { + // SMART is the default (D1); only an explicit verbatim request turns it off. + const wireMode = mode === "verbatim" ? "VERBATIM" : "SMART"; + const vocabulary = geminiVocabulary(keyterms); + const now = Date.now(); + const body = { + uses: 1, + expireTime: new Date(now + TOKEN_MS).toISOString(), + newSessionExpireTime: new Date(now + NEW_SESSION_MS).toISOString(), + liveConnectConstraints: { + model: GEMINI_TRANSCRIBE_MODEL, + config: { + responseModalities: ["TEXT"], + inputAudioTranscription: geminiTranscriptionConfig(vocabulary, wireMode), + }, + }, + lockAdditionalFields: [], + }; + let response: Response; + try { + response = await fetch(GEMINI_AUTH_TOKENS_URL, { + method: "POST", + headers: { "x-goog-api-key": apiKey, "content-type": "application/json" }, + body: JSON.stringify(body), + redirect: "error", + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + } catch { + throw new Error(GEMINI_SESSION_FAILED); + } + if (!response.ok) { + // Google's error text may echo request details; it is never read. + await response.body?.cancel().catch(() => {}); + throw new Error(GEMINI_SESSION_FAILED); + } + let name: unknown; + try { name = ((await response.json()) as { name?: unknown } | null)?.name; } catch { throw new Error(GEMINI_SESSION_FAILED); } + if (typeof name !== "string" || !TOKEN_NAME.test(name)) throw new Error(GEMINI_SESSION_FAILED); + return { + url: GEMINI_TRANSCRIBE_URL, + token: name, + expiresAt: now + NEW_SESSION_MS, + params: { + model: GEMINI_TRANSCRIBE_MODEL, + mode: wireMode, + sampleRate: "16000", + vocabulary: JSON.stringify(vocabulary), + }, + }; + }, + }); +} diff --git a/packages/ui-server/src/voice/speech-providers.ts b/packages/ui-server/src/voice/speech-providers.ts index 94029344db..68e67682fd 100644 --- a/packages/ui-server/src/voice/speech-providers.ts +++ b/packages/ui-server/src/voice/speech-providers.ts @@ -4,11 +4,14 @@ * * - `deepgram` — mints a short-lived Deepgram token and the full streaming WS * URL (base params + domain keyterms baked in). + * - `gemini` — mints a single-use constrained Gemini Live token for + * gemini-3.5-transcribe-live (`gemini-speech.ts`). * - `webspeech` — no server session; the browser's SpeechRecognition does the * work, so it returns empty url/token. * * VOICE_PROVIDER selects the provider; default is deepgram when - * DEEPGRAM_API_KEY is set, otherwise selection fails. An external value takes + * DEEPGRAM_API_KEY is set, then gemini when GEMINI_API_KEY is the only key, + * otherwise selection fails. An external value takes * precedence over auto-detection and must match an explicit VOICE_PROVIDER. * Both arrive here as the resolved * {@link VoiceConfig} — this module reads no environment. @@ -18,6 +21,7 @@ import type { SpeechProvider } from "@schlessera/brain-ui-sdk/server"; import { defineSpeechProvider, SpeechTranscriptionError } from "@schlessera/brain-ui-sdk/server"; import type { VoiceConfig } from "../config/env.js"; import { mintDeepgramToken } from "./deepgram-token.js"; +import { createGeminiSpeechProvider } from "./gemini-speech.js"; const DEEPGRAM_WS_URL = "wss://api.deepgram.com/v1/listen"; @@ -140,15 +144,24 @@ export function pickSpeechProvider(voice: VoiceConfig, supplied?: SpeechProvider } return createDeepgramSpeechProvider(voice.deepgramApiKey); } + if (configured === "gemini") { + if (!voice.geminiApiKey) { + throw new Error("VOICE_PROVIDER=gemini but GEMINI_API_KEY is not set."); + } + return createGeminiSpeechProvider(voice.geminiApiKey); + } if (configured) { throw new Error( - `Unknown VOICE_PROVIDER="${configured}" (expected "deepgram" or "webspeech").` + `Unknown VOICE_PROVIDER="${configured}" (expected "deepgram", "gemini" or "webspeech").` ); } - // Auto-detect: Deepgram when its key is present; otherwise fail loudly. + // Auto-detect: Deepgram when its key is present. A Gemini key alone makes + // Gemini the only registered provider, so it is used (D3); it never takes + // precedence over Deepgram. Otherwise fail loudly. if (voice.deepgramApiKey) return createDeepgramSpeechProvider(voice.deepgramApiKey); + if (voice.geminiApiKey) return createGeminiSpeechProvider(voice.geminiApiKey); throw new Error( - 'No speech provider configured. Set DEEPGRAM_API_KEY, or set ' + + 'No speech provider configured. Set DEEPGRAM_API_KEY or GEMINI_API_KEY, or set ' + 'VOICE_PROVIDER=webspeech to explicitly opt into the browser speech API ' + "(which streams audio to Google on Chromium)." ); @@ -165,6 +178,15 @@ function assertSpeechProvider(provider: SpeechProvider): void { throw new Error(`Invalid SpeechProvider "${provider.id}": capabilities.${capability} must be boolean.`); } } + for (const field of ["label", "destination"] as const) { + const value = provider[field]; + if (value !== undefined && (typeof value !== "string" || !value.trim())) { + throw new Error(`Invalid SpeechProvider "${provider.id}": ${field} must be a nonempty string when supplied.`); + } + } + if (provider.capabilities.smartTranscription !== undefined && typeof provider.capabilities.smartTranscription !== "boolean") { + throw new Error(`Invalid SpeechProvider "${provider.id}": capabilities.smartTranscription must be boolean when supplied.`); + } if (provider.transcribeRecording !== undefined && typeof provider.transcribeRecording !== "function") { throw new Error(`Invalid SpeechProvider "${provider.id}": transcribeRecording must be a function when supplied.`); } diff --git a/packages/ui-server/tests/gemini-speech.test.ts b/packages/ui-server/tests/gemini-speech.test.ts new file mode 100644 index 0000000000..1144277678 --- /dev/null +++ b/packages/ui-server/tests/gemini-speech.test.ts @@ -0,0 +1,230 @@ +import { afterEach, describe, expect, spyOn, test } from "bun:test"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { defineSpeechProvider, type SpeechProvider } from "@schlessera/brain-ui-sdk/server"; +import { runSpeechProviderContract } from "@schlessera/brain-ui-sdk/testing"; +import type { VoiceConfig } from "../src/config/env"; +import { + createGeminiSpeechProvider, GEMINI_AUTH_TOKENS_URL, GEMINI_SESSION_FAILED, GEMINI_TRANSCRIBE_MODEL, GEMINI_TRANSCRIBE_URL, +} from "../src/voice/gemini-speech"; +import { pickSpeechProvider } from "../src/voice/speech-providers"; +import { httpContractApp } from "./helpers/http-contract-app"; + +const KEY = "odysseus-fixture-gemini-key"; +const TOKEN = "auth_tokens/ithaca-fixture-ephemeral"; + +interface Seen { method: string; url: string; headers: Record; body: any } +type Answer = (seen: Seen) => Response | Promise; + +/** + * A loopback stand-in for Google's auth_tokens endpoint. The provider's + * `fetch` to the real URL is redirected here, so the request crosses an + * actual HTTP hop (method, headers, serialized body) and nothing leaves the + * machine. Everything else is refused, as the test preload would. + */ +function authTokensDouble(answer: Answer = () => Response.json({ name: TOKEN })) { + const seen: Seen[] = []; + const server = Bun.serve({ + hostname: "127.0.0.1", port: 0, + async fetch(request) { + const record = { method: request.method, url: request.url, headers: Object.fromEntries(request.headers), body: JSON.parse(await request.text()) }; + seen.push(record); + return answer(record); + }, + }); + const realFetch = globalThis.fetch; + const mock = spyOn(globalThis, "fetch").mockImplementation(Object.assign(async (input: Parameters[0], init?: Parameters[1]) => { + if (String(input) !== GEMINI_AUTH_TOKENS_URL) throw new Error(`Unexpected request to ${String(input)}`); + return realFetch(`http://127.0.0.1:${server.port}/v1beta/auth_tokens`, init); + }, { preconnect: fetch.preconnect })); + return { seen, dispose: () => { mock.mockRestore(); server.stop(true); } }; +} + +let active: Array<() => void> = []; +afterEach(() => { for (const dispose of active.splice(0)) dispose(); }); +function double(answer?: Answer) { const d = authTokensDouble(answer); active.push(d.dispose); return d; } + +function probe(failing: boolean) { + const d = authTokensDouble(failing ? () => new Response(`API key ${KEY} not valid`, { status: 403 }) : undefined); + return { + provider: createGeminiSpeechProvider(KEY), + keyterms: () => d.seen.at(-1)?.body.liveConnectConstraints.config.inputAudioTranscription.customVocabulary ?? [], + dispose: d.dispose, + }; +} + +runSpeechProviderContract({ name: "built-in Gemini Transcribe Live with a loopback auth_tokens double", create: () => probe(false), failing: () => probe(true) }, { describe, test, expect }); + +describe("Gemini dictation session", () => { + test("mints one constrained single-use token locking model, TEXT modality and SMART transcription", async () => { + const d = double(); + const before = Date.now(); + const session = await createGeminiSpeechProvider(KEY).createSession({ keyterms: ["Ithaca", "Penelope"] }); + const after = Date.now(); + expect(d.seen).toHaveLength(1); + const [request] = d.seen; + expect(request!.method).toBe("POST"); + expect(request!.headers["x-goog-api-key"]).toBe(KEY); + expect(request!.headers["content-type"]).toBe("application/json"); + const { expireTime, newSessionExpireTime, ...rest } = request!.body; + expect(rest, "GEMINI_CONSTRAINT_LOCK").toEqual({ + uses: 1, + liveConnectConstraints: { + model: GEMINI_TRANSCRIBE_MODEL, + config: { responseModalities: ["TEXT"], inputAudioTranscription: { mode: "SMART", customVocabulary: ["Ithaca", "Penelope"] } }, + }, + lockAdditionalFields: [], + }); + expect(Date.parse(newSessionExpireTime)).toBeGreaterThanOrEqual(before + 60_000 - 1); + expect(Date.parse(newSessionExpireTime)).toBeLessThanOrEqual(after + 60_000); + expect(Date.parse(expireTime)).toBeGreaterThanOrEqual(before + 11 * 60_000 - 1); + 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"]) }, + }); + expect(JSON.stringify(session)).not.toContain(KEY); + }); + + test("verbatim is used only when asked for, in the lock and the browser's setup alike", async () => { + const d = double(); + const provider = createGeminiSpeechProvider(KEY); + 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.liveConnectConstraints.config.inputAudioTranscription)).toEqual([{ mode: "VERBATIM" }, { mode: "SMART" }, { mode: "SMART" }]); + expect([verbatim, smart, unset].map((session) => [session.params!.mode, session.params!.vocabulary])).toEqual([["VERBATIM", "[]"], ["SMART", "[]"], ["SMART", "[]"]]); + }); + + test("vocabulary is the existing keyterms, bounded to 100 terms of at most 64 UTF-8 bytes", async () => { + const d = double(); + const long = "Ω".repeat(33); // 66 UTF-8 bytes, 33 characters + const terms = ["", " ", "Telemachus", long, "Telemachus", "x".repeat(64), "x".repeat(65), ...Array.from({ length: 150 }, (_, i) => `Ithaca harbor ${i}`)]; + const session = await createGeminiSpeechProvider(KEY).createSession({ keyterms: terms }); + const sent: string[] = d.seen[0]!.body.liveConnectConstraints.config.inputAudioTranscription.customVocabulary; + expect(sent).toHaveLength(100); + expect(sent.slice(0, 3)).toEqual(["Telemachus", "x".repeat(64), "Ithaca harbor 0"]); + expect(sent).not.toContain(long); + for (const term of sent) expect(new TextEncoder().encode(term).byteLength).toBeLessThanOrEqual(64); + expect(JSON.parse(session.params!.vocabulary!)).toEqual(sent); + }); + + const failures: Array<[string, Answer | "network"]> = [ + ["an authentication refusal echoing the key", () => new Response(`API key ${KEY} not valid. Please pass a valid API key.`, { status: 400 })], + ["a provider error", () => Response.json({ error: { message: `quota for ${KEY}` } }, { status: 500 })], + ["a non-JSON success", () => new Response(`${KEY}`, { status: 200 })], + ["a success without a token name", () => Response.json({ expireTime: "2026-07-12T09:00:00Z" })], + ["a success naming something other than an auth token", () => Response.json({ name: `projects/${KEY}` })], + ["a transport failure", "network"], + ]; + for (const [name, answer] of failures) test(`${name} fails with the fixed message and never leaks the key or Google's text`, async () => { + const logs: string[] = []; + const spies = (["log", "info", "warn", "error", "debug"] as const).map((level) => spyOn(console, level).mockImplementation((...args: unknown[]) => { logs.push(args.map(String).join(" ")); })); + let mock: ReturnType | undefined; + try { + if (answer === "network") mock = spyOn(globalThis, "fetch").mockImplementation(Object.assign(async () => { throw new TypeError(`connect failed for ${GEMINI_AUTH_TOKENS_URL}?key=${KEY}`); }, { preconnect: fetch.preconnect })); + else double(answer); + let caught: unknown; + try { await createGeminiSpeechProvider(KEY).createSession({ keyterms: ["Ithaca"] }); } catch (error) { caught = error; } + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toBe(GEMINI_SESSION_FAILED); + expect(String((caught as Error).stack)).not.toContain(KEY); + expect((caught as Error & { cause?: unknown }).cause).toBeUndefined(); + expect(logs.join("\n")).not.toContain(KEY); + } finally { mock?.mockRestore(); for (const spy of spies) spy.mockRestore(); } + }); + + test("a missing key is refused at construction", () => { + expect(() => createGeminiSpeechProvider(" ")).toThrow("GEMINI_API_KEY"); + }); +}); + +const voice = (overrides: Partial): VoiceConfig => ({ provider: null, deepgramApiKey: null, geminiApiKey: null, keytermLimit: 0, cacheDir: "/tmp", ...overrides }); + +describe("Gemini selection over the single built-in provider", () => { + test("VOICE_PROVIDER=gemini needs GEMINI_API_KEY", () => { + expect(() => pickSpeechProvider(voice({ provider: "gemini" }))).toThrow("VOICE_PROVIDER=gemini but GEMINI_API_KEY is not set."); + expect(pickSpeechProvider(voice({ provider: "gemini", geminiApiKey: KEY, deepgramApiKey: "unused" })).id).toBe("gemini"); + }); + + test("a Gemini key is used without VOICE_PROVIDER only when it is the only key; Deepgram keeps precedence", () => { + expect(pickSpeechProvider(voice({ geminiApiKey: KEY })).id).toBe("gemini"); + expect(pickSpeechProvider(voice({ geminiApiKey: KEY, deepgramApiKey: "fixture-deepgram" })).id).toBe("deepgram"); + expect(pickSpeechProvider(voice({ provider: "deepgram", geminiApiKey: KEY, deepgramApiKey: "fixture-deepgram" })).id).toBe("deepgram"); + expect(() => pickSpeechProvider(voice({}))).toThrow("Set DEEPGRAM_API_KEY or GEMINI_API_KEY"); + expect(() => pickSpeechProvider(voice({ provider: "athena" }))).toThrow('expected "deepgram", "gemini" or "webspeech"'); + }); + + test("the declared capabilities are streaming, SMART, keyterms, manual Done and no saved audio", () => { + const provider = pickSpeechProvider(voice({ provider: "gemini", geminiApiKey: KEY })); + expect(provider.capabilities).toEqual({ streaming: true, interimResults: true, keyterms: true, endpointing: false, smartTranscription: true }); + expect(provider.transcribeRecording).toBeUndefined(); + expect(provider.label).toBe("Google Gemini 3.5 Transcribe Live"); + expect(provider.destination).toContain("Google"); + }); + + test("supplied providers' optional label, destination and smartTranscription are validated", () => { + const base = { id: "fixture-speech", capabilities: { streaming: true, interimResults: false, keyterms: false, endpointing: false }, createSession: async () => ({ url: "", expiresAt: 0 }) }; + const invalid: Array<[Partial & Record, string]> = [ + [{ label: "" }, "label must be a nonempty string"], + [{ destination: 7 as unknown as string }, "destination must be a nonempty string"], + [{ capabilities: { ...base.capabilities, smartTranscription: "yes" as unknown as boolean } }, "smartTranscription must be boolean"], + ]; + for (const [overrides, message] of invalid) { + expect(() => pickSpeechProvider(voice({}), { ...base, ...overrides } as SpeechProvider)).toThrow(message); + } + const valid = defineSpeechProvider({ ...base, label: "Fixture", destination: "Audio stays on this fixture.", capabilities: { ...base.capabilities, smartTranscription: false } }); + expect(pickSpeechProvider(voice({}), valid)).toBe(valid); + }); +}); + +/** The brain's keyterm cache, as the builder writes it, so the route forwards real terms. */ +function keyterms(t: Awaited>, terms: string[]) { + mkdirSync(t.app.config.voice.cacheDir, { recursive: true }); + writeFileSync(join(t.app.config.voice.cacheDir, "keyterms.json"), JSON.stringify({ version: 2, generatedAt: Date.now(), keyterms: terms, count: terms.length, overrides: [] })); +} + +describe("Gemini dictation through the mounted app", () => { + test("VOICE_PROVIDER=gemini serves capabilities and a constrained session on the real routes", async () => { + const d = double(); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "gemini", GEMINI_API_KEY: KEY } }); + try { + const capabilities = await t.fetch("/api/voice/capabilities"); + expect(capabilities.status).toBe(200); + const expected = { streaming: true, interimResults: true, keyterms: true, endpointing: false, smartTranscription: true, savedAudio: false }; + expect(await capabilities.json()).toEqual({ providerId: "gemini", capabilities: expected }); + expect(d.seen, "discovery mints nothing").toHaveLength(0); + keyterms(t, ["Ithaca", "Penelope"]); + const response = await t.fetch("/api/voice/session", { method: "POST" }); + expect(response.status).toBe(200); + const text = await response.text(); + expect(text).not.toContain(KEY); + const body = JSON.parse(text); + expect(body).toMatchObject({ providerId: "gemini", url: GEMINI_TRANSCRIBE_URL, token: TOKEN, capabilities: expected }); + expect(body.params.mode).toBe("SMART"); + expect(d.seen).toHaveLength(1); + expect(d.seen[0]!.body.liveConnectConstraints.config.inputAudioTranscription).toEqual({ mode: "SMART", customVocabulary: ["Ithaca", "Penelope"] }); + } finally { await t.close(); } + }); + + test("a refused mint is the fixed 500 and no other provider is tried", async () => { + const d = double(() => new Response(`API key ${KEY} expired`, { status: 403 })); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "", GEMINI_API_KEY: KEY } }); + try { + keyterms(t, ["Ithaca"]); + const response = await t.fetch("/api/voice/session", { method: "POST" }); + expect(response.status).toBe(500); + const text = await response.text(); + expect(JSON.parse(text)).toEqual({ error: GEMINI_SESSION_FAILED }); + expect(text).not.toContain(KEY); + expect(d.seen).toHaveLength(1); + } finally { await t.close(); } + }); + + test("with both keys and no VOICE_PROVIDER the host keeps Deepgram", async () => { + const t = await httpContractApp({ env: { VOICE_PROVIDER: "", GEMINI_API_KEY: KEY, DEEPGRAM_API_KEY: "fixture-deepgram" } }); + try { + expect((await (await t.fetch("/api/voice/capabilities")).json()).providerId).toBe("deepgram"); + } finally { await t.close(); } + }); +}); From 63251dca270ee833f949bb113c02c252e1f1c9fc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 13:14:15 +0100 Subject: [PATCH 5/9] fix(ui-server): keep legacy speech misconfiguration a route error, not a boot failure The registry threw at construction for an invalid legacy speechProvider, a VOICE_PROVIDER mismatch or an unregistered VOICE_PROVIDER. Those were documented route-time 500 { error } responses; failing construction would take the whole server down over a voice setting. Only misuse of the new speechProviders/defaultSpeechProviderId options now fails construction. The session route parses a selection only from a JSON request, so legacy POSTs with ignored text bodies keep working. The rewritten legacy tests are restored to their main versions. Co-Authored-By: Claude Opus 5.5 --- docs/decisions/dictation-speech.md | 10 +++-- docs/extending/speech.md | 6 +-- docs/integration-contract/package-api.md | 8 ++-- packages/ui-server/src/routes/voice.ts | 11 ++++- .../ui-server/src/voice/speech-providers.ts | 43 ++++++++++++++----- .../ui-server/tests/external-speech.test.ts | 20 ++++----- .../tests/http-discovery-voice.test.ts | 2 +- .../tests/saved-transcription.test.ts | 4 +- .../tests/selectable-dictation.test.ts | 4 +- 9 files changed, 71 insertions(+), 37 deletions(-) diff --git a/docs/decisions/dictation-speech.md b/docs/decisions/dictation-speech.md index 96af9518dc..0c252d4ce5 100644 --- a/docs/decisions/dictation-speech.md +++ b/docs/decisions/dictation-speech.md @@ -39,9 +39,13 @@ Deepgram only when its key is present, otherwise failure. Browser speech is an explicit opt-in; it never becomes a fallback after a missing key or provider failure. -The approved #3707 registration rules move provider validation and host-default -mismatch errors to construction; session validation stays inside the mounted -session route's error boundary. A provider id is nonempty, trimmed and +Legacy configuration errors stay inside the mounted session route's existing +error boundary: an invalid by-value `speechProvider`, a `VOICE_PROVIDER` that +mismatches it, or a `VOICE_PROVIDER` naming an unregistered provider still lets +the server start and answers the voice routes with the existing 500 `{ error }`. +Only misuse of the additive #3707 options (`speechProviders` together with +`speechProvider`, an invalid or duplicate list entry, an unregistered +`defaultSpeechProviderId`) fails construction. A provider id is nonempty, trimmed and lowercase, matching environment resolution. All four capabilities are boolean; `createSession` is callable. Sessions carry a string URL, finite nonnegative expiry and optional string token/string-record params. Empty URL and zero diff --git a/docs/extending/speech.md b/docs/extending/speech.md index fb7c08ccb8..8c33eeb6d3 100644 --- a/docs/extending/speech.md +++ b/docs/extending/speech.md @@ -40,14 +40,14 @@ A supplied value takes precedence over automatic Deepgram key detection. If `config.voice.provider` is set (including by `VOICE_PROVIDER`), it must equal the supplied id. Ids are nonempty, trimmed and lowercase. Without a value, `deepgram`/`webspeech` keep their existing selection rules; absent credentials -never select browser speech. A mismatch or invalid registration fails construction. Session validation and -legacy provider failures return 500 `{ error }` from the protected +never select browser speech. A mismatch, an invalid legacy value, session +validation and provider failures return 500 `{ error }` from the protected `POST /api/voice/session`, without trying another service. To offer several services, pass `createApp({ speechProviders: [first, second], defaultSpeechProviderId: first.id })`. The list adds to configured built-ins; duplicate ids (including built-in collisions), supplying both registration options, -and unregistered host defaults fail construction. Browser speech remains opt-in. +and an unregistered `defaultSpeechProviderId` fail construction. Browser speech remains opt-in. The legacy single value replaces built-ins. A saved dictation choice overrides the host default; a removed saved choice blocks dictation until explicitly changed. Registration snapshots metadata, capabilities and bound methods; changing a supplied diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 2a9db44a0f..abbe3c4468 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1502,13 +1502,15 @@ the supplied implementation. It validates a nonempty trimmed lowercase id, four boolean capabilities and callable `createSession` before invoking it. The returned `SpeechSession` has a string URL, finite nonnegative expiry, optional string token and optional string-record params. Empty URL/zero expiry -remain supported for browser/local sessions. Invalid registrations and host-default mismatches fail construction. Session -validation and legacy provider failures retain the 500 `{ error }` envelope without fallback. +remain supported for browser/local sessions. An invalid legacy value, a +`VOICE_PROVIDER` mismatch or an unregistered `VOICE_PROVIDER` keeps the server +running; the voice routes answer with the existing 500 `{ error }` envelope, +as do session validation and provider failures, without fallback. The deprecated token route remains Deepgram-specific. `CreateAppOptions.speechProviders?: SpeechProvider[]` adds implementations to configured built-ins. Supplying it together with legacy `speechProvider`, duplicate -ids, invalid implementations or an unregistered host default fails construction. +ids, invalid list entries or an unregistered `defaultSpeechProviderId` fails construction. Legacy `speechProvider` replaces all built-ins and must match `VOICE_PROVIDER`. `defaultSpeechProviderId?: string` sets the host default ahead of `VOICE_PROVIDER`, then registered Deepgram; a legacy supplied value is its own default. Deepgram diff --git a/packages/ui-server/src/routes/voice.ts b/packages/ui-server/src/routes/voice.ts index ac6ab9d300..64631d5d3d 100644 --- a/packages/ui-server/src/routes/voice.ts +++ b/packages/ui-server/src/routes/voice.ts @@ -29,7 +29,11 @@ export function createVoiceRoutes(deps: VoiceRoutesDeps): Hono { return new Hono() .get("/voice/providers", (c) => { c.header("Cache-Control", "no-store"); - return c.json(speechProviders.discovery(getDictationSettings(db))); + try { + return c.json(speechProviders.discovery(getDictationSettings(db))); + } catch (err) { + return c.json({ error: err instanceof Error ? err.message : "Voice providers failed" }, 500); + } }) .get("/voice/dictation/settings", (c) => { c.header("Cache-Control", "no-store"); @@ -66,7 +70,10 @@ export function createVoiceRoutes(deps: VoiceRoutesDeps): Hono { .post("/voice/session", async (c) => { let request: VoiceSessionRequest = {}; try { - const raw = await c.req.text(); + // Legacy clients POST without a JSON body (or with ignored text); only an + // explicit JSON request expresses a selection, and it is validated strictly. + const json = /^application\/json\b/i.test(c.req.header("content-type") ?? ""); + const raw = json ? await c.req.text() : ""; if (raw) { const body = JSON.parse(raw); if (!body || typeof body !== "object" || Array.isArray(body) || diff --git a/packages/ui-server/src/voice/speech-providers.ts b/packages/ui-server/src/voice/speech-providers.ts index ba541d752e..2ff65027bd 100644 --- a/packages/ui-server/src/voice/speech-providers.ts +++ b/packages/ui-server/src/voice/speech-providers.ts @@ -164,7 +164,13 @@ function configuredSpeechProviders(voice: VoiceConfig): SpeechProvider[] { } /** Construction fixes identities, metadata, capabilities and executors. Settings - * only choose among these values; they never construct or probe a provider. */ + * only choose among these values; they never construct or probe a provider. + * + * Misuse of the additive options (`speechProviders`, `defaultSpeechProviderId`) + * fails construction. Legacy misconfiguration (an invalid by-value + * `speechProvider`, a `VOICE_PROVIDER` that names an unregistered or + * mismatching provider) keeps its documented meaning: the server starts and + * the voice routes answer with the existing 500 `{ error }` envelope. */ export function createSpeechProviderRegistry(voice: VoiceConfig, options: { speechProvider?: SpeechProvider; speechProviders?: SpeechProvider[]; @@ -173,10 +179,8 @@ export function createSpeechProviderRegistry(voice: VoiceConfig, options: { if (options.speechProvider !== undefined && options.speechProviders !== undefined) { throw new Error("Supply either speechProvider or speechProviders, not both."); } - const supplied = options.speechProvider; - const values = supplied !== undefined ? [supplied] : [...configuredSpeechProviders(voice), ...(options.speechProviders ?? [])]; const providers = new Map(); - for (const value of values) { + const register = (value: SpeechProvider) => { assertSpeechProvider(value); if (providers.has(value.id)) throw new Error(`Duplicate SpeechProvider id "${value.id}".`); providers.set(value.id, Object.freeze({ @@ -187,13 +191,32 @@ export function createSpeechProviderRegistry(voice: VoiceConfig, options: { createSession: value.createSession.bind(value), ...(value.transcribeRecording ? { transcribeRecording: value.transcribeRecording.bind(value) } : {}), })); + }; + const supplied = options.speechProvider; + let legacyError: Error | null = null; + const defer = (fn: () => void) => { try { fn(); } catch (error) { legacyError ??= error instanceof Error ? error : new Error(String(error)); } }; + if (supplied !== undefined) { + defer(() => register(supplied)); + defer(() => { + if (voice.provider && voice.provider !== supplied.id) { + throw new Error(`VOICE_PROVIDER="${voice.provider}" does not match supplied SpeechProvider "${supplied.id}".`); + } + }); + } else { + for (const value of configuredSpeechProviders(voice)) register(value); + for (const value of options.speechProviders ?? []) register(value); + } + if (options.defaultSpeechProviderId !== undefined && !providers.has(options.defaultSpeechProviderId)) { + throw new Error(`defaultSpeechProviderId "${options.defaultSpeechProviderId}" is not a registered speech provider.`); } - if (supplied && voice.provider && supplied.id !== voice.provider) { - throw new Error(`VOICE_PROVIDER="${voice.provider}" does not match supplied SpeechProvider "${supplied.id}".`); + const host = options.defaultSpeechProviderId ?? supplied?.id ?? voice.provider ?? (providers.has("deepgram") ? "deepgram" : null); + if (legacyError === null && host !== null && !providers.has(host)) { + legacyError = host === "deepgram" ? new Error("VOICE_PROVIDER=deepgram but DEEPGRAM_API_KEY is not set.") + : new Error(`Unknown VOICE_PROVIDER="${host}" (expected a registered speech provider: ${[...providers.keys()].join(", ") || "none"}).`); } - const host = options.defaultSpeechProviderId ?? (supplied?.id ?? voice.provider ?? (providers.has("deepgram") ? "deepgram" : null)); - if (host !== null && !providers.has(host)) throw new Error("The host default speech provider is not registered."); + const failed = (): never => { throw legacyError!; }; const discovery = (settings: DictationSettings): VoiceProvidersResponse => { + if (legacyError) failed(); const saved = settings.defaultProvider; const savedUsable = saved !== null && providers.has(saved); const effective = saved !== null ? savedUsable ? saved : null : host ?? (providers.size === 1 ? providers.keys().next().value! : null); @@ -205,8 +228,8 @@ export function createSpeechProviderRegistry(voice: VoiceConfig, options: { }; }; return { - has: (id: string) => providers.has(id), - get: (id: string) => providers.get(id), + has: (id: string) => legacyError === null && providers.has(id), + get: (id: string): SpeechProvider | undefined => legacyError ? failed() : providers.get(id), discovery, effective(settings: DictationSettings): SpeechProvider { const id = discovery(settings).dictation.effective; diff --git a/packages/ui-server/tests/external-speech.test.ts b/packages/ui-server/tests/external-speech.test.ts index e00db4385f..43a968d3e7 100644 --- a/packages/ui-server/tests/external-speech.test.ts +++ b/packages/ui-server/tests/external-speech.test.ts @@ -43,11 +43,6 @@ test("a supplied provider wins over automatic Deepgram discovery but never an ex const provider = externalProvider({ createSession: async () => { calls++; return localSession; } }); for (const selection of ["", "fixture-speech", "deepgram", "webspeech", "unknown"]) { const before = calls; - if (selection && selection !== provider.id) { - await expect(httpContractApp({ env: { VOICE_PROVIDER: selection, DEEPGRAM_API_KEY: "unused-fixture-key" }, speechProvider: provider })).rejects.toThrow(`VOICE_PROVIDER="${selection}" does not match supplied SpeechProvider "fixture-speech".`); - expect(calls).toBe(before); - continue; - } const t = await httpContractApp({ env: { VOICE_PROVIDER: selection, DEEPGRAM_API_KEY: "unused-fixture-key" }, speechProvider: provider }); try { const response = await t.fetch("/api/voice/session", { method: "POST" }); @@ -94,10 +89,6 @@ test("a provider failure stays a session error even when a built-in key is confi test("selection without an external value preserves opt-in browser speech and fails closed otherwise", async () => { for (const selection of ["", "deepgram", "unknown", "webspeech"]) { - if (selection === "deepgram" || selection === "unknown") { - await expect(httpContractApp({ env: { VOICE_PROVIDER: selection, DEEPGRAM_API_KEY: "" } })).rejects.toThrow("host default speech provider is not registered"); - continue; - } const t = await httpContractApp({ env: { VOICE_PROVIDER: selection, DEEPGRAM_API_KEY: "" } }); try { const response = await t.fetch("/api/voice/session", { method: "POST" }); @@ -118,11 +109,16 @@ for (const [field, value] of [ ["id", ""], ["id", " Fixture "], ["capabilities", {}], ["capabilities", { streaming: "true", interimResults: false, keyterms: false, endpointing: false }], ["createSession", null], ] as const) { - test(`construction rejects invalid provider ${field}: ${JSON.stringify(value)}`, async () => { + test(`the mounted route rejects invalid provider ${field}: ${JSON.stringify(value)}`, async () => { let called = false; const provider = externalProvider({ createSession: async () => { called = true; return localSession; }, [field]: value } as unknown as Partial); - await expect(httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProvider: provider })).rejects.toThrow("Invalid SpeechProvider"); - expect(called).toBe(false); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProvider: provider }); + try { + const response = await t.fetch("/api/voice/session", { method: "POST" }); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: expect.stringContaining("Invalid SpeechProvider") }); + expect(called).toBe(false); + } finally { await t.close(); } }); } diff --git a/packages/ui-server/tests/http-discovery-voice.test.ts b/packages/ui-server/tests/http-discovery-voice.test.ts index 061ff31758..ec18672bed 100644 --- a/packages/ui-server/tests/http-discovery-voice.test.ts +++ b/packages/ui-server/tests/http-discovery-voice.test.ts @@ -74,7 +74,7 @@ test("mounted voice session and legacy token use only short-lived injected grant try { for (const path of ["/api/voice/session", "/api/voice/token"]) { const before = Date.now(); - const response = await t.fetch(path, { method: "POST" }); + const response = await t.fetch(path, { method: "POST", body: "ignored non-JSON input" }); expect(response.status).toBe(200); const body = await response.json(); expect(body.token).toBe("fixture-short-lived-token"); diff --git a/packages/ui-server/tests/saved-transcription.test.ts b/packages/ui-server/tests/saved-transcription.test.ts index 5ba21e39e6..d5f8c1efd3 100644 --- a/packages/ui-server/tests/saved-transcription.test.ts +++ b/packages/ui-server/tests/saved-transcription.test.ts @@ -206,7 +206,9 @@ test("optional capability declarations must match the method and Web Speech refu const provider = fake(async () => ({ text: "Ithaca" })); provider.capabilities.savedAudio = !withMethod; if (!withMethod) delete provider.transcribeRecording; - await expect(httpContractApp({ env: { VOICE_PROVIDER: "fixture-speech" }, speechProvider: provider })).rejects.toThrow("savedAudio contradicts transcribeRecording"); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "fixture-speech" }, speechProvider: provider }); + try { expect((await t.fetch("/api/voice/capabilities")).status).toBe(500); expect((await t.fetch(path(randomUUID()), put())).status).toBe(500); } + finally { await t.close(); } } const webspeech = await httpContractApp(); try { diff --git a/packages/ui-server/tests/selectable-dictation.test.ts b/packages/ui-server/tests/selectable-dictation.test.ts index d1d73340f2..cc5ddee624 100644 --- a/packages/ui-server/tests/selectable-dictation.test.ts +++ b/packages/ui-server/tests/selectable-dictation.test.ts @@ -26,7 +26,7 @@ const audio = new Uint8Array([1, 2, 3]); const path = (id: string) => `/api/voice/recordings/${id}/transcription`; const upload = (provider?: string): RequestInit => ({ method: "PUT", body: audio, headers: { "Content-Type": "audio/webm", "Content-SHA256": createHash("sha256").update(audio).digest("hex"), ...(provider !== undefined ? { "Speech-Provider": provider } : {}) } }); -const mint = (providerId?: string, smart?: boolean): RequestInit => ({ method: "POST", ...(providerId !== undefined ? { body: JSON.stringify({ providerId, smart }) } : {}) }); +const mint = (providerId?: string, smart?: boolean): RequestInit => ({ method: "POST", ...(providerId !== undefined ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ providerId, smart }) } : {}) }); const save = (t: HttpContractApp, defaultProvider: string | null, revision = "0", smart = true, headers = {}) => t.fetch(settingsPath, { method: "PUT", headers: { "Content-Type": "application/json", "If-Match": `"${revision}"`, ...headers }, body: JSON.stringify({ defaultProvider, smart }), }); @@ -215,7 +215,7 @@ test("invalid settings are total and malformed requests do not change them", asy expect((await t.fetch(settingsPath, { method: "PUT", headers: { "If-Match": '"0"' }, body })).status).toBe(400); } for (const body of ["{", "null", "[]", '{"providerId":42}', '{"smart":1}']) { - expect((await t.fetch("/api/voice/session", { method: "POST", body })).status).toBe(400); + expect((await t.fetch("/api/voice/session", { method: "POST", headers: { "Content-Type": "application/json" }, body })).status).toBe(400); } expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); } finally { writer.close(); await t.close(); } From 8d11639a389c36243f68128e60b12dc58d6443ca Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 13:29:28 +0100 Subject: [PATCH 6/9] docs: repair dictation citations moved by the speech registry Co-Authored-By: Claude Opus 5.5 --- docs/decisions/dictation-speech.md | 8 ++++---- docs/plans/selectable-dictation.md | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/decisions/dictation-speech.md b/docs/decisions/dictation-speech.md index a3f173d6f7..e572a5cd2b 100644 --- a/docs/decisions/dictation-speech.md +++ b/docs/decisions/dictation-speech.md @@ -33,7 +33,7 @@ or bypass the host's permission and turn machinery. `createApp({ speechProvider })` supplies an implementation by value. It wins over automatic Deepgram discovery. An explicit `config.voice.provider` must match its id; a mismatch fails instead of choosing either implementation -(`createSpeechProviderRegistry`, `packages/ui-server/src/voice/speech-providers.ts:168-195`). +(`createSpeechProviderRegistry`, `packages/ui-server/src/voice/speech-providers.ts:174-242`). Without the value, existing selection remains: explicit built-ins, automatic Deepgram only when its key is present, otherwise failure. Browser speech is an explicit opt-in; it never becomes a fallback after a missing key or provider @@ -129,7 +129,7 @@ path through the brain server under these rulings: recognition of playback via a live track remains a browser path, and on-device recognition is outside the baseline. Thus Deepgram is the only built-in saved-audio implementation; external providers may omit the optional method on the existing seam -(`transcribeRecording?`, `packages/ui-sdk/src/server/speech.ts:38-43`). +(`transcribeRecording?`, `packages/ui-sdk/src/server/speech.ts:40-45`). The server derives the advertised capability from that method, rather than trusting a flag disconnected from its executor (`speechCapabilities`, `packages/ui-server/src/voice/speech-providers.ts:153-155`). @@ -173,13 +173,13 @@ transient/capacity rejection: provider errors, rate limits and definitive provider timeouts. Unknown outcomes stay terminal. Audio/media, parameter, validation and authentication failures do not offer Retry. Classification and attempt counts belong to the receipt, not an automatic client retry loop -(`transcriptionFailure`, `packages/ui-server/src/routes/transcriptions.ts:21-36`). +(`transcriptionFailure`, `packages/ui-server/src/routes/transcriptions.ts:22-37`). This qualified rule supersedes an unqualified promise of one call even after an explicit retry. Plain repeats and uncertain outcomes never redispatch. The upload budget is **10,041,155 bytes**, a derived policy value rather than a duration check (`MAX_TRANSCRIPTION_BYTES`, -`packages/ui-server/src/routes/transcriptions.ts:14-18`). The +`packages/ui-server/src/routes/transcriptions.ts:15-19`). The [October 8 bitrate finding](https://github.com/schlessera/brain-kit/issues/1021#issuecomment-6055498109) reran the V1 probe's track-ended case three times per desktop engine, with Chromium 153.0.8010.12 and Firefox 155.0 in Playwright 1.63.0's Ubuntu 24.04.4 diff --git a/docs/plans/selectable-dictation.md b/docs/plans/selectable-dictation.md index d4a768b2a4..6d37cf235a 100644 --- a/docs/plans/selectable-dictation.md +++ b/docs/plans/selectable-dictation.md @@ -21,12 +21,12 @@ and of the ordinary chat/task model. - One server provider per host. `pickSpeechProvider` returns the supplied by-value provider, an explicit `VOICE_PROVIDER` built-in, Deepgram when its key is present, or throws - (`pickSpeechProvider`, `packages/ui-server/src/voice/speech-providers.ts:127-155`). + (`pickSpeechProvider` in `speech-providers.ts` at `a63e564`; #3707 replaced it with `createSpeechProviderRegistry`). - Every route calls it again per request. The session route mints for whatever it returns - (`.post("/voice/session"`, `packages/ui-server/src/routes/voice.ts:32-58`), + (`POST /voice/session` in `routes/voice.ts` at `a63e564`), and so does the saved-audio upload, before claiming a receipt - (`app.put(path`, `packages/ui-server/src/routes/transcriptions.ts:82-111`). + (the upload `PUT` in `routes/transcriptions.ts` at `a63e564`). - The browser already keys clients by provider id (`createAsrClientRegistry`, `packages/ui-sdk/src/client/asr.ts:41-60`; `registerAsrClients`, `packages/ui-react/src/voice/asr-clients.ts:16-41`). @@ -229,7 +229,7 @@ Content-Type: application/json - The value is stored in the operational settings KV as `voice.dictation` (`{ defaultProvider: string | null, smart: boolean, revision: number }`). The reader is total: a corrupt or invalid row reads as `{ null, true, 0 }` - (`getSetting`, `packages/ui-server/src/db/settings.ts:26-41`). + (`getSetting`, `packages/ui-server/src/db/settings.ts:27-42`). `defaultProvider: null` clears the saved choice. - Writes need a human owner. This route enforces that itself; it does not assume the Models route's guard. Any authenticated human session may read. From 85a69245d9453f6740d3ee2cfedfcea5fd61a3cf Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 13:45:08 +0100 Subject: [PATCH 7/9] CONTRACT: fix(ui-server,ui-react): send the REST auth-token shape and keep Done's last audio MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address the three verified review findings on #3717 (#3708). - The ephemeral-token request used @google/genai's option names (`liveConnectConstraints`, `lockAdditionalFields`) as wire fields. It now sends the REST AuthToken body that the SDK 2.24.0 serializer produces: `bidiGenerateContentSetup` with the locked setup, plus a `fieldMask` that names exactly the setup fields present, with `customVocabulary` omitted from both when there are no keyterms. The loopback double checks a fixture of that captured body, so it no longer mirrors the implementation. Docs and the plan's §6 example follow. The plan's host-default paragraph now separates construction-time `defaultSpeechProviderId` errors from the route-time `VOICE_PROVIDER` 500. - Done stopped capture before flushing, so it dropped up to one 4,096-sample worklet block (~93 ms) of the final words. The capture worklet now answers a "flush" port message with its partial block, and the Gemini client sends those samples and the partial frame before `audioStreamEnd`, all within the existing 3 s drain bound. A hard stop stays immediate. Live conversation never flushes, and its blocks are unchanged. - An abnormal close during Done (e.g. Google's 1011) settled the drain as if it were clean. It is now reported first. useDictation turns a failure reported while Done drains into the ended notice for the retained words, instead of clearing it in the successful-Done reset. Co-Authored-By: Claude Opus 5.5 --- docs/extending/speech.md | 10 +- docs/integration-contract/package-api.md | 12 +- docs/plans/selectable-dictation.md | 36 +++--- packages/ui-react/src/voice/asr-gemini.ts | 51 +++++--- .../ui-react/src/voice/dictation-capture.ts | 8 +- packages/ui-react/src/voice/pcm-capture.ts | 79 +++++++++--- packages/ui-react/src/voice/use-dictation.ts | 17 ++- packages/ui-react/tests/asr-gemini.test.ts | 120 +++++++++++++++++- .../browser/dictation-gemini.offline.tsx | 74 ++++++++++- .../render/dictation-provider-end.test.tsx | 35 +++++ packages/ui-server/src/voice/gemini-speech.ts | 41 +++--- .../tests/fixtures/gemini-auth-token-wire.ts | 54 ++++++++ .../ui-server/tests/gemini-speech.test.ts | 36 ++++-- 13 files changed, 475 insertions(+), 98 deletions(-) create mode 100644 packages/ui-server/tests/fixtures/gemini-auth-token-wire.ts diff --git a/docs/extending/speech.md b/docs/extending/speech.md index 4d78587bf1..695edd19d7 100644 --- a/docs/extending/speech.md +++ b/docs/extending/speech.md @@ -248,9 +248,13 @@ The key stays on the server. For each take the server sends one `POST https://generativelanguage.googleapis.com/v1beta/auth_tokens` with the key in `x-goog-api-key` and receives a single-use ephemeral token: `uses: 1`, 60 seconds to connect (`newSessionExpireTime`, also the session's -`expiresAt`), 11 minutes overall (`expireTime`). Its `liveConnectConstraints` -lock the model, the `TEXT` response modality and the transcription config, so -the token cannot open any other Live session. The transcription config is +`expiresAt`), 11 minutes overall (`expireTime`). Its `bidiGenerateContentSetup` +carries the model, the `TEXT` response modality and the transcription config, +and its `fieldMask` names exactly those fields, so they are locked and the +token cannot open any other Live session. (`liveConnectConstraints` and +`lockAdditionalFields` are the `@google/genai` option names; the REST body is +what that SDK serializes them to.) The browser's `setup` frame repeats the +locked setup field for field. The transcription config is `mode: "SMART"` unless `createSession` receives `mode: "verbatim"`, plus the brain's existing keyterms as `customVocabulary`: at most 100 terms of at most 64 UTF-8 bytes, in order. No chat, history, screen or corpus context is sent. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 34745dd4df..b69b9d1a54 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1547,11 +1547,13 @@ without the key is a selection error. Its capabilities are `streaming`, false, and `savedAudio` false. Each session is one `POST https://generativelanguage.googleapis.com/v1beta/auth_tokens` (`x-goog-api-key`) minting a single-use token (`uses: 1`, connect within 60 s, -expire after 11 min) whose `liveConnectConstraints` lock -`models/gemini-3.5-transcribe-live`, `responseModalities: ["TEXT"]` and -`inputAudioTranscription` (`mode` `SMART` unless `verbatim` is requested; -`customVocabulary` from the keyterms, at most 100 terms of at most 64 UTF-8 -bytes, omitted when empty), with `lockAdditionalFields: []`. The session is +expire after 11 min) whose `bidiGenerateContentSetup` sets +`models/gemini-3.5-transcribe-live`, `generationConfig.responseModalities: +["TEXT"]` and `inputAudioTranscription` (`mode` `SMART` unless `verbatim` is +requested; `customVocabulary` from the keyterms, at most 100 terms of at most +64 UTF-8 bytes, omitted when empty), and whose `fieldMask` locks exactly the +fields set (`model,generationConfig.responseModalities,inputAudioTranscription.mode`, +plus `inputAudioTranscription.customVocabulary` when present). The session is `{ url: , token: "auth_tokens/…", expiresAt: , params: { model, mode, sampleRate: "16000", vocabulary: } }`. Any mint failure is 500 diff --git a/docs/plans/selectable-dictation.md b/docs/plans/selectable-dictation.md index d4a768b2a4..b72a1ff884 100644 --- a/docs/plans/selectable-dictation.md +++ b/docs/plans/selectable-dictation.md @@ -71,7 +71,7 @@ dependency: both sides speak the documented wire protocol, as | Interim text arrives as `serverContent.interimInputTranscription.text` and may change. Final text arrives as `serverContent.inputTranscription.text` on a pause, turn completion or finalization; in SMART mode the final text is the cleaned text. `Transcription.finished` exists in the SDK type | Live guide; SDK `LiveServerContent`, `Transcription` | | `{"realtimeInput":{"audioStreamEnd":true}}` finalizes the turn immediately; the server's VAD is the fallback | Live guide | | A live session lasts at most 10 minutes. There is no diarization or word timestamps | Live guide; model page | -| Ephemeral tokens: `POST https://generativelanguage.googleapis.com/v1beta/auth_tokens` with `x-goog-api-key`; `uses` defaults to 1 (resumption does not count as a use); `expireTime` defaults to 30 minutes and is under 20 hours; `newSessionExpireTime` defaults to 60 s; `liveConnectConstraints` locks model and config; `lockAdditionalFields` locks further fields | Token guide; SDK `CreateAuthTokenConfig` | +| Ephemeral tokens: `POST https://generativelanguage.googleapis.com/v1beta/auth_tokens` with `x-goog-api-key`; `uses` defaults to 1 (resumption does not count as a use); `expireTime` defaults to 30 minutes and is under 20 hours; `newSessionExpireTime` defaults to 60 s. The SDK's `liveConnectConstraints` and `lockAdditionalFields` options serialize to the REST fields `bidiGenerateContentSetup` (the locked Live setup) and `fieldMask` (the locked field paths; an empty `lockAdditionalFields` masks exactly the setup fields present) | Token guide; SDK `CreateAuthTokenConfig`; @google/genai 2.24.0 `createAuthTokenConfigToMldev`, `convertBidiSetupToTokenSetup` | | 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 | @@ -148,9 +148,9 @@ The host default is `defaultSpeechProviderId` (new construction option), else `VOICE_PROVIDER`, else `deepgram` when Deepgram is registered, else none. The Deepgram rule keeps today's auto-detect. A host that already sets `GEMINI_API_KEY` for chat models gains Gemini as a choice, but its dictation -keeps going to Deepgram until the user picks Gemini. A host default naming an -unregistered id is a construction error, as an unknown `VOICE_PROVIDER` is -today. A legacy by-value `speechProvider` is the host default and must still +keeps going to Deepgram until the user picks Gemini. An unregistered +`defaultSpeechProviderId` fails construction, while legacy `VOICE_PROVIDER` +misconfiguration keeps its route-time 500 `{ error }`. A legacy by-value `speechProvider` is the host default and must still match an explicit `VOICE_PROVIDER`. ### Effective provider for the next take (first match wins) @@ -301,17 +301,22 @@ tap mic ─► client reads its cached discovery snapshot (refreshed on Settings POST https://generativelanguage.googleapis.com/v1beta/auth_tokens x-goog-api-key: -{ "uses": 1, - "expireTime": "", +{ "expireTime": "", "newSessionExpireTime": "", - "liveConnectConstraints": { + "uses": 1, + "bidiGenerateContentSetup": { "model": "models/gemini-3.5-transcribe-live", - "config": { "responseModalities": ["TEXT"], - "inputAudioTranscription": { "mode": "SMART", - "customVocabulary": ["Ithaca", "Penelope", "…"] } } }, - "lockAdditionalFields": [] } + "generationConfig": { "responseModalities": ["TEXT"] }, + "inputAudioTranscription": { "mode": "SMART", + "customVocabulary": ["Ithaca", "Penelope", "…"] } }, + "fieldMask": "model,generationConfig.responseModalities,inputAudioTranscription.mode,inputAudioTranscription.customVocabulary" } ``` + This is the REST AuthToken that `@google/genai` 2.24.0 serializes from + `authTokens.create({ config: { liveConnectConstraints, lockAdditionalFields: [] } })`; + those two are SDK option names, not wire fields. Without keyterms, + `customVocabulary` is omitted from both the setup and the mask. + and returns ```json @@ -325,10 +330,11 @@ x-goog-api-key: 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`. -- The constraint locks model, modality and transcription config. Any - additional field the client sends is rejected or overridden by Google, which - is the point of the lock. Whether an empty `lockAdditionalFields` locks - exactly the constrained fields is a #3710 check. +- 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. - 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 diff --git a/packages/ui-react/src/voice/asr-gemini.ts b/packages/ui-react/src/voice/asr-gemini.ts index 77ca334501..41b4f8a57e 100644 --- a/packages/ui-react/src/voice/asr-gemini.ts +++ b/packages/ui-react/src/voice/asr-gemini.ts @@ -72,6 +72,8 @@ export class GeminiAsrClient implements AsrClient { private filled = 0; private reported = false; private settleDrain: (() => void) | null = null; + /** Done has the worklet's tail and the partial frame; audioStreamEnd may follow. */ + private tailFlushed = false; private inbound: Promise = Promise.resolve(); private readonly setup: string; @@ -114,10 +116,11 @@ export class GeminiAsrClient implements AsrClient { socket.onerror = () => { if (this.socket === socket) this.fail("Gemini socket error", "network"); }; socket.onclose = (event: CloseEvent) => { if (this.socket !== socket) return; - if (this.phase === "draining") { this.finishDrain(); return; } - // A clean close (Google's session limit, an expired token) ends the - // take; anything else is also a connection failure. + // A clean close (Google's session limit, an expired token, or the end of + // a drained Done) ends the take; anything else is a connection failure, + // during Done too, so the kept words carry a notice saying why. if (event.code !== 1000) this.report("Gemini session closed", "network"); + if (this.phase === "draining") { this.finishDrain(); return; } this.end(); }; @@ -137,30 +140,46 @@ export class GeminiAsrClient implements AsrClient { this.teardown(); } - /** Done: end the input, wait up to 3 s for the last final, then close. Heard words are kept. */ + /** + * 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. + */ async drainAndStop(): Promise { if (this.phase !== "live") { this.stop(); return; } this.phase = "draining"; - this.microphone?.stop(); this.opts.onAudioLevel?.(0); + const microphone = this.microphone; await new Promise((resolve) => { const timer = setTimeout(() => this.finishDrain(), GEMINI_DRAIN_MS); - this.settleDrain = () => { clearTimeout(timer); resolve(); }; - if (this.filled) { - this.enqueue(this.frame.slice(0, this.filled)); - this.filled = 0; - } - // Before setupComplete the stream end waits with the queued audio. - if (this.setupDone) this.endInput(); + const settle = () => { clearTimeout(timer); resolve(); }; + this.settleDrain = settle; + // Up to one worklet block (~93 ms) of the last words is still in the + // worklet; its acknowledged flush delivers it through capture() first. + void (microphone?.flush() ?? Promise.resolve()).then(() => { + if (this.settleDrain !== settle) return; + microphone?.stop(); + if (this.filled) { + this.enqueue(this.frame.slice(0, this.filled)); + this.filled = 0; + } + if (this.settleDrain !== settle) return; + this.tailFlushed = true; + // Before setupComplete the stream end waits with the queued audio. + if (this.setupDone) this.endInput(); + }); }); this.stop(); } private capture(pcm: Int16Array, rms: number): void { - if (this.phase !== "live") return; - this.opts.onAudioLevel?.(Math.min(1, rms * 4)); + // 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)); + 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); let offset = 0; - while (offset < pcm.length && this.phase === "live") { + while (offset < pcm.length && open()) { const take = Math.min(GEMINI_FRAME_SAMPLES - this.filled, pcm.length - offset); this.frame.set(pcm.subarray(offset, offset + take), this.filled); this.filled += take; @@ -212,7 +231,7 @@ export class GeminiAsrClient implements AsrClient { if (message.setupComplete && !this.setupDone) { this.setupDone = true; if (this.handshake) { clearTimeout(this.handshake); this.handshake = null; } - if (this.phase === "draining") this.endInput(); + if (this.phase === "draining" && this.tailFlushed) this.endInput(); else for (const frame of this.queue.splice(0)) if (!this.send(frame)) return; } const content = message.serverContent; diff --git a/packages/ui-react/src/voice/dictation-capture.ts b/packages/ui-react/src/voice/dictation-capture.ts index c0069875d6..8fa032cce4 100644 --- a/packages/ui-react/src/voice/dictation-capture.ts +++ b/packages/ui-react/src/voice/dictation-capture.ts @@ -14,7 +14,13 @@ type VoiceStore = BrainUiRoot["stores"]["voice"]; * One dictation a `useDictation` hook started, on the root it started it * on, with the client capturing it once one exists. */ -export type Capture = { root: object; client: AsrClient | null; failure?: DictationFailure }; +export type Capture = { + root: object; + client: AsrClient | null; + failure?: DictationFailure; + /** A failure the client reported while a Done drained it: that Done ends with a notice. */ + drainFailure?: DictationFailure; +}; /** * The dictation each root's voice store is showing, by the capture that diff --git a/packages/ui-react/src/voice/pcm-capture.ts b/packages/ui-react/src/voice/pcm-capture.ts index 546dca2743..298e18a541 100644 --- a/packages/ui-react/src/voice/pcm-capture.ts +++ b/packages/ui-react/src/voice/pcm-capture.ts @@ -31,10 +31,46 @@ export function createPcmResampler(from: number, to: number): (block: Float32Arr export interface PcmMicrophone { /** Resolves once audio flows; rejects when the microphone or worklet cannot open. */ ready: Promise; + /** + * Graceful end of input: the worklet posts the samples it holds short of a + * full block, `receive` gets them after every block posted before them, + * and then this resolves. Capture keeps running; the caller stops it. + * Resolves at once when nothing is capturing, and when `stop()` runs first. + */ + flush(): Promise; /** Idempotent hard stop: worklet, source, tracks and AudioContext. */ stop(): void; } +/** Samples the worklet gathers before it posts a block. */ +export const PCM_CAPTURE_BLOCK = 4096; + +/** + * The capture worklet, as the AudioWorkletGlobalScope evaluates it. It posts + * each full block as a bare Float32Array, which is all live conversation ever + * receives. Only a "flush" request makes it post `{ flushed }`, the partial + * block it holds, which also acknowledges the request. + */ +const PCM_CAPTURE_WORKLET = `class Capture extends AudioWorkletProcessor { + constructor() { + super(); this.samples = new Float32Array(${PCM_CAPTURE_BLOCK}); this.used = 0; + this.port.onmessage = ({ data }) => { + if (data !== "flush") return; + this.port.postMessage({ flushed: this.samples.slice(0, this.used) }); this.used = 0; + }; + } + process(inputs) { + const input = inputs[0]?.[0]; + if (input) for (const sample of input) { + this.samples[this.used++] = sample; + if (this.used === this.samples.length) { + this.port.postMessage(this.samples.slice()); this.used = 0; + } + } + return true; + } +} registerProcessor("brain-pcm-capture", Capture);`; + /** * Open the microphone and deliver resampled PCM16 LE blocks with their RMS * level. `interrupted` reports a track the browser ended (device unplugged, @@ -51,8 +87,11 @@ export function openPcmMicrophone( let context: AudioContext | undefined; let node: AudioWorkletNode | undefined; let source: MediaStreamAudioSourceNode | undefined; + const flushes: Array<() => void> = []; + const settleFlushes = () => { for (const settle of flushes.splice(0)) settle(); }; const stop = () => { stopped = true; + settleFlushes(); if (node) { node.port.onmessage = null; node.disconnect(); node = undefined; } source?.disconnect(); source = undefined; stream?.getTracks().forEach((track) => track.stop()); @@ -64,30 +103,23 @@ export function openPcmMicrophone( if (stopped) { stop(); return; } for (const track of stream.getAudioTracks()) track.addEventListener("ended", () => { if (!stopped) { stop(); interrupted(); } }, { once: true }); context = new AudioContext(); - const code = `class Capture extends AudioWorkletProcessor { - constructor() { super(); this.samples = new Float32Array(4096); this.used = 0; } - process(inputs) { - const input = inputs[0]?.[0]; - if (input) for (const sample of input) { - this.samples[this.used++] = sample; - if (this.used === this.samples.length) { - this.port.postMessage(this.samples.slice()); this.used = 0; - } - } - return true; - } - } registerProcessor("brain-pcm-capture", Capture);`; - const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" })); + const url = URL.createObjectURL(new Blob([PCM_CAPTURE_WORKLET], { type: "text/javascript" })); try { await context.audioWorklet.addModule(url); } finally { URL.revokeObjectURL(url); } if (stopped) { stop(); return; } source = context.createMediaStreamSource(stream); node = new AudioWorkletNode(context, "brain-pcm-capture", { numberOfInputs: 1, numberOfOutputs: 0 }); const resample = createPcmResampler(context.sampleRate, rate); - node.port.onmessage = ({ data }: MessageEvent) => { - if (stopped) return; + const deliver = (block: Float32Array) => { let energy = 0; - for (const value of data) energy += value * value; - receive(resample(data), data.length ? Math.sqrt(energy / data.length) : 0); + for (const value of block) energy += value * value; + receive(resample(block), block.length ? Math.sqrt(energy / block.length) : 0); + }; + node.port.onmessage = ({ data }: MessageEvent) => { + if (stopped) return; + if (data instanceof Float32Array) { deliver(data); return; } + if (!(data?.flushed instanceof Float32Array)) return; + if (data.flushed.length) deliver(data.flushed); + settleFlushes(); }; source.connect(node); await context.resume(); @@ -95,7 +127,16 @@ export function openPcmMicrophone( opened(); } catch (error) { stop(); throw error; } })(); - return { ready, stop }; + const flush = () => { + if (stopped || !node) return Promise.resolve(); + const port = node.port; + return new Promise((resolve) => { + flushes.push(resolve); + // The worklet answers after every block it already posted. + port.postMessage("flush"); + }); + }; + return { ready, flush, stop }; } /** Little-endian bytes of PCM16 samples, independent of platform endianness. */ diff --git a/packages/ui-react/src/voice/use-dictation.ts b/packages/ui-react/src/voice/use-dictation.ts index 98b0c8009d..28da7bcad3 100644 --- a/packages/ui-react/src/voice/use-dictation.ts +++ b/packages/ui-react/src/voice/use-dictation.ts @@ -111,6 +111,7 @@ export function useDictation() { onError: (err) => { if (!live(capture)) return; capture.failure = dictationFailure(err); + if (stopping.has(capture)) capture.drainFailure = capture.failure; setError(dictationExplanation(capture.failure, "open")); }, }); @@ -211,14 +212,26 @@ export function useDictation() { // drain, so nothing sees the drain over and the words not yet in review. // Auth cancellation may have invalidated a Done still awaiting drain. if (commitToReview && capture && !stopping.has(capture)) return; - const handled = endDictation(root.stores.voice, commitToReview, drained || ownDrain ? { draining: false } : {}); + // A failure the client reported while it drained (an abnormal close, a + // socket error) ends this Done as the provider-ended path would: the + // kept words carry a notice saying why. One reported earlier, which the + // take survived, does not: Done is not a provider failure. + const { finalText, partial } = root.stores.voice.getState(); + const notice = commitToReview && drained && capture?.drainFailure + ? { reason: capture.drainFailure, phase: "ended" as const, retained: Boolean([finalText, partial].join(" ").trim()) } + : null; + const handled = endDictation(root.stores.voice, commitToReview, { + ...(drained || ownDrain ? { draining: false } : {}), + ...(notice ? { dictationNotice: notice } : {}), + }); if (capture) { release(capture); // Ended: nothing it reports from now on is heard. stopping.delete(capture); } // Another hook's drain still owns the buffer: leave it to that drain. - if (handled) resetCapture(); + // endDictation already cleared the transcript; a notice stays shown. + if (handled && !notice) resetCapture(); if (drainFailure) throw drainFailure.error; }, [releaseCapture, resetCapture, root] diff --git a/packages/ui-react/tests/asr-gemini.test.ts b/packages/ui-react/tests/asr-gemini.test.ts index 5c353cfb81..f1335af0ea 100644 --- a/packages/ui-react/tests/asr-gemini.test.ts +++ b/packages/ui-react/tests/asr-gemini.test.ts @@ -4,7 +4,7 @@ import type { AsrEvent, VoiceSessionResponse } from "@schlessera/brain-ui-sdk/cl import { GEMINI_DRAIN_MS, GEMINI_FRAME_SAMPLES, GEMINI_HANDSHAKE_MS, GEMINI_MAX_BUFFERED_BYTES, GEMINI_PRESETUP_FRAMES, GeminiAsrClient, } from "../src/voice/asr-gemini"; -import { createPcmResampler } from "../src/voice/pcm-capture"; +import { createPcmResampler, PCM_CAPTURE_BLOCK } from "../src/voice/pcm-capture"; /** * GeminiAsrClient against a scripted microphone, AudioContext/worklet and @@ -27,23 +27,51 @@ function replaceGlobals(values: Record): () => void { interface Timer { id: number; at: number; run: () => void } -/** A scripted browser: microphone, AudioContext + worklet, WebSocket and (optionally) timers. */ +type Port = { onmessage: ((event: { data: any }) => void) | null; postMessage(data: unknown): void }; +/** Two ends of a MessageChannel: each message arrives asynchronously, in order. */ +function channel(): [Port, Port] { + const a: Port = { onmessage: null, postMessage: (data) => queueMicrotask(() => b.onmessage?.({ data })) }; + const b: Port = { onmessage: null, postMessage: (data) => queueMicrotask(() => a.onmessage?.({ data })) }; + return [a, b]; +} +interface Processor { port: Port; process(inputs: Float32Array[][]): boolean } + +/** + * A scripted browser: microphone, AudioContext, WebSocket and (optionally) + * timers. The worklet is the real one: `addModule` evaluates the source the + * client put in its Blob URL, and each AudioWorkletNode runs that processor + * behind an asynchronous port. + */ function scriptedBrowser({ rate = 48_000, timers = false, answerSetup = true } = {}) { const tracks: Array<{ readyState: string; stop(): void; ended?: () => void }> = []; const contexts: FakeContext[] = []; const nodes: FakeNode[] = []; const sockets: FakeSocket[] = []; + const blobs = new Map(); + const processors = new Map Processor>(); + let nextPort: Port | null = null; + class WorkletProcessor { port: Port; constructor() { this.port = nextPort!; nextPort = null; } } class FakeNode { - port: { onmessage: ((event: { data: Float32Array }) => void) | null } = { onmessage: null }; + port: Port; + processor: Processor; connected = true; - constructor() { nodes.push(this); } + constructor(_context: unknown, name: string) { + const [node, worklet] = channel(); + this.port = node; + nextPort = worklet; + this.processor = new (processors.get(name)!)(); + nodes.push(this); + } disconnect() { this.connected = false; } } class FakeContext { sampleRate = rate; state = "running"; closes = 0; - audioWorklet = { addModule: async () => {} }; + audioWorklet = { addModule: async (url: string) => { + const source = await blobs.get(url)!.text(); + new Function("AudioWorkletProcessor", "registerProcessor", source)(WorkletProcessor, (name: string, processor: new () => Processor) => processors.set(name, processor)); + } }; constructor() { contexts.push(this); } createMediaStreamSource() { return { connect() {}, disconnect() {} }; } async resume() {} @@ -82,7 +110,15 @@ function scriptedBrowser({ rate = 48_000, timers = false, answerSetup = true } = setTimeout: (run: () => void, delay = 0) => { const timer = { id: nextId++, at: now + delay, run }; pending.push(timer); return timer.id; }, clearTimeout: (id: number) => { const index = pending.findIndex((timer) => timer.id === id); if (index >= 0) pending.splice(index, 1); }, } : {}; - const restore = replaceGlobals({ + const objectUrls = { create: Object.getOwnPropertyDescriptor(URL, "createObjectURL"), revoke: Object.getOwnPropertyDescriptor(URL, "revokeObjectURL") }; + Object.defineProperty(URL, "createObjectURL", { configurable: true, writable: true, value: (blob: Blob) => { const url = `blob:fixture/${blobs.size}`; blobs.set(url, blob); return url; } }); + Object.defineProperty(URL, "revokeObjectURL", { configurable: true, writable: true, value: () => {} }); + const restoreUrls = () => { + for (const [name, descriptor] of [["createObjectURL", objectUrls.create], ["revokeObjectURL", objectUrls.revoke]] as const) { + if (descriptor) Object.defineProperty(URL, name, descriptor); else Reflect.deleteProperty(URL, name); + } + }; + const restoreGlobals = replaceGlobals({ WebSocket: FakeSocket, AudioContext: FakeContext, AudioWorkletNode: FakeNode, ...timerGlobals, navigator: { mediaDevices: { async getUserMedia() { const track = { readyState: "live", stop() { this.readyState = "ended"; }, addEventListener(_: string, listener: () => void) { this.ended = listener; } } as (typeof tracks)[number] & { addEventListener(type: string, listener: () => void): void }; @@ -90,6 +126,7 @@ function scriptedBrowser({ rate = 48_000, timers = false, answerSetup = true } = return { getTracks: () => [track], getAudioTracks: () => [track] }; } } }, }); + const restore = () => { restoreGlobals(); restoreUrls(); }; return { tracks, contexts, nodes, sockets, restore, pending, /** Advance scripted time, running due timers in order. */ @@ -100,6 +137,11 @@ function scriptedBrowser({ rate = 48_000, timers = false, answerSetup = true } = for (let i = 0; i < samples; i++) block[i] = Math.sin((2 * Math.PI * frequency * i) / rate) * amplitude; nodes.at(-1)!.port.onmessage?.({ data: block }); }, + /** Hardware-rate samples through the real worklet, in 128-sample render quanta. */ + render(samples: Float32Array) { + const processor = nodes.at(-1)!.processor; + for (let at = 0; at < samples.length; at += 128) processor.process([[samples.subarray(at, Math.min(at + 128, samples.length))]]); + }, }; } @@ -307,6 +349,7 @@ describe("GeminiAsrClient wire behaviour", () => { h.speak(GEMINI_FRAME_SAMPLES * 3 + 300); let settled = false; const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); const audio = h.socket().audio(); expect(audio.map((frame) => atob(frame.data).length)).toEqual([3200, 200]); expect(JSON.parse(h.socket().sent.at(-1)!)).toEqual({ realtimeInput: { audioStreamEnd: true } }); @@ -320,6 +363,71 @@ describe("GeminiAsrClient wire behaviour", () => { expect(h.closes(), "Done is not a provider end").toBe(0); }); + test("Done flushes the worklet's partial block: its samples reach the socket before audioStreamEnd", async () => { + // A 16 kHz context, so the resampler passes samples through one to one. + const h = harness({ rate: 16_000 }); + await h.client.start(); + await tick(); await tick(); + // One full worklet block, then 3,968 samples the worklet holds short of + // the next one: about 250 ms of the last words at 16 kHz. + const tail = PCM_CAPTURE_BLOCK - 128; + const spoken = Float32Array.from({ length: PCM_CAPTURE_BLOCK + tail }, (_, i) => Math.sin((2 * Math.PI * 440 * i) / 16_000) * 0.3); + h.render(spoken); + await tick(); + const beforeDone = decode(h.socket().audio()).length; + expect(beforeDone, "only whole worklet blocks flow while live").toBe(Math.floor(PCM_CAPTURE_BLOCK / GEMINI_FRAME_SAMPLES) * GEMINI_FRAME_SAMPLES); + const draining = h.client.drainAndStop(); + await tick(); await tick(); + const sent = h.socket().sent.map((frame) => JSON.parse(frame)); + const end = sent.findIndex((frame) => frame.realtimeInput?.audioStreamEnd === true); + expect(end, "audioStreamEnd is sent").toBeGreaterThan(0); + expect(sent.slice(end + 1).some((frame) => frame.realtimeInput?.audio), "no audio after audioStreamEnd").toBe(false); + const received = decode(sent.slice(0, end).filter((frame) => frame.realtimeInput?.audio).map((frame) => frame.realtimeInput.audio)); + const expected = createPcmResampler(16_000, 16_000)(spoken); + expect(received.length, "GEMINI_DONE_KEEPS_WORKLET_TAIL").toBe(spoken.length); + expect([...received], "GEMINI_DONE_KEEPS_WORKLET_TAIL samples").toEqual([...expected]); + expect(h.tracks[0]!.readyState, "the microphone closes once the tail is in").toBe("ended"); + h.socket().server({ serverContent: { turnComplete: true } }); + await draining; + }); + + test("hard stop does not wait for the worklet's tail", async () => { + const h = harness({ rate: 16_000 }); + await h.client.start(); + await tick(); await tick(); + h.render(new Float32Array(1_000).fill(0.2)); + h.client.stop(); + expect(h.tracks[0]!.readyState).toBe("ended"); + expect(h.socket().readyState).toBe(3); + await tick(); await tick(); + expect(h.socket().audio(), "nothing of the tail is sent").toHaveLength(0); + expect(h.socket().sent.some((frame) => JSON.parse(frame).realtimeInput?.audioStreamEnd), "no graceful end").toBe(false); + }); + + for (const [name, end, code] of [ + ["an abnormal close", (s: ReturnType) => s.socket().end(1011), "network"], + ["a socket error", (s: ReturnType) => s.socket().onerror?.(), "network"], + ["a model error", (s: ReturnType) => s.socket().server({ error: { message: `Token ${TOKEN} rejected` } }), "unknown"], + ["Google's clean close", (s: ReturnType) => s.socket().end(1000), null], + ] as const) test(`${name} during Done settles the drain${code ? " and reports a failure" : " as a clean end"}`, async () => { + const h = harness(); + await h.client.start(); + await tick(); await tick(); + h.socket().server({ serverContent: { inputTranscription: { text: "Ask Nestor", finished: false } } }); + await tick(); + let settled = false; + const draining = h.client.drainAndStop().then(() => { settled = true; }); + await tick(); + expect(settled).toBe(false); + end(h); + await draining; + expect(h.errors.map((error) => (error as Error & { code?: string }).code), "GEMINI_DRAIN_CLOSE_CLASSIFIED").toEqual(code ? [code] : []); + for (const error of h.errors) expect(error.message).not.toContain(TOKEN); + expect(h.events).toEqual([{ type: "final", text: "Ask Nestor", endsTurn: false }]); + expect(h.closes(), "Done is not a provider end").toBe(0); + expect(h.contexts[0]!.state).toBe("closed"); + }); + test("Done is bounded at 3 s when no final arrives", async () => { const h = harness({ timers: true }); 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 ba2ba1778f..262bca6835 100644 --- a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx +++ b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx @@ -17,6 +17,7 @@ import type { VoiceSessionResponse } from "@schlessera/brain-ui-sdk/client"; import { BrainUiProvider } from "../../src/root-context.js"; import { createBrainUiRoot, type BrainUiRoot } from "../../src/root.js"; import { ChatPage } from "../../src/components/chat/chat-page.js"; +import { createPcmResampler } from "../../src/voice/pcm-capture.js"; import { installFaultNetwork, type FaultNetwork, type FaultSocket } from "./offline/fault-network.ts"; const ITHACA = "odysseus-ithaca"; @@ -93,19 +94,34 @@ function hardware(ctx: TestContext, rate: number) { constructor(options?: AudioContextOptions) { super({ ...options, sampleRate: options?.sampleRate ?? rate }); contexts.push(this); } } Object.defineProperty(window, "AudioContext", { configurable: true, writable: true, value: HardwareContext }); + // Every message the capture worklet posts, as the client's handler sees it. + const OriginalNode = window.AudioWorkletNode; + const nodeDescriptor = Object.getOwnPropertyDescriptor(window, "AudioWorkletNode"); + const worklet: { blocks: Float32Array[]; flushed: Float32Array[] } = { blocks: [], flushed: [] }; + class RecordingNode extends OriginalNode { + constructor(...args: ConstructorParameters) { + super(...args); + this.port.addEventListener("message", ({ data }) => { + if (data instanceof Float32Array) worklet.blocks.push(data); + else if (data?.flushed instanceof Float32Array) worklet.flushed.push(data.flushed); + }); + } + } + Object.defineProperty(window, "AudioWorkletNode", { configurable: true, writable: true, value: RecordingNode }); const media = navigator.mediaDevices; const gum = Object.getOwnPropertyDescriptor(media, "getUserMedia"); const streams: MediaStream[] = []; Object.defineProperty(media, "getUserMedia", { configurable: true, writable: true, value: async () => { const stream = destination.stream.clone(); streams.push(stream); return stream; } }); ctx.onTestFinished(() => { if (descriptor) Object.defineProperty(window, "AudioContext", descriptor); else Reflect.deleteProperty(window, "AudioContext"); + if (nodeDescriptor) Object.defineProperty(window, "AudioWorkletNode", nodeDescriptor); else Reflect.deleteProperty(window, "AudioWorkletNode"); if (gum) Object.defineProperty(media, "getUserMedia", gum); else Reflect.deleteProperty(media, "getUserMedia"); oscillator.stop(); streams.forEach((stream) => stream.getTracks().forEach((track) => track.stop())); destination.stream.getTracks().forEach((track) => track.stop()); void source.close(); }); - return { contexts, streams }; + return { contexts, streams, worklet }; } const dictate = (s: Scene) => s.host.querySelector('[data-composer] [role="button"][aria-label="Dictate"]'); @@ -123,6 +139,12 @@ function json(socket: FaultSocket): Array> { } const audioFrames = (socket: FaultSocket) => json(socket).filter((frame) => frame.realtimeInput?.audio).map((frame) => frame.realtimeInput.audio as { data: string; mimeType: string }); +function pcm16(frames: Array<{ data: string }>): Int16Array { + const bytes = Uint8Array.from(frames.map((frame) => atob(frame.data)).join(""), (char) => char.charCodeAt(0)); + const view = new DataView(bytes.buffer); + return Int16Array.from({ length: bytes.length / 2 }, (_, i) => view.getInt16(i * 2, true)); +} + function decode(frames: Array<{ data: string }>): Float32Array { const bytes = Uint8Array.from(frames.map((frame) => atob(frame.data)).join(""), (char) => char.charCodeAt(0)); const view = new DataView(bytes.buffer); @@ -243,3 +265,53 @@ test("unmount hard-stops capture: tracks, AudioContext and socket are released a expect(speech.sent.length, "no audio after teardown").toBe(sent); expect(json(speech).some((frame) => frame.realtimeInput?.audioStreamEnd), "a hard stop sends no graceful end").toBe(false); }); + +test("Done keeps the worklet's partial block: every captured sample reaches Google before audioStreamEnd", { timeout: 30_000 }, async (ctx) => { + const rate = 48_000; + const audio = hardware(ctx, rate); + const s = await mount(ctx); + const speech = await startDictating(s); + speech.deliver({ setupComplete: {} }); + await expect.poll(() => audio.worklet.blocks.length, { message: "the worklet posts whole blocks", timeout: 10_000 }).toBeGreaterThanOrEqual(3); + // Stop the audio clock part-way into a block (one is ~85 ms at 48 kHz), so + // the worklet holds a tail short of a block when Done is pressed. + const posted = audio.worklet.blocks.length; + await expect.poll(() => audio.worklet.blocks.length, { timeout: 5_000 }).toBeGreaterThan(posted); + await new Promise((resolve) => setTimeout(resolve, 40)); + await audio.contexts[0]!.suspend(); + 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(audio.worklet.flushed, "GEMINI_BROWSER_DONE_KEEPS_TAIL: the worklet handed over its partial block").toHaveLength(1); + expect(audio.worklet.flushed[0]!.length, "GEMINI_BROWSER_DONE_KEEPS_TAIL: the tail is short of a block and not empty").toBeGreaterThan(0); + expect(audio.worklet.flushed[0]!.length).toBeLessThan(4096); + const sent = json(speech); + const end = sent.findIndex((frame) => frame.realtimeInput?.audioStreamEnd === true); + expect(sent.slice(end + 1).some((frame) => frame.realtimeInput?.audio), "no audio after audioStreamEnd").toBe(false); + const resample = createPcmResampler(rate, 16_000); + const expected = [...audio.worklet.blocks, ...audio.worklet.flushed].flatMap((block) => [...resample(block)]); + const received = pcm16(sent.slice(0, end).filter((frame) => frame.realtimeInput?.audio).map((frame) => frame.realtimeInput.audio)); + 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 } }); + await expect.poll(() => s.ui.stores.voice.getState().mode, { message: "the drain ended the dictation" }).toBe("idle"); +}); + +test("Google closing with 1011 while Done drains keeps the words and explains the failure", { timeout: 30_000 }, async (ctx) => { + const audio = hardware(ctx, 48_000); + const s = await mount(ctx); + const speech = await startDictating(s); + 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."); + 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"); + // Google's own close frame with an internal-error code: a completed close + // 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().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-react/tests/render/dictation-provider-end.test.tsx b/packages/ui-react/tests/render/dictation-provider-end.test.tsx index 76a5bbc8d9..747654108f 100644 --- a/packages/ui-react/tests/render/dictation-provider-end.test.tsx +++ b/packages/ui-react/tests/render/dictation-provider-end.test.tsx @@ -598,3 +598,38 @@ test("cancelled and superseded session fetches never create startup notices", as expect(voice(root).dictationNotice, "cancelled start is quiet").toBeNull(); expect(FakeRecognition.all.length).toBe(0); }); + +// A client whose Done fails part-way (Gemini's abnormal close or socket error +// while it drains) reports the failure, then resolves its drain. The Done +// still hands the words to review, and the failure survives it as the notice. +for (const words of [true, false]) test(`an error reported while Done drains survives the Done as the ended notice (${words ? "words retained" : "empty"})`, async () => { + const session: VoiceSessionResponse = { providerId: "drain-fails", url: "wss://speech.invalid/v1/listen", token: "odysseus-grant", expiresAt: Date.now() + 60_000, capabilities }; + const root = createBrainUiRoot({ storage: null, request: async (input) => { + const path = new URL(input, "http://localhost").pathname; + if (path === "/api/voice/session") return Response.json(session); + if (path === "/api/voice/overrides") return Response.json({ overrides: [] }); + if (path === "/api/status") return Response.json({ contentRenderers: [] }); + throw new Error(`Unexpected dictation fixture request: ${path}`); + } }); + roots.push(root); + let options!: Parameters[1]>[0]; + let settle!: () => void; + root.asr.register("drain-fails", (opts) => { + options = opts; + return { start: async () => {}, stop() {}, drainAndStop: () => new Promise((resolve) => { settle = resolve; }) }; + }); + const { dictation } = await mount(root); + await listen(root, dictation); + if (words) act(() => options.onEvent({ type: "final", text: "Ask Nestor", endsTurn: false })); + let done!: Promise; + act(() => { done = dictation.result.current.stop(); }); + expect(voice(root).draining).toBe(true); + await act(async () => { + options.onError(Object.assign(new Error("Gemini session closed"), { code: "network" })); + settle(); + await done; + }); + expect(voice(root).mode).toBe("idle"); + expect(voice(root).reviewText).toBe(words ? "Ask Nestor" : ""); + expect(voice(root).dictationNotice, "DONE_DRAIN_FAILURE_NOTICE").toEqual({ reason: "network", phase: "ended", retained: words }); +}); diff --git a/packages/ui-server/src/voice/gemini-speech.ts b/packages/ui-server/src/voice/gemini-speech.ts index b5c9a6ce90..4979465d03 100644 --- a/packages/ui-server/src/voice/gemini-speech.ts +++ b/packages/ui-server/src/voice/gemini-speech.ts @@ -2,11 +2,13 @@ * Gemini 3.5 Transcribe Live dictation, server side (#3708). * * The long-lived GEMINI_API_KEY never leaves this closure. Each take mints one - * single-use ephemeral token through the documented REST endpoint, with - * `liveConnectConstraints` locking the model, the TEXT modality and the - * transcription configuration, so a browser holding the token cannot open any - * other Live session with it. No SDK dependency: the request is the wire shape - * Google documents, as `gemini-conversation.ts` speaks the Live wire directly. + * single-use ephemeral token through the REST `auth_tokens` endpoint, whose + * `bidiGenerateContentSetup` and `fieldMask` lock the model, the TEXT modality + * and the transcription configuration, so a browser holding the token cannot + * open any other Live session with it. No SDK dependency: the body is the REST + * AuthToken that @google/genai 2.24.0 serializes for `authTokens.create` + * (`liveConnectConstraints` and `lockAdditionalFields` are SDK option names, + * not wire fields), as `gemini-conversation.ts` speaks the Live wire directly. * * Errors never carry the key or Google's response text: every failure is the * one message below, which the session route returns in its 500 envelope. @@ -53,9 +55,19 @@ function geminiVocabulary(keyterms: readonly string[]): string[] { return terms; } -/** The transcription config the token locks and the browser's setup repeats. */ -function geminiTranscriptionConfig(vocabulary: readonly string[], mode: "SMART" | "VERBATIM") { - return { mode, ...(vocabulary.length ? { customVocabulary: [...vocabulary] } : {}) }; +/** + * The Live setup the token locks, which the browser's `setup` frame repeats + * field for field (`GeminiAsrClient`), and the field mask naming exactly the + * fields present: an empty vocabulary is neither set nor locked. + */ +function geminiLockedSetup(vocabulary: readonly string[], mode: "SMART" | "VERBATIM") { + const setup = { + model: GEMINI_TRANSCRIBE_MODEL, + generationConfig: { responseModalities: ["TEXT"] }, + inputAudioTranscription: { mode, ...(vocabulary.length ? { customVocabulary: [...vocabulary] } : {}) }, + }; + const fieldMask = ["model", "generationConfig.responseModalities", "inputAudioTranscription.mode", ...(vocabulary.length ? ["inputAudioTranscription.customVocabulary"] : [])].join(","); + return { setup, fieldMask }; } export function createGeminiSpeechProvider(apiKey: string): SpeechProvider { @@ -77,18 +89,13 @@ export function createGeminiSpeechProvider(apiKey: string): SpeechProvider { const wireMode = mode === "verbatim" ? "VERBATIM" : "SMART"; const vocabulary = geminiVocabulary(keyterms); const now = Date.now(); + const { setup, fieldMask } = geminiLockedSetup(vocabulary, wireMode); const body = { - uses: 1, expireTime: new Date(now + TOKEN_MS).toISOString(), newSessionExpireTime: new Date(now + NEW_SESSION_MS).toISOString(), - liveConnectConstraints: { - model: GEMINI_TRANSCRIBE_MODEL, - config: { - responseModalities: ["TEXT"], - inputAudioTranscription: geminiTranscriptionConfig(vocabulary, wireMode), - }, - }, - lockAdditionalFields: [], + uses: 1, + bidiGenerateContentSetup: setup, + fieldMask, }; let response: Response; try { diff --git a/packages/ui-server/tests/fixtures/gemini-auth-token-wire.ts b/packages/ui-server/tests/fixtures/gemini-auth-token-wire.ts new file mode 100644 index 0000000000..8d24ae493e --- /dev/null +++ b/packages/ui-server/tests/fixtures/gemini-auth-token-wire.ts @@ -0,0 +1,54 @@ +/** + * The REST AuthToken body Google's own client sends to `auth_tokens`, captured + * offline and kept verbatim, so the Gemini dictation tests check the provider + * against a wire schema it did not write. + * + * Provenance: @google/genai 2.24.0 (the installed version), `ai.authTokens.create` + * 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 + * `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. + */ + +/** Keyterms `["Ithaca", "Penelope"]`, SMART. */ +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"}`, +); + +/** No keyterms, SMART: `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"}`, +); + +/** Every top-level field the captured AuthToken bodies carry. */ +const AUTH_TOKEN_FIELDS = Object.keys(AUTH_TOKEN_WITH_VOCABULARY).sort(); + +/** + * Why a body is not this AuthToken shape, or null when it is: exactly the + * captured top-level fields, and a field mask naming exactly the setup's leaf + * fields. Google's REST surface rejects unknown fields, so the loopback double + * answers 400 with this reason. + */ +export function authTokenWireError(body: unknown): string | null { + if (!body || typeof body !== "object" || Array.isArray(body)) return "body is not an object"; + const keys = Object.keys(body).sort(); + if (JSON.stringify(keys) !== JSON.stringify(AUTH_TOKEN_FIELDS)) return `top-level fields ${keys.join(",")} are not ${AUTH_TOKEN_FIELDS.join(",")}`; + const token = body as { uses: unknown; bidiGenerateContentSetup: unknown; fieldMask: unknown }; + if (token.uses !== 1) return "uses is not 1"; + if (typeof token.fieldMask !== "string") return "fieldMask is not a string"; + const setup = token.bidiGenerateContentSetup; + if (!setup || typeof setup !== "object") return "bidiGenerateContentSetup is not an object"; + const leaves = (value: object, prefix = ""): string[] => Object.entries(value).flatMap(([key, child]) => + child && typeof child === "object" && !Array.isArray(child) ? leaves(child, `${prefix}${key}.`) : [`${prefix}${key}`]); + const present = leaves(setup).sort().join(","); + const masked = token.fieldMask.split(",").sort().join(","); + if (present !== masked) return `fieldMask ${token.fieldMask} does not name the setup fields ${present}`; + return null; +} diff --git a/packages/ui-server/tests/gemini-speech.test.ts b/packages/ui-server/tests/gemini-speech.test.ts index 1144277678..6629e2f49b 100644 --- a/packages/ui-server/tests/gemini-speech.test.ts +++ b/packages/ui-server/tests/gemini-speech.test.ts @@ -8,6 +8,7 @@ import { createGeminiSpeechProvider, GEMINI_AUTH_TOKENS_URL, GEMINI_SESSION_FAILED, GEMINI_TRANSCRIBE_MODEL, GEMINI_TRANSCRIBE_URL, } from "../src/voice/gemini-speech"; import { pickSpeechProvider } from "../src/voice/speech-providers"; +import { AUTH_TOKEN_WITH_VOCABULARY, AUTH_TOKEN_WITHOUT_VOCABULARY, authTokenWireError } from "./fixtures/gemini-auth-token-wire"; import { httpContractApp } from "./helpers/http-contract-app"; const KEY = "odysseus-fixture-gemini-key"; @@ -20,7 +21,10 @@ type Answer = (seen: Seen) => Response | Promise; * A loopback stand-in for Google's auth_tokens endpoint. The provider's * `fetch` to the real URL is redirected here, so the request crosses an * actual HTTP hop (method, headers, serialized body) and nothing leaves the - * machine. Everything else is refused, as the test preload would. + * machine. Everything else is refused, as the test preload would. Like + * Google's REST surface, it refuses a body that is not the AuthToken shape + * captured from @google/genai's own serializer (the fixture), so a request + * built from SDK option names fails here before any answer is scripted. */ function authTokensDouble(answer: Answer = () => Response.json({ name: TOKEN })) { const seen: Seen[] = []; @@ -29,6 +33,8 @@ function authTokensDouble(answer: Answer = () => Response.json({ name: TOKEN })) async fetch(request) { const record = { method: request.method, url: request.url, headers: Object.fromEntries(request.headers), body: JSON.parse(await request.text()) }; seen.push(record); + const invalid = authTokenWireError(record.body); + if (invalid) return Response.json({ error: { code: 400, message: `Invalid JSON payload received: ${invalid}` } }, { status: 400 }); return answer(record); }, }); @@ -48,7 +54,7 @@ function probe(failing: boolean) { const d = authTokensDouble(failing ? () => new Response(`API key ${KEY} not valid`, { status: 403 }) : undefined); return { provider: createGeminiSpeechProvider(KEY), - keyterms: () => d.seen.at(-1)?.body.liveConnectConstraints.config.inputAudioTranscription.customVocabulary ?? [], + keyterms: () => d.seen.at(-1)?.body.bidiGenerateContentSetup.inputAudioTranscription.customVocabulary ?? [], dispose: d.dispose, }; } @@ -67,14 +73,9 @@ describe("Gemini dictation session", () => { expect(request!.headers["x-goog-api-key"]).toBe(KEY); expect(request!.headers["content-type"]).toBe("application/json"); const { expireTime, newSessionExpireTime, ...rest } = request!.body; - expect(rest, "GEMINI_CONSTRAINT_LOCK").toEqual({ - uses: 1, - liveConnectConstraints: { - model: GEMINI_TRANSCRIBE_MODEL, - config: { responseModalities: ["TEXT"], inputAudioTranscription: { mode: "SMART", customVocabulary: ["Ithaca", "Penelope"] } }, - }, - lockAdditionalFields: [], - }); + const { expireTime: _e, newSessionExpireTime: _n, ...captured } = AUTH_TOKEN_WITH_VOCABULARY; + expect(authTokenWireError(request!.body), "GEMINI_CONSTRAINT_LOCK wire schema").toBeNull(); + expect(rest, "GEMINI_CONSTRAINT_LOCK").toEqual(captured); expect(Date.parse(newSessionExpireTime)).toBeGreaterThanOrEqual(before + 60_000 - 1); expect(Date.parse(newSessionExpireTime)).toBeLessThanOrEqual(after + 60_000); expect(Date.parse(expireTime)).toBeGreaterThanOrEqual(before + 11 * 60_000 - 1); @@ -86,13 +87,22 @@ describe("Gemini dictation session", () => { expect(JSON.stringify(session)).not.toContain(KEY); }); + test("without keyterms the lock neither sets nor masks customVocabulary", async () => { + const d = double(); + await createGeminiSpeechProvider(KEY).createSession({ keyterms: [] }); + const { expireTime: _e, newSessionExpireTime: _n, ...rest } = d.seen[0]!.body; + const { expireTime: _ce, newSessionExpireTime: _cn, ...captured } = AUTH_TOKEN_WITHOUT_VOCABULARY; + expect(rest, "GEMINI_CONSTRAINT_LOCK").toEqual(captured); + }); + test("verbatim is used only when asked for, in the lock and the browser's setup alike", async () => { const d = double(); const provider = createGeminiSpeechProvider(KEY); 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.liveConnectConstraints.config.inputAudioTranscription)).toEqual([{ mode: "VERBATIM" }, { mode: "SMART" }, { mode: "SMART" }]); + expect(d.seen.map((seen) => seen.body.bidiGenerateContentSetup.inputAudioTranscription)).toEqual([{ mode: "VERBATIM" }, { mode: "SMART" }, { mode: "SMART" }]); + 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", "[]"]]); }); @@ -101,7 +111,7 @@ describe("Gemini dictation session", () => { const long = "Ω".repeat(33); // 66 UTF-8 bytes, 33 characters const terms = ["", " ", "Telemachus", long, "Telemachus", "x".repeat(64), "x".repeat(65), ...Array.from({ length: 150 }, (_, i) => `Ithaca harbor ${i}`)]; const session = await createGeminiSpeechProvider(KEY).createSession({ keyterms: terms }); - const sent: string[] = d.seen[0]!.body.liveConnectConstraints.config.inputAudioTranscription.customVocabulary; + const sent: string[] = d.seen[0]!.body.bidiGenerateContentSetup.inputAudioTranscription.customVocabulary; expect(sent).toHaveLength(100); expect(sent.slice(0, 3)).toEqual(["Telemachus", "x".repeat(64), "Ithaca harbor 0"]); expect(sent).not.toContain(long); @@ -203,7 +213,7 @@ describe("Gemini dictation through the mounted app", () => { expect(body).toMatchObject({ providerId: "gemini", url: GEMINI_TRANSCRIBE_URL, token: TOKEN, capabilities: expected }); expect(body.params.mode).toBe("SMART"); expect(d.seen).toHaveLength(1); - expect(d.seen[0]!.body.liveConnectConstraints.config.inputAudioTranscription).toEqual({ mode: "SMART", customVocabulary: ["Ithaca", "Penelope"] }); + expect(d.seen[0]!.body.bidiGenerateContentSetup).toEqual(AUTH_TOKEN_WITH_VOCABULARY.bidiGenerateContentSetup); } finally { await t.close(); } }); From 0e5e26ae9878ffc337fc2e9d46c101899cbaa908 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 15:03:12 +0100 Subject: [PATCH 8/9] feat(ui-server): built-in dictation providers disclose their label and destination Deepgram and browser speech now carry label/destination like Gemini, so discovery and the Voice settings need no client-side per-id mapping. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/voice/speech-providers.ts | 4 ++++ packages/ui-server/tests/gemini-speech.test.ts | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/packages/ui-server/src/voice/speech-providers.ts b/packages/ui-server/src/voice/speech-providers.ts index 5322667455..fd96511237 100644 --- a/packages/ui-server/src/voice/speech-providers.ts +++ b/packages/ui-server/src/voice/speech-providers.ts @@ -58,6 +58,8 @@ function buildDeepgramUrl(keyterms: string[]): string { export function createDeepgramSpeechProvider(apiKey: string | null): SpeechProvider { return defineSpeechProvider({ id: "deepgram", + label: "Deepgram", + destination: "Microphone audio streams from this browser to Deepgram (nova-3).", capabilities: { streaming: true, interimResults: true, @@ -108,6 +110,8 @@ export function createDeepgramSpeechProvider(apiKey: string | null): SpeechProvi export const webspeechSpeechProvider: SpeechProvider = defineSpeechProvider({ id: "webspeech", + label: "Browser speech recognition", + destination: "Your browser recognizes speech; on Chromium, microphone audio goes to Google.", capabilities: { streaming: true, interimResults: true, diff --git a/packages/ui-server/tests/gemini-speech.test.ts b/packages/ui-server/tests/gemini-speech.test.ts index eeb01a6d2a..e01b725700 100644 --- a/packages/ui-server/tests/gemini-speech.test.ts +++ b/packages/ui-server/tests/gemini-speech.test.ts @@ -167,6 +167,11 @@ describe("Gemini registration in the dictation registry", () => { expect(effective(voice({ provider: "deepgram", geminiApiKey: KEY, deepgramApiKey: "fixture-deepgram" })).id).toBe("deepgram"); const both = createSpeechProviderRegistry(voice({ geminiApiKey: KEY, deepgramApiKey: "fixture-deepgram" })); expect(both.discovery(NONE_SAVED).providers.map(p => p.id)).toEqual(["deepgram", "gemini"]); + // Built-ins disclose their own name and destination; clients need no per-id mapping. + expect(both.discovery(NONE_SAVED).providers.map(p => [p.label, p.destination !== undefined])).toEqual([["Deepgram", true], ["Google Gemini 3.5 Transcribe Live", true]]); + const browser = createSpeechProviderRegistry(voice({ provider: "webspeech" })).discovery(NONE_SAVED).providers[0]!; + expect(browser).toMatchObject({ id: "webspeech", label: "Browser speech recognition" }); + expect(browser.destination).toContain("Google"); expect(both.effective({ ...NONE_SAVED, defaultProvider: "gemini" }).id).toBe("gemini"); expect(() => effective(voice({}))).toThrow("Set DEEPGRAM_API_KEY or GEMINI_API_KEY"); expect(() => effective(voice({ provider: "athena" }))).toThrow('Unknown VOICE_PROVIDER="athena"'); From 704ed662a3490e67823ede711b3ddbbdacdd3382 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 15:52:20 +0100 Subject: [PATCH 9/9] docs(changeset): describe Gemini registration under the dictation registry Co-Authored-By: Claude Opus 5.5 --- .changeset/gemini-transcribe-live-dictation.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/gemini-transcribe-live-dictation.md b/.changeset/gemini-transcribe-live-dictation.md index c92078d0ad..58d6245270 100644 --- a/.changeset/gemini-transcribe-live-dictation.md +++ b/.changeset/gemini-transcribe-live-dictation.md @@ -4,6 +4,6 @@ "@schlessera/brain-ui-react": minor --- -Add Google Gemini 3.5 Transcribe Live as a built-in dictation provider (#3708). `GEMINI_API_KEY` registers it as `gemini`; `VOICE_PROVIDER=gemini` selects it, and without `VOICE_PROVIDER` it is used only when `DEEPGRAM_API_KEY` is unset, so Deepgram keeps precedence. The key stays on the server: each take mints a single-use ephemeral token whose constraints lock `gemini-3.5-transcribe-live`, text output and the transcription config (SMART by default, the brain's keyterms as vocabulary, at most 100 terms of 64 bytes). Any mint failure is the session route's 500 `{ error: "Gemini dictation session failed" }`, with neither the key nor Google's text. The browser's `gemini` client streams 16 kHz mono PCM16 in 100 ms frames, resampled from the hardware rate, with bounded pre-setup buffering, handshake, upload backlog and Done drain; interim text replaces the partial and each final commits once. Gemini cannot transcribe saved recordings. Live conversation's microphone capture now shares the same worklet and resampler, unchanged byte for byte. +Add Google Gemini 3.5 Transcribe Live as a built-in dictation provider (#3708). `GEMINI_API_KEY` registers it as the selectable dictation provider `gemini`. A key never makes it the host default: it is used through `VOICE_PROVIDER=gemini`, a saved Voice-settings choice, or as the only registered provider, and Deepgram stays the host default when its key is set. The Deepgram and browser-speech built-ins now also disclose a `label` and `destination` in `GET /voice/providers`. The key stays on the server: each take mints a single-use ephemeral token whose constraints lock `gemini-3.5-transcribe-live`, text output and the transcription config (SMART by default, the brain's keyterms as vocabulary, at most 100 terms of 64 bytes). Any mint failure is the session route's 500 `{ error: "Gemini dictation session failed" }`, with neither the key nor Google's text. The browser's `gemini` client streams 16 kHz mono PCM16 in 100 ms frames, resampled from the hardware rate, with bounded pre-setup buffering, handshake, upload backlog and Done drain; interim text replaces the partial and each final commits once. Gemini cannot transcribe saved recordings. Live conversation's microphone capture now shares the same worklet and resampler, unchanged byte for byte. -SDK additions: optional `SpeechProvider.label` and `destination`, `createSession({ mode?: "smart" | "verbatim" })`, and `SpeechCapabilities.smartTranscription`. The server validates the new optional fields, and `runSpeechProviderContract` checks their types and that a SMART provider mints for both modes. Keyless tests prove protocol and resource behaviour only; acceptance by Google, accuracy and latency are qualified separately. +The server requires `label` and `destination`, when supplied, to be nonempty strings, and `runSpeechProviderContract` checks the optional SDK fields' types and that a SMART provider mints for both modes. Keyless tests prove protocol and resource behaviour only; acceptance by Google, accuracy and latency are qualified separately.