diff --git a/.changeset/gemini-transcribe-live-dictation.md b/.changeset/gemini-transcribe-live-dictation.md new file mode 100644 index 0000000000..58d6245270 --- /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 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. + +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. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index b10d44d741..9a9e5b8104 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -2187,6 +2187,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/README.md b/docs/extending/README.md index 6e82126069..76953db2c1 100644 --- a/docs/extending/README.md +++ b/docs/extending/README.md @@ -194,8 +194,8 @@ first-party code: `EMBEDDING_PROVIDERS`, `COMPLETION_PROVIDERS`, `@schlessera/brain-compute-boat` package and is unavailable until it ships), `BUILTIN_EMITTERS` in `packages/core/src/lib/skills/index.ts`, the `FIRST_PARTY_BACKENDS` table in `packages/ui-server/src/agent/backend.ts`, and — the same thing written by hand -rather than as a registry — the two `VOICE_PROVIDER` names `pickSpeechProvider` -accepts in `packages/ui-server/src/voice/speech-providers.ts`. +rather than as a registry — the built-in dictation providers `configuredSpeechProviders` registers in +`packages/ui-server/src/voice/speech-providers.ts`. Promotion is therefore only a question for some of the seams. The two client seams are not in it: a `ToolRenderer` pack and an `AsrClient` are registered by diff --git a/docs/extending/speech.md b/docs/extending/speech.md index 8c33eeb6d3..b7a3f41515 100644 --- a/docs/extending/speech.md +++ b/docs/extending/speech.md @@ -64,7 +64,13 @@ 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, +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 @@ -247,6 +253,67 @@ 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 `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. +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 198306bf38..423fc4bcf5 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -848,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` | 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/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, optional smartTranscription) | 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. 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 e905aa5abf..757326f160 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1521,9 +1521,9 @@ ids, invalid list entries or an unregistered `defaultSpeechProviderId` fails con 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. +and Gemini each register when their key is configured (a key adds a choice and +never makes Gemini the host default); browser speech registers only through +`VOICE_PROVIDER=webspeech`. 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. @@ -1560,6 +1560,49 @@ 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 `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 +`{ 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/plans/selectable-dictation.md b/docs/plans/selectable-dictation.md index 6d37cf235a..5693074d3a 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/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..41b4f8a57e --- /dev/null +++ b/packages/ui-react/src/voice/asr-gemini.ts @@ -0,0 +1,293 @@ +// 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; + /** 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; + + 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; + // 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(); + }; + + 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: 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.opts.onAudioLevel?.(0); + const microphone = this.microphone; + await new Promise((resolve) => { + const timer = setTimeout(() => this.finishDrain(), GEMINI_DRAIN_MS); + 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 { + // 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 && 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; + 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.tailFlushed) 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/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 new file mode 100644 index 0000000000..298e18a541 --- /dev/null +++ b/packages/ui-react/src/voice/pcm-capture.ts @@ -0,0 +1,148 @@ +/** + * 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; + /** + * 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, + * 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 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()); + 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 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); + const deliver = (block: Float32Array) => { + let energy = 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(); + if (stopped) { stop(); return; } + opened(); + } catch (error) { stop(); throw error; } + })(); + 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. */ +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/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 new file mode 100644 index 0000000000..f1335af0ea --- /dev/null +++ b/packages/ui-react/tests/asr-gemini.test.ts @@ -0,0 +1,519 @@ +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, PCM_CAPTURE_BLOCK } 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 } + +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: Port; + processor: Processor; + connected = true; + 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 (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() {} + 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 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 }; + tracks.push(track); + return { getTracks: () => [track], getAudioTracks: () => [track] }; + } } }, + }); + const restore = () => { restoreGlobals(); restoreUrls(); }; + 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 }); + }, + /** 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))]]); + }, + }; +} + +// 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; }); + 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 } }); + 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 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(); + 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..262bca6835 --- /dev/null +++ b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx @@ -0,0 +1,317 @@ +/// +/** + * 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 { createPcmResampler } from "../../src/voice/pcm-capture.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 }); + // 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, worklet }; +} + +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 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); + 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); +}); + +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/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-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-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 77ed4e4e15..76c8afbf11 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -2022,7 +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. */ + /** 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; } diff --git a/packages/ui-sdk/src/server/speech.ts b/packages/ui-sdk/src/server/speech.ts index 72ba876cf4..69ee358b55 100644 --- a/packages/ui-sdk/src/server/speech.ts +++ b/packages/ui-sdk/src/server/speech.ts @@ -25,13 +25,17 @@ 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[]; mode?: "smart" | "verbatim" }): Promise; /** Optional saved-audio path. Call only the provider from the server with its 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 d8ce5680cd..439dcb65d1 100644 --- a/packages/ui-server/README.md +++ b/packages/ui-server/README.md @@ -415,6 +415,7 @@ under the [service terms](../geo/README.md#configuration). | `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** — When registering built-in Deepgram dictation | +| `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. A configured key makes Gemini a selectable dictation provider; it becomes the default only through VOICE_PROVIDER=gemini, a saved choice, or as the only registered provider. | **required** — When registering built-in Gemini 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 +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` | 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) | +| `VOICE_PROVIDER` | Host default dictation provider: "deepgram", "gemini", "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 configured GEMINI_API_KEY only adds a choice. 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/config/env.ts b/packages/ui-server/src/config/env.ts index 91695b494c..c2defc3a24 100644 --- a/packages/ui-server/src/config/env.ts +++ b/packages/ui-server/src/config/env.ts @@ -699,10 +699,20 @@ export const ENV_VARS: readonly EnvVarDescriptor[] = [ default: null, required: "When registering built-in Deepgram dictation", }, + { + 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. A configured key " + + "makes Gemini a selectable dictation provider; it becomes the default only through VOICE_PROVIDER=gemini, a saved " + + "choice, or as the only registered provider.", + default: null, + required: "When registering built-in Gemini dictation", + }, { name: "VOICE_PROVIDER", description: - '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.', + 'Host default dictation provider: "deepgram", "gemini", "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 configured GEMINI_API_KEY only adds a choice. A saved dictation choice overrides the host default; an unavailable saved choice never falls back.', default: "(auto-detect)", required: false, }, @@ -835,6 +845,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 +1224,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..4979465d03 --- /dev/null +++ b/packages/ui-server/src/voice/gemini-speech.ts @@ -0,0 +1,133 @@ +/** + * 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 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. + * 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 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 { + 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 { setup, fieldMask } = geminiLockedSetup(vocabulary, wireMode); + const body = { + expireTime: new Date(now + TOKEN_MS).toISOString(), + newSessionExpireTime: new Date(now + NEW_SESSION_MS).toISOString(), + uses: 1, + bidiGenerateContentSetup: setup, + fieldMask, + }; + 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 2ff65027bd..fd96511237 100644 --- a/packages/ui-server/src/voice/speech-providers.ts +++ b/packages/ui-server/src/voice/speech-providers.ts @@ -4,6 +4,8 @@ * * - `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. * @@ -19,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"; @@ -55,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, @@ -105,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, @@ -117,7 +124,7 @@ export const webspeechSpeechProvider: SpeechProvider = defineSpeechProvider({ }, }); -const NO_SPEECH_PROVIDER = 'No speech provider configured. Set DEEPGRAM_API_KEY, or set ' + +const NO_SPEECH_PROVIDER = '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).'; @@ -127,17 +134,20 @@ 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.`); } } + 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.`); } @@ -154,11 +164,12 @@ 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. */ +/** Built-ins registered from configuration. A key adds a choice; it never + * makes that provider the host default (D3). Browser speech stays opt-in. */ function configuredSpeechProviders(voice: VoiceConfig): SpeechProvider[] { const providers: SpeechProvider[] = []; if (voice.deepgramApiKey) providers.push(createDeepgramSpeechProvider(voice.deepgramApiKey)); + if (voice.geminiApiKey) providers.push(createGeminiSpeechProvider(voice.geminiApiKey)); if (voice.provider === "webspeech") providers.push(webspeechSpeechProvider); return providers; } @@ -212,6 +223,7 @@ export function createSpeechProviderRegistry(voice: VoiceConfig, options: { 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.") + : host === "gemini" ? new Error("VOICE_PROVIDER=gemini but GEMINI_API_KEY is not set.") : new Error(`Unknown VOICE_PROVIDER="${host}" (expected a registered speech provider: ${[...providers.keys()].join(", ") || "none"}).`); } const failed = (): never => { throw legacyError!; }; 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 new file mode 100644 index 0000000000..e01b725700 --- /dev/null +++ b/packages/ui-server/tests/gemini-speech.test.ts @@ -0,0 +1,253 @@ +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 { createSpeechProviderRegistry } 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"; +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. 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[] = []; + 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); + const invalid = authTokenWireError(record.body); + if (invalid) return Response.json({ error: { code: 400, message: `Invalid JSON payload received: ${invalid}` } }, { status: 400 }); + 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.bidiGenerateContentSetup.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; + 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); + 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("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.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", "[]"]]); + }); + + 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.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); + 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 }); + +const NONE_SAVED = { defaultProvider: null, smart: true, revision: "0" }; +const effective = (config: VoiceConfig, supplied?: SpeechProvider) => + createSpeechProviderRegistry(config, supplied ? { speechProvider: supplied } : {}).effective(NONE_SAVED); + +describe("Gemini registration in the dictation registry", () => { + test("VOICE_PROVIDER=gemini needs GEMINI_API_KEY, as a route error rather than a boot failure", () => { + expect(() => effective(voice({ provider: "gemini" }))).toThrow("VOICE_PROVIDER=gemini but GEMINI_API_KEY is not set."); + expect(effective(voice({ provider: "gemini", geminiApiKey: KEY, deepgramApiKey: "unused" })).id).toBe("gemini"); + }); + + test("a Gemini key adds a choice; it is used unsaved only as the only provider, and Deepgram stays the host default (D3)", () => { + expect(effective(voice({ geminiApiKey: KEY })).id).toBe("gemini"); + expect(effective(voice({ geminiApiKey: KEY, deepgramApiKey: "fixture-deepgram" })).id).toBe("deepgram"); + 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"'); + }); + + test("the declared capabilities are streaming, SMART, keyterms, manual Done and no saved audio", () => { + const provider = effective(voice({ provider: "gemini", geminiApiKey: KEY })); + expect(provider.capabilities).toEqual({ streaming: true, interimResults: true, keyterms: true, endpointing: false, smartTranscription: true, savedAudio: false }); + 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(() => effective(voice({}), { ...base, ...overrides } as SpeechProvider)).toThrow(message); + expect(() => createSpeechProviderRegistry(voice({}), { speechProviders: [{ ...base, ...overrides } as SpeechProvider] })).toThrow(message); + } + const valid = defineSpeechProvider({ ...base, label: "Fixture", destination: "Audio stays on this fixture.", capabilities: { ...base.capabilities, smartTranscription: false } }); + expect(effective(voice({}), valid)).toMatchObject({ id: "fixture-speech", label: "Fixture", destination: "Audio stays on this fixture." }); + }); +}); + +/** 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.bidiGenerateContentSetup).toEqual(AUTH_TOKEN_WITH_VOCABULARY.bidiGenerateContentSetup); + } 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(); } + }); +});