diff --git a/.changeset/selectable-dictation.md b/.changeset/selectable-dictation.md new file mode 100644 index 0000000000..eb1fda9e82 --- /dev/null +++ b/.changeset/selectable-dictation.md @@ -0,0 +1,11 @@ +--- +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-react": minor +--- + +Register multiple dictation providers, discover their destinations and capabilities, +and persist an owner-controlled default with revision checks. Bind session minting +and saved-audio uploads to the explicitly disclosed provider, and reject retries +that change a receipt's provider. Preserve bodyless clients and legacy by-value +registration while exposing additive protocol types and client helpers. diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index 0e6079c480..e01ed418f9 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -1107,6 +1107,7 @@ signatures (every public export and the types it is made of) success: boolean; }>; checkWorkerHost: () => Promise; + dictationSettings: () => Promise; fileResolve: (path: string) => Promise<{ ancestors: string[]; exists: boolean; @@ -1228,6 +1229,7 @@ signatures (every public export and the types it is made of) timeZone: null | string; }>; refreshModels: () => Promise; + saveDictationSettings: (settings: DictationSettings) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; @@ -1333,7 +1335,8 @@ signatures (every public export and the types it is made of) voiceOverrides: (signal?: AbortSignal) => Promise<{ overrides: PronunciationOverride[]; }>; - voiceSession: (signal?: AbortSignal) => Promise; + voiceProviders: () => Promise; + voiceSession: (signal?: AbortSignal, selection?: VoiceSessionRequest) => Promise; voiceToken: () => Promise; vpnCheck: () => Promise<{ vpn: boolean; @@ -1601,6 +1604,7 @@ signatures (every public export and the types it is made of) success: boolean; }>; checkWorkerHost: () => Promise; + dictationSettings: () => Promise; fileResolve: (path: string) => Promise<{ ancestors: string[]; exists: boolean; @@ -1722,6 +1726,7 @@ signatures (every public export and the types it is made of) timeZone: null | string; }>; refreshModels: () => Promise; + saveDictationSettings: (settings: import("@schlessera/brain-ui-sdk").DictationSettings) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; @@ -1827,7 +1832,8 @@ signatures (every public export and the types it is made of) voiceOverrides: (signal?: AbortSignal) => Promise<{ overrides: import("@schlessera/brain-ui-sdk").PronunciationOverride[]; }>; - voiceSession: (signal?: AbortSignal) => Promise; + voiceProviders: () => Promise; + voiceSession: (signal?: AbortSignal, selection?: import("@schlessera/brain-ui-sdk").VoiceSessionRequest) => Promise; voiceToken: () => Promise; vpnCheck: () => Promise<{ vpn: boolean; diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 4815058a91..994f391eb5 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -168,6 +168,7 @@ export "." (./src/index.ts) type DialogueEvidence type DialoguePage type DialogueRecord + type DictationSettings type Draft type DraftAttachment type DraftAttachmentResponse @@ -468,6 +469,8 @@ export "." (./src/index.ts) type VoiceCapabilitiesResponse type VoiceKeytermsResponse type VoiceMode + type VoiceProvidersResponse + type VoiceSessionRequest type VoiceSessionResponse type VoiceTokenResponse type WikilinkMapResponse @@ -742,6 +745,7 @@ export "./client" (./src/client/index.ts) type DialogueEvidence type DialoguePage type DialogueRecord + type DictationSettings type Draft type DraftAttachment type DraftAttachmentResponse @@ -1133,6 +1137,8 @@ export "./client" (./src/client/index.ts) type VoiceCapabilitiesResponse type VoiceKeytermsResponse type VoiceMode + type VoiceProvidersResponse + type VoiceSessionRequest type VoiceSessionResponse type VoiceTokenResponse type WebSocketClose @@ -1602,6 +1608,7 @@ export "./protocol" (./src/protocol.ts) type DialogueEvidence type DialoguePage type DialogueRecord + type DictationSettings type Draft type DraftAttachment type DraftAttachmentResponse @@ -1896,6 +1903,8 @@ export "./protocol" (./src/protocol.ts) type VoiceCapabilitiesResponse type VoiceKeytermsResponse type VoiceMode + type VoiceProvidersResponse + type VoiceSessionRequest type VoiceSessionResponse type VoiceTokenResponse type WikilinkMapResponse @@ -2408,6 +2417,7 @@ export "./server" (./src/server/index.ts) type DialogueEvidence type DialoguePage type DialogueRecord + type DictationSettings type Draft type DraftAttachment type DraftAttachmentResponse @@ -2845,6 +2855,8 @@ export "./server" (./src/server/index.ts) type VoiceCapabilitiesResponse type VoiceKeytermsResponse type VoiceMode + type VoiceProvidersResponse + type VoiceSessionRequest type VoiceSessionResponse type VoiceTokenResponse type WebSearchBrief @@ -7297,6 +7309,12 @@ signatures (every public export and the types it is made of) identity: string; evidence: DialogueEvidence; } + DictationSettings (packages/ui-sdk/src/protocol.ts) + export interface DictationSettings { + defaultProvider: string | null; + smart: boolean; + revision: string; + } Draft (packages/ui-sdk/src/protocol.ts) export interface Draft { draftId: string; @@ -11391,13 +11409,17 @@ signatures (every public export and the types it is made of) keyterms: boolean; endpointing: boolean; savedAudio?: boolean; + smartTranscription?: boolean; } SpeechProvider (packages/ui-sdk/src/server/speech.ts) export interface SpeechProvider { id: string; + label?: string; + destination?: string; capabilities: SpeechCapabilities; createSession(opts: { keyterms: string[]; + mode?: "smart" | "verbatim"; }): Promise; transcribeRecording?(input: { audio: Uint8Array; @@ -12444,6 +12466,29 @@ signatures (every public export and the types it is made of) } VoiceMode (packages/ui-sdk/src/protocol.ts) export type VoiceMode = "idle" | "dictate" | "conversation"; + VoiceProvidersResponse (packages/ui-sdk/src/protocol.ts) + export interface VoiceProvidersResponse { + providers: Array<{ + id: string; + label: string; + destination?: string; + capabilities: SpeechCapabilities; + }>; + dictation: { + saved: string | null; + savedUsable: boolean; + host: string | null; + effective: string | null; + source: "saved" | "host" | "only" | "none" | "unavailable"; + smart: boolean; + revision: string; + }; + } + VoiceSessionRequest (packages/ui-sdk/src/protocol.ts) + export interface VoiceSessionRequest { + providerId?: string; + smart?: boolean; + } VoiceSessionResponse (packages/ui-sdk/src/protocol.ts) export interface VoiceSessionResponse { providerId: string; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 1d59be16b5..b10d44d741 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -511,6 +511,8 @@ signatures (every public export and the types it is made of) dbPath?: string; renderer?: AppRenderer; speechProvider?: SpeechProvider; + speechProviders?: SpeechProvider[]; + defaultSpeechProviderId?: string; conversationProvider?: LiveConversationProvider; labeller?: LabellerOptions; turnTimeoutMs?: number; diff --git a/docs/decisions/dictation-speech.md b/docs/decisions/dictation-speech.md index ad079f1a88..e572a5cd2b 100644 --- a/docs/decisions/dictation-speech.md +++ b/docs/decisions/dictation-speech.md @@ -33,21 +33,26 @@ or bypass the host's permission and turn machinery. `createApp({ speechProvider })` supplies an implementation by value. It wins over automatic Deepgram discovery. An explicit `config.voice.provider` must match its id; a mismatch fails instead of choosing either implementation -(`pickSpeechProvider`, `packages/ui-server/src/voice/speech-providers.ts:127-155`). +(`createSpeechProviderRegistry`, `packages/ui-server/src/voice/speech-providers.ts:174-242`). Without the value, existing selection remains: explicit built-ins, automatic Deepgram only when its key is present, otherwise failure. Browser speech is an explicit opt-in; it never becomes a fallback after a missing key or provider failure. -Provider validation and session validation happen inside the mounted session -route's existing error boundary. A provider id is nonempty, trimmed and +Legacy configuration errors stay inside the mounted session route's existing +error boundary: an invalid by-value `speechProvider`, a `VOICE_PROVIDER` that +mismatches it, or a `VOICE_PROVIDER` naming an unregistered provider still lets +the server start and answers the voice routes with the existing 500 `{ error }`. +Only misuse of the additive #3707 options (`speechProviders` together with +`speechProvider`, an invalid or duplicate list entry, an unregistered +`defaultSpeechProviderId`) fails construction. A provider id is nonempty, trimmed and lowercase, matching environment resolution. All four capabilities are boolean; `createSession` is callable. Sessions carry a string URL, finite nonnegative expiry and optional string token/string-record params. Empty URL and zero -expiry remain valid for browser/local implementations. Unknown configuration, -mismatch, invalid implementations/results and minting failures return the -existing 500 `{ error }` envelope. Authentication and the deprecated -Deepgram-specific token route keep their existing meanings. +expiry remain valid for browser/local implementations. Invalid session results +and legacy minting failures retain the existing 500 `{ error }` envelope. +Authentication and the deprecated Deepgram-specific token route keep their +existing meanings. Keyterms are built only for a provider declaring support. The route snapshots identity/capabilities before minting; the matching client receives the minted @@ -124,10 +129,10 @@ path through the brain server under these rulings: recognition of playback via a live track remains a browser path, and on-device recognition is outside the baseline. Thus Deepgram is the only built-in saved-audio implementation; external providers may omit the optional method on the existing seam -(`transcribeRecording?`, `packages/ui-sdk/src/server/speech.ts:38-43`). +(`transcribeRecording?`, `packages/ui-sdk/src/server/speech.ts:40-45`). The server derives the advertised capability from that method, rather than trusting a flag disconnected from its executor -(`speechCapabilities`, `packages/ui-server/src/voice/speech-providers.ts:180-182`). +(`speechCapabilities`, `packages/ui-server/src/voice/speech-providers.ts:153-155`). An absent capability keeps playback, typing and retention available, with the tray's explicit unavailable explanation. @@ -168,13 +173,13 @@ transient/capacity rejection: provider errors, rate limits and definitive provider timeouts. Unknown outcomes stay terminal. Audio/media, parameter, validation and authentication failures do not offer Retry. Classification and attempt counts belong to the receipt, not an automatic client retry loop -(`transcriptionFailure`, `packages/ui-server/src/routes/transcriptions.ts:21-36`). +(`transcriptionFailure`, `packages/ui-server/src/routes/transcriptions.ts:22-37`). This qualified rule supersedes an unqualified promise of one call even after an explicit retry. Plain repeats and uncertain outcomes never redispatch. The upload budget is **10,041,155 bytes**, a derived policy value rather than a duration check (`MAX_TRANSCRIPTION_BYTES`, -`packages/ui-server/src/routes/transcriptions.ts:14-18`). The +`packages/ui-server/src/routes/transcriptions.ts:15-19`). The [October 8 bitrate finding](https://github.com/schlessera/brain-kit/issues/1021#issuecomment-6055498109) reran the V1 probe's track-ended case three times per desktop engine, with Chromium 153.0.8010.12 and Firefox 155.0 in Playwright 1.63.0's Ubuntu 24.04.4 diff --git a/docs/extending/speech.md b/docs/extending/speech.md index f2cf310530..8c33eeb6d3 100644 --- a/docs/extending/speech.md +++ b/docs/extending/speech.md @@ -40,10 +40,29 @@ A supplied value takes precedence over automatic Deepgram key detection. If `config.voice.provider` is set (including by `VOICE_PROVIDER`), it must equal the supplied id. Ids are nonempty, trimmed and lowercase. Without a value, `deepgram`/`webspeech` keep their existing selection rules; absent credentials -never select browser speech. A mismatch or provider failure returns 500 -`{ error }` from the existing protected `POST /api/voice/session`, without -trying another service. Validation occurs on that request, before calling an -invalid provider or publishing an invalid session. +never select browser speech. A mismatch, an invalid legacy value, session +validation and provider failures return 500 `{ error }` from the protected +`POST /api/voice/session`, without trying another service. + +To offer several services, pass `createApp({ speechProviders: [first, second], +defaultSpeechProviderId: first.id })`. The list adds to configured built-ins; +duplicate ids (including built-in collisions), supplying both registration options, +and an unregistered `defaultSpeechProviderId` fail construction. Browser speech remains opt-in. +The legacy single value replaces built-ins. A saved dictation choice overrides +the host default; a removed saved choice blocks dictation until explicitly changed. +Registration snapshots metadata, capabilities and bound methods; changing a supplied +object afterward does not alter the registered set or running operations. + +Optional `label` and `destination` describe the service to users. Keep credentials +out of both. Declare `smartTranscription: true` only if `createSession` honors +`mode: "smart" | "verbatim"`; the server passes mode only for that capability. +The saved switch starts true. Existing implementations need no new fields. +Use `voiceProviders()` for discovery (no mint), then send the disclosed id in +`voiceSession(signal, { providerId, smart })`. Saved recordings send +`Speech-Provider` with the confirmed id; a retry must retain the receipt's provider. +See the [HTTP specification](../http-api.md#selectable-dictation-providers) for +settings revisions, exact selection errors and the no-fallback rule. Gemini's +built-in factory is implemented separately in #3708; no placeholder is registered. The four streaming capabilities are boolean. Optional `savedAudio` is derived from a callable `transcribeRecording`; a contradictory explicit declaration is rejected. `streaming` describes streaming recognition, `interimResults` controls partial display, `keyterms` controls domain-term diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index 25b1fed554..dee3dbcdf9 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -142,6 +142,9 @@ row's real mounting check. They do not establish mounting by themselves. | `POST /api/status/worker-host` | `mounted supported handler: POST /api/status/worker-host` | T | | `GET /api/voice/keyterms` | `mounted supported handler: GET /api/voice/keyterms` | N | | `GET /api/voice/overrides` | `mounted supported handler: GET /api/voice/overrides` | N | +| `GET /api/voice/providers` | `mounted supported handler: GET /api/voice/providers` | R | +| `GET /api/voice/dictation/settings` | `mounted supported handler: GET /api/voice/dictation/settings` | R | +| `PUT /api/voice/dictation/settings` | `mounted supported handler: PUT /api/voice/dictation/settings` | R | | `GET /api/voice/capabilities` | `mounted supported handler: GET /api/voice/capabilities` | R | | `GET /api/voice/recordings/:recordingId/transcription` | `mounted supported handler: GET /api/voice/recordings/:recordingId/transcription` | R | | `PUT /api/voice/recordings/:recordingId/transcription` | `mounted supported handler: PUT /api/voice/recordings/:recordingId/transcription` | R | @@ -507,7 +510,7 @@ track measurements and unchanged original bytes; the composer transport creates no inbox thread. Detailed parser/intake/containment checks live in [track-intake.test.ts](../packages/ui-server/tests/track-intake.test.ts). -**R** — [saved-transcription.test.ts](../packages/ui-server/tests/saved-transcription.test.ts): concurrent real-route claims/retries, server hashes, body caps, account access, terminal outcomes, tombstones and keyless provider transport. +**R** — [selectable-dictation.test.ts](../packages/ui-server/tests/selectable-dictation.test.ts) covers exact provider selection, settings revisions/authority and held mint/upload binding; [saved-transcription.test.ts](../packages/ui-server/tests/saved-transcription.test.ts): concurrent real-route claims/retries, server hashes, body caps, account access, terminal outcomes, tombstones and keyless provider transport. **RV — User history restoration.** `turn-revert.test.ts` exercises raw restoration, Undo, partial conflicts, operation identity, authorization, original voice and diff --git a/docs/http-api.md b/docs/http-api.md index fdac577570..198306bf38 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion and individual safety-review routes mounted by `createApp`: 176 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion and individual safety-review routes mounted by `createApp`: 179 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -184,6 +184,9 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/tracks` | I | Resolve canonical imported-track evidence | Paired React track-block/export transport; no independent retrieval API selected. | | GET | `/api/tool-permissions` | I | List remembered always-allow grants | React approval settings; paired administrative transport. Permission behavior remains governed by its own contract. | | DELETE | `/api/tool-permissions/:tool` | I | Revoke one remembered grant | React approval settings; paired administrative transport. Permission behavior remains governed by its own contract. | +| GET | `/api/voice/providers` | S | Read registered dictation providers and effective selection; never mint | Authenticated discovery, no-store. | +| GET | `/api/voice/dictation/settings` | S | Read brain-wide dictation choice, SMART mode and revision | Independent of live conversation settings. | +| PUT | `/api/voice/dictation/settings` | S | Save dictation choice with If-Match revision | Human owner/ambient only; stale writes never overwrite. | | GET | `/api/voice/capabilities` | S | Read active-provider capabilities without minting a credential | Saved-audio discovery and independent clients; additive #1021 contract. | | GET | `/api/voice/recordings/:recordingId/transcription` | S | Read an account-owned durable transcription receipt | Saved-audio status recovery; never dispatches a provider. | | PUT | `/api/voice/recordings/:recordingId/transcription` | S | Explicitly upload or retry saved audio | Account ownership, verified hash, bounded body and durable claim protect idempotency. | @@ -209,7 +212,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 176 declared endpoints are mounted regardless of backend, renderer or +All 179 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. @@ -224,7 +227,7 @@ Range. WebSocket upgrade requires an actual GET. `ALL /api/*` installs origin policy, configured CORS and authentication. With nonempty `ALLOWED_ORIGINS`, CORS middleware answers allowed **OPTIONS /api/** preflights with 204 before authentication, advertising GET, POST, PUT, -DELETE, the `Content-Type`, `If-Match` and `Idempotency-Key` and `Content-SHA256` headers, and credentials. Origin policy runs first; a rejected +DELETE, the `Content-Type`, `If-Match`, `Idempotency-Key`, `Content-SHA256` and `Speech-Provider` headers, and credentials. Origin policy runs first; a rejected origin gets 403. Without that configured middleware there is no universal OPTIONS endpoint: authentication/routing decide the response. These are transport behaviors, not independently supported OPTIONS resource operations. @@ -845,7 +848,7 @@ SDK speech-session payloads rather than exposing long-lived provider keys: | Supported operation | Inputs/defaults | Success | Errors and behavior | | --- | --- | --- | --- | -| POST `/api/voice/session` | No inputs; configured active speech provider, including `createApp({ speechProvider })` | `VoiceSessionResponse`: providerId, connection url, optional token/params, expiresAt and capabilities (streaming, interimResults, keyterms, endpointing, derived savedAudio) | 500 `{ error }` for unavailable provider/minting, invalid provider/session, or explicit provider/value mismatch; no fallback. Keyterms are included only when supported by the provider; browser/local sessions can omit token and use empty URL/zero expiry. | +| POST `/api/voice/session` | Optional JSON `VoiceSessionRequest` `{ providerId?, smart? }`; absent body uses the effective provider | `VoiceSessionResponse`: providerId, connection url, optional token/params, expiresAt and capabilities (streaming, interimResults, keyterms, endpointing, derived savedAudio) | An explicit unregistered provider gives 409 `speech_provider_unavailable` before minting; malformed/non-object JSON or wrong field types give 400 `voice_session_invalid`. No effective provider or mint/session validation failure gives 500 `{ error }`; no fallback. Keyterms are included only when supported by the provider; browser/local sessions can omit token and use empty URL/zero expiry. | | POST `/api/voice/token` | No inputs | `{ token, expiresAt }` | Deprecated Deepgram-specific alias retained for client migration; mints directly with 60-second requested TTL, 500 `{ error }` on failure. | | GET `/api/voice/keyterms` | `rebuild=1` forces cache rebuild; all other values read normal cache | `{ keyterms: string[], generatedAt, count }` | 500 `{ error }` on read/build failure, including a missing, corrupt, locked or unreadable index. Without a usable optional `@schlessera/brain` peer, or with an index version core cannot read, 200 with an empty vocabulary that is never cached ([optional core peer](integration-contract/package-api.md#ui-server-optional-core-peer-breaking-host-migration-697)). | | GET `/api/voice/overrides` | No inputs | `{ overrides: [{ match, replacement }] }` | Configured pronunciation replacements; 500 `{ error }` on cache read/build failure. | @@ -1357,6 +1360,44 @@ authority and disclosure rules are security properties and are pinned by records whose file it can currently read. Only the owner's rows and details carry `markedBy: { label, you }`; other principals' responses omit the field. +## Selectable dictation providers + +`GET /api/voice/providers` returns `VoiceProvidersResponse`: `providers[]` +contains `{ id, label, destination?, capabilities }`; `dictation` contains +`{ saved, savedUsable, host, effective, source, smart, revision }`. Ids absent +from selection are `null`, `savedUsable` is false when nothing is saved, and +`source` is `saved | host | only | none | unavailable`. Discovery is authenticated, +`no-store`, and never mints credentials or probes providers. Labels default to +ids; saved-audio support comes from the optional provider method. + +The registered set is fixed at construction. The saved choice wins if registered; +if removed, it blocks dictation without fallback. With no saved choice, use the +host default, otherwise the sole registered provider, otherwise none. Multiple +providers without a default require a deliberate choice. `/voice/capabilities` +keeps its response shape and reports this effective provider. + +`GET /api/voice/dictation/settings` returns `DictationSettings` +`{ defaultProvider: string | null, smart: boolean, revision: string }` and a quoted +revision `ETag`. Defaults are `{ defaultProvider: null, smart: true, revision: "0" }`. +Corrupt/invalid operational KV `voice.dictation` rows use those defaults; storage +uses a numeric revision. `PUT` accepts `{ defaultProvider, smart? }` (`smart` +defaults true); `null` clears the saved choice. Send `If-Match: ""` +(the unquoted revision is also accepted). Only human `owner`/`ambient` principals +may write; others receive 403 `{ error: "owner_required" }`. Unknown providers +return 400 `speech_provider_unknown`, invalid bodies 400 `dictation_settings_invalid`, +missing If-Match 428 `dictation_settings_stale`, and stale writes 409 +`dictation_settings_stale` with `current`. A successful write returns 200 with the +new settings/revision and ETag. Reads and writes are `no-store`; neither mints a +session, changes a running take, nor touches conversation settings or history. + +`POST /api/voice/session` resolves a supplied `providerId` exactly, before minting, +regardless of current defaults. It snapshots identity/capabilities for the response. +`smart` overrides the saved mode for this request; only a provider declaring +`smartTranscription` receives `mode: "smart" | "verbatim"`. Omitted mode uses the +saved switch (initially true). A failed exact mint returns generic 500 +`{ error: "Voice session failed" }` without provider diagnostics or credentials. +Bodyless legacy requests retain their previous response/error shape. + ## Saved-audio transcription The protected `GET /api/voice/capabilities` returns `VoiceCapabilitiesResponse` @@ -1390,7 +1431,14 @@ specifies the receipt fields, errors, retry decision and permanent retention. `PUT` responds 200 with the stored receipt, including provider failures; a failed plain replay gives 409. `?retry=` is the only retry request, with at most three user retries and no automatic provider calls. -Unsupported providers return 501 `saved_audio_unsupported`. +`Speech-Provider: ` binds upload admission to exactly the disclosed provider, +before reading the audio and before claiming a receipt. An unknown id returns +409 `speech_provider_unavailable`; a streaming-only provider returns 501 +`saved_audio_unsupported`. Neither claims or dispatches. Without this header, +legacy uploads resolve the effective provider at request admission. A retry +naming a different provider returns 409 `transcription_provider_mismatch` with +its original receipt and never dispatches. Plain repeats, tombstones, unknown +outcomes and the retry ceiling retain their existing semantics. `DELETE ?disposition=accepted|discarded` returns 200 with a `consumed` receipt; an invalid disposition gives 400. It removes text, retains the immutable id and hash, and inserts a hashless tombstone if no upload has claimed yet. diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index d8a097c00d..6f8a293b40 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -1050,3 +1050,18 @@ expiry are rechecked at delivery after settlement. `snapshotComplete` and detector completeness are separate; neither omitted details nor a review receipt replace the aggregate. Route absence and refused reads are explicitly unavailable. Existing history visibility and mutation authority remain intact. + + +### Selectable dictation providers (additive, #3707) + +The [dictation routes](../http-api.md#selectable-dictation-providers) add +read-only `/api/voice/providers` discovery and revisioned +`/api/voice/dictation/settings` GET/PUT. The registered set is fixed; a removed +saved choice blocks dictation. Only human owners/ambient accounts write settings. +`POST /api/voice/session` accepts optional `{ providerId, smart }`; an explicit +id is exact or 409 `speech_provider_unavailable`, never a fallback. Bodyless +clients and `/voice/capabilities` retain their shapes. Discovery never mints. +Saved-audio PUT binds `Speech-Provider` before claim/body consumption; absent +headers preserve effective-provider resolution. Retry provider changes return +409 `transcription_provider_mismatch` with the receipt. Settings revisions, +error codes, response schemas and operation binding are supported HTTP promises. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index fa42f0ecdd..abbe3c4468 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1502,10 +1502,35 @@ the supplied implementation. It validates a nonempty trimmed lowercase id, four boolean capabilities and callable `createSession` before invoking it. The returned `SpeechSession` has a string URL, finite nonnegative expiry, optional string token and optional string-record params. Empty URL/zero expiry -remain supported for browser/local sessions. Validation, mismatch and provider -failures return the existing 500 `{ error }` envelope without fallback. +remain supported for browser/local sessions. An invalid legacy value, a +`VOICE_PROVIDER` mismatch or an unregistered `VOICE_PROVIDER` keeps the server +running; the voice routes answer with the existing 500 `{ error }` envelope, +as do session validation and provider failures, without fallback. The deprecated token route remains Deepgram-specific. +`CreateAppOptions.speechProviders?: SpeechProvider[]` adds implementations to +configured built-ins. Supplying it together with legacy `speechProvider`, duplicate +ids, invalid list entries or an unregistered `defaultSpeechProviderId` fails construction. +Legacy `speechProvider` replaces all built-ins and must match `VOICE_PROVIDER`. +`defaultSpeechProviderId?: string` sets the host default ahead of `VOICE_PROVIDER`, +then registered Deepgram; a legacy supplied value is its own default. Deepgram +registers when its key is configured; browser speech registers only through +`VOICE_PROVIDER=webspeech`. The Gemini built-in registration point is reserved for +#3708's factory; this change does not advertise a placeholder Gemini implementation. +A saved brain-wide choice overrides the host default. Removed saved choices block +selection; with neither saved nor host choice only a sole provider is selected. + +`SpeechProvider` adds optional `label?: string`, `destination?: string` and +`createSession` option `mode?: "smart" | "verbatim"`; `SpeechCapabilities` adds +`smartTranscription?: boolean`. Mode is passed only to providers declaring it. +Identity, capabilities, metadata and executor references are fixed at registration. +`VoiceProvidersResponse`, `DictationSettings`, `VoiceSessionRequest` are exported +protocol types for the [HTTP shapes](../http-api.md#selectable-dictation-providers). +`createBrainApi` adds `voiceProviders()`, `dictationSettings()` and +`saveDictationSettings(settings: DictationSettings)` (sends the revision as +If-Match). `voiceSession(signal?, selection?: VoiceSessionRequest)` sends no body +when selection is omitted. Explicit selection never substitutes another provider. + The route builds keyterms only when supported, snapshots provider identity and capabilities, and publishes `VoiceSessionResponse` with connection material. The client's matching `AsrClientFactory` receives that whole session through diff --git a/docs/plans/selectable-dictation.md b/docs/plans/selectable-dictation.md index d4a768b2a4..6d37cf235a 100644 --- a/docs/plans/selectable-dictation.md +++ b/docs/plans/selectable-dictation.md @@ -21,12 +21,12 @@ and of the ordinary chat/task model. - One server provider per host. `pickSpeechProvider` returns the supplied by-value provider, an explicit `VOICE_PROVIDER` built-in, Deepgram when its key is present, or throws - (`pickSpeechProvider`, `packages/ui-server/src/voice/speech-providers.ts:127-155`). + (`pickSpeechProvider` in `speech-providers.ts` at `a63e564`; #3707 replaced it with `createSpeechProviderRegistry`). - Every route calls it again per request. The session route mints for whatever it returns - (`.post("/voice/session"`, `packages/ui-server/src/routes/voice.ts:32-58`), + (`POST /voice/session` in `routes/voice.ts` at `a63e564`), and so does the saved-audio upload, before claiming a receipt - (`app.put(path`, `packages/ui-server/src/routes/transcriptions.ts:82-111`). + (the upload `PUT` in `routes/transcriptions.ts` at `a63e564`). - The browser already keys clients by provider id (`createAsrClientRegistry`, `packages/ui-sdk/src/client/asr.ts:41-60`; `registerAsrClients`, `packages/ui-react/src/voice/asr-clients.ts:16-41`). @@ -229,7 +229,7 @@ Content-Type: application/json - The value is stored in the operational settings KV as `voice.dictation` (`{ defaultProvider: string | null, smart: boolean, revision: number }`). The reader is total: a corrupt or invalid row reads as `{ null, true, 0 }` - (`getSetting`, `packages/ui-server/src/db/settings.ts:26-41`). + (`getSetting`, `packages/ui-server/src/db/settings.ts:27-42`). `defaultProvider: null` clears the saved choice. - Writes need a human owner. This route enforces that itself; it does not assume the Models route's guard. Any authenticated human session may read. diff --git a/packages/ui-react/src/lib/api-client.ts b/packages/ui-react/src/lib/api-client.ts index d5392ab175..109c0268f5 100644 --- a/packages/ui-react/src/lib/api-client.ts +++ b/packages/ui-react/src/lib/api-client.ts @@ -16,6 +16,9 @@ import type { VoiceKeytermsResponse, VoiceTokenResponse, VoiceSessionResponse, + VoiceSessionRequest, + VoiceProvidersResponse, + DictationSettings, PronunciationOverride, ProviderInfo, UnavailableProfileInfo, @@ -505,8 +508,14 @@ export function createBrainApi( ), /** Mint a dictation session for the active speech provider. */ - voiceSession: (signal?: AbortSignal) => - fetchJson("/voice/session", { method: "POST", signal }), + voiceSession: (signal?: AbortSignal, selection?: VoiceSessionRequest) => + fetchJson("/voice/session", { method: "POST", signal, ...(selection !== undefined ? { body: JSON.stringify(selection) } : {}) }), + + voiceProviders: () => fetchJson("/voice/providers"), + dictationSettings: () => fetchJson("/voice/dictation/settings"), + saveDictationSettings: (settings: DictationSettings) => + fetchJson("/voice/dictation/settings", { method: "PUT", headers: { "If-Match": `"${settings.revision}"` }, + body: JSON.stringify({ defaultProvider: settings.defaultProvider, smart: settings.smart }) }), /** @deprecated use voiceSession(); kept during client transition. */ voiceToken: () => diff --git a/packages/ui-react/src/lib/recordings.ts b/packages/ui-react/src/lib/recordings.ts index ad7f77aeca..1606b40f70 100644 --- a/packages/ui-react/src/lib/recordings.ts +++ b/packages/ui-react/src/lib/recordings.ts @@ -784,7 +784,7 @@ export function createRecordingStore(options: RecordingStoreOptions): RecordingS if (response.ok) await applyReceipt(partition, id, result); else if (result.receipt) await applyReceipt(partition, id, result.receipt); else { - const preclaim: Record = { recording_id_invalid: 400, recording_hash_invalid: 400, recording_empty: 400, recording_too_large: 413, recording_media_unsupported: 415, saved_audio_unsupported: 501, transcription_not_found: 404, transcription_retry_stale: 409 }; + const preclaim: Record = { recording_id_invalid: 400, recording_hash_invalid: 400, recording_empty: 400, recording_too_large: 413, recording_media_unsupported: 415, saved_audio_unsupported: 501, speech_provider_unavailable: 409, transcription_not_found: 404, transcription_retry_stale: 409 }; if (preclaim[result.error] === response.status) definitiveRejection = typeof result.message === "string" ? result.message : "The recording was rejected before transcription. The recording is kept."; throw new Error(result.message ?? "Could not transcribe. The recording is kept."); } diff --git a/packages/ui-react/tests/api-client.test.ts b/packages/ui-react/tests/api-client.test.ts index 8ec33c5cb7..7a549670d1 100644 --- a/packages/ui-react/tests/api-client.test.ts +++ b/packages/ui-react/tests/api-client.test.ts @@ -241,3 +241,18 @@ test("retained session listing opts in and encodes its exclusive cursor without expect(cap.urls).toEqual(["/api/sessions?includeRetainedConversations=true&retainedAfter=ithaca%20%2F%3F%26"]); expect(response).toEqual(fixture); }); + + +test("dictation selection client preserves legacy requests and sends exact provider and revision", async () => { + const cap = captureUrl({}); + const signal = new AbortController().signal; + await api.voiceSession(signal); + expect(cap.inits[0]?.body).toBeUndefined(); expect(cap.inits[0]?.signal).toBe(signal); + await api.voiceSession(signal, { providerId: "beta", smart: false }); + expect(JSON.parse(String(cap.inits[1]?.body))).toEqual({ providerId: "beta", smart: false }); + await api.voiceProviders(); await api.dictationSettings(); + await api.saveDictationSettings({ defaultProvider: "alpha", smart: true, revision: "4" }); + expect(cap.urls).toEqual(["/api/voice/session", "/api/voice/session", "/api/voice/providers", "/api/voice/dictation/settings", "/api/voice/dictation/settings"]); + expect(new Headers(cap.inits[4]?.headers).get("If-Match")).toBe('"4"'); + expect(JSON.parse(String(cap.inits[4]?.body))).toEqual({ defaultProvider: "alpha", smart: true }); +}); diff --git a/packages/ui-react/tests/recording-transcription.test.ts b/packages/ui-react/tests/recording-transcription.test.ts index 2e88ec4efa..f7319ddac9 100644 --- a/packages/ui-react/tests/recording-transcription.test.ts +++ b/packages/ui-react/tests/recording-transcription.test.ts @@ -161,7 +161,7 @@ test("an ambiguous upload stays recoverable while the host has not claimed its b }); -for (const [status, error] of [[413, "recording_too_large"], [415, "recording_media_unsupported"], [400, "recording_hash_invalid"], [501, "saved_audio_unsupported"]] as const) test(`definitive pre-claim ${status} rejection leaves audio reviewable`, async () => { +for (const [status, error] of [[413, "recording_too_large"], [415, "recording_media_unsupported"], [400, "recording_hash_invalid"], [501, "saved_audio_unsupported"], [409, "speech_provider_unavailable"]] as const) test(`definitive pre-claim ${status} rejection leaves audio reviewable`, async () => { const f = fixture(); await f.seed("saved"); let uploads = 0; f.root.request = async (url, init) => { if (url.endsWith("capabilities")) return Response.json({ capabilities: { savedAudio: true } }); if (init?.method === "PUT") { uploads++; return Response.json({ error, message: "Recording rejected before provider dispatch." }, { status }); } return new Response("{}", { status: 404 }); }; const s = f.make(); await expect(s.transcribe("account:odysseus", f.id, () => {})).rejects.toThrow(); await s.syncTranscriptions(); diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index b274e74714..77ed4e4e15 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -1990,6 +1990,31 @@ export interface TranscriptionErrorResponse { receipt?: RecordingTranscription; } +/** An explicit provider is exact; omitted selection retains legacy resolution. */ +export interface VoiceSessionRequest { + providerId?: string; + smart?: boolean; +} + +export interface DictationSettings { + defaultProvider: string | null; + smart: boolean; + revision: string; +} + +export interface VoiceProvidersResponse { + providers: Array<{ id: string; label: string; destination?: string; capabilities: SpeechCapabilities }>; + dictation: { + saved: string | null; + savedUsable: boolean; + host: string | null; + effective: string | null; + source: "saved" | "host" | "only" | "none" | "unavailable"; + smart: boolean; + revision: string; + }; +} + export interface SpeechCapabilities { streaming: boolean; interimResults: boolean; @@ -1997,6 +2022,8 @@ export interface SpeechCapabilities { endpointing: boolean; /** Absent/false means saved recordings cannot be transcribed. Derived from the optional server method. */ savedAudio?: boolean; + /** Supports SMART cleanup of the current unsent dictation. */ + smartTranscription?: boolean; } /** @deprecated superseded by VoiceSessionResponse; kept for client migration. */ diff --git a/packages/ui-sdk/src/server/speech.ts b/packages/ui-sdk/src/server/speech.ts index 54b23fe5d8..72ba876cf4 100644 --- a/packages/ui-sdk/src/server/speech.ts +++ b/packages/ui-sdk/src/server/speech.ts @@ -25,13 +25,15 @@ export interface SpeechSession { */ export interface SpeechProvider { id: string; + label?: string; + destination?: string; capabilities: SpeechCapabilities; /** * Mint one dictation session. `keyterms` are domain terms from the brain's * keyterm builder — providers without keyterm support ignore them * (capabilities.keyterms = false). */ - createSession(opts: { keyterms: string[] }): Promise; + createSession(opts: { keyterms: string[]; mode?: "smart" | "verbatim" }): Promise; /** Optional saved-audio path. Call only the provider from the server with its * server-held credential; forward bytes unchanged. Reject on failure. No * automatic retries. Untyped errors are terminal unknown outcomes. */ diff --git a/packages/ui-server/README.md b/packages/ui-server/README.md index bf9203fa97..d8ce5680cd 100644 --- a/packages/ui-server/README.md +++ b/packages/ui-server/README.md @@ -414,7 +414,7 @@ under the [service terms](../geo/README.md#configuration). | `COASTLINE_CACHE_DIR` | Directory holding fetched map geometry. Cached forever; coastlines do not move. | $BRAIN_PATH/.brain-ui/geo | | `COOKIE_SECRET` | Secret signing the session cookie. | **required** — AUTH_MODE=password | | `DB_PATH` | SQLite file for the UI's own database (sessions, passkeys, settings). The turn journal keeps its own database beside it, DB_PATH.journal.db, with the same permissions. Must resolve outside the brain; an in-brain operational-state layout refuses boot with migration guidance. The server factory defaults to ./brain-ui.db; brain-ui-cron defaults to the container path /data/db/brain-ui.db. | ./brain-ui.db (server); /data/db/brain-ui.db (brain-ui-cron) | -| `DEEPGRAM_API_KEY` | Deepgram API key for streaming ASR (short-lived tokens are minted from it). | **required** — VOICE_PROVIDER=deepgram (or any voice use without VOICE_PROVIDER=webspeech) | +| `DEEPGRAM_API_KEY` | Deepgram API key for streaming ASR (short-lived tokens are minted from it). | **required** — When registering built-in Deepgram dictation | | `GITHUB_TOKEN` | Generic GitHub token fallback. Used for skill installs when BRAIN_UI_SKILLS_GITHUB_TOKEN is unset; the host sync mirror transport falls back to it when BRAIN_UI_SYNC_GITHUB_TOKEN is unset. These GitHub tokens never reach brain maintenance workers. | — | | `HOME` | Fallback anchor for the BRAIN_PATH default and the pi config dir (~/.pi). | /root | | `HOST` | Bind host; consulted by the auth validation to decide whether AUTH_MODE=none is loopback-safe. | (empty) | @@ -431,7 +431,7 @@ under the [service terms](../geo/README.md#configuration). | `TYPESAFE_API_KEY` | TypeSafe AI key for the classification pass that draws markdown the model typed as kit blocks (D42). Absent = pass disabled; the answer renders as markdown either way. | — | | `VOICE_CACHE_DIR` | Directory holding the keyterm cache JSON. | $BRAIN_PATH/.brain-ui | | `VOICE_KEYTERM_LIMIT` | Maximum custom-vocabulary terms built from the brain database. | 500 | -| `VOICE_PROVIDER` | Speech provider: "deepgram", "webspeech" (opt-in only — Chromium streams audio to Google), or the id supplied through createApp({ speechProvider }). An explicit name must match a supplied value. Unset prefers that value, otherwise auto-detects deepgram when its key is present. | (auto-detect) | +| `VOICE_PROVIDER` | Host default dictation provider: "deepgram", "webspeech" (explicit opt-in; Chromium streams audio to Google), or a registered by-value id. createApp({ defaultSpeechProviderId }) takes precedence. A legacy speechProvider replaces built-ins and must match this name. Unset prefers that value, otherwise registered deepgram. A saved dictation choice overrides the host default; an unavailable saved choice never falls back. | (auto-detect) | | `WEBAUTHN_ORIGINS` | Comma-separated extra origins allowed for WebAuthn ceremonies. | (empty) | | `WEBAUTHN_RP_ID` | Relying-party id override for proxies that rewrite Host. | (derived from the request origin) | | `WEBAUTHN_RP_NAME` | Relying-party display name shown by authenticators. | Brain UI | diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 12c3f5a92d..bc264f5e39 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -72,6 +72,7 @@ import { createGovernanceRoutes } from "./routes/governance.js"; import { createTranscriptionRoutes } from "./routes/transcriptions.js"; import { createTranscriptionWrites } from "./voice/transcription-writes.js"; import { createSettingsWrites } from "./db/settings-writes.js"; +import { createSpeechProviderRegistry } from "./voice/speech-providers.js"; import { createVoiceRoutes } from "./routes/voice.js"; import { createFilesRoutes, HTML_PREVIEW_CSP, HTML_PREVIEW_PATH } from "./routes/files.js"; import { createInboxIntake } from "./inbox/intake.js"; @@ -238,6 +239,10 @@ export interface CreateAppOptions { * @experimental Part of the SpeechProvider seam until 1.0. */ speechProvider?: SpeechProvider; + /** Additional by-value dictation providers, fixed at construction. */ + speechProviders?: SpeechProvider[]; + /** Must name a registered dictation provider. */ + defaultSpeechProviderId?: string; /** * Live-conversation provider (#957), registered separately from dictation. * Absent: the host does not advertise `liveConversation` and refuses the @@ -341,6 +346,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise settings.saveDictationSettings(db, expected, value), setSetting: (key: string, value: unknown) => settings.setSetting(db, key, value), setHiddenModelIds: (ids: string[]) => settings.setHiddenModelIds(db, ids), setDefaultModelId: (id: string | null) => settings.setDefaultModelId(db, id), @@ -55,6 +56,7 @@ export function createSettingsWrites(db: Database, writer?: SqliteWriter, log?: return result.value; }); return { + saveDictationSettings: (...args) => invoke("saveDictationSettings", args), setSetting: (...args) => invoke("setSetting", args), setHiddenModelIds: (...args) => invoke("setHiddenModelIds", args), setDefaultModelId: (...args) => invoke("setDefaultModelId", args), diff --git a/packages/ui-server/src/db/settings.ts b/packages/ui-server/src/db/settings.ts index a5d54716e3..9b051d7178 100644 --- a/packages/ui-server/src/db/settings.ts +++ b/packages/ui-server/src/db/settings.ts @@ -12,6 +12,7 @@ import { isBillingMode, isThinkingLevel, type BillingMode, + type DictationSettings, type ThinkingLevel, } from "@schlessera/brain-ui-sdk/protocol"; @@ -189,3 +190,26 @@ export function getDetailRetentionDays(db: Database, log?: Logger): number { export function setDetailRetentionDays(db: Database, days: number): void { setSetting(db, DETAIL_RETENTION_KEY, days); } + +const DICTATION_KEY = "voice.dictation"; +/** Invalid rows are discarded as a whole; removed provider ids stay saved. */ +export function getDictationSettings(db: Database): DictationSettings { + const fallback = { defaultProvider: null, smart: true, revision: "0" }; + const value = getSetting(db, DICTATION_KEY, null); + if (!value || typeof value !== "object" || Array.isArray(value)) return fallback; + const row = value as Record; + if (!(row.defaultProvider === null || typeof row.defaultProvider === "string" && row.defaultProvider.length > 0 && row.defaultProvider === row.defaultProvider.trim().toLowerCase()) || + typeof row.smart !== "boolean" || typeof row.revision !== "number" || !Number.isSafeInteger(row.revision) || row.revision < 0) return fallback; + return { defaultProvider: row.defaultProvider, smart: row.smart, revision: String(row.revision) }; +} + +/** The revision comparison and write run in the same writer transaction. */ +export function saveDictationSettings(db: Database, expected: string, value: { defaultProvider: string | null; smart: boolean }) { + return db.transaction(() => { + const current = getDictationSettings(db); + if (expected !== current.revision || Number(current.revision) >= Number.MAX_SAFE_INTEGER) return { saved: false, current }; + const revision = Number(current.revision) + 1; + setSetting(db, DICTATION_KEY, { ...value, revision }); + return { saved: true, current: { ...value, revision: String(revision) } }; + }).immediate(); +} diff --git a/packages/ui-server/src/routes/transcriptions.ts b/packages/ui-server/src/routes/transcriptions.ts index b991a5ff38..16ccb74be8 100644 --- a/packages/ui-server/src/routes/transcriptions.ts +++ b/packages/ui-server/src/routes/transcriptions.ts @@ -1,11 +1,12 @@ +import type { Database } from "bun:sqlite"; +import { getDictationSettings } from "../db/settings.js"; import { createHash } from "node:crypto"; import { Hono, type Context } from "hono"; -import { SpeechTranscriptionError, type SpeechProvider } from "@schlessera/brain-ui-sdk/server"; +import { SpeechTranscriptionError } from "@schlessera/brain-ui-sdk/server"; import type { TranscriptionFailure } from "@schlessera/brain-ui-sdk/protocol"; import type { AppEnv } from "../app-env.js"; -import type { VoiceConfig } from "../config/env.js"; import { getKeyterms, type KeytermSettings } from "../voice/keyterm-builder.js"; -import { pickSpeechProvider, speechCapabilities } from "../voice/speech-providers.js"; +import { speechCapabilities, type SpeechProviderRegistry } from "../voice/speech-providers.js"; import { refuse, TranscriptionError } from "../voice/transcription-store.js"; import type { AwaitableTranscriptionStore } from "../voice/transcription-writes.js"; @@ -54,7 +55,8 @@ async function readAudio(c: Context): Promise { return new Uint8Array(Buffer.concat(chunks, bytes)); } export function createTranscriptionRoutes(deps: { - store: AwaitableTranscriptionStore; voice: VoiceConfig; keyterms: KeytermSettings; speechProvider?: SpeechProvider; + store: AwaitableTranscriptionStore; keyterms: KeytermSettings; + speechProviders: SpeechProviderRegistry; db: Database; }): Hono { const app = new Hono(); const run = (handler: (c: Context, principalId: string, id: string) => Promise) => async (c: Context) => { @@ -80,7 +82,10 @@ export function createTranscriptionRoutes(deps: { return c.json(await deps.store.remove(principalId, id, disposition)); })); app.put(path, run(async (c, principalId, id) => { - const provider = pickSpeechProvider(deps.voice, deps.speechProvider); + const selected = c.req.header("Speech-Provider"); + const provider = selected !== undefined ? deps.speechProviders.get(selected) + : deps.speechProviders.effective(getDictationSettings(deps.db)); + if (!provider) return refuse(409, "speech_provider_unavailable", "That dictation service isn't available on this host."); if (!speechCapabilities(provider).savedAudio) return refuse(501, "saved_audio_unsupported", "Saved-audio transcription is unavailable."); const contentType = c.req.header("content-type") ?? ""; if (!MEDIA.test(contentType)) return refuse(415, "recording_media_unsupported", "Upload a WebM, Ogg or MP4 audio container."); diff --git a/packages/ui-server/src/routes/voice.ts b/packages/ui-server/src/routes/voice.ts index 413c12ad19..64631d5d3d 100644 --- a/packages/ui-server/src/routes/voice.ts +++ b/packages/ui-server/src/routes/voice.ts @@ -1,44 +1,98 @@ +import type { Database } from "bun:sqlite"; +import type { AppEnv } from "../app-env.js"; +import { getDictationSettings } from "../db/settings.js"; +import type { SettingsWrites } from "../db/settings-writes.js"; import { Hono } from "hono"; import type { VoiceKeytermsResponse, VoiceTokenResponse, VoiceSessionResponse, + VoiceSessionRequest, } from "@schlessera/brain-ui-sdk/protocol"; import type { VoiceConfig } from "../config/env.js"; -import type { SpeechProvider, SpeechSession } from "@schlessera/brain-ui-sdk/server"; +import type { SpeechSession } from "@schlessera/brain-ui-sdk/server"; import { mintDeepgramToken } from "../voice/deepgram-token.js"; import { getKeyterms, type KeytermSettings } from "../voice/keyterm-builder.js"; -import { pickSpeechProvider, speechCapabilities } from "../voice/speech-providers.js"; +import { type SpeechProviderRegistry, speechCapabilities } from "../voice/speech-providers.js"; interface VoiceRoutesDeps { voice: VoiceConfig; keyterms: KeytermSettings; - speechProvider?: SpeechProvider; + speechProviders: SpeechProviderRegistry; + db: Database; + settingsWrites: SettingsWrites; } -export function createVoiceRoutes(deps: VoiceRoutesDeps): Hono { - const { voice, keyterms, speechProvider } = deps; +export function createVoiceRoutes(deps: VoiceRoutesDeps): Hono { + const { voice, keyterms, speechProviders, db, settingsWrites } = deps; - return new Hono() + return new Hono() + .get("/voice/providers", (c) => { + c.header("Cache-Control", "no-store"); + try { + return c.json(speechProviders.discovery(getDictationSettings(db))); + } catch (err) { + return c.json({ error: err instanceof Error ? err.message : "Voice providers failed" }, 500); + } + }) + .get("/voice/dictation/settings", (c) => { + c.header("Cache-Control", "no-store"); + const settings = getDictationSettings(db); + c.header("ETag", `"${settings.revision}"`); + return c.json(settings); + }) + .put("/voice/dictation/settings", async (c) => { + c.header("Cache-Control", "no-store"); + const principal = c.get("principal"); + if (principal?.kind !== "owner" && principal?.kind !== "ambient") return c.json({ error: "owner_required" }, 403); + const match = c.req.header("If-Match"); + if (match === undefined) return c.json({ error: "dictation_settings_stale", message: "If-Match is required.", current: getDictationSettings(db) }, 428); + const body = await c.req.json().catch(() => null); + if (!body || typeof body !== "object" || Array.isArray(body) || + !(body.defaultProvider === null || typeof body.defaultProvider === "string") || + (body.smart !== undefined && typeof body.smart !== "boolean")) return c.json({ error: "dictation_settings_invalid" }, 400); + if (body.defaultProvider !== null && !speechProviders.has(body.defaultProvider)) return c.json({ error: "speech_provider_unknown", message: "That dictation service isn't available on this host." }, 400); + const expected = /^"[0-9]+"$/.test(match) ? match.slice(1, -1) : match; + const result = await settingsWrites.saveDictationSettings(expected, { defaultProvider: body.defaultProvider, smart: body.smart ?? true }); + if (!result.saved) return c.json({ error: "dictation_settings_stale", message: "Changed on another device.", current: result.current }, 409); + c.header("ETag", `"${result.current.revision}"`); + return c.json(result.current); + }) .get("/voice/capabilities", (c) => { c.header("Cache-Control", "no-store"); try { - const provider = pickSpeechProvider(voice, speechProvider); + const provider = speechProviders.effective(getDictationSettings(db)); return c.json({ providerId: provider.id, capabilities: speechCapabilities(provider) }); } catch (err) { return c.json({ error: err instanceof Error ? err.message : "Voice capabilities failed" }, 500); } }) .post("/voice/session", async (c) => { + let request: VoiceSessionRequest = {}; + try { + // Legacy clients POST without a JSON body (or with ignored text); only an + // explicit JSON request expresses a selection, and it is validated strictly. + const json = /^application\/json\b/i.test(c.req.header("content-type") ?? ""); + const raw = json ? await c.req.text() : ""; + if (raw) { + const body = JSON.parse(raw); + if (!body || typeof body !== "object" || Array.isArray(body) || + (body.providerId !== undefined && typeof body.providerId !== "string") || + (body.smart !== undefined && typeof body.smart !== "boolean")) return c.json({ error: "voice_session_invalid" }, 400); + request = body; + } + } catch { return c.json({ error: "voice_session_invalid" }, 400); } try { - const provider = pickSpeechProvider(voice, speechProvider); + const settings = getDictationSettings(db); + const provider = request.providerId !== undefined ? speechProviders.get(request.providerId) : speechProviders.effective(settings); + if (!provider) return c.json({ error: "speech_provider_unavailable", message: "That dictation service isn't available on this host." }, 409); const providerId = provider.id; const capabilities = speechCapabilities(provider); // Only fetch domain keyterms when the provider can use them. const terms = capabilities.keyterms ? getKeyterms(keyterms, false).keyterms : []; - const session = await provider.createSession({ keyterms: terms }); + const session = await provider.createSession({ keyterms: terms, ...(capabilities.smartTranscription ? { mode: (request.smart ?? settings.smart) ? "smart" : "verbatim" } as const : {}) }); assertSpeechSession(session); const body: VoiceSessionResponse = { providerId, @@ -51,7 +105,7 @@ export function createVoiceRoutes(deps: VoiceRoutesDeps): Hono { return c.json(body); } catch (err) { return c.json( - { error: err instanceof Error ? err.message : "Voice session failed" }, + { error: request.providerId !== undefined ? "Voice session failed" : err instanceof Error ? err.message : "Voice session failed" }, 500 ); } diff --git a/packages/ui-server/src/voice/speech-providers.ts b/packages/ui-server/src/voice/speech-providers.ts index 94029344db..2ff65027bd 100644 --- a/packages/ui-server/src/voice/speech-providers.ts +++ b/packages/ui-server/src/voice/speech-providers.ts @@ -7,13 +7,14 @@ * - `webspeech` — no server session; the browser's SpeechRecognition does the * work, so it returns empty url/token. * - * VOICE_PROVIDER selects the provider; default is deepgram when - * DEEPGRAM_API_KEY is set, otherwise selection fails. An external value takes - * precedence over auto-detection and must match an explicit VOICE_PROVIDER. + * Registration is fixed at construction. VOICE_PROVIDER selects a host default; + * saved settings choose among registered providers without automatic fallback. + * A legacy external value replaces built-ins and must match VOICE_PROVIDER. * Both arrive here as the resolved * {@link VoiceConfig} — this module reads no environment. */ +import type { DictationSettings, VoiceProvidersResponse } from "@schlessera/brain-ui-sdk/protocol"; import type { SpeechProvider } from "@schlessera/brain-ui-sdk/server"; import { defineSpeechProvider, SpeechTranscriptionError } from "@schlessera/brain-ui-sdk/server"; import type { VoiceConfig } from "../config/env.js"; @@ -116,43 +117,9 @@ export const webspeechSpeechProvider: SpeechProvider = defineSpeechProvider({ }, }); -/** - * Select the active speech provider from the resolved voice config. - * - * webspeech is OPT-IN ONLY (`VOICE_PROVIDER=webspeech`): on Chromium it streams - * microphone audio to Google, so it must never be a silent fallback when the - * Deepgram key goes missing. Every other unresolved case throws so the caller - * 500s loudly instead of quietly degrading to third-party egress. - */ -export function pickSpeechProvider(voice: VoiceConfig, supplied?: SpeechProvider): SpeechProvider { - const configured = voice.provider; - if (supplied !== undefined) { - assertSpeechProvider(supplied); - if (configured && configured !== supplied.id) { - throw new Error(`VOICE_PROVIDER="${configured}" does not match supplied SpeechProvider "${supplied.id}".`); - } - return supplied; - } - if (configured === "webspeech") return webspeechSpeechProvider; - if (configured === "deepgram") { - if (!voice.deepgramApiKey) { - throw new Error("VOICE_PROVIDER=deepgram but DEEPGRAM_API_KEY is not set."); - } - return createDeepgramSpeechProvider(voice.deepgramApiKey); - } - if (configured) { - throw new Error( - `Unknown VOICE_PROVIDER="${configured}" (expected "deepgram" or "webspeech").` - ); - } - // Auto-detect: Deepgram when its key is present; otherwise fail loudly. - if (voice.deepgramApiKey) return createDeepgramSpeechProvider(voice.deepgramApiKey); - throw new Error( - 'No speech provider configured. Set DEEPGRAM_API_KEY, or set ' + - 'VOICE_PROVIDER=webspeech to explicitly opt into the browser speech API ' + - "(which streams audio to Google on Chromium)." - ); -} +const NO_SPEECH_PROVIDER = 'No speech provider configured. Set DEEPGRAM_API_KEY, or set ' + + 'VOICE_PROVIDER=webspeech to explicitly opt into the browser speech API ' + + '(which streams audio to Google on Chromium).'; /** Validate a by-value implementation before invoking it or building keyterms. */ function assertSpeechProvider(provider: SpeechProvider): void { @@ -160,6 +127,12 @@ function assertSpeechProvider(provider: SpeechProvider): void { !provider.id || provider.id !== provider.id.trim().toLowerCase()) { throw new Error("Invalid SpeechProvider: id must be a nonempty, trimmed, lowercase string."); } + for (const field of ["label", "destination"] as const) { + if (provider[field] !== undefined && typeof provider[field] !== "string") throw new Error(`Invalid SpeechProvider: ${field} must be a string.`); + } + if (provider.capabilities?.smartTranscription !== undefined && typeof provider.capabilities.smartTranscription !== "boolean") { + throw new Error("Invalid SpeechProvider: smartTranscription must be boolean."); + } for (const capability of ["streaming", "interimResults", "keyterms", "endpointing"] as const) { if (typeof provider.capabilities?.[capability] !== "boolean") { throw new Error(`Invalid SpeechProvider "${provider.id}": capabilities.${capability} must be boolean.`); @@ -180,3 +153,91 @@ function assertSpeechProvider(provider: SpeechProvider): void { export function speechCapabilities(provider: SpeechProvider) { return { ...provider.capabilities, savedAudio: typeof provider.transcribeRecording === "function" }; } + +/** Built-in registration point: add createGeminiSpeechProvider(voice.geminiApiKey) + * here when #3708 supplies that factory. No placeholder provider is advertised. */ +function configuredSpeechProviders(voice: VoiceConfig): SpeechProvider[] { + const providers: SpeechProvider[] = []; + if (voice.deepgramApiKey) providers.push(createDeepgramSpeechProvider(voice.deepgramApiKey)); + if (voice.provider === "webspeech") providers.push(webspeechSpeechProvider); + return providers; +} + +/** Construction fixes identities, metadata, capabilities and executors. Settings + * only choose among these values; they never construct or probe a provider. + * + * Misuse of the additive options (`speechProviders`, `defaultSpeechProviderId`) + * fails construction. Legacy misconfiguration (an invalid by-value + * `speechProvider`, a `VOICE_PROVIDER` that names an unregistered or + * mismatching provider) keeps its documented meaning: the server starts and + * the voice routes answer with the existing 500 `{ error }` envelope. */ +export function createSpeechProviderRegistry(voice: VoiceConfig, options: { + speechProvider?: SpeechProvider; + speechProviders?: SpeechProvider[]; + defaultSpeechProviderId?: string; +} = {}) { + if (options.speechProvider !== undefined && options.speechProviders !== undefined) { + throw new Error("Supply either speechProvider or speechProviders, not both."); + } + const providers = new Map(); + const register = (value: SpeechProvider) => { + assertSpeechProvider(value); + if (providers.has(value.id)) throw new Error(`Duplicate SpeechProvider id "${value.id}".`); + providers.set(value.id, Object.freeze({ + id: value.id, + ...(value.label !== undefined ? { label: value.label } : {}), + ...(value.destination !== undefined ? { destination: value.destination } : {}), + capabilities: Object.freeze(speechCapabilities(value)), + createSession: value.createSession.bind(value), + ...(value.transcribeRecording ? { transcribeRecording: value.transcribeRecording.bind(value) } : {}), + })); + }; + const supplied = options.speechProvider; + let legacyError: Error | null = null; + const defer = (fn: () => void) => { try { fn(); } catch (error) { legacyError ??= error instanceof Error ? error : new Error(String(error)); } }; + if (supplied !== undefined) { + defer(() => register(supplied)); + defer(() => { + if (voice.provider && voice.provider !== supplied.id) { + throw new Error(`VOICE_PROVIDER="${voice.provider}" does not match supplied SpeechProvider "${supplied.id}".`); + } + }); + } else { + for (const value of configuredSpeechProviders(voice)) register(value); + for (const value of options.speechProviders ?? []) register(value); + } + if (options.defaultSpeechProviderId !== undefined && !providers.has(options.defaultSpeechProviderId)) { + throw new Error(`defaultSpeechProviderId "${options.defaultSpeechProviderId}" is not a registered speech provider.`); + } + const host = options.defaultSpeechProviderId ?? supplied?.id ?? voice.provider ?? (providers.has("deepgram") ? "deepgram" : null); + if (legacyError === null && host !== null && !providers.has(host)) { + legacyError = host === "deepgram" ? new Error("VOICE_PROVIDER=deepgram but DEEPGRAM_API_KEY is not set.") + : new Error(`Unknown VOICE_PROVIDER="${host}" (expected a registered speech provider: ${[...providers.keys()].join(", ") || "none"}).`); + } + const failed = (): never => { throw legacyError!; }; + const discovery = (settings: DictationSettings): VoiceProvidersResponse => { + if (legacyError) failed(); + const saved = settings.defaultProvider; + const savedUsable = saved !== null && providers.has(saved); + const effective = saved !== null ? savedUsable ? saved : null : host ?? (providers.size === 1 ? providers.keys().next().value! : null); + const source = saved !== null ? savedUsable ? "saved" : "unavailable" : host !== null ? "host" : effective !== null ? "only" : "none"; + return { + providers: [...providers.values()].map(provider => ({ id: provider.id, label: provider.label ?? provider.id, + ...(provider.destination !== undefined ? { destination: provider.destination } : {}), capabilities: { ...provider.capabilities } })), + dictation: { saved, savedUsable, host, effective, source, smart: settings.smart, revision: settings.revision }, + }; + }; + return { + has: (id: string) => legacyError === null && providers.has(id), + get: (id: string): SpeechProvider | undefined => legacyError ? failed() : providers.get(id), + discovery, + effective(settings: DictationSettings): SpeechProvider { + const id = discovery(settings).dictation.effective; + if (id !== null) return providers.get(id)!; + // Preserve the original unconfigured-client error text. + if (!providers.size && settings.defaultProvider === null) throw new Error(NO_SPEECH_PROVIDER); + throw new Error("No effective speech provider. Choose an available dictation service in Settings."); + }, + }; +} +export type SpeechProviderRegistry = ReturnType; diff --git a/packages/ui-server/src/voice/transcription-store.ts b/packages/ui-server/src/voice/transcription-store.ts index be370b6a62..d36b2d1158 100644 --- a/packages/ui-server/src/voice/transcription-store.ts +++ b/packages/ui-server/src/voice/transcription-store.ts @@ -72,6 +72,7 @@ export function transcriptionOperations(db: Database, accountKey: (principal: Pr if (row.status === "transcribing") return refuse(409, "transcription_in_progress", "Transcription is already in progress.", stored); if (row.status === "outcome_unknown") return refuse(409, "transcription_outcome_unknown", "The provider may have processed this audio. It cannot be retried.", stored); if (!retry) return refuse(409, "transcription_failed", "Review the failed transcription before choosing a retry.", stored); + if (providerId !== row.provider_id) return refuse(409, "transcription_provider_mismatch", "Retry with the original transcription service.", stored); if (retry !== row.attempt_id) return refuse(409, "transcription_retry_stale", "This retry names an older attempt.", stored); if (!stored.failure?.retryable) return refuse(409, "transcription_not_retryable", "This provider rejection cannot be retried.", stored); if (row.retry_count >= 3) return refuse(409, "transcription_retry_limit", "All three retries have been used. The recording is kept.", stored); diff --git a/packages/ui-server/tests/drafts-settings-offloop.test.ts b/packages/ui-server/tests/drafts-settings-offloop.test.ts index fb1b8e57c3..e9628757ed 100644 --- a/packages/ui-server/tests/drafts-settings-offloop.test.ts +++ b/packages/ui-server/tests/drafts-settings-offloop.test.ts @@ -1,3 +1,4 @@ +import { createSpeechProviderRegistry } from "../src/voice/speech-providers"; import { expect, test } from "bun:test"; import { createHash, randomUUID } from "node:crypto"; import { mkdtempSync, rmSync } from "node:fs"; @@ -129,7 +130,7 @@ test("a transcription claim commits at FULL before provider dispatch; duplicates }; const app = new Hono(); app.use("*", async (c, next) => { c.set("principal", f.owner); await next(); }); - app.route("/", createTranscriptionRoutes({ store, speechProvider, voice: { provider: speechProvider.id, deepgramApiKey: null, keytermLimit: 0, cacheDir: f.root }, keyterms: { brainPath: f.root, cacheDir: f.root, limit: 0 } })); + app.route("/", createTranscriptionRoutes({ store, db: f.db, speechProviders: createSpeechProviderRegistry({ provider: speechProvider.id, deepgramApiKey: null, keytermLimit: 0, cacheDir: f.root }, { speechProvider }), keyterms: { brainPath: f.root, cacheDir: f.root, limit: 0 } })); const id = randomUUID(), audio = new Uint8Array([1, 2, 3]); const hash = createHash("sha256").update(audio).digest("hex"); const path = `/voice/recordings/${id}/transcription`; diff --git a/packages/ui-server/tests/helpers/http-contract-app.ts b/packages/ui-server/tests/helpers/http-contract-app.ts index 00fc4ceec2..fb07a77ae3 100644 --- a/packages/ui-server/tests/helpers/http-contract-app.ts +++ b/packages/ui-server/tests/helpers/http-contract-app.ts @@ -27,6 +27,8 @@ export async function httpContractApp(options: { renderer?: CreateAppOptions["renderer"]; registry?: CreateAppOptions["registry"]; speechProvider?: SpeechProvider; + speechProviders?: SpeechProvider[]; + defaultSpeechProviderId?: string; } = {}) { const root = mkdtempSync(join(tmpdir(), "brain-http-contract-")); const brainPath = join(root, "brain"); @@ -81,6 +83,8 @@ else if (args[0] === "sync") console.log("Fixture sync complete"); try { const appOptions: CreateAppOptions & { speechProvider?: SpeechProvider } = { config, observability, + speechProviders: options.speechProviders, + defaultSpeechProviderId: options.defaultSpeechProviderId, registry: options.registry ?? createStaticBackendRegistry([backend]), ...(options.speechProvider ? { speechProvider: options.speechProvider } : {}), ...(options.staticRoot ? { staticRoot } : {}), diff --git a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts index 83d8e004f2..9acb8c595b 100644 --- a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts +++ b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts @@ -111,6 +111,9 @@ export const mountLifetimes: Record = { "POST /share-target": { init: { method: "POST" }, status: 303, verify: async (r) => { expect(r.headers.get("location")).toBe("/?share_error=no_worker"); } }, "POST /api/render": { init: json("POST", { content: "# Arrival", contentType: "markdown", format: "png" }), status: 501, body: { error: "render_unavailable" } }, "GET /api/geo/coastline": { path: "/api/geo/coastline?bbox=15.6,38.2,15.8,38.32", body: { coastline: [], attribution: "© OpenStreetMap contributors" } }, + "GET /api/voice/providers": { body: { dictation: { effective: "webspeech", source: "host" } } }, + "GET /api/voice/dictation/settings": { body: { defaultProvider: null, smart: true, revision: "0" } }, + "PUT /api/voice/dictation/settings": { init: { method: "PUT", headers: { "If-Match": '"0"' }, body: JSON.stringify({ defaultProvider: "webspeech", smart: false }) }, body: { defaultProvider: "webspeech", smart: false, revision: "1" } }, "GET /api/voice/capabilities": { body: { providerId: "webspeech", capabilities: { savedAudio: false } } }, "GET /api/voice/recordings/:recordingId/transcription": { path: "/api/voice/recordings/00000000-0000-4000-8000-000000000001/transcription", status: 404, body: { error: "transcription_not_found" } }, "PUT /api/voice/recordings/:recordingId/transcription": { path: "/api/voice/recordings/00000000-0000-4000-8000-000000000001/transcription", init: { method: "PUT" }, status: 501, body: { error: "saved_audio_unsupported" } }, diff --git a/packages/ui-server/tests/selectable-dictation.test.ts b/packages/ui-server/tests/selectable-dictation.test.ts new file mode 100644 index 0000000000..cc5ddee624 --- /dev/null +++ b/packages/ui-server/tests/selectable-dictation.test.ts @@ -0,0 +1,248 @@ +import { expect, test } from "bun:test"; +import { createHash, randomUUID } from "node:crypto"; +import type { SpeechProvider } from "@schlessera/brain-ui-sdk/server"; +import { SpeechTranscriptionError } from "@schlessera/brain-ui-sdk/server"; +import { httpContractApp, type HttpContractApp } from "./helpers/http-contract-app"; +import { createSettingsWrites } from "../src/db/settings-writes"; +import { getDictationSettings } from "../src/db/settings"; +import { generateSignedCookie } from "hono/cookie"; +import { createPrincipal } from "../src/db/principals"; +import { Database } from "bun:sqlite"; + +function doubles() { + const calls = { alpha: [] as unknown[], beta: [] as unknown[], audio: [] as Uint8Array[] }; + const alpha: SpeechProvider = { id: "alpha", label: "Ithaca dictation", destination: "Audio goes to the Ithaca fixture.", + capabilities: { streaming: true, interimResults: true, keyterms: false, endpointing: true }, + async createSession(options) { calls.alpha.push(options); return { url: "", expiresAt: 0 }; }, + async transcribeRecording({ audio }) { calls.audio.push(audio); return { text: "Odysseus reaches Ithaca." }; }, + }; + const beta: SpeechProvider = { id: "beta", capabilities: { streaming: true, interimResults: true, keyterms: false, endpointing: false, smartTranscription: true }, + async createSession(options) { calls.beta.push(options); return { url: "", expiresAt: 0 }; }, + }; + return { alpha, beta, calls }; +} +const settingsPath = "/api/voice/dictation/settings"; +const audio = new Uint8Array([1, 2, 3]); +const path = (id: string) => `/api/voice/recordings/${id}/transcription`; +const upload = (provider?: string): RequestInit => ({ method: "PUT", body: audio, + headers: { "Content-Type": "audio/webm", "Content-SHA256": createHash("sha256").update(audio).digest("hex"), ...(provider !== undefined ? { "Speech-Provider": provider } : {}) } }); +const mint = (providerId?: string, smart?: boolean): RequestInit => ({ method: "POST", ...(providerId !== undefined ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ providerId, smart }) } : {}) }); +const save = (t: HttpContractApp, defaultProvider: string | null, revision = "0", smart = true, headers = {}) => t.fetch(settingsPath, { + method: "PUT", headers: { "Content-Type": "application/json", "If-Match": `"${revision}"`, ...headers }, body: JSON.stringify({ defaultProvider, smart }), +}); +function gate() { + let release!: () => void; + const promise = new Promise(resolve => { release = resolve; }); + return { promise, release }; +} + +// The plan's Deepgram/Gemini rows use the same alpha/beta executors by value. +for (const row of [ + { name: "zero", ids: [], saved: null, host: undefined, effective: null, source: "none" }, + { name: "zero with saved", ids: [], saved: "removed", host: undefined, effective: null, source: "unavailable" }, + { name: "one with host", ids: ["alpha"], saved: null, host: "alpha", effective: "alpha", source: "host" }, + { name: "one without host", ids: ["beta"], saved: null, host: undefined, effective: "beta", source: "only" }, + { name: "two with host", ids: ["alpha", "beta"], saved: null, host: "alpha", effective: "alpha", source: "host" }, + { name: "saved overrides host", ids: ["alpha", "beta"], saved: "beta", host: "alpha", effective: "beta", source: "saved" }, + { name: "removed blocks host", ids: ["alpha", "beta"], saved: "removed", host: "alpha", effective: null, source: "unavailable" }, + { name: "two require choice", ids: ["alpha", "beta"], saved: null, host: undefined, effective: null, source: "none" }, + { name: "legacy supplied", ids: ["alpha"], saved: "alpha", host: "alpha", effective: "alpha", source: "saved", legacy: true }, +]) test(`selection matrix: ${row.name}; legacy bodyless session and upload use the effective provider`, async () => { + const { alpha, beta, calls } = doubles(); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, defaultSpeechProviderId: row.host, + ...("legacy" in row ? { speechProvider: alpha } : { speechProviders: row.ids.map(id => id === "alpha" ? alpha : beta) }) }); + try { + if (row.saved) { + // Model persisted settings from another startup, including a removed id. + const writer = new Database(t.app.config.dbPath); + try { await createSettingsWrites(writer).setSetting("voice.dictation", { defaultProvider: row.saved, smart: false, revision: 3 }); } + finally { writer.close(); } + } + const discovery = await t.fetch("/api/voice/providers"); + expect(discovery.status).toBe(200); expect(discovery.headers.get("cache-control")).toBe("no-store"); + const body = await discovery.json(); + expect(body.providers.map((p: { id: string }) => p.id)).toEqual(row.ids); + expect(body.dictation).toEqual({ saved: row.saved, savedUsable: row.saved !== null && row.ids.some(id => id === row.saved), host: row.host ?? null, + effective: row.effective, source: row.source, smart: !row.saved, revision: row.saved ? "3" : "0" }); + expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); + const capabilities = await t.fetch("/api/voice/capabilities"); + const session = await t.fetch("/api/voice/session", mint()); + expect(session.status).toBe(row.effective ? 200 : 500); + expect(capabilities.status).toBe(session.status); + if (row.effective) { + const expected = row.effective === "alpha" ? alpha : beta; + expect(await capabilities.text()).toBe(JSON.stringify({ providerId: expected.id, capabilities: { ...expected.capabilities, savedAudio: expected.id === "alpha" } })); + expect(await session.text()).toBe(JSON.stringify({ providerId: expected.id, url: "", expiresAt: 0, capabilities: { ...expected.capabilities, savedAudio: expected.id === "alpha" } })); + } + expect(calls.alpha).toEqual(row.effective === "alpha" ? [{ keyterms: [] }] : []); + expect(calls.beta).toEqual(row.effective === "beta" ? [{ keyterms: [], mode: row.saved ? "verbatim" : "smart" }] : []); + const result = await t.fetch(path(randomUUID()), upload()); + expect(result.status).toBe(row.effective === "alpha" ? 200 : row.effective === "beta" ? 501 : 500); + expect(calls.audio).toEqual(row.effective === "alpha" ? [audio] : []); + } finally { await t.close(); } +}); + +test("held mint keeps the requested provider across a default save", async () => { + const { alpha, beta, calls } = doubles(); const entered = gate(), held = gate(); + const original = beta.createSession; + beta.createSession = async opts => { const result = await original(opts); entered.release(); await held.promise; return result; }; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "alpha" }); + let pending: Promise | undefined; + try { + pending = Promise.resolve(t.fetch("/api/voice/session", mint("beta", false))); + // Race-safe even under the mutation: a wrong provider resolves immediately. + await Promise.race([entered.promise, pending]); + expect(calls.beta, "the disclosed beta provider must mint, even while alpha is the default").toEqual([{ keyterms: [], mode: "verbatim" }]); + expect((await save(t, "beta")).status).toBe(200); + expect((await save(t, "alpha", "1")).status).toBe(200); + held.release(); const result = await (await pending).json(); + expect(result.providerId).toBe("beta"); expect(result.capabilities.smartTranscription).toBe(true); + expect(calls.alpha).toEqual([]); expect(calls.audio).toEqual([]); + } finally { held.release(); await pending; await t.close(); } +}); + +test("held upload keeps the header provider across a default save", async () => { + const { alpha, beta, calls } = doubles(); const entered = gate(), held = gate(); + const original = alpha.transcribeRecording!; + alpha.transcribeRecording = async opts => { const result = await original(opts); entered.release(); await held.promise; return result; }; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "beta" }); + let pending: Promise | undefined; + try { + const id = randomUUID(); pending = Promise.resolve(t.fetch(path(id), upload("alpha"))); + await Promise.race([entered.promise, pending]); + expect(calls.audio, "the disclosed alpha provider must receive the audio despite the streaming-only default").toEqual([audio]); + expect((await save(t, "alpha")).status).toBe(200); + expect((await save(t, "beta", "1")).status).toBe(200); + held.release(); const receipt = await (await pending).json(); + expect(receipt.providerId).toBe("alpha"); expect(receipt.status).toBe("done"); + expect(await (await t.fetch(path(id), upload("alpha"))).json()).toEqual(receipt); + expect(calls.audio).toHaveLength(1); expect(calls.alpha).toEqual([]); expect(calls.beta).toEqual([]); + } finally { held.release(); await pending; await t.close(); } +}); + +test("upload admission freezes the header before the request body finishes", async () => { + const { alpha, beta, calls } = doubles(); const reading = gate(); let finish!: () => void; + const body = new ReadableStream({ start(c) { c.enqueue(audio); finish = () => { finish = () => {}; c.close(); }; }, pull() { reading.release(); } }, { highWaterMark: 0 }); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "alpha" }); + let pending: Promise | undefined; + try { + pending = Promise.resolve(t.fetch(path(randomUUID()), { ...upload("alpha"), body, duplex: "half" } as RequestInit)); + await reading.promise; + expect((await save(t, "beta")).status).toBe(200); + finish(); const result = await (await pending).json(); + expect(result.providerId).toBe("alpha"); expect(calls.audio).toEqual([audio]); expect(calls.beta).toEqual([]); + } finally { finish(); await pending; await t.close(); } +}); + +test("exact selections refuse unknown providers and streaming-only uploads before claims; failures never fall back", async () => { + const { alpha, beta, calls } = doubles(); + beta.createSession = async options => { calls.beta.push(options); throw new Error("fixture-secret-not-for-client"); }; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta], defaultSpeechProviderId: "alpha" }); + try { + for (const id of ["removed", ""]) { + const response = await t.fetch("/api/voice/session", mint(id)); + expect(response.status).toBe(409); expect((await response.json()).error).toBe("speech_provider_unavailable"); + } + for (const provider of ["removed", "beta"]) { + const id = randomUUID(), response = await t.fetch(path(id), upload(provider)); + expect(response.status).toBe(provider === "beta" ? 501 : 409); + expect((await t.fetch(path(id))).status).toBe(404); + } + const failure = await t.fetch("/api/voice/session", mint("beta")); + expect(failure.status).toBe(500); expect(await failure.text()).not.toContain("fixture-secret"); + expect(calls.beta).toEqual([{ keyterms: [], mode: "smart" }]); expect(calls.alpha).toEqual([]); expect(calls.audio).toEqual([]); + } finally { await t.close(); } +}); + +test("retry cannot change the provider of a durable receipt", async () => { + const { alpha, beta, calls } = doubles(); let otherCalls = 0; + alpha.transcribeRecording = async ({ audio }) => { calls.audio.push(audio); throw new SpeechTranscriptionError("provider_error", 503); }; + // A second saved-audio implementation is needed to reach the receipt check. + const other: SpeechProvider = { ...alpha, id: "other", async transcribeRecording() { otherCalls++; return { text: "Ithaca" }; } }; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta, other], defaultSpeechProviderId: "alpha" }); + try { + const id = randomUUID(), receipt = await (await t.fetch(path(id), upload("alpha"))).json(); + expect(receipt.status).toBe("failed"); + expect((await save(t, "other")).status).toBe(200); + const response = await t.fetch(`${path(id)}?retry=${receipt.attemptId}`, upload("other")); + expect(response.status).toBe(409); expect(await response.json()).toEqual({ error: "transcription_provider_mismatch", message: "Retry with the original transcription service.", receipt }); + expect(calls.audio).toHaveLength(1); expect(otherCalls).toBe(0); expect(calls.beta).toEqual([]); + expect((await t.fetch(`${path(id)}?retry=${receipt.attemptId}`, upload("alpha"))).status).toBe(200); + expect(calls.audio).toHaveLength(2); + } finally { await t.close(); } +}); + +test("settings enforce owner authority and atomic revisions without minting", async () => { + const { alpha, beta, calls } = doubles(); const secret = "odysseus-dictation-cookie-secret"; + const t = await httpContractApp({ env: { VOICE_PROVIDER: "", AUTH_MODE: "password", COOKIE_SECRET: secret, BRAIN_UI_PASSWORD_HASH: "fixture" }, speechProviders: [alpha, beta] }); + try { + const owner = createPrincipal(t.app.db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const agent = createPrincipal(t.app.db, { authMethod: "delegated", label: "Eurylochus", createdBy: owner.id, ttlSeconds: 3600 }); + const cookie = async (id: string) => ({ cookie: (await generateSignedCookie("brain_ui_session", id, secret)).split(";")[0]! }); + const ownerHeaders = await cookie(owner.id); + expect((await t.fetch(settingsPath)).status).toBe(401); + expect((await t.fetch("/api/voice/providers")).status).toBe(401); + expect((await save(t, "alpha", "0", true, await cookie(agent.id))).status).toBe(403); + const initial = await t.fetch(settingsPath, { headers: ownerHeaders }); + expect(await initial.json()).toEqual({ defaultProvider: null, smart: true, revision: "0" }); + expect(initial.headers.get("etag")).toBe('"0"'); + expect((await t.fetch(settingsPath, { method: "PUT", headers: ownerHeaders, body: JSON.stringify({ defaultProvider: "alpha" }) })).status).toBe(428); + const unknown = await save(t, "removed", "0", true, ownerHeaders); + expect(unknown.status).toBe(400); expect((await unknown.json()).error).toBe("speech_provider_unknown"); + const concurrent = await Promise.all([save(t, "alpha", "0", false, ownerHeaders), save(t, "beta", "0", false, ownerHeaders)]); + expect(concurrent.map(r => r.status).sort()).toEqual([200, 409]); + const current = await concurrent.find(r => r.status === 200)!.json(); + expect(current.revision).toBe("1"); expect(current.smart).toBe(false); + expect(await concurrent.find(r => r.status === 409)!.json()).toEqual({ error: "dictation_settings_stale", message: "Changed on another device.", current }); + expect((await save(t, null, "1", true, ownerHeaders)).status).toBe(200); + expect(getDictationSettings(t.app.db)).toEqual({ defaultProvider: null, smart: true, revision: "2" }); + const reader = new Database(t.app.config.dbPath); + try { expect(getDictationSettings(reader)).toEqual(getDictationSettings(t.app.db)); } finally { reader.close(); } + expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); + } finally { await t.close(); } +}); + +test("invalid settings are total and malformed requests do not change them", async () => { + const { alpha, beta, calls } = doubles(); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta] }); + const writer = new Database(t.app.config.dbPath); + try { + for (const value of ["{", "null", "[]", '{"defaultProvider":"alpha","smart":true,"revision":-1}', '{"defaultProvider":"alpha","smart":"yes","revision":1}']) { + writer.query("INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES ('voice.dictation', ?, 0)").run(value); + expect(await (await t.fetch(settingsPath)).json()).toEqual({ defaultProvider: null, smart: true, revision: "0" }); + } + for (const body of ["{", "null", "[]", '{}', '{"defaultProvider":"alpha","smart":1}']) { + expect((await t.fetch(settingsPath, { method: "PUT", headers: { "If-Match": '"0"' }, body })).status).toBe(400); + } + for (const body of ["{", "null", "[]", '{"providerId":42}', '{"smart":1}']) { + expect((await t.fetch("/api/voice/session", { method: "POST", headers: { "Content-Type": "application/json" }, body })).status).toBe(400); + } + expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); + } finally { writer.close(); await t.close(); } +}); + +test("registration validates duplicate ids, mutually exclusive options and unregistered defaults at construction", async () => { + const { alpha, beta } = doubles(); + for (const options of [{ speechProviders: [alpha, alpha] }, { speechProvider: alpha, speechProviders: [beta] }, + { speechProviders: [alpha], defaultSpeechProviderId: "removed" }, { speechProviders: [{ ...alpha, id: " Alpha " }] }, + { speechProviders: [{ ...alpha, capabilities: { ...alpha.capabilities, savedAudio: false } }] }]) { + await expect(httpContractApp({ env: { VOICE_PROVIDER: "" }, ...options })).rejects.toThrow(); + } + await expect(httpContractApp({ env: { VOICE_PROVIDER: "", DEEPGRAM_API_KEY: "fixture" }, speechProviders: [{ ...alpha, id: "deepgram" }] })).rejects.toThrow("Duplicate"); +}); + +test("built-ins register by key and browser speech remains opt-in; options precede environment defaults", async () => { + const { alpha, beta, calls } = doubles(); + const t = await httpContractApp({ env: { VOICE_PROVIDER: "", DEEPGRAM_API_KEY: "fixture-private-key" }, speechProviders: [alpha, beta] }); + try { + const response = await t.fetch("/api/voice/providers"), raw = await response.text(), body = JSON.parse(raw); + expect(raw).not.toContain("fixture-private-key"); expect(body.providers.map((p: { id: string }) => p.id)).toEqual(["deepgram", "alpha", "beta"]); + expect(body.dictation.host).toBe("deepgram"); expect(body.dictation.effective).toBe("deepgram"); + expect(calls).toEqual({ alpha: [], beta: [], audio: [] }); + } finally { await t.close(); } + const browser = await httpContractApp({ env: { VOICE_PROVIDER: "webspeech" }, speechProviders: [alpha], defaultSpeechProviderId: "alpha" }); + try { + const body = await (await browser.fetch("/api/voice/providers")).json(); + expect(body.providers.map((p: { id: string }) => p.id)).toEqual(["webspeech", "alpha"]); expect(body.dictation.host).toBe("alpha"); + } finally { await browser.close(); } +});