From 6494a4a793d9ac65558655add8fa9bf1346b4487 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 21:04:06 -0400 Subject: [PATCH 01/55] feat(contracts): voice transcription settings, upload RPC, and dictation keybinding Adds the environment-backed transcription contract the web and desktop composers build on: a voiceTranscription server setting with a secret API key, a voice.createTranscriptionUrl RPC that mints a capability URL for the recorded audio, and the composer.toggleDictation command bound to mod+shift+space. Co-Authored-By: Claude Opus 5.5 --- .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/index.ts | 1 + packages/contracts/src/keybindings.ts | 1 + packages/contracts/src/rpc.ts | 18 +++++ packages/contracts/src/settings.ts | 31 ++++++++ packages/contracts/src/voiceTranscription.ts | 71 +++++++++++++++++++ packages/shared/src/keybindings.ts | 1 + 7 files changed, 125 insertions(+) create mode 100644 packages/contracts/src/voiceTranscription.ts diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index f9eaedb48bd70..a24cf48e43a1a 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -43,6 +43,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.vcsSwitchRef]: AuthSourceControlWriteScope, [WS_METHODS.vcsInit]: AuthSourceControlWriteScope, + // Transcribing spends this environment's speech-to-text credentials. + [WS_METHODS.voiceCreateTranscriptionUrl]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksUpsert]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksDelete]: AuthOrchestrationOperateScope, diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 7f38a38dbbae9..ca71a573cf9b7 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -49,6 +49,7 @@ export * from "./project.ts"; export * from "./filesystem.ts"; export * from "./agentSessions.ts"; export * from "./assets.ts"; +export * from "./voiceTranscription.ts"; export * from "./review.ts"; export * from "./mcpApps.ts"; export * from "./browserImport.ts"; diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 066e52d9e0f88..ff73522874c26 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -99,6 +99,7 @@ export const STATIC_KEYBINDING_COMMANDS = [ "composer.workspace", "composer.previousWorktree", "composer.branch", + "composer.toggleDictation", "chat.new", "chat.newLocal", "chat.newWithoutProject", diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index d7a11234c4467..81ed208831112 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -101,6 +101,12 @@ import { AttachmentDeleteInput, AttachmentUploadSigningKeyError, } from "./assets.ts"; +import { + VoiceTranscriptionCreateUrlInput, + VoiceTranscriptionCreateUrlResult, + VoiceTranscriptionNotConfiguredError, + VoiceTranscriptionSigningKeyError, +} from "./voiceTranscription.ts"; import { PersistChatAttachmentsError, PersistChatAttachmentsInput, @@ -401,6 +407,7 @@ export const WS_METHODS = { assetsPersistChatAttachments: "assets.persistChatAttachments", attachmentsCreateUploadUrl: "attachments.createUploadUrl", attachmentsDelete: "attachments.delete", + voiceCreateTranscriptionUrl: "voice.createTranscriptionUrl", mcpAppsCallTool: "mcpApps.callTool", mcpAppsToolInfo: "mcpApps.toolInfo", @@ -1310,6 +1317,16 @@ const WsAttachmentsCreateUploadUrlRpc = Rpc.make(WS_METHODS.attachmentsCreateUpl error: Schema.Union([AttachmentUploadSigningKeyError, EnvironmentAuthorizationError]), }); +const WsVoiceCreateTranscriptionUrlRpc = Rpc.make(WS_METHODS.voiceCreateTranscriptionUrl, { + payload: VoiceTranscriptionCreateUrlInput, + success: VoiceTranscriptionCreateUrlResult, + error: Schema.Union([ + VoiceTranscriptionNotConfiguredError, + VoiceTranscriptionSigningKeyError, + EnvironmentAuthorizationError, + ]), +}); + const WsAttachmentsDeleteRpc = Rpc.make(WS_METHODS.attachmentsDelete, { payload: AttachmentDeleteInput, error: EnvironmentAuthorizationError, @@ -2003,6 +2020,7 @@ export const WsRpcGroup = RpcGroup.make( WsAssetsCreateUrlRpc, WsAssetsPersistChatAttachmentsRpc, WsAttachmentsCreateUploadUrlRpc, + WsVoiceCreateTranscriptionUrlRpc, WsAttachmentsDeleteRpc, WsMcpAppsCallToolRpc, WsMcpAppsToolInfoRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 620f659befea2..f5ad9c81a0fa3 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -778,6 +778,24 @@ export const AntigravitySettings = makeProviderSettingsSchema( ); export type AntigravitySettings = typeof AntigravitySettings.Type; +export const DEFAULT_VOICE_TRANSCRIPTION_BASE_URL = "https://api.openai.com/v1"; +export const DEFAULT_VOICE_TRANSCRIPTION_MODEL = "gpt-transcribe"; + +/** Any OpenAI-compatible `/audio/transcriptions` endpoint: OpenAI, Groq, a whisper.cpp server. */ +export const VoiceTranscriptionSettings = Schema.Struct({ + enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + baseUrl: TrimmedString.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_VOICE_TRANSCRIPTION_BASE_URL)), + ), + model: TrimmedString.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_VOICE_TRANSCRIPTION_MODEL)), + ), + /** ISO-639-1 code. Empty lets the model detect the language. */ + language: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + apiKey: TrimmedString.pipe(secretSetting, Schema.withDecodingDefault(Effect.succeed(""))), +}); +export type VoiceTranscriptionSettings = typeof VoiceTranscriptionSettings.Type; + export const UsageLimitSourceConfig = Schema.Struct({ kind: Schema.Literal("cliproxy"), label: Schema.optional(TrimmedNonEmptyString), @@ -1255,6 +1273,9 @@ export const ServerSettings = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed({})), ), observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))), + voiceTranscription: VoiceTranscriptionSettings.pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), sourceControlHosts: Schema.Record(Schema.String, SourceControlHostSettings).pipe( Schema.withDecodingDefault(Effect.succeed({})), ), @@ -1520,6 +1541,16 @@ export const ServerSettingsPatch = Schema.Struct({ otlpLogsUrl: Schema.optionalKey(TrimmedString), }), ), + /** An omitted `apiKey` keeps the saved key; an empty one removes it. */ + voiceTranscription: Schema.optionalKey( + Schema.Struct({ + enabled: Schema.optionalKey(Schema.Boolean), + baseUrl: Schema.optionalKey(TrimmedString), + model: Schema.optionalKey(TrimmedString), + language: Schema.optionalKey(TrimmedString), + apiKey: Schema.optionalKey(TrimmedString), + }), + ), /** * Merges per host: a patched field replaces the saved one, so a client sends a per-server-host * map whole, with the redaction marker for each saved secret it keeps. An empty or omitted diff --git a/packages/contracts/src/voiceTranscription.ts b/packages/contracts/src/voiceTranscription.ts new file mode 100644 index 0000000000000..4be7fd99ec798 --- /dev/null +++ b/packages/contracts/src/voiceTranscription.ts @@ -0,0 +1,71 @@ +import * as Schema from "effect/Schema"; + +import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** OpenAI, Groq, and whisper.cpp all reject uploads above 25 MB. */ +export const VOICE_TRANSCRIPTION_MAX_AUDIO_BYTES = 25 * 1024 * 1024; +export const VOICE_TRANSCRIPTION_URL_TTL_MS = 2 * 60_000; + +/** Container types without codec parameters; clients strip `;codecs=...` before minting. */ +export const VoiceTranscriptionAudioMimeType = Schema.Literals([ + "audio/webm", + "audio/ogg", + "audio/mp4", + "audio/mpeg", + "audio/wav", +]); +export type VoiceTranscriptionAudioMimeType = typeof VoiceTranscriptionAudioMimeType.Type; + +export const VoiceTranscriptionCreateUrlInput = Schema.Struct({ + mimeType: VoiceTranscriptionAudioMimeType, + sizeBytes: NonNegativeInt.check( + Schema.isGreaterThanOrEqualTo(1), + Schema.isLessThanOrEqualTo(VOICE_TRANSCRIPTION_MAX_AUDIO_BYTES), + ), +}); +export type VoiceTranscriptionCreateUrlInput = typeof VoiceTranscriptionCreateUrlInput.Type; + +export const VoiceTranscriptionCreateUrlResult = Schema.Struct({ + relativeUrl: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)), + expiresAt: Schema.Number, +}); +export type VoiceTranscriptionCreateUrlResult = typeof VoiceTranscriptionCreateUrlResult.Type; + +/** 200 body of `POST `. */ +export const VoiceTranscriptionResult = Schema.Struct({ + text: Schema.String, +}); +export type VoiceTranscriptionResult = typeof VoiceTranscriptionResult.Type; + +export const VoiceTranscriptionFailureCode = Schema.Literals([ + "not_configured", + "invalid_upload", + "upstream_rejected_credentials", + "upstream_failed", +]); +export type VoiceTranscriptionFailureCode = typeof VoiceTranscriptionFailureCode.Type; + +/** Non-2xx body of `POST `. */ +export const VoiceTranscriptionFailure = Schema.Struct({ + code: VoiceTranscriptionFailureCode, + message: Schema.String, +}); +export type VoiceTranscriptionFailure = typeof VoiceTranscriptionFailure.Type; + +export class VoiceTranscriptionNotConfiguredError extends Schema.TaggedError()( + "VoiceTranscriptionNotConfiguredError", + { + message: Schema.String, + }, +) {} + +export class VoiceTranscriptionSigningKeyError extends Schema.TaggedError()( + "VoiceTranscriptionSigningKeyError", + { + cause: Schema.Defect(), + }, +) { + override get message(): string { + return "Failed to load the voice transcription signing key."; + } +} diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index b511f830f69b5..c108969108e86 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -203,6 +203,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+a", command: "composer.mode", when: "!terminalFocus" }, { key: "mod+shift+x", command: "composer.workspace", when: "!terminalFocus" }, { key: "mod+shift+g", command: "composer.branch", when: "!terminalFocus" }, + { key: "mod+shift+space", command: "composer.toggleDictation", when: "!terminalFocus" }, { key: "mod+shift+l", command: "composer.previousWorktree", when: "!terminalFocus" }, { key: "mod+shift+k", command: "pullRequest.copyNumber", when: "!terminalFocus" }, { key: "mod+shift+arrowup", command: "modelPicker.previousProvider", when: "modelPickerOpen" }, From debc567b29239ac0cf0fc6f2fce01f55e6934877 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 21:12:01 -0400 Subject: [PATCH 02/55] feat(server): store the voice transcription API key in the secret store The key moves into ServerSecretStore on write, reaches clients only as the redaction marker, and is materialized for server reads. A patch that omits apiKey keeps the saved key; an empty apiKey removes it. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/serverSettings.test.ts | 41 ++++++++++++++++++++++++++ apps/server/src/settingsSecrets.ts | 17 ++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 8e90ecff2525d..f009c70286a7c 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1312,6 +1312,47 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettingsWithSecrets())), ); + it.effect( + "stores the voice transcription key as a secret and keeps it across partial patches", + () => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const store = yield* ServerSecretStore.ServerSecretStore; + const saved = yield* service.updateSettings({ + voiceTranscription: { enabled: true, apiKey: "sk-voice-secret" }, + }); + assert.strictEqual(saved.voiceTranscription.apiKey, "sk-voice-secret"); + assert.notInclude(yield* fs.readFileString(config.settingsPath), "sk-voice-secret"); + assert.isTrue(Option.isSome(yield* store.get("voice-transcription-api-key"))); + const client = ServerSettingsModule.redactServerSettingsForClient(saved); + assert.strictEqual(client.voiceTranscription.apiKey, "••••••"); + assert.notInclude(JSON.stringify(client), "sk-voice-secret"); + + const edited = yield* service.updateSettings({ + voiceTranscription: { model: "whisper-1" }, + }); + assert.deepInclude(edited.voiceTranscription, { + enabled: true, + model: "whisper-1", + apiKey: "sk-voice-secret", + }); + const echoed = yield* service.updateSettings({ + voiceTranscription: { apiKey: client.voiceTranscription.apiKey }, + }); + assert.strictEqual(echoed.voiceTranscription.apiKey, "sk-voice-secret"); + assert.strictEqual( + (yield* service.getSettings).voiceTranscription.apiKey, + "sk-voice-secret", + ); + + const removed = yield* service.updateSettings({ voiceTranscription: { apiKey: "" } }); + assert.strictEqual(removed.voiceTranscription.apiKey, ""); + assert.isTrue(Option.isNone(yield* store.get("voice-transcription-api-key"))); + }).pipe(Effect.provide(layerServerSettingsWithSecrets())), + ); + it.effect("moves saved provider credentials to the secret store when settings load", () => Effect.gen(function* () { const service = yield* ServerSettingsModule.ServerSettingsService; diff --git a/apps/server/src/settingsSecrets.ts b/apps/server/src/settingsSecrets.ts index b80ccabc03603..984ad606ada14 100644 --- a/apps/server/src/settingsSecrets.ts +++ b/apps/server/src/settingsSecrets.ts @@ -5,6 +5,7 @@ import { EasDeviceHostConfig, type ServerSettings, UsageLimitSourceConfig, + VoiceTranscriptionSettings, secretSettingsFields, } from "@t3tools/contracts"; import { acpRegistryClient } from "@t3tools/provider-acp-registry/client"; @@ -33,6 +34,7 @@ const providerSecretFields = new Map([ ]); const usageLimitSecretFields = secretSettingsFields(UsageLimitSourceConfig); const easDeviceHostSecretFields = secretSettingsFields(EasDeviceHostConfig); +const voiceTranscriptionSecretFields = secretSettingsFields(VoiceTranscriptionSettings); const encode = (value: string) => Buffer.from(value, "utf8").toString("base64url"); export interface SettingsSecret { @@ -155,5 +157,18 @@ export function mapSettingsSecrets( ) as EasDeviceHostConfig, ); - return { ...settings, providerInstances, sourceControlHosts, usageLimitSources, easDeviceHosts }; + const voiceTranscription = mapFields( + settings.voiceTranscription, + voiceTranscriptionSecretFields, + () => "voice-transcription-api-key", + ) as ServerSettings["voiceTranscription"]; + + return { + ...settings, + providerInstances, + sourceControlHosts, + usageLimitSources, + easDeviceHosts, + voiceTranscription, + }; } From 90cb31d6c103caf7055ed35fa48d1628dc2d4e9e Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 21:19:42 -0400 Subject: [PATCH 03/55] feat(server): transcribe voice recordings through a signed upload route VoiceTranscription mints a short-lived capability URL signed with the attachment upload key, then POST /api/voice/transcriptions/:token forwards the recording to the configured OpenAI-compatible /audio/transcriptions endpoint and answers with its text. Failures come back as a VoiceTranscriptionFailure: 400 invalid_upload, 409 not_configured, and 502 for upstream credential rejections and other upstream failures. The audio is held in memory only for the request. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/assets/AttachmentUpload.ts | 7 +- apps/server/src/http.ts | 73 ++++ apps/server/src/server.ts | 8 + .../VoiceTranscription.test.ts | 326 ++++++++++++++++ .../voiceTranscription/VoiceTranscription.ts | 349 ++++++++++++++++++ 5 files changed, 760 insertions(+), 3 deletions(-) create mode 100644 apps/server/src/voiceTranscription/VoiceTranscription.test.ts create mode 100644 apps/server/src/voiceTranscription/VoiceTranscription.ts diff --git a/apps/server/src/assets/AttachmentUpload.ts b/apps/server/src/assets/AttachmentUpload.ts index efbe6a5ba6a87..51c2ecb29c7df 100644 --- a/apps/server/src/assets/AttachmentUpload.ts +++ b/apps/server/src/assets/AttachmentUpload.ts @@ -64,7 +64,8 @@ function decodeClaims(encodedPayload: string): AttachmentUploadClaims | null { } } -const loadSigningSecret = Effect.gen(function* () { +/** Shared with voice transcription upload tokens; each token's `kind` keeps the two apart. */ +export const loadUploadSigningSecret = Effect.gen(function* () { const secretStore = yield* ServerSecretStore.ServerSecretStore; return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32); }); @@ -72,7 +73,7 @@ const loadSigningSecret = Effect.gen(function* () { export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* ( input: AttachmentCreateUploadUrlInput, ) { - const secret = yield* loadSigningSecret.pipe( + const secret = yield* loadUploadSigningSecret.pipe( Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })), ); const config = yield* ServerConfig.ServerConfig; @@ -125,7 +126,7 @@ export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validat return null; } - const secret = yield* loadSigningSecret.pipe( + const secret = yield* loadUploadSigningSecret.pipe( Effect.tapError((cause) => Effect.logError("Failed to load the attachment upload signing key.", { cause }), ), diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 189c2b5b2898d..3f5935424f31c 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -3,6 +3,8 @@ import { AuthOrchestrationOperateScope, AuthOrchestrationReadScope, EnvironmentHttpApi, + type VoiceTranscriptionFailure, + type VoiceTranscriptionFailureCode, } from "@t3tools/contracts"; import { isDevProxiedPath } from "@t3tools/shared/devProxy"; import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; @@ -20,6 +22,7 @@ import { cast } from "effect/Function"; import { HttpClient, HttpClientResponse, + HttpIncomingMessage, HttpMiddleware, HttpRouter, HttpServerResponse, @@ -48,6 +51,7 @@ import { failEnvironmentInternal, } from "./auth/http.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; +import * as VoiceTranscription from "./voiceTranscription/VoiceTranscription.ts"; import { WEBHOOK_ROUTE_PREFIX } from "./scheduledTasks/ScheduledTaskService.ts"; import { browserApiCorsAllowedHeaders, @@ -495,6 +499,75 @@ export const layerAttachmentUploadRoute = HttpRouter.add( }), ); +const VOICE_TRANSCRIPTION_FAILURE_STATUS = { + invalid_upload: 400, + not_configured: 409, + upstream_rejected_credentials: 502, + upstream_failed: 502, +} as const satisfies Record; + +const voiceTranscriptionFailure = (code: VoiceTranscriptionFailureCode, message: string) => + HttpServerResponse.jsonUnsafe({ code, message } satisfies VoiceTranscriptionFailure, { + status: VOICE_TRANSCRIPTION_FAILURE_STATUS[code], + headers: { "cache-control": "no-store" }, + }); + +export const layerVoiceTranscriptionRoute = HttpRouter.add( + "POST", + `${VoiceTranscription.VOICE_TRANSCRIPTION_ROUTE_PREFIX}/*`, + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const voiceTranscription = yield* VoiceTranscription.VoiceTranscription; + const url = HttpServerRequest.toURL(request); + const claims = Option.isSome(url) + ? yield* voiceTranscription.verifyUploadToken( + url.value.pathname.slice( + `${VoiceTranscription.VOICE_TRANSCRIPTION_ROUTE_PREFIX}/`.length, + ), + ) + : Option.none(); + if (Option.isNone(claims)) { + return voiceTranscriptionFailure( + "invalid_upload", + "This transcription link is invalid or has expired.", + ); + } + const { sizeBytes } = claims.value; + if (Number(request.headers["content-length"]) !== sizeBytes) { + return voiceTranscriptionFailure( + "invalid_upload", + `Content-Length must match the recording size of ${sizeBytes} bytes.`, + ); + } + const audio = yield* request.arrayBuffer.pipe( + Effect.map((buffer) => new Uint8Array(buffer)), + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(sizeBytes)), + Effect.option, + ); + if (Option.isNone(audio)) { + return voiceTranscriptionFailure("invalid_upload", "Could not read the recording."); + } + + return yield* voiceTranscription.transcribe(claims.value, audio.value).pipe( + Effect.map((result) => + HttpServerResponse.jsonUnsafe(result, { headers: { "cache-control": "no-store" } }), + ), + Effect.catchTags({ + VoiceTranscriptionNotConfiguredError: (error) => + Effect.succeed(voiceTranscriptionFailure("not_configured", error.message)), + VoiceTranscriptionInvalidUploadError: (error) => + Effect.succeed(voiceTranscriptionFailure("invalid_upload", error.message)), + VoiceTranscriptionCredentialsRejectedError: (error) => + Effect.succeed(voiceTranscriptionFailure("upstream_rejected_credentials", error.message)), + VoiceTranscriptionUpstreamError: (error) => + Effect.logWarning("Voice transcription failed upstream.", { cause: error }).pipe( + Effect.as(voiceTranscriptionFailure("upstream_failed", error.message)), + ), + }), + ); + }), +); + const decodeBuildManifest = Schema.decodeUnknownEffect( Schema.fromJsonString( Schema.Record( diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 48d701103c077..053efbe97314d 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -93,6 +93,7 @@ import * as ProviderAdapterRegistry from "./orchestration-v2/ProviderAdapterRegi import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; import * as ProviderUsageLimitsIngestion from "./provider/ProviderUsageLimitsIngestion.ts"; import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; +import * as VoiceTranscription from "./voiceTranscription/VoiceTranscription.ts"; import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts"; import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts"; import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; @@ -277,6 +278,11 @@ const layerUsage = UsageService.layer.pipe( Layer.provide(layerServerSettings), ); +const layerVoiceTranscription = VoiceTranscription.layer.pipe( + Layer.provide(layerServerSettings), + Layer.provide(ServerSecretStore.layer), +); + const layerResourceDiagnostics = Layer.mergeAll( HostResources.layer, layerResourceTelemetry, @@ -669,6 +675,7 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe( const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe( Layer.provideMerge(layerUsage), + Layer.provideMerge(layerVoiceTranscription), Layer.provideMerge(layerBackground), Layer.provideMerge(layerResourceDiagnostics), Layer.provideMerge(TraceDiagnostics.layer), @@ -704,6 +711,7 @@ const layerMakeRoutes = Layer.mergeAll( ServerHttp.layerOtlpTracesProxyRoute, ServerHttp.layerAssetRoute, ServerHttp.layerAttachmentUploadRoute, + ServerHttp.layerVoiceTranscriptionRoute, DeviceHubProxy.layer, ServerBrowserStream.routeLayer, ServerHttp.layerStaticAndDevRoute, diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts new file mode 100644 index 0000000000000..a5c8245268bfd --- /dev/null +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -0,0 +1,326 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import type { VoiceTranscriptionSettings } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; +import { + HttpClient, + type HttpClientRequest, + HttpClientResponse, + HttpRouter, + HttpServerRequest, + HttpServerResponse, +} from "effect/http"; + +import { issueAttachmentUploadUrl } from "../assets/AttachmentUpload.ts"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ServerConfig from "../config.ts"; +import * as ServerHttp from "../http.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as VoiceTranscription from "./VoiceTranscription.ts"; + +const audio = new Uint8Array([1, 2, 3, 4, 5, 6]); + +function setup( + settings: Partial, + upstream: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect = () => + Effect.succeed(Response.json({ text: "hello world" })), +) { + const requests: Array = []; + const client = HttpClient.make((request) => + Effect.suspend(() => { + requests.push(request); + return upstream(request); + }).pipe(Effect.map((response) => HttpClientResponse.fromWeb(request, response))), + ); + const layer = VoiceTranscription.layer.pipe( + Layer.provideMerge( + ServerSettings.layerTest({ + voiceTranscription: { enabled: true, apiKey: "sk-test", ...settings }, + }), + ), + Layer.provide(Layer.succeed(HttpClient.HttpClient, client)), + Layer.provideMerge(ServerSecretStore.layer), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-voice-test-" })), + Layer.provideMerge(NodeServices.layer), + ); + return { layer, requests }; +} + +const mint = Effect.gen(function* () { + const voice = yield* VoiceTranscription.VoiceTranscription; + return yield* voice.createUploadUrl({ mimeType: "audio/webm", sizeBytes: audio.byteLength }); +}); + +const post = ( + relativeUrl: string, + options: { readonly body?: Uint8Array; readonly contentLength?: number } = {}, +) => + Effect.gen(function* () { + const body = options.body ?? audio; + const app = yield* HttpRouter.toHttpEffect(ServerHttp.layerVoiceTranscriptionRoute); + const request = new Request(`http://t3.test${relativeUrl}`, { + method: "POST", + body: new Blob([new Uint8Array(body)]), + headers: { + "content-type": "audio/webm", + "content-length": String(options.contentLength ?? body.byteLength), + }, + }); + const response = HttpServerResponse.toWeb( + yield* app.pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + HttpServerRequest.fromWeb(request), + ), + ), + ); + return { + status: response.status, + body: (yield* Effect.promise(() => response.json())) as Record, + }; + }).pipe(Effect.scoped); + +const formOf = (request: HttpClientRequest.HttpClientRequest) => { + if (request.body._tag !== "FormData") + throw new Error(`expected FormData, got ${request.body._tag}`); + return request.body.formData; +}; + +describe("VoiceTranscription", () => { + it("lets the cross-origin hosted web app read the transcript", async () => { + const layerApp = Layer.mergeAll( + ServerHttp.layerVoiceTranscriptionRoute, + ServerHttp.layerBrowserApiCors, + ).pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-voice-cors-test-" })), + Layer.provide(NodeServices.layer), + ); + const { handler, dispose } = HttpRouter.toWebHandler(layerApp, { disableLogger: true }); + const services = Context.make( + VoiceTranscription.VoiceTranscription, + VoiceTranscription.VoiceTranscription.of({ + createUploadUrl: () => Effect.die("unused"), + verifyUploadToken: () => + Effect.succeedSome({ + version: 1, + kind: "voice-transcription", + mimeType: "audio/webm", + sizeBytes: audio.byteLength, + expiresAt: Number.MAX_SAFE_INTEGER, + } as const), + transcribe: () => Effect.succeed({ text: "hello world" }), + }), + ); + try { + const url = "https://backend.example/api/voice/transcriptions/token"; + const preflight = await handler( + new Request(url, { + method: "OPTIONS", + headers: { + origin: "https://app.t3.codes", + "access-control-request-method": "POST", + "access-control-request-headers": "content-type", + }, + }), + services, + ); + expect(preflight.status).toBe(204); + expect(preflight.headers.get("access-control-allow-origin")).toBe("*"); + + const response = await handler( + new Request(url, { + method: "POST", + body: new Blob([audio]), + headers: { + origin: "https://app.t3.codes", + "content-type": "audio/webm", + "content-length": String(audio.byteLength), + }, + }), + services, + ); + expect(response.status).toBe(200); + expect(response.headers.get("access-control-allow-origin")).toBe("*"); + expect(await response.json()).toEqual({ text: "hello world" }); + } finally { + await dispose(); + } + }); + + it.effect.each([ + { settings: { enabled: false }, message: "turned off" }, + { settings: { apiKey: "" }, message: "OpenAI API key" }, + { settings: { model: "" }, message: "model name" }, + { settings: { baseUrl: "" }, message: "endpoint URL" }, + { settings: { baseUrl: "ftp://whisper.local" }, message: "not valid" }, + ] as const)("refuses to mint an upload URL when $message", ({ settings, message }) => { + const { layer } = setup(settings); + return Effect.gen(function* () { + const error = yield* Effect.flip(mint); + expect(error._tag).toBe("VoiceTranscriptionNotConfiguredError"); + expect(error.message).toContain(message); + }).pipe(Effect.provide(layer)); + }); + + it.effect("transcribes through a keyless local server with the singular language hint", () => { + const { layer, requests } = setup({ + baseUrl: "http://whisper.local:8080/v1/", + model: "whisper-1", + language: "en", + apiKey: "", + }); + return Effect.gen(function* () { + const issued = yield* mint; + expect(issued.relativeUrl.startsWith("/api/voice/transcriptions/")).toBe(true); + const response = yield* post(issued.relativeUrl); + + expect(response).toEqual({ status: 200, body: { text: "hello world" } }); + expect(requests).toHaveLength(1); + const request = requests[0]!; + expect(request.url).toBe("http://whisper.local:8080/v1/audio/transcriptions"); + expect(request.headers.authorization).toBeUndefined(); + const form = formOf(request); + expect(form.get("model")).toBe("whisper-1"); + expect(form.get("response_format")).toBe("json"); + expect(form.getAll("language")).toEqual(["en"]); + expect(form.has("languages[]")).toBe(false); + const file = form.get("file") as File; + expect(file.name).toBe("audio.webm"); + expect(file.type).toBe("audio/webm"); + expect(new Uint8Array(yield* Effect.promise(() => file.arrayBuffer()))).toEqual(audio); + }).pipe(Effect.provide(layer)); + }); + + it.effect.each([ + { language: "fr", languages: ["fr"] }, + { language: "", languages: [] }, + ])( + "sends gpt-transcribe language hint $language as languages with the key", + ({ language, languages }) => { + const { layer, requests } = setup({ language }); + return Effect.gen(function* () { + expect((yield* post((yield* mint).relativeUrl)).status).toBe(200); + const request = requests[0]!; + expect(request.url).toBe("https://api.openai.com/v1/audio/transcriptions"); + expect(request.headers.authorization).toBe("Bearer sk-test"); + const form = formOf(request); + expect(form.get("model")).toBe("gpt-transcribe"); + expect(form.getAll("languages[]")).toEqual(languages); + expect(form.has("language")).toBe(false); + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect.each([ + { + upstream: Response.json( + { error: { message: "Incorrect API key provided: sk-test." } }, + { status: 401 }, + ), + code: "upstream_rejected_credentials", + message: "api.openai.com rejected the API key (HTTP 401): Incorrect API key provided: [key].", + }, + { + upstream: Response.json({ error: "model not loaded" }, { status: 500 }), + code: "upstream_failed", + message: "api.openai.com answered HTTP 500: model not loaded", + }, + { + upstream: new Response("bad gateway", { status: 503 }), + code: "upstream_failed", + message: "api.openai.com answered HTTP 503.", + }, + { + upstream: Response.json({ transcript: "wrong shape" }), + code: "upstream_failed", + message: "api.openai.com returned an unexpected response.", + }, + ])( + "answers $code with a 502 for upstream HTTP $upstream.status", + ({ upstream, code, message }) => { + const { layer } = setup({}, () => Effect.succeed(upstream)); + return Effect.gen(function* () { + const response = yield* post((yield* mint).relativeUrl); + expect(response.status).toBe(502); + expect(response.body.code).toBe(code); + expect(response.body.message).toContain(message); + expect(JSON.stringify(response.body)).not.toContain("sk-test"); + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect("answers upstream_failed when the service does not answer in time", () => + Effect.gen(function* () { + const reached = yield* Deferred.make(); + const { layer } = setup({}, () => + Deferred.succeed(reached, undefined).pipe(Effect.andThen(Effect.never)), + ); + yield* Effect.gen(function* () { + const pending = yield* Effect.forkChild(post((yield* mint).relativeUrl)); + yield* Deferred.await(reached); + yield* TestClock.adjust("90 seconds"); + const response = yield* Fiber.join(pending); + expect(response.status).toBe(502); + expect(response.body).toEqual({ + code: "upstream_failed", + message: "The transcription service at api.openai.com did not answer within 90 seconds.", + }); + }).pipe(Effect.provide(layer)); + }), + ); + + it.effect( + "rejects tampered, expired, foreign, and mis-sized uploads before calling upstream", + () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + const issued = yield* mint; + const attachment = yield* issueAttachmentUploadUrl({ + type: "file", + name: "audio.webm", + mimeType: "audio/webm", + sizeBytes: audio.byteLength, + }); + const attachmentToken = attachment.relativeUrl.split("/").at(-1)!; + const rejected = [ + yield* post(`${issued.relativeUrl}x`), + yield* post(`/api/voice/transcriptions/${attachmentToken}`), + yield* post(issued.relativeUrl, { contentLength: audio.byteLength + 1 }), + yield* post(issued.relativeUrl, { + body: audio.slice(1), + contentLength: audio.byteLength - 1, + }), + ]; + yield* TestClock.adjust("2 minutes"); + rejected.push(yield* post(issued.relativeUrl)); + + for (const response of rejected) { + expect(response.status).toBe(400); + expect(response.body.code).toBe("invalid_upload"); + } + expect(requests).toHaveLength(0); + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect("answers not_configured when transcription is turned off after minting", () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + const issued = yield* mint; + const settings = yield* ServerSettings.ServerSettingsService; + yield* settings.updateSettings({ voiceTranscription: { enabled: false } }); + const response = yield* post(issued.relativeUrl); + expect(response.status).toBe(409); + expect(response.body).toEqual({ + code: "not_configured", + message: "Voice transcription is turned off for this environment.", + }); + expect(requests).toHaveLength(0); + }).pipe(Effect.provide(layer)); + }); +}); diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts new file mode 100644 index 0000000000000..1b0c3b75412f4 --- /dev/null +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -0,0 +1,349 @@ +import { + DEFAULT_VOICE_TRANSCRIPTION_BASE_URL, + VOICE_TRANSCRIPTION_URL_TTL_MS, + VoiceTranscriptionAudioMimeType, + type VoiceTranscriptionCreateUrlInput, + type VoiceTranscriptionCreateUrlResult, + VoiceTranscriptionNotConfiguredError, + type VoiceTranscriptionResult, + type VoiceTranscriptionSettings, + VoiceTranscriptionSigningKeyError, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import { identity } from "effect/Function"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http"; + +import { loadUploadSigningSecret } from "../assets/AttachmentUpload.ts"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { + base64UrlDecodeUtf8, + base64UrlEncode, + signPayload, + timingSafeEqualBase64Url, +} from "../auth/utils.ts"; +import * as ServerSettings from "../serverSettings.ts"; + +export const VOICE_TRANSCRIPTION_ROUTE_PREFIX = "/api/voice/transcriptions"; + +const UPSTREAM_TIMEOUT_SECONDS = 90; +const UPSTREAM_MESSAGE_MAX_LENGTH = 300; + +const AUDIO_FILE_EXTENSIONS = { + "audio/webm": "webm", + "audio/ogg": "ogg", + "audio/mp4": "mp4", + "audio/mpeg": "mp3", + "audio/wav": "wav", +} as const satisfies Record; + +const VoiceTranscriptionClaims = Schema.Struct({ + version: Schema.Literal(1), + kind: Schema.Literal("voice-transcription"), + mimeType: VoiceTranscriptionAudioMimeType, + sizeBytes: Schema.Number, + expiresAt: Schema.Number, +}); +export type VoiceTranscriptionClaims = typeof VoiceTranscriptionClaims.Type; + +const claimsJson = Schema.fromJsonString(VoiceTranscriptionClaims); +const decodeClaims = Schema.decodeUnknownOption(claimsJson); +const encodeClaims = Schema.encodeSync(claimsJson); + +const decodeTranscript = Schema.decodeUnknownEffect(Schema.Struct({ text: Schema.String })); +// OpenAI nests the message under `error`; some compatible servers send `error` as a plain string. +const decodeUpstreamError = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + error: Schema.Union([Schema.Struct({ message: Schema.String }), Schema.String]), + }), + ), +); + +export class VoiceTranscriptionInvalidUploadError extends Schema.TaggedError()( + "VoiceTranscriptionInvalidUploadError", + { + expectedBytes: Schema.Number, + receivedBytes: Schema.Number, + }, +) { + override get message(): string { + return `The recording was ${this.receivedBytes} bytes, expected ${this.expectedBytes}.`; + } +} + +export class VoiceTranscriptionCredentialsRejectedError extends Schema.TaggedError()( + "VoiceTranscriptionCredentialsRejectedError", + { + host: Schema.String, + status: Schema.Number, + upstreamMessage: Schema.optional(Schema.String), + }, +) { + override get message(): string { + return `The transcription service at ${this.host} rejected the API key (HTTP ${this.status})${ + this.upstreamMessage ? `: ${this.upstreamMessage}` : "." + }`; + } +} + +export class VoiceTranscriptionUpstreamError extends Schema.TaggedError()( + "VoiceTranscriptionUpstreamError", + { + host: Schema.String, + stage: Schema.Literals(["request", "timeout", "status", "response"]), + status: Schema.optional(Schema.Number), + upstreamMessage: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + switch (this.stage) { + case "request": + return `Could not reach the transcription service at ${this.host}.`; + case "timeout": + return `The transcription service at ${this.host} did not answer within ${UPSTREAM_TIMEOUT_SECONDS} seconds.`; + case "status": + return `The transcription service at ${this.host} answered HTTP ${this.status}${ + this.upstreamMessage ? `: ${this.upstreamMessage}` : "." + }`; + case "response": + return `The transcription service at ${this.host} returned an unexpected response.`; + } + } +} + +export class VoiceTranscription extends Context.Service< + VoiceTranscription, + { + readonly createUploadUrl: ( + input: VoiceTranscriptionCreateUrlInput, + ) => Effect.Effect< + VoiceTranscriptionCreateUrlResult, + VoiceTranscriptionNotConfiguredError | VoiceTranscriptionSigningKeyError + >; + readonly verifyUploadToken: ( + token: string, + ) => Effect.Effect>; + readonly transcribe: ( + claims: VoiceTranscriptionClaims, + audio: Uint8Array, + ) => Effect.Effect< + VoiceTranscriptionResult, + | VoiceTranscriptionNotConfiguredError + | VoiceTranscriptionInvalidUploadError + | VoiceTranscriptionCredentialsRejectedError + | VoiceTranscriptionUpstreamError + >; + } +>()("t3/voiceTranscription/VoiceTranscription") {} + +interface TranscriptionEndpoint { + readonly url: string; + readonly host: string; + readonly model: string; + readonly language: string; + readonly apiKey: string; +} + +function resolveEndpoint( + settings: VoiceTranscriptionSettings, +): Effect.Effect { + const notConfigured = (message: string) => + Effect.fail(new VoiceTranscriptionNotConfiguredError({ message })); + if (!settings.enabled) { + return notConfigured("Voice transcription is turned off for this environment."); + } + const baseUrl = settings.baseUrl.replace(/\/+$/, ""); + if (!baseUrl) return notConfigured("Voice transcription needs an endpoint URL."); + if (!settings.model) return notConfigured("Voice transcription needs a model name."); + // Local whisper.cpp-style servers take no key, but OpenAI itself always does. + if (!settings.apiKey && baseUrl === DEFAULT_VOICE_TRANSCRIPTION_BASE_URL) { + return notConfigured("Add an OpenAI API key to use voice transcription."); + } + const url = URL.parse(`${baseUrl}/audio/transcriptions`); + if (!url || (url.protocol !== "https:" && url.protocol !== "http:")) { + return notConfigured("The voice transcription endpoint URL is not valid."); + } + return Effect.succeed({ + url: url.toString(), + host: url.host, + model: settings.model, + language: settings.language, + apiKey: settings.apiKey, + }); +} + +function transcriptionForm( + endpoint: TranscriptionEndpoint, + claims: VoiceTranscriptionClaims, + audio: Uint8Array, +) { + const form = new FormData(); + form.append( + "file", + new Blob([audio], { type: claims.mimeType }), + `audio.${AUDIO_FILE_EXTENSIONS[claims.mimeType]}`, + ); + form.append("model", endpoint.model); + form.append("response_format", "json"); + if (endpoint.language) { + // gpt-transcribe takes a `languages` array instead of `language` and rejects both together. + form.append( + endpoint.model.startsWith("gpt-transcribe") ? "languages[]" : "language", + endpoint.language, + ); + } + return form; +} + +const readUpstreamMessage = ( + response: HttpClientResponse.HttpClientResponse, + endpoint: TranscriptionEndpoint, +) => + response.text.pipe( + Effect.map((body) => + Option.getOrUndefined( + Option.map(decodeUpstreamError(body), ({ error }) => { + const message = typeof error === "string" ? error : error.message; + const redacted = endpoint.apiKey ? message.replaceAll(endpoint.apiKey, "[key]") : message; + return redacted.slice(0, UPSTREAM_MESSAGE_MAX_LENGTH); + }), + ), + ), + Effect.orElseSucceed(() => undefined), + ); + +const make = Effect.gen(function* () { + const settingsService = yield* ServerSettings.ServerSettingsService; + const secretStore = yield* ServerSecretStore.ServerSecretStore; + const client = yield* HttpClient.HttpClient; + + const signingSecret = loadUploadSigningSecret.pipe( + Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore), + ); + + const loadEndpoint = settingsService.getSettings.pipe( + Effect.tapError((cause) => + Effect.logError("Failed to read voice transcription settings.", { cause }), + ), + Effect.mapError( + () => + new VoiceTranscriptionNotConfiguredError({ + message: "Could not read the voice transcription settings.", + }), + ), + Effect.flatMap((settings) => resolveEndpoint(settings.voiceTranscription)), + ); + + const createUploadUrl = Effect.fn("VoiceTranscription.createUploadUrl")(function* ( + input: VoiceTranscriptionCreateUrlInput, + ) { + yield* loadEndpoint; + const secret = yield* signingSecret.pipe( + Effect.mapError((cause) => new VoiceTranscriptionSigningKeyError({ cause })), + ); + const expiresAt = (yield* Clock.currentTimeMillis) + VOICE_TRANSCRIPTION_URL_TTL_MS; + const encodedPayload = base64UrlEncode( + encodeClaims({ + version: 1, + kind: "voice-transcription", + mimeType: input.mimeType, + sizeBytes: input.sizeBytes, + expiresAt, + }), + ); + return { + relativeUrl: `${VOICE_TRANSCRIPTION_ROUTE_PREFIX}/${encodedPayload}.${signPayload(encodedPayload, secret)}`, + expiresAt, + }; + }); + + const verifyUploadToken = Effect.fn("VoiceTranscription.verifyUploadToken")(function* ( + token: string, + ) { + const [encodedPayload, signature, unexpectedSegment] = token.split("."); + if (!encodedPayload || !signature || unexpectedSegment !== undefined) { + return Option.none(); + } + const secret = yield* signingSecret.pipe( + Effect.tapError((cause) => + Effect.logError("Failed to load the voice transcription signing key.", { cause }), + ), + Effect.option, + ); + if ( + Option.isNone(secret) || + !timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret.value)) + ) { + return Option.none(); + } + const claims = Option.flatMap( + Option.liftThrowable(base64UrlDecodeUtf8)(encodedPayload), + decodeClaims, + ); + const nowMs = yield* Clock.currentTimeMillis; + return Option.filter(claims, (decoded) => decoded.expiresAt > nowMs); + }); + + const transcribe = Effect.fn("VoiceTranscription.transcribe")(function* ( + claims: VoiceTranscriptionClaims, + audio: Uint8Array, + ) { + if (audio.byteLength !== claims.sizeBytes) { + return yield* new VoiceTranscriptionInvalidUploadError({ + expectedBytes: claims.sizeBytes, + receivedBytes: audio.byteLength, + }); + } + const endpoint = yield* loadEndpoint; + const upstreamError = ( + fields: Omit[0], "host">, + ) => new VoiceTranscriptionUpstreamError({ host: endpoint.host, ...fields }); + + const request = HttpClientRequest.post(endpoint.url).pipe( + HttpClientRequest.bodyFormData(transcriptionForm(endpoint, claims, audio)), + endpoint.apiKey ? HttpClientRequest.bearerToken(endpoint.apiKey) : identity, + HttpClientRequest.acceptJson, + ); + return yield* Effect.gen(function* () { + const response = yield* client + .execute(request) + .pipe(Effect.mapError((cause) => upstreamError({ stage: "request", cause }))); + if (response.status === 401 || response.status === 403) { + const upstreamMessage = yield* readUpstreamMessage(response, endpoint); + return yield* new VoiceTranscriptionCredentialsRejectedError({ + host: endpoint.host, + status: response.status, + ...(upstreamMessage ? { upstreamMessage } : {}), + }); + } + if (response.status < 200 || response.status >= 300) { + const upstreamMessage = yield* readUpstreamMessage(response, endpoint); + return yield* upstreamError({ + stage: "status", + status: response.status, + ...(upstreamMessage ? { upstreamMessage } : {}), + }); + } + const { text } = yield* response.json.pipe( + Effect.flatMap(decodeTranscript), + Effect.mapError((cause) => upstreamError({ stage: "response", cause })), + ); + return { text } satisfies VoiceTranscriptionResult; + }).pipe( + Effect.timeoutOrElse({ + duration: `${UPSTREAM_TIMEOUT_SECONDS} seconds`, + orElse: () => Effect.fail(upstreamError({ stage: "timeout" })), + }), + ); + }); + + return VoiceTranscription.of({ createUploadUrl, verifyUploadToken, transcribe }); +}); + +export const layer = Layer.effect(VoiceTranscription, make); From 7fe49cf214b4dfc6b7402196152fcfde1ed687b6 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 21:19:43 -0400 Subject: [PATCH 04/55] feat(server): serve voice.createTranscriptionUrl over the WebSocket RPC Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/RpcAuthorization.test.ts | 6 ++++++ apps/server/src/observability/RpcInstrumentation.ts | 1 + apps/server/src/ws.test.ts | 2 ++ apps/server/src/ws.ts | 4 ++++ 4 files changed, 13 insertions(+) diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 390e33aa42293..ec3d8565b35d5 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -81,6 +81,12 @@ describe("RPC authorization scopes", () => { ); }); + it("requires operate access to spend the environment's transcription credentials", () => { + expect(requiredScopeForRpcMethod(WS_METHODS.voiceCreateTranscriptionUrl)).toBe( + AuthOrchestrationOperateScope, + ); + }); + it("requires write access to import agent session history", () => { expect(requiredScopeForRpcMethod(WS_METHODS.agentSessionsScan)).toBe( AuthOrchestrationReadScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 3f3942e75d082..4901abf191f51 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -154,6 +154,7 @@ const RPC_AGGREGATES = { [WS_METHODS.assetsPersistChatAttachments]: "orchestration", [WS_METHODS.attachmentsCreateUploadUrl]: "workspace", [WS_METHODS.attachmentsDelete]: "workspace", + [WS_METHODS.voiceCreateTranscriptionUrl]: "voice", [WS_METHODS.providerUploadFeedback]: "provider", [WS_METHODS.mcpAppsCallTool]: "provider", [WS_METHODS.mcpAppsToolInfo]: "provider", diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index a9a028ec94bdf..f568fa7eab1a5 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -84,6 +84,7 @@ import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; import * as UsageService from "./usage/UsageService.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; +import * as VoiceTranscription from "./voiceTranscription/VoiceTranscription.ts"; import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts"; @@ -352,6 +353,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(UsageService.UsageService)({}), Layer.mock(VcsProvisioningService.VcsProvisioningService)({}), Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}), + Layer.mock(VoiceTranscription.VoiceTranscription)({}), Layer.mock(WorkspaceEntries.WorkspaceEntries)({}), Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}), Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 763365ceeddc1..4ff6489519234 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -255,6 +255,7 @@ import { import * as AgentSessionScanner from "./project/AgentSessionScanner.ts"; import * as AgentSessionImporter from "./project/AgentSessionImporter.ts"; import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; +import * as VoiceTranscription from "./voiceTranscription/VoiceTranscription.ts"; const CONFIG_DISCOVERY_TIMEOUT = Duration.seconds(5); const isProviderUploadFeedbackError = Schema.is(ProviderUploadFeedbackError); @@ -1286,6 +1287,7 @@ export const layerWsRpc = ( const serverSettings = yield* ServerSettings.ServerSettingsService; const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const voiceTranscription = yield* VoiceTranscription.VoiceTranscription; const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; @@ -2709,6 +2711,8 @@ export const layerWsRpc = ( ), [WS_METHODS.attachmentsCreateUploadUrl]: (input) => issueAttachmentUploadUrl(input), [WS_METHODS.attachmentsDelete]: (input) => deletePendingAttachment(input.attachmentId), + [WS_METHODS.voiceCreateTranscriptionUrl]: (input) => + voiceTranscription.createUploadUrl(input), [WS_METHODS.agentSessionsScan]: () => agentSessionScanner.scan, [WS_METHODS.agentSessionsImport]: (input) => agentSessionImporter.importRecentAgentThreads(input), From d66d26802d5a7e2283c6f752e6d1f79d22e02da4 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 21:28:15 -0400 Subject: [PATCH 05/55] feat(client-runtime): environment-backed voice transcriber Adds createEnvironmentVoiceTranscriber, which uploads a recording to the capability URL the environment mints and maps the server's failure body to the controller's error codes, so the API key never leaves the environment. The controller now surfaces a transcriber's own failure message instead of a generic one. Moves the metering helpers out of the mobile app so the web recorder can share them. Co-Authored-By: Claude Opus 5.5 --- .../voice-input/ComposerDictationControl.tsx | 2 +- .../voice-input/VoiceInputProvider.tsx | 3 +- .../voice-input/voiceInputMetering.ts | 13 -- .../src/voice-input/controller.ts | 10 +- .../environmentTranscriber.test.ts | 178 +++++++++++++++++ .../src/voice-input/environmentTranscriber.ts | 186 ++++++++++++++++++ .../client-runtime/src/voice-input/index.ts | 9 + .../src/voice-input/metering.ts | 25 +++ 8 files changed, 410 insertions(+), 16 deletions(-) delete mode 100644 apps/mobile/src/features/voice-input/voiceInputMetering.ts create mode 100644 packages/client-runtime/src/voice-input/environmentTranscriber.test.ts create mode 100644 packages/client-runtime/src/voice-input/environmentTranscriber.ts create mode 100644 packages/client-runtime/src/voice-input/metering.ts diff --git a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx index 3e7d852be7554..77b284faacd34 100644 --- a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx +++ b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx @@ -24,8 +24,8 @@ import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; import { cn } from "../../lib/cn"; +import { VOICE_WAVEFORM_SAMPLE_COUNT } from "@t3tools/client-runtime/voice-input"; import type { VoiceComposerPresentation } from "./voiceInputPresentation"; -import { VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering"; const DICTATION_TIMING = { duration: 220, diff --git a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx index 48f75b4ff32ec..ccbd8f4e1dbb1 100644 --- a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx +++ b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx @@ -33,12 +33,13 @@ import { getLocalVoiceTranscriber } from "../../native/voiceTranscription"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { getNativeShowcaseScene } from "../showcase/nativeShowcaseScene"; import { + normalizeVoiceInputDecibels, VOICE_RECORDING_LIMIT_SECONDS, + VOICE_WAVEFORM_SAMPLE_COUNT, voiceInputBlocksSubmission, type VoiceInputState, } from "@t3tools/client-runtime/voice-input"; import { createLazyVoiceRecorder, type LazyVoiceRecorder } from "./lazyVoiceRecorder"; -import { normalizeVoiceInputDecibels, VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering"; import { VoiceInputSession } from "./voiceInputSession"; const INITIAL_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null }; diff --git a/apps/mobile/src/features/voice-input/voiceInputMetering.ts b/apps/mobile/src/features/voice-input/voiceInputMetering.ts deleted file mode 100644 index c3ba75ab4968a..0000000000000 --- a/apps/mobile/src/features/voice-input/voiceInputMetering.ts +++ /dev/null @@ -1,13 +0,0 @@ -export const VOICE_WAVEFORM_SAMPLE_COUNT = 64; - -const VOICE_NOISE_FLOOR_DECIBELS = -60; -const VOICE_NOISE_FLOOR_AMPLITUDE = 10 ** (VOICE_NOISE_FLOOR_DECIBELS / 20); - -export function normalizeVoiceInputDecibels(decibels: number | undefined) { - if (decibels === undefined || !Number.isFinite(decibels)) return 0; - if (decibels <= VOICE_NOISE_FLOOR_DECIBELS) return 0; - if (decibels >= 0) return 1; - - const amplitude = 10 ** (decibels / 20); - return Math.sqrt((amplitude - VOICE_NOISE_FLOOR_AMPLITUDE) / (1 - VOICE_NOISE_FLOOR_AMPLITUDE)); -} diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index b9d0f54f67672..35b0058f54e30 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -1,6 +1,10 @@ import { replaceTextRange } from "@t3tools/shared/composerTrigger"; -import type { PreparedVoiceTranscription, VoiceTranscriber } from "./transcription.ts"; +import { + VoiceTranscriptionError, + type PreparedVoiceTranscription, + type VoiceTranscriber, +} from "./transcription.ts"; export const VOICE_RECORDING_LIMIT_SECONDS = 5 * 60; @@ -167,6 +171,7 @@ function preparationErrorMessage(error: unknown): string { if (errorCode(error) === "unsupported-locale") { return "Voice transcription is not available for this language."; } + if (error instanceof VoiceTranscriptionError) return error.message; return "Could not prepare voice transcription."; } @@ -174,6 +179,9 @@ function transcriptionErrorMessage(error: unknown): string { if (error instanceof Error && error.message === "voice-operation-busy") { return "Voice transcription is still finishing. Try again shortly."; } + // Transcribers phrase their failures for the user, such as the environment's own + // reason for rejecting an upload. Anything else is an unexpected defect. + if (error instanceof VoiceTranscriptionError) return error.message; return "Could not transcribe this recording."; } diff --git a/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts b/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts new file mode 100644 index 0000000000000..0494c70fda967 --- /dev/null +++ b/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { + createEnvironmentVoiceTranscriber, + type EnvironmentVoiceTranscriberDependencies, +} from "./environmentTranscriber.ts"; +import { VoiceTranscriptionError } from "./transcription.ts"; + +const RECORDING_URI = "blob:https://app.example/recording"; + +type PostResponse = { readonly status: number; readonly body: unknown }; + +function createHarness(options: { + readonly audio?: Blob; + readonly language?: string; + readonly post?: PostResponse | ((init: RequestInit) => Promise); + readonly createTranscriptionUrl?: EnvironmentVoiceTranscriberDependencies["createTranscriptionUrl"]; + readonly resolveUrl?: EnvironmentVoiceTranscriberDependencies["resolveUrl"]; +}) { + const audio = options.audio ?? new Blob(["audio-bytes"], { type: "audio/webm;codecs=opus" }); + const posts: Array<{ url: string; init: RequestInit }> = []; + const mintInputs: Array<{ mimeType: string; sizeBytes: number }> = []; + const post = options.post ?? { status: 200, body: { text: "hello world" } }; + const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + if (url === RECORDING_URI) return new Response(audio); + posts.push({ url, init: init ?? {} }); + if (typeof post === "function") return post(init ?? {}); + return new Response(JSON.stringify(post.body), { + status: post.status, + headers: { "content-type": "application/json" }, + }); + }); + const transcriber = createEnvironmentVoiceTranscriber({ + language: () => options.language ?? "", + fallbackLocale: () => "fr-FR", + createTranscriptionUrl: + options.createTranscriptionUrl ?? + (async (input) => { + mintInputs.push(input); + return { relativeUrl: "/api/voice/abc", expiresAt: 1 }; + }), + resolveUrl: options.resolveUrl ?? ((relativeUrl) => `https://env.example${relativeUrl}`), + fetch: fetch as unknown as typeof globalThis.fetch, + }); + return { transcriber, posts, mintInputs }; +} + +async function transcribe( + harness: ReturnType, + signal: AbortSignal = new AbortController().signal, +) { + const prepared = await harness.transcriber.prepare({ signal }); + return prepared.transcribe(RECORDING_URI, { signal }); +} + +async function transcriptionError(promise: Promise): Promise { + const error = await promise.then( + () => null, + (cause: unknown) => cause, + ); + expect(error).toBeInstanceOf(VoiceTranscriptionError); + return error as VoiceTranscriptionError; +} + +describe("createEnvironmentVoiceTranscriber", () => { + it("posts the recording to the minted URL as its container type and returns the text", async () => { + const harness = createHarness({}); + await expect(transcribe(harness)).resolves.toBe("hello world"); + + expect(harness.mintInputs).toEqual([{ mimeType: "audio/webm", sizeBytes: 11 }]); + expect(harness.posts).toHaveLength(1); + const [post] = harness.posts; + expect(post?.url).toBe("https://env.example/api/voice/abc"); + expect(post?.init.method).toBe("POST"); + expect(post?.init.headers).toEqual({ "content-type": "audio/webm" }); + expect(await new Response(post?.init.body as Blob).text()).toBe("audio-bytes"); + }); + + it("uses the configured language as the locale and falls back to the device locale", async () => { + const signal = new AbortController().signal; + expect((await createHarness({ language: "de" }).transcriber.prepare({ signal })).locale).toBe( + "de", + ); + expect((await createHarness({}).transcriber.prepare({ signal })).locale).toBe("fr-FR"); + }); + + it("surfaces the environment's failure message and marks a missing configuration unavailable", async () => { + const rejected = await transcriptionError( + transcribe( + createHarness({ + post: { status: 502, body: { code: "upstream_failed", message: "Groq is down." } }, + }), + ), + ); + expect(rejected).toMatchObject({ code: "transcription-failed", message: "Groq is down." }); + + const unconfigured = await transcriptionError( + transcribe( + createHarness({ + post: { status: 409, body: { code: "not_configured", message: "Add an API key." } }, + }), + ), + ); + expect(unconfigured).toMatchObject({ code: "unavailable", message: "Add an API key." }); + + const opaque = await transcriptionError( + transcribe(createHarness({ post: { status: 500, body: "" } })), + ); + expect(opaque.code).toBe("transcription-failed"); + }); + + it("maps a refused URL mint to unavailable when the environment is not configured", async () => { + const unconfigured = await transcriptionError( + transcribe( + createHarness({ + createTranscriptionUrl: async () => { + throw { _tag: "VoiceTranscriptionNotConfiguredError", message: "no key" }; + }, + }), + ), + ); + expect(unconfigured.code).toBe("unavailable"); + + const offline = await transcriptionError( + transcribe( + createHarness({ + createTranscriptionUrl: async () => { + throw new Error("socket closed"); + }, + }), + ), + ); + expect(offline.code).toBe("transcription-failed"); + + const disconnected = await transcriptionError( + transcribe(createHarness({ resolveUrl: () => null })), + ); + expect(disconnected.code).toBe("transcription-failed"); + }); + + it("settles as cancelled only after the upload itself has been aborted", async () => { + const controller = new AbortController(); + let uploadSettled = false; + const harness = createHarness({ + post: (init) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => { + void Promise.resolve().then(() => { + uploadSettled = true; + reject(new DOMException("aborted", "AbortError")); + }); + }); + }), + }); + const pending = transcribe(harness, controller.signal); + await vi.waitFor(() => expect(harness.posts).toHaveLength(1)); + controller.abort(); + const cancelled = await transcriptionError(pending); + expect(cancelled.code).toBe("cancelled"); + expect(uploadSettled).toBe(true); + }); + + it.each([ + ["an unsupported container", new Blob(["x"], { type: "audio/flac" })], + ["an empty recording", new Blob([], { type: "audio/mp4" })], + [ + "an oversized recording", + new Blob([new Uint8Array(25 * 1024 * 1024 + 1)], { type: "audio/ogg" }), + ], + ])("rejects %s before minting a URL", async (_label, audio) => { + const harness = createHarness({ audio }); + const error = await transcriptionError(transcribe(harness)); + expect(error.code).toBe("transcription-failed"); + expect(harness.mintInputs).toHaveLength(0); + expect(harness.posts).toHaveLength(0); + }); +}); diff --git a/packages/client-runtime/src/voice-input/environmentTranscriber.ts b/packages/client-runtime/src/voice-input/environmentTranscriber.ts new file mode 100644 index 0000000000000..96c6ed9842ba1 --- /dev/null +++ b/packages/client-runtime/src/voice-input/environmentTranscriber.ts @@ -0,0 +1,186 @@ +import { + VOICE_TRANSCRIPTION_MAX_AUDIO_BYTES, + VoiceTranscriptionAudioMimeType, + VoiceTranscriptionFailure, + VoiceTranscriptionResult, + type VoiceTranscriptionCreateUrlInput, + type VoiceTranscriptionCreateUrlResult, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { + VoiceTranscriptionError, + throwIfVoiceTranscriptionAborted, + type VoiceTranscriber, +} from "./transcription.ts"; + +export type EnvironmentVoiceTranscriberDependencies = { + /** Configured ISO-639-1 code. Empty lets the model detect the language. */ + readonly language: () => string; + /** Locale used for transcript spacing when no language is configured. */ + readonly fallbackLocale: () => string; + /** Rejects with the RPC's tagged error when the environment refuses to mint a URL. */ + readonly createTranscriptionUrl: ( + input: VoiceTranscriptionCreateUrlInput, + ) => Promise; + /** Null when the environment has no reachable HTTP base, such as while disconnected. */ + readonly resolveUrl: (relativeUrl: string) => string | null; + readonly fetch: typeof globalThis.fetch; +}; + +const decodeMimeType = Schema.decodeUnknownOption(VoiceTranscriptionAudioMimeType); +const decodeResult = Schema.decodeUnknownOption(VoiceTranscriptionResult); +const decodeFailure = Schema.decodeUnknownOption(VoiceTranscriptionFailure); + +function containerMimeType(blobType: string): VoiceTranscriptionAudioMimeType | null { + return Option.getOrNull(decodeMimeType(blobType.split(";")[0]?.trim().toLowerCase())); +} + +function isNotConfiguredError(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "_tag" in error && + error._tag === "VoiceTranscriptionNotConfiguredError" + ); +} + +function isAbortError(error: unknown): boolean { + return error instanceof Error && error.name === "AbortError"; +} + +async function readJson(response: Response): Promise { + try { + return await response.json(); + } catch { + return null; + } +} + +function failureFromResponse(status: number, body: unknown): VoiceTranscriptionError { + const failure = Option.getOrNull(decodeFailure(body)); + if (!failure) { + return new VoiceTranscriptionError( + "transcription-failed", + `The environment could not transcribe the recording (HTTP ${status}).`, + ); + } + return new VoiceTranscriptionError( + failure.code === "not_configured" ? "unavailable" : "transcription-failed", + failure.message, + ); +} + +/** + * Uploads the recording to the environment, which forwards it to the configured + * speech-to-text API. The API key never leaves the environment, so the client only + * needs the capability URL the environment mints per recording. + */ +export function createEnvironmentVoiceTranscriber( + dependencies: EnvironmentVoiceTranscriberDependencies, +): VoiceTranscriber { + const transcribe = async (uri: string, { signal }: { readonly signal: AbortSignal }) => { + throwIfVoiceTranscriptionAborted(signal); + let blob: Blob; + try { + blob = await (await dependencies.fetch(uri)).blob(); + } catch (error) { + throw new VoiceTranscriptionError( + "transcription-failed", + "The recording is no longer available.", + { cause: error }, + ); + } + throwIfVoiceTranscriptionAborted(signal); + + const mimeType = containerMimeType(blob.type); + if (!mimeType) { + throw new VoiceTranscriptionError( + "transcription-failed", + "This browser's recording format is not supported.", + ); + } + if (blob.size === 0) { + throw new VoiceTranscriptionError("transcription-failed", "No audio was recorded."); + } + if (blob.size > VOICE_TRANSCRIPTION_MAX_AUDIO_BYTES) { + throw new VoiceTranscriptionError( + "transcription-failed", + "The recording is too large to transcribe.", + ); + } + + let minted: VoiceTranscriptionCreateUrlResult; + try { + minted = await dependencies.createTranscriptionUrl({ mimeType, sizeBytes: blob.size }); + } catch (error) { + if (isNotConfiguredError(error)) { + throw new VoiceTranscriptionError( + "unavailable", + "Voice input is not configured on this environment.", + { cause: error }, + ); + } + throw new VoiceTranscriptionError( + "transcription-failed", + "Could not reach the environment to transcribe the recording.", + { cause: error }, + ); + } + throwIfVoiceTranscriptionAborted(signal); + + const url = dependencies.resolveUrl(minted.relativeUrl); + if (url === null) { + throw new VoiceTranscriptionError( + "transcription-failed", + "The environment is not connected.", + ); + } + + let response: Response; + try { + response = await dependencies.fetch(url, { + method: "POST", + headers: { "content-type": mimeType }, + body: blob, + signal, + }); + } catch (error) { + if (isAbortError(error) || signal.aborted) { + throw new VoiceTranscriptionError("cancelled", "Voice transcription was cancelled.", { + cause: error, + }); + } + throw new VoiceTranscriptionError( + "transcription-failed", + "Could not reach the environment to transcribe the recording.", + { cause: error }, + ); + } + + const body = await readJson(response); + if (!response.ok) { + throw failureFromResponse(response.status, body); + } + const result = Option.getOrNull(decodeResult(body)); + if (!result) { + throw new VoiceTranscriptionError( + "transcription-failed", + "The environment returned an unexpected transcription response.", + ); + } + return result.text; + }; + + return { + prepare: async ({ signal }) => { + throwIfVoiceTranscriptionAborted(signal); + const language = dependencies.language().trim(); + return { + locale: language.length > 0 ? language : dependencies.fallbackLocale(), + transcribe, + }; + }, + }; +} diff --git a/packages/client-runtime/src/voice-input/index.ts b/packages/client-runtime/src/voice-input/index.ts index 61fb338514275..e746a7da833d1 100644 --- a/packages/client-runtime/src/voice-input/index.ts +++ b/packages/client-runtime/src/voice-input/index.ts @@ -9,6 +9,15 @@ export { type VoiceRecorder, type VoiceRecorderStatus, } from "./controller.ts"; +export { + createEnvironmentVoiceTranscriber, + type EnvironmentVoiceTranscriberDependencies, +} from "./environmentTranscriber.ts"; +export { + normalizeVoiceInputDecibels, + voiceInputDecibelsFromByteSamples, + VOICE_WAVEFORM_SAMPLE_COUNT, +} from "./metering.ts"; export { VoiceTranscriptionError, throwIfVoiceTranscriptionAborted, diff --git a/packages/client-runtime/src/voice-input/metering.ts b/packages/client-runtime/src/voice-input/metering.ts new file mode 100644 index 0000000000000..d9198dd392197 --- /dev/null +++ b/packages/client-runtime/src/voice-input/metering.ts @@ -0,0 +1,25 @@ +export const VOICE_WAVEFORM_SAMPLE_COUNT = 64; + +const VOICE_NOISE_FLOOR_DECIBELS = -60; +const VOICE_NOISE_FLOOR_AMPLITUDE = 10 ** (VOICE_NOISE_FLOOR_DECIBELS / 20); + +export function normalizeVoiceInputDecibels(decibels: number | undefined) { + if (decibels === undefined || !Number.isFinite(decibels)) return 0; + if (decibels <= VOICE_NOISE_FLOOR_DECIBELS) return 0; + if (decibels >= 0) return 1; + + const amplitude = 10 ** (decibels / 20); + return Math.sqrt((amplitude - VOICE_NOISE_FLOOR_AMPLITUDE) / (1 - VOICE_NOISE_FLOOR_AMPLITUDE)); +} + +/** Decibels of a PCM sample window in the Web Audio byte range (128 is silence). */ +export function voiceInputDecibelsFromByteSamples(samples: ArrayLike): number { + if (samples.length === 0) return Number.NEGATIVE_INFINITY; + let sumOfSquares = 0; + for (let index = 0; index < samples.length; index += 1) { + const centered = ((samples[index] ?? 128) - 128) / 128; + sumOfSquares += centered * centered; + } + const rms = Math.sqrt(sumOfSquares / samples.length); + return rms === 0 ? Number.NEGATIVE_INFINITY : 20 * Math.log10(rms); +} From cfc1ff2159164a38445ded55683acc2463dfb30d Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 21:33:58 -0400 Subject: [PATCH 06/55] feat(contracts): add an xAI provider to voice transcription settings xAI's speech-to-text endpoint is /v1/stt with its own form fields, so a base URL alone cannot reach it. Settings now carry a provider, and each provider's hosted base URL and default model live in one table. Co-Authored-By: Claude Opus 5.5 --- .../voiceTranscription/VoiceTranscription.ts | 7 +++-- packages/contracts/src/settings.ts | 27 +++++++++++++++---- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts index 1b0c3b75412f4..393d5fe1d30de 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -1,5 +1,5 @@ import { - DEFAULT_VOICE_TRANSCRIPTION_BASE_URL, + VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS, VOICE_TRANSCRIPTION_URL_TTL_MS, VoiceTranscriptionAudioMimeType, type VoiceTranscriptionCreateUrlInput, @@ -162,7 +162,10 @@ function resolveEndpoint( if (!baseUrl) return notConfigured("Voice transcription needs an endpoint URL."); if (!settings.model) return notConfigured("Voice transcription needs a model name."); // Local whisper.cpp-style servers take no key, but OpenAI itself always does. - if (!settings.apiKey && baseUrl === DEFAULT_VOICE_TRANSCRIPTION_BASE_URL) { + if ( + !settings.apiKey && + baseUrl === VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS[settings.provider].baseUrl + ) { return notConfigured("Add an OpenAI API key to use voice transcription."); } const url = URL.parse(`${baseUrl}/audio/transcriptions`); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index f5ad9c81a0fa3..a8747947649bb 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -778,17 +778,33 @@ export const AntigravitySettings = makeProviderSettingsSchema( ); export type AntigravitySettings = typeof AntigravitySettings.Type; -export const DEFAULT_VOICE_TRANSCRIPTION_BASE_URL = "https://api.openai.com/v1"; -export const DEFAULT_VOICE_TRANSCRIPTION_MODEL = "gpt-transcribe"; +/** + * `openai-compatible` posts to `/audio/transcriptions` (OpenAI, Groq, a whisper.cpp + * server); `xai` posts to `/stt`, whose form fields differ. + */ +export const VoiceTranscriptionProvider = Schema.Literals(["openai-compatible", "xai"]); +export type VoiceTranscriptionProvider = typeof VoiceTranscriptionProvider.Type; + +/** A key is required whenever `baseUrl` is still the provider's hosted default. */ +export const VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS = { + "openai-compatible": { baseUrl: "https://api.openai.com/v1", model: "gpt-transcribe" }, + xai: { baseUrl: "https://api.x.ai/v1", model: "grok-voice-transcribe-2.0" }, +} as const satisfies Record; -/** Any OpenAI-compatible `/audio/transcriptions` endpoint: OpenAI, Groq, a whisper.cpp server. */ export const VoiceTranscriptionSettings = Schema.Struct({ enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + provider: VoiceTranscriptionProvider.pipe( + Schema.withDecodingDefault(Effect.succeed("openai-compatible" as const)), + ), baseUrl: TrimmedString.pipe( - Schema.withDecodingDefault(Effect.succeed(DEFAULT_VOICE_TRANSCRIPTION_BASE_URL)), + Schema.withDecodingDefault( + Effect.succeed(VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS["openai-compatible"].baseUrl), + ), ), model: TrimmedString.pipe( - Schema.withDecodingDefault(Effect.succeed(DEFAULT_VOICE_TRANSCRIPTION_MODEL)), + Schema.withDecodingDefault( + Effect.succeed(VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS["openai-compatible"].model), + ), ), /** ISO-639-1 code. Empty lets the model detect the language. */ language: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), @@ -1545,6 +1561,7 @@ export const ServerSettingsPatch = Schema.Struct({ voiceTranscription: Schema.optionalKey( Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean), + provider: Schema.optionalKey(VoiceTranscriptionProvider), baseUrl: Schema.optionalKey(TrimmedString), model: Schema.optionalKey(TrimmedString), language: Schema.optionalKey(TrimmedString), From 9a03a81b7c26ea7cc3a7cd0c82a1e1154e0c0e6e Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 21:34:08 -0400 Subject: [PATCH 07/55] feat(web): MediaRecorder voice recorder and environment transcriber binding The recorder implements the shared VoiceRecorder contract over getUserMedia and MediaRecorder behind an injectable environment. It opens the microphone only from the permission request a user action triggers, negotiates a container the environment accepts, exposes the recording as a blob URL after stop, stops itself at the duration limit, and stops every track on release so the OS microphone indicator turns off before transcription. The web binding mints the capability URL through the guarded RPC command and resolves it against the connection's HTTP base, which covers local, remote, and tunnel connections. Promise.withResolvers is replaced because the web app compiles against ES2023. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/lib/voiceRecorder.test.ts | 187 +++++++++++++ apps/web/src/lib/voiceRecorder.ts | 247 ++++++++++++++++++ apps/web/src/state/voiceTranscription.ts | 48 ++++ .../src/voice-input/controller.ts | 5 +- .../src/voice-input/metering.test.ts | 21 ++ 5 files changed, 507 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/lib/voiceRecorder.test.ts create mode 100644 apps/web/src/lib/voiceRecorder.ts create mode 100644 apps/web/src/state/voiceTranscription.ts create mode 100644 packages/client-runtime/src/voice-input/metering.test.ts diff --git a/apps/web/src/lib/voiceRecorder.test.ts b/apps/web/src/lib/voiceRecorder.test.ts new file mode 100644 index 0000000000000..5bd55f7a02f4d --- /dev/null +++ b/apps/web/src/lib/voiceRecorder.test.ts @@ -0,0 +1,187 @@ +import type { VoiceRecorderStatus } from "@t3tools/client-runtime/voice-input"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + createWebVoiceRecorder, + type MediaRecorderLike, + type VoiceRecorderEnvironment, +} from "./voiceRecorder"; + +type Listener = (event: never) => void; + +class FakeMediaRecorder implements MediaRecorderLike { + state: RecordingState = "inactive"; + readonly mimeType: string; + private readonly listeners = new Map(); + + constructor( + readonly stream: MediaStream, + readonly options: MediaRecorderOptions, + private readonly chunk: Blob, + ) { + this.mimeType = options.mimeType ?? ""; + } + + addEventListener(type: string, listener: unknown): void { + this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener as Listener]); + } + + start(): void { + this.state = "recording"; + } + + stop(): void { + this.state = "inactive"; + for (const listener of this.listeners.get("dataavailable") ?? []) { + listener({ data: this.chunk } as never); + } + for (const listener of this.listeners.get("stop") ?? []) listener(undefined as never); + } +} + +function createFakeStream() { + const tracks = [{ stop: vi.fn() }, { stop: vi.fn() }]; + return { stream: { getTracks: () => tracks } as unknown as MediaStream, tracks }; +} + +function createHarness(overrides: Partial = {}) { + const { stream, tracks } = createFakeStream(); + const recorders: FakeMediaRecorder[] = []; + const statuses: VoiceRecorderStatus[] = []; + const created: Blob[] = []; + const revoked: string[] = []; + const environment: VoiceRecorderEnvironment = { + getUserMedia: vi.fn(async () => stream), + queryMicrophonePermission: async () => "prompt", + isTypeSupported: (mimeType) => mimeType === "audio/webm;codecs=opus", + createMediaRecorder: (target, options) => { + const recorder = new FakeMediaRecorder(target, options, new Blob(["pcm"])); + recorders.push(recorder); + return recorder; + }, + createLevelMeter: () => null, + createObjectURL: (blob) => { + created.push(blob); + return `blob:recording-${created.length}`; + }, + revokeObjectURL: (url) => { + revoked.push(url); + }, + denialIsPermanent: false, + ...overrides, + }; + const web = createWebVoiceRecorder(environment, (status) => statuses.push(status)); + return { web, environment, tracks, recorders, statuses, created, revoked }; +} + +async function startRecording(harness: ReturnType) { + expect(await harness.web.requestPermission()).toEqual({ granted: true, canAskAgain: true }); + await harness.web.configureRecording(); + await harness.web.recorder.prepareToRecordAsync(); + harness.web.recorder.record({ forDuration: 300 }); +} + +function refusal(name: "NotAllowedError" | "SecurityError") { + return async () => { + throw new DOMException("refused", name); + }; +} + +describe("createWebVoiceRecorder", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("records into a blob URL that exists only after stop, then turns the microphone off", async () => { + const harness = createHarness(); + await startRecording(harness); + expect(harness.web.recorder.uri).toBeNull(); + expect(harness.web.startedAt).not.toBeNull(); + expect(harness.recorders[0]?.options).toEqual({ mimeType: "audio/webm;codecs=opus" }); + + await harness.web.recorder.stop(); + expect(harness.web.recorder.uri).toBe("blob:recording-1"); + expect(harness.created[0]?.type).toBe("audio/webm;codecs=opus"); + expect(await harness.created[0]?.text()).toBe("pcm"); + expect(harness.web.startedAt).toBeNull(); + + await harness.web.releaseRecording(); + for (const track of harness.tracks) expect(track.stop).toHaveBeenCalledTimes(1); + + harness.web.deleteRecording("blob:recording-1"); + expect(harness.revoked).toEqual(["blob:recording-1"]); + expect(harness.web.recorder.uri).toBeNull(); + }); + + it("falls back through the container list for engines without opus webm", async () => { + const safari = createHarness({ isTypeSupported: (mimeType) => mimeType === "audio/mp4" }); + await startRecording(safari); + expect(safari.recorders[0]?.options).toEqual({ mimeType: "audio/mp4" }); + + const unknown = createHarness({ isTypeSupported: () => false }); + await startRecording(unknown); + expect(unknown.recorders[0]?.options).toEqual({}); + }); + + it("stops itself at the duration limit and reports the finished recording", async () => { + const harness = createHarness(); + await startRecording(harness); + vi.useFakeTimers(); + harness.web.recorder.record({ forDuration: 2 }); + await vi.advanceTimersByTimeAsync(1_999); + expect(harness.statuses).toEqual([]); + await vi.advanceTimersByTimeAsync(1); + expect(harness.statuses).toEqual([ + { isFinished: true, hasError: false, error: null, url: "blob:recording-1" }, + ]); + }); + + it("resolves stop without a recording when nothing started", async () => { + const harness = createHarness(); + await harness.web.recorder.stop(); + await harness.web.requestPermission(); + await harness.web.configureRecording(); + await harness.web.recorder.prepareToRecordAsync(); + await harness.web.recorder.stop(); + expect(harness.web.recorder.uri).toBeNull(); + await harness.web.releaseRecording(); + for (const track of harness.tracks) expect(track.stop).toHaveBeenCalledTimes(1); + }); + + it("releases a stream acquired for the permission prompt even if recording never configures", async () => { + const harness = createHarness(); + await harness.web.requestPermission(); + await harness.web.releaseRecording(); + for (const track of harness.tracks) expect(track.stop).toHaveBeenCalledTimes(1); + }); + + it("tells a blocked microphone apart from a dismissed prompt", async () => { + const dismissed = createHarness({ getUserMedia: refusal("NotAllowedError") }); + expect(await dismissed.web.requestPermission()).toEqual({ granted: false, canAskAgain: true }); + + const blocked = createHarness({ + getUserMedia: refusal("NotAllowedError"), + queryMicrophonePermission: async () => "denied", + }); + expect(await blocked.web.requestPermission()).toEqual({ granted: false, canAskAgain: false }); + + const desktop = createHarness({ + getUserMedia: refusal("NotAllowedError"), + denialIsPermanent: true, + }); + expect(await desktop.web.requestPermission()).toEqual({ granted: false, canAskAgain: false }); + + const insecure = createHarness({ + getUserMedia: refusal("SecurityError"), + queryMicrophonePermission: async () => null, + }); + expect(await insecure.web.requestPermission()).toEqual({ granted: false, canAskAgain: true }); + + const broken = createHarness({ + getUserMedia: async () => { + throw new DOMException("no device", "NotFoundError"); + }, + }); + await expect(broken.web.requestPermission()).rejects.toMatchObject({ name: "NotFoundError" }); + }); +}); diff --git a/apps/web/src/lib/voiceRecorder.ts b/apps/web/src/lib/voiceRecorder.ts new file mode 100644 index 0000000000000..63cde1e2000ed --- /dev/null +++ b/apps/web/src/lib/voiceRecorder.ts @@ -0,0 +1,247 @@ +import { + normalizeVoiceInputDecibels, + voiceInputDecibelsFromByteSamples, + type VoiceRecorder, + type VoiceRecorderStatus, +} from "@t3tools/client-runtime/voice-input"; + +import { isElectron } from "~/env"; + +/** Containers the environment accepts, best first. Safari records only mp4. */ +const PREFERRED_AUDIO_MIME_TYPES = [ + "audio/webm;codecs=opus", + "audio/webm", + "audio/ogg;codecs=opus", + "audio/ogg", + "audio/mp4", +] as const; + +export interface VoiceLevelMeter { + /** Current microphone level from 0 (silence) to 1 (full scale). */ + readLevel(): number; + close(): void; +} + +export type MediaRecorderLike = Pick< + MediaRecorder, + "state" | "mimeType" | "start" | "stop" | "addEventListener" +>; + +export interface VoiceRecorderEnvironment { + readonly getUserMedia: (constraints: MediaStreamConstraints) => Promise; + /** Null when the Permissions API cannot answer for the microphone. */ + readonly queryMicrophonePermission: () => Promise; + readonly isTypeSupported: (mimeType: string) => boolean; + readonly createMediaRecorder: ( + stream: MediaStream, + options: MediaRecorderOptions, + ) => MediaRecorderLike; + readonly createLevelMeter: (stream: MediaStream) => VoiceLevelMeter | null; + readonly createObjectURL: (blob: Blob) => string; + readonly revokeObjectURL: (url: string) => void; + /** True where the page cannot prompt again, so a refusal needs a settings change. */ + readonly denialIsPermanent: boolean; +} + +export interface WebVoiceRecorder { + readonly recorder: VoiceRecorder; + /** Epoch milliseconds when the current recording started, null otherwise. */ + readonly startedAt: number | null; + requestPermission(): Promise<{ readonly granted: boolean; readonly canAskAgain: boolean }>; + configureRecording(): Promise; + /** Stops every microphone track. Safe to call at any time. */ + releaseRecording(): Promise; + deleteRecording(uri: string): void; + readLevel(): number; +} + +function stopTracks(stream: MediaStream | null): void { + for (const track of stream?.getTracks() ?? []) track.stop(); +} + +function isPermissionRefusal(error: unknown): boolean { + return ( + error instanceof DOMException && + (error.name === "NotAllowedError" || error.name === "SecurityError") + ); +} + +export function createWebVoiceRecorder( + environment: VoiceRecorderEnvironment, + onStatus: (status: VoiceRecorderStatus) => void, +): WebVoiceRecorder { + // Acquired by requestPermission, because a browser only prompts through + // getUserMedia, and adopted by configureRecording. + let pendingStream: MediaStream | null = null; + let stream: MediaStream | null = null; + let meter: VoiceLevelMeter | null = null; + let mediaRecorder: MediaRecorderLike | null = null; + let started = false; + let stopped: Promise | null = null; + let chunks: Blob[] = []; + let recordingUri: string | null = null; + let limitTimer: ReturnType | null = null; + let startedAt: number | null = null; + + const clearLimitTimer = () => { + if (limitTimer !== null) clearTimeout(limitTimer); + limitTimer = null; + }; + + const recorder: VoiceRecorder = { + get uri() { + return recordingUri; + }, + prepareToRecordAsync: async () => { + if (!stream) throw new Error("The microphone is not open."); + const mimeType = PREFERRED_AUDIO_MIME_TYPES.find(environment.isTypeSupported); + const next = environment.createMediaRecorder(stream, mimeType ? { mimeType } : {}); + let resolve!: () => void; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + chunks = []; + next.addEventListener("dataavailable", (event) => { + if (event.data.size > 0) chunks.push(event.data); + }); + next.addEventListener("stop", () => { + const blob = new Blob(chunks, { type: next.mimeType || mimeType || "" }); + chunks = []; + recordingUri = environment.createObjectURL(blob); + clearLimitTimer(); + startedAt = null; + resolve(); + }); + next.addEventListener("error", () => { + onStatus({ + isFinished: false, + hasError: true, + error: "The microphone stopped recording.", + url: null, + }); + }); + mediaRecorder = next; + started = false; + stopped = promise; + }, + record: ({ forDuration }) => { + if (!mediaRecorder) throw new Error("The recorder is not prepared."); + mediaRecorder.start(); + started = true; + startedAt = Date.now(); + limitTimer = setTimeout(() => { + void recorder + .stop() + .then(() => + onStatus({ isFinished: true, hasError: false, error: null, url: recordingUri }), + ); + }, forDuration * 1000); + }, + stop: async () => { + clearLimitTimer(); + const current = mediaRecorder; + if (!current) return; + // A recorder that never started fires no stop event, and one whose + // tracks ended already fired it. + if (started) { + if (current.state !== "inactive") current.stop(); + await stopped; + } + mediaRecorder = null; + stopped = null; + started = false; + startedAt = null; + }, + }; + + return { + recorder, + get startedAt() { + return startedAt; + }, + requestPermission: async () => { + stopTracks(pendingStream); + pendingStream = null; + try { + pendingStream = await environment.getUserMedia({ audio: true }); + return { granted: true, canAskAgain: true }; + } catch (error) { + if (!isPermissionRefusal(error)) throw error; + const state = environment.denialIsPermanent + ? "denied" + : await environment.queryMicrophonePermission(); + return { granted: false, canAskAgain: state !== "denied" }; + } + }, + configureRecording: async () => { + stream = pendingStream ?? (await environment.getUserMedia({ audio: true })); + pendingStream = null; + meter = environment.createLevelMeter(stream); + }, + releaseRecording: async () => { + clearLimitTimer(); + meter?.close(); + meter = null; + stopTracks(stream); + stream = null; + stopTracks(pendingStream); + pendingStream = null; + startedAt = null; + }, + deleteRecording: (uri) => { + environment.revokeObjectURL(uri); + if (uri === recordingUri) recordingUri = null; + }, + readLevel: () => meter?.readLevel() ?? 0, + }; +} + +function createAnalyserLevelMeter(stream: MediaStream): VoiceLevelMeter | null { + if (typeof AudioContext === "undefined") return null; + const context = new AudioContext(); + const analyser = context.createAnalyser(); + analyser.fftSize = 512; + context.createMediaStreamSource(stream).connect(analyser); + if (context.state === "suspended") void context.resume().catch(() => undefined); + const samples = new Uint8Array(analyser.fftSize); + return { + readLevel: () => { + analyser.getByteTimeDomainData(samples); + return normalizeVoiceInputDecibels(voiceInputDecibelsFromByteSamples(samples)); + }, + close: () => { + void context.close().catch(() => undefined); + }, + }; +} + +export function createBrowserVoiceRecorderEnvironment(): VoiceRecorderEnvironment { + return { + getUserMedia: (constraints) => + navigator.mediaDevices?.getUserMedia + ? navigator.mediaDevices.getUserMedia(constraints) + : // Plain-http origins other than localhost have no mediaDevices at all. + Promise.reject( + new DOMException("Microphone access needs a secure context.", "SecurityError"), + ), + queryMicrophonePermission: async () => { + try { + // lib.dom's PermissionName omits "microphone" although every engine answers it. + const status = await navigator.permissions.query({ + name: "microphone" as PermissionName, + }); + return status.state; + } catch { + return null; + } + }, + isTypeSupported: (mimeType) => + typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(mimeType), + createMediaRecorder: (stream, options) => new MediaRecorder(stream, options), + createLevelMeter: createAnalyserLevelMeter, + createObjectURL: (blob) => URL.createObjectURL(blob), + revokeObjectURL: (url) => URL.revokeObjectURL(url), + // Electron grants the page's request itself, so a refusal can only come from the OS. + denialIsPermanent: isElectron, + }; +} diff --git a/apps/web/src/state/voiceTranscription.ts b/apps/web/src/state/voiceTranscription.ts new file mode 100644 index 0000000000000..b5f7fea0ff373 --- /dev/null +++ b/apps/web/src/state/voiceTranscription.ts @@ -0,0 +1,48 @@ +import { AuthOrchestrationOperateScope, WS_METHODS, type EnvironmentId } from "@t3tools/contracts"; +import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; +import { + createEnvironmentRpcCommand, + runAtomCommand, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { + createEnvironmentVoiceTranscriber, + type VoiceTranscriber, +} from "@t3tools/client-runtime/voice-input"; + +import { connectionAtomRuntime } from "../connection/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { readEnvironmentScope, readPreparedConnection } from "./session"; + +export const voiceTranscriptionEnvironment = { + createTranscriptionUrl: createEnvironmentRpcCommand(connectionAtomRuntime, { + label: "environment-command:voice:create-transcription-url", + tag: WS_METHODS.voiceCreateTranscriptionUrl, + }), +}; + +export function createWebVoiceTranscriber( + environmentId: EnvironmentId, + language: () => string, +): VoiceTranscriber { + return createEnvironmentVoiceTranscriber({ + language, + fallbackLocale: () => navigator.language || "en-US", + createTranscriptionUrl: async (input) => { + const result = await runAtomCommand( + appAtomRegistry, + voiceTranscriptionEnvironment.createTranscriptionUrl, + { environmentId, input }, + { reportFailure: false }, + ); + if (result._tag !== "Success") throw squashAtomCommandFailure(result); + return result.value; + }, + resolveUrl: (relativeUrl) => { + if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return null; + const connection = readPreparedConnection(environmentId); + return connection ? resolveAssetUrl(connection.httpBaseUrl, relativeUrl) : null; + }, + fetch: (input, init) => fetch(input, init), + }); +} diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index 35b0058f54e30..30d7c14d129de 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -132,7 +132,10 @@ let activeTranscriptionOperation: Promise | null = null; function acquireSession(): VoiceInputSession | null { if (activeSession) return null; - const { promise, resolve } = Promise.withResolvers(); + let resolve!: () => void; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); const token = { abandoned: false, released: promise, release: resolve }; activeSession = token; return token; diff --git a/packages/client-runtime/src/voice-input/metering.test.ts b/packages/client-runtime/src/voice-input/metering.test.ts new file mode 100644 index 0000000000000..a067f57b7d7d6 --- /dev/null +++ b/packages/client-runtime/src/voice-input/metering.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { normalizeVoiceInputDecibels, voiceInputDecibelsFromByteSamples } from "./metering.ts"; + +describe("voice input metering", () => { + it("maps silence to an empty meter and a full-scale signal to a full one", () => { + expect(normalizeVoiceInputDecibels(voiceInputDecibelsFromByteSamples([128, 128, 128]))).toBe(0); + expect( + normalizeVoiceInputDecibels(voiceInputDecibelsFromByteSamples([0, 255, 0, 255])), + ).toBeGreaterThan(0.99); + expect(normalizeVoiceInputDecibels(voiceInputDecibelsFromByteSamples([]))).toBe(0); + }); + + it("grows with the signal between the noise floor and full scale", () => { + const quiet = normalizeVoiceInputDecibels(voiceInputDecibelsFromByteSamples([129, 127])); + const speech = normalizeVoiceInputDecibels(voiceInputDecibelsFromByteSamples([160, 96])); + expect(quiet).toBeGreaterThanOrEqual(0); + expect(speech).toBeGreaterThan(quiet); + expect(speech).toBeLessThan(1); + }); +}); From 204191e8e6d272992811b2a00b2fec83fab3cbe5 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 21:36:51 -0400 Subject: [PATCH 08/55] feat(server): transcribe voice recordings through xAI speech-to-text Each voice transcription provider now has an entry in one protocol table that gives its URL path, accepted audio formats, and form builder. xAI posts to /stt with model, an optional language, and the file last, since xAI may ignore fields sent after it. xAI does not accept WebM. Minting an upload URL for WebM under xAI fails with not-configured, and a WebM upload minted before switching to xAI answers invalid_upload without calling upstream. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/http.ts | 2 + .../VoiceTranscription.test.ts | 70 +++++++++- .../voiceTranscription/VoiceTranscription.ts | 120 ++++++++++++++---- 3 files changed, 159 insertions(+), 33 deletions(-) diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 3f5935424f31c..e3493ad7e73f1 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -557,6 +557,8 @@ export const layerVoiceTranscriptionRoute = HttpRouter.add( Effect.succeed(voiceTranscriptionFailure("not_configured", error.message)), VoiceTranscriptionInvalidUploadError: (error) => Effect.succeed(voiceTranscriptionFailure("invalid_upload", error.message)), + VoiceTranscriptionUnsupportedFormatError: (error) => + Effect.succeed(voiceTranscriptionFailure("invalid_upload", error.message)), VoiceTranscriptionCredentialsRejectedError: (error) => Effect.succeed(voiceTranscriptionFailure("upstream_rejected_credentials", error.message)), VoiceTranscriptionUpstreamError: (error) => diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts index a5c8245268bfd..b6d72e35db90e 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -1,6 +1,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; -import type { VoiceTranscriptionSettings } from "@t3tools/contracts"; +import type { + VoiceTranscriptionAudioMimeType, + VoiceTranscriptionSettings, +} from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -51,10 +54,18 @@ function setup( return { layer, requests }; } -const mint = Effect.gen(function* () { - const voice = yield* VoiceTranscription.VoiceTranscription; - return yield* voice.createUploadUrl({ mimeType: "audio/webm", sizeBytes: audio.byteLength }); -}); +const mintAs = (mimeType: VoiceTranscriptionAudioMimeType) => + Effect.gen(function* () { + const voice = yield* VoiceTranscription.VoiceTranscription; + return yield* voice.createUploadUrl({ mimeType, sizeBytes: audio.byteLength }); + }); +const mint = mintAs("audio/webm"); + +const xai = { + provider: "xai", + baseUrl: "https://api.x.ai/v1", + model: "grok-voice-transcribe-2.0", +} as const; const post = ( relativeUrl: string, @@ -155,6 +166,8 @@ describe("VoiceTranscription", () => { it.effect.each([ { settings: { enabled: false }, message: "turned off" }, { settings: { apiKey: "" }, message: "OpenAI API key" }, + { settings: { ...xai, apiKey: "" }, message: "xAI API key" }, + { settings: xai, message: "xAI does not accept audio/webm recordings." }, { settings: { model: "" }, message: "model name" }, { settings: { baseUrl: "" }, message: "endpoint URL" }, { settings: { baseUrl: "ftp://whisper.local" }, message: "not valid" }, @@ -216,6 +229,53 @@ describe("VoiceTranscription", () => { }, ); + it.effect.each([ + { language: "en", fields: ["model", "language", "file"] }, + { language: "", fields: ["model", "file"] }, + ])( + "transcribes through xAI speech-to-text with language hint '$language' and the file last", + ({ language, fields }) => { + const { layer, requests } = setup({ ...xai, language }, () => + Effect.succeed( + Response.json({ text: "hello grok", language: "en", duration: 1.2, words: [] }), + ), + ); + return Effect.gen(function* () { + const response = yield* post((yield* mintAs("audio/wav")).relativeUrl); + + expect(response).toEqual({ status: 200, body: { text: "hello grok" } }); + expect(requests).toHaveLength(1); + const request = requests[0]!; + expect(request.method).toBe("POST"); + expect(request.url).toBe("https://api.x.ai/v1/stt"); + expect(request.headers.authorization).toBe("Bearer sk-test"); + const form = formOf(request); + expect([...form.keys()]).toEqual(fields); + expect(form.get("model")).toBe("grok-voice-transcribe-2.0"); + expect(form.getAll("language")).toEqual(language ? [language] : []); + const file = form.get("file") as File; + expect(file.name).toBe("audio.wav"); + expect(file.type).toBe("audio/wav"); + expect(new Uint8Array(yield* Effect.promise(() => file.arrayBuffer()))).toEqual(audio); + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect("refuses a WebM upload minted before switching to xAI without calling upstream", () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + const issued = yield* mint; + const settings = yield* ServerSettings.ServerSettingsService; + yield* settings.updateSettings({ voiceTranscription: xai }); + const response = yield* post(issued.relativeUrl); + expect(response).toEqual({ + status: 400, + body: { code: "invalid_upload", message: "xAI does not accept audio/webm recordings." }, + }); + expect(requests).toHaveLength(0); + }).pipe(Effect.provide(layer)); + }); + it.effect.each([ { upstream: Response.json( diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts index 393d5fe1d30de..06c193c10456e 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -5,6 +5,7 @@ import { type VoiceTranscriptionCreateUrlInput, type VoiceTranscriptionCreateUrlResult, VoiceTranscriptionNotConfiguredError, + type VoiceTranscriptionProvider, type VoiceTranscriptionResult, type VoiceTranscriptionSettings, VoiceTranscriptionSigningKeyError, @@ -41,6 +42,52 @@ const AUDIO_FILE_EXTENSIONS = { "audio/wav": "wav", } as const satisfies Record; +interface TranscriptionFormInput { + readonly model: string; + readonly language: string; + readonly file: Blob; + readonly fileName: string; +} + +interface ProviderProtocol { + readonly name: string; + readonly path: string; + readonly acceptedMimeTypes: ReadonlyArray; + readonly form: (input: TranscriptionFormInput) => FormData; +} + +const PROVIDER_PROTOCOLS = { + "openai-compatible": { + name: "OpenAI", + path: "audio/transcriptions", + acceptedMimeTypes: VoiceTranscriptionAudioMimeType.literals, + form: ({ model, language, file, fileName }) => { + const form = new FormData(); + form.append("file", file, fileName); + form.append("model", model); + form.append("response_format", "json"); + if (language) { + // gpt-transcribe takes a `languages` array instead of `language` and rejects both together. + form.append(model.startsWith("gpt-transcribe") ? "languages[]" : "language", language); + } + return form; + }, + }, + xai: { + name: "xAI", + path: "stt", + acceptedMimeTypes: ["audio/ogg", "audio/mp4", "audio/mpeg", "audio/wav"], + form: ({ model, language, file, fileName }) => { + const form = new FormData(); + form.append("model", model); + if (language) form.append("language", language); + // xAI may ignore fields sent after `file`, so it must be last. + form.append("file", file, fileName); + return form; + }, + }, +} as const satisfies Record; + const VoiceTranscriptionClaims = Schema.Struct({ version: Schema.Literal(1), kind: Schema.Literal("voice-transcription"), @@ -76,6 +123,23 @@ export class VoiceTranscriptionInvalidUploadError extends Schema.TaggedError()( + "VoiceTranscriptionUnsupportedFormatError", + { + providerName: Schema.String, + mimeType: VoiceTranscriptionAudioMimeType, + }, +) { + override get message(): string { + return unsupportedFormatMessage(this.providerName, this.mimeType); + } +} + +const unsupportedFormatMessage = ( + providerName: string, + mimeType: VoiceTranscriptionAudioMimeType, +) => `${providerName} does not accept ${mimeType} recordings.`; + export class VoiceTranscriptionCredentialsRejectedError extends Schema.TaggedError()( "VoiceTranscriptionCredentialsRejectedError", { @@ -136,6 +200,7 @@ export class VoiceTranscription extends Context.Service< VoiceTranscriptionResult, | VoiceTranscriptionNotConfiguredError | VoiceTranscriptionInvalidUploadError + | VoiceTranscriptionUnsupportedFormatError | VoiceTranscriptionCredentialsRejectedError | VoiceTranscriptionUpstreamError >; @@ -143,6 +208,7 @@ export class VoiceTranscription extends Context.Service< >()("t3/voiceTranscription/VoiceTranscription") {} interface TranscriptionEndpoint { + readonly protocol: ProviderProtocol; readonly url: string; readonly host: string; readonly model: string; @@ -161,18 +227,20 @@ function resolveEndpoint( const baseUrl = settings.baseUrl.replace(/\/+$/, ""); if (!baseUrl) return notConfigured("Voice transcription needs an endpoint URL."); if (!settings.model) return notConfigured("Voice transcription needs a model name."); - // Local whisper.cpp-style servers take no key, but OpenAI itself always does. + const protocol = PROVIDER_PROTOCOLS[settings.provider]; + // Local whisper.cpp-style servers take no key, but the hosted defaults always do. if ( !settings.apiKey && baseUrl === VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS[settings.provider].baseUrl ) { - return notConfigured("Add an OpenAI API key to use voice transcription."); + return notConfigured(`Add an ${protocol.name} API key to use voice transcription.`); } - const url = URL.parse(`${baseUrl}/audio/transcriptions`); + const url = URL.parse(`${baseUrl}/${protocol.path}`); if (!url || (url.protocol !== "https:" && url.protocol !== "http:")) { return notConfigured("The voice transcription endpoint URL is not valid."); } return Effect.succeed({ + protocol, url: url.toString(), host: url.host, model: settings.model, @@ -181,29 +249,6 @@ function resolveEndpoint( }); } -function transcriptionForm( - endpoint: TranscriptionEndpoint, - claims: VoiceTranscriptionClaims, - audio: Uint8Array, -) { - const form = new FormData(); - form.append( - "file", - new Blob([audio], { type: claims.mimeType }), - `audio.${AUDIO_FILE_EXTENSIONS[claims.mimeType]}`, - ); - form.append("model", endpoint.model); - form.append("response_format", "json"); - if (endpoint.language) { - // gpt-transcribe takes a `languages` array instead of `language` and rejects both together. - form.append( - endpoint.model.startsWith("gpt-transcribe") ? "languages[]" : "language", - endpoint.language, - ); - } - return form; -} - const readUpstreamMessage = ( response: HttpClientResponse.HttpClientResponse, endpoint: TranscriptionEndpoint, @@ -246,7 +291,12 @@ const make = Effect.gen(function* () { const createUploadUrl = Effect.fn("VoiceTranscription.createUploadUrl")(function* ( input: VoiceTranscriptionCreateUrlInput, ) { - yield* loadEndpoint; + const endpoint = yield* loadEndpoint; + if (!endpoint.protocol.acceptedMimeTypes.includes(input.mimeType)) { + return yield* new VoiceTranscriptionNotConfiguredError({ + message: unsupportedFormatMessage(endpoint.protocol.name, input.mimeType), + }); + } const secret = yield* signingSecret.pipe( Effect.mapError((cause) => new VoiceTranscriptionSigningKeyError({ cause })), ); @@ -304,12 +354,26 @@ const make = Effect.gen(function* () { }); } const endpoint = yield* loadEndpoint; + // The provider can change between minting and uploading. + if (!endpoint.protocol.acceptedMimeTypes.includes(claims.mimeType)) { + return yield* new VoiceTranscriptionUnsupportedFormatError({ + providerName: endpoint.protocol.name, + mimeType: claims.mimeType, + }); + } const upstreamError = ( fields: Omit[0], "host">, ) => new VoiceTranscriptionUpstreamError({ host: endpoint.host, ...fields }); const request = HttpClientRequest.post(endpoint.url).pipe( - HttpClientRequest.bodyFormData(transcriptionForm(endpoint, claims, audio)), + HttpClientRequest.bodyFormData( + endpoint.protocol.form({ + model: endpoint.model, + language: endpoint.language, + file: new Blob([audio], { type: claims.mimeType }), + fileName: `audio.${AUDIO_FILE_EXTENSIONS[claims.mimeType]}`, + }), + ), endpoint.apiKey ? HttpClientRequest.bearerToken(endpoint.apiKey) : identity, HttpClientRequest.acceptJson, ); From de220b44ef001462f9f837ea36cf44b236679544 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 21:59:12 -0400 Subject: [PATCH 09/55] feat(web): voice input in the composer Adds a microphone button to the composer's action cluster when the environment has voice transcription enabled and the user may operate it. Clicking it records; clicking the same button in the same spot again stops, transcribes through the environment, and inserts the text at the selection the recording captured. The cancel control, level meter, and timer grow leftward from that button so it never moves. Esc cancels, the editor is read-only and sending is blocked while voice input runs, and the shortcut and command palette reach the same toggle. Every recording is converted to 16 kHz mono WAV before upload, because xAI rejects WebM and whisper.cpp would otherwise need ffmpeg. A denied microphone explains the fix for the platform, including a System Settings link on macOS once the desktop bridge lists the microphone pane. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/ChatView.tsx | 4 + apps/web/src/components/CommandPalette.tsx | 32 ++- apps/web/src/components/chat/ChatComposer.tsx | 73 +++++- ...ComposerVoiceInputControl.browser.test.tsx | 129 ++++++++++ .../chat/ComposerVoiceInputControl.tsx | 231 ++++++++++++++++++ .../components/chat/useComposerVoiceInput.ts | 135 ++++++++++ .../chat/voiceInputErrorPresentation.test.ts | 54 ++++ .../chat/voiceInputErrorPresentation.ts | 38 +++ apps/web/src/lib/microphoneSettings.ts | 22 ++ apps/web/src/lib/voiceRecorder.test.ts | 2 +- apps/web/src/lib/voiceRecorder.ts | 10 +- apps/web/src/lib/voiceWav.browser.test.ts | 32 +++ apps/web/src/lib/voiceWav.test.ts | 38 +++ apps/web/src/lib/voiceWav.ts | 67 +++++ apps/web/src/state/voiceTranscription.ts | 2 + .../environmentTranscriber.test.ts | 22 ++ .../src/voice-input/environmentTranscriber.ts | 14 ++ 17 files changed, 897 insertions(+), 8 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx create mode 100644 apps/web/src/components/chat/ComposerVoiceInputControl.tsx create mode 100644 apps/web/src/components/chat/useComposerVoiceInput.ts create mode 100644 apps/web/src/components/chat/voiceInputErrorPresentation.test.ts create mode 100644 apps/web/src/components/chat/voiceInputErrorPresentation.ts create mode 100644 apps/web/src/lib/microphoneSettings.ts create mode 100644 apps/web/src/lib/voiceWav.browser.test.ts create mode 100644 apps/web/src/lib/voiceWav.test.ts create mode 100644 apps/web/src/lib/voiceWav.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1f9eb813a455f..cb41ea00652c5 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -5869,6 +5869,10 @@ export default function ChatView(props: ChatViewProps) { "composer.effort": openComposerControl("composer.effort"), "composer.mode": openComposerControl("composer.mode"), "composer.workspace": openComposerControl("composer.workspace"), + "composer.toggleDictation": ({ event }) => { + if (event.repeat) return; + return composerRef.current?.toggleDictation() === true; + }, "composer.cycleHost": ({ event }) => { if (!canChangeEnvironment) return false; if (event.repeat) return; diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index dd6db0fc6ac52..508fed9176650 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -69,6 +69,7 @@ import { MessageSquareDashedIcon, LinkIcon, MessageSquareIcon, + MicIcon, MonitorIcon, MoonIcon, PaletteIcon, @@ -242,7 +243,11 @@ import { Kbd, KbdGroup } from "./ui/kbd"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext"; +import { + ComposerHandleContext, + useComposerHandleContext, + type ComposerHandleRef, +} from "../composerHandleContext"; import type { ChatComposerHandle } from "./chat/ChatComposer"; import { getProjectOrderKey } from "../logicalProject"; import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; @@ -705,6 +710,10 @@ function CommandPaletteDialog(props: { ); } +function toggleComposerDictation(composerHandleRef: ComposerHandleRef | null): void { + composerHandleRef?.current?.toggleDictation(); +} + function OpenCommandPaletteDialog(props: { readonly openIntent: CommandPaletteOpenIntent | null; readonly setOpen: (open: boolean) => void; @@ -1008,6 +1017,15 @@ function OpenCommandPaletteDialog(props: { const currentProjectEnvironmentId = activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null; const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null; + const canOperateCurrentEnvironment = useEnvironmentScope( + currentProjectEnvironmentId, + AuthOrchestrationOperateScope, + ); + const voiceInputAvailable = + canOperateCurrentEnvironment && + environments.find((environment) => environment.environmentId === currentProjectEnvironmentId) + ?.serverConfig?.settings.voiceTranscription.enabled === true; + const composerHandleRef = useComposerHandleContext(); const scratchTargetEnvironmentId = scratchEnvironmentId( currentProjectEnvironmentId ?? primaryEnvironmentId, ); @@ -1650,6 +1668,18 @@ function OpenCommandPaletteDialog(props: { }); } + if (voiceInputAvailable) { + actionItems.push({ + kind: "action", + value: "voice-input", + title: "Voice input", + searchTerms: ["dictate", "dictation", "microphone", "speech", "transcribe", "voice"], + icon: , + shortcutCommand: "composer.toggleDictation", + run: async () => toggleComposerDictation(composerHandleRef), + }); + } + const promptLinkTarget = paletteRouteTarget ? paletteRouteTarget.kind === "server" ? paletteRouteTarget.threadRef diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index f600b831c53e6..95ed31d16afbf 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1066,6 +1066,8 @@ import { } from "lucide-react"; import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText"; import { hasProviderSetup } from "./ProviderStatusBanner"; +import { ComposerVoiceInputControl } from "./ComposerVoiceInputControl"; +import { useComposerVoiceInput } from "./useComposerVoiceInput"; import { applyProviderInstanceSettings, deriveProviderInstanceEntries, @@ -1458,6 +1460,8 @@ export interface ChatComposerHandle { isModelPickerOpen: () => boolean; isCaretAtStart: () => boolean; compactContext: () => void; + /** Starts dictation, or stops and transcribes. False when voice input is not offered here. */ + toggleDictation: () => boolean; readSnapshot: () => { value: string; cursor: number; @@ -2078,6 +2082,37 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); const questionPreparations = useQuestionAttachmentPreparation((state) => state.counts); const prompt = composerDraft.prompt; + const composerEditorRef = useRef(null); + const readVoiceDraftStable = useStableCallback(() => { + const text = promptRef.current; + return { + ownerKey: composerDraftTargetKey, + text, + selection: composerEditorRef.current?.readSelectionRange() ?? { + start: text.length, + end: text.length, + }, + }; + }); + // Voice input must be known before sendDisabledReason, but the commit goes through + // applyPromptReplacement, which is declared further down. The effect below the + // declaration fills this in, since a closure may not capture it earlier. + const voiceCommitRef = useRef< + ((text: string, selection: { readonly start: number; readonly end: number }) => void) | null + >(null); + const commitVoiceDraftStable = useStableCallback( + (text: string, selection: { readonly start: number; readonly end: number }) => { + voiceCommitRef.current?.(text, selection); + }, + ); + const voiceInput = useComposerVoiceInput({ + environmentId, + ownerKey: composerDraftTargetKey, + language: settings.voiceTranscription.language, + draftText: prompt, + readDraft: readVoiceDraftStable, + commitDraft: commitVoiceDraftStable, + }); const composerImages = attachmentDraft.images; const composerFiles = attachmentDraft.files; const inlineFileIdSet = (() => { @@ -2356,6 +2391,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); const sendDisabledReason = externalSendDisabledReason ?? + (voiceInput.busy ? "Finish voice input first." : null) ?? (multipleModelSelections?.length === 0 ? "Select at least one model." : null) ?? (activePendingProgress ? attachmentBlockReason @@ -2480,7 +2516,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) !hasMultilinePrompt && pendingUserInputs.length === 0; - const composerEditorRef = useRef(null); const pasteAsTextShortcutUntilRef = useRef(0); const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set }>({ targetKey: "", @@ -2843,6 +2878,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (!activePendingProgress || (supportsQuestionAttachments && activePendingProgress.activeQuestion?.allowCustomAnswer !== false)); + const showComposerVoiceAction = + settings.voiceTranscription.enabled && + canOperateThread && + !isConnecting && + !isComposerApprovalState && + !projectSelectionRequired && + !isChoiceOnlyPendingQuestion && + !activePendingIsResponding; const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; const isComposerMenuLoading = @@ -3784,6 +3827,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return true; }; const applyPromptReplacementStable = useStableCallback(applyPromptReplacement); + useLayoutEffect(() => { + voiceCommitRef.current = (text, selection) => { + applyPromptReplacement(0, promptRef.current.length, text, { + expandedCursorAfterReplace: selection.start, + }); + }; + }); const readComposerSnapshot = (): { value: string; @@ -6117,6 +6167,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) focusAt: (cursor: number) => { composerEditorRef.current?.focusAt(cursor); }, + toggleDictation: () => { + if (!showComposerVoiceAction && !voiceInput.busy) return false; + voiceInput.toggle(); + return true; + }, restoreAfterTimelineReachedEnd, collapseForTimelineScrollKey: (key) => { const scrollNode = getTimelineScrollableNode(); @@ -7207,7 +7262,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComposerApprovalState || projectSelectionRequired || isChoiceOnlyPendingQuestion || - activePendingIsResponding + activePendingIsResponding || + voiceInput.busy } /> @@ -7322,6 +7378,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) : null} + {showComposerVoiceAction || voiceInput.busy ? ( + + ) : null} > = {}, +) { + return ( +
+ null} + readLevel={() => 0} + onToggle={() => {}} + onCancel={() => {}} + onOpenSettings={() => {}} + {...overrides} + /> +
+ ); +} + +const toggleButton = (container: HTMLElement) => + [...container.querySelectorAll("button")].at(-1)!; + +describe("ComposerVoiceInputControl", () => { + it("keeps the stop control exactly where the mic button was, so a second click in the same spot stops", async () => { + const onToggle = vi.fn(); + await using screen = await render(control(IDLE, { onToggle })); + const idleButton = toggleButton(screen.container); + expect(idleButton.getAttribute("aria-label")).toBe("Voice input"); + const idleRect = idleButton.getBoundingClientRect(); + await act(async () => idleButton.click()); + expect(onToggle).toHaveBeenCalledTimes(1); + + await screen.rerender(control(RECORDING, { onToggle })); + const stopButton = toggleButton(screen.container); + expect(stopButton.getAttribute("aria-label")).toBe("Stop and transcribe"); + const recordingRect = stopButton.getBoundingClientRect(); + expect(recordingRect.left).toBe(idleRect.left); + expect(recordingRect.top).toBe(idleRect.top); + expect(recordingRect.width).toBe(idleRect.width); + expect(recordingRect.height).toBe(idleRect.height); + expect(screen.container.querySelector('[aria-label="Cancel voice input"]')).not.toBeNull(); + + await act(async () => stopButton.click()); + expect(onToggle).toHaveBeenCalledTimes(2); + }); + + it("disables the stop control while transcribing but keeps cancel available", async () => { + const onCancel = vi.fn(); + await using screen = await render(control(TRANSCRIBING, { onCancel })); + expect(toggleButton(screen.container).disabled).toBe(true); + expect(screen.container.querySelector('[role="status"]')).not.toBeNull(); + const cancel = screen.container.querySelector( + '[aria-label="Cancel voice input"]', + )!; + expect(cancel.disabled).toBe(false); + await act(async () => cancel.click()); + expect(onCancel).toHaveBeenCalledTimes(1); + }); + + it("counts recording time from the recorder's start", async () => { + let startedAt: number | null = null; + await using screen = await render(control(PREPARING, { readStartedAt: () => startedAt })); + vi.useFakeTimers(); + try { + startedAt = Date.now(); + await screen.rerender(control(RECORDING, { readStartedAt: () => startedAt })); + expect(screen.container.textContent).toContain("0:00"); + await act(async () => { + await vi.advanceTimersByTimeAsync(62_000); + }); + expect(screen.container.textContent).toContain("1:02"); + } finally { + vi.useRealTimers(); + } + }); + + it("explains a blocked microphone and offers the fix the platform has", async () => { + const denied: VoiceInputState = { + phase: "error", + error: "Microphone access is required for voice input.", + errorAction: "settings", + }; + const onOpenSettings = vi.fn(); + await using screen = await render( + control(denied, { + onOpenSettings, + errorContext: { secureContext: true, canOpenSystemSettings: true }, + }), + ); + expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( + "System Settings", + ); + const open = [...screen.container.querySelectorAll("button")].find( + (button) => button.textContent === "Open settings", + )!; + await act(async () => open.click()); + expect(onOpenSettings).toHaveBeenCalledTimes(1); + + const onToggle = vi.fn(); + await screen.rerender( + control( + { phase: "error", error: "No speech was detected.", errorAction: "retry" }, + { onToggle }, + ), + ); + expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( + "No speech was detected.", + ); + const retry = [...screen.container.querySelectorAll("button")].find( + (button) => button.textContent === "Retry", + )!; + await act(async () => retry.click()); + expect(onToggle).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/web/src/components/chat/ComposerVoiceInputControl.tsx b/apps/web/src/components/chat/ComposerVoiceInputControl.tsx new file mode 100644 index 0000000000000..54c7e6206fae3 --- /dev/null +++ b/apps/web/src/components/chat/ComposerVoiceInputControl.tsx @@ -0,0 +1,231 @@ +import type { VoiceInputState } from "@t3tools/client-runtime/voice-input"; +import { CircleAlertIcon, MicIcon, XIcon } from "lucide-react"; +import { memo, useEffect, useLayoutEffect, useRef, useState } from "react"; + +import { useMediaQuery } from "~/hooks/useMediaQuery"; +import { + canOpenMicrophoneSystemSettings, + openMicrophoneSystemSettings, +} from "~/lib/microphoneSettings"; +import { cn } from "~/lib/utils"; +import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { + resolveVoiceInputErrorPresentation, + type VoiceInputErrorContext, +} from "./voiceInputErrorPresentation"; + +/** At most 15 meter updates a second, and none outside the recording phase. */ +export const VOICE_METER_INTERVAL_MS = 66; +const VOICE_METER_BAR_COUNT = 5; +const VOICE_METER_REST_SCALE = 0.15; + +const BROWSER_ERROR_CONTEXT: VoiceInputErrorContext = { + secureContext: typeof window !== "undefined" && window.isSecureContext, + canOpenSystemSettings: canOpenMicrophoneSystemSettings, +}; + +export function formatVoiceElapsed(seconds: number): string { + const whole = Math.max(0, Math.floor(seconds)); + return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`; +} + +function keepEditorSelection(event: React.PointerEvent) { + event.preventDefault(); +} + +function VoiceLevelBars({ readLevel }: { readLevel: () => number }) { + const barsRef = useRef(null); + useLayoutEffect(() => { + const container = barsRef.current; + if (!container) return; + const bars = Array.from(container.children).filter( + (child): child is HTMLElement => child instanceof HTMLElement, + ); + const history = Array.from({ length: bars.length }).fill(0); + const paint = () => { + bars.forEach((bar, index) => { + bar.style.transform = `scaleY(${Math.max(VOICE_METER_REST_SCALE, history[index] ?? 0)})`; + }); + }; + paint(); + const interval = setInterval(() => { + history.shift(); + history.push(readLevel()); + paint(); + }, VOICE_METER_INTERVAL_MS); + return () => clearInterval(interval); + }, [readLevel]); + return ( +
+ {Array.from({ length: VOICE_METER_BAR_COUNT }, (_, index) => ( + + ))} +
+ ); +} + +function RecordingDot({ muted = false }: { muted?: boolean }) { + return ( + + ); +} + +function VoiceElapsed({ + readStartedAt, + running, +}: { + readStartedAt: () => number | null; + running: boolean; +}) { + const [seconds, setSeconds] = useState(0); + useEffect(() => { + if (!running) return; + const interval = setInterval(() => { + const startedAt = readStartedAt(); + setSeconds(startedAt === null ? 0 : (Date.now() - startedAt) / 1000); + }, 1000); + return () => clearInterval(interval); + }, [running, readStartedAt]); + return ( + + {formatVoiceElapsed(seconds)} + + ); +} + +export interface ComposerVoiceInputControlProps { + readonly state: VoiceInputState; + readonly shortcutLabel: string | null; + readonly readStartedAt: () => number | null; + readonly readLevel: () => number; + /** Starts recording, or stops and transcribes. The same button in the same spot does both. */ + readonly onToggle: () => void; + readonly onCancel: () => void; + readonly errorContext?: VoiceInputErrorContext; + readonly onOpenSettings?: () => void; +} + +export const ComposerVoiceInputControl = memo(function ComposerVoiceInputControl( + props: ComposerVoiceInputControlProps, +) { + const { state, shortcutLabel, readStartedAt, readLevel, onToggle, onCancel } = props; + const errorContext = props.errorContext ?? BROWSER_ERROR_CONTEXT; + const onOpenSettings = props.onOpenSettings ?? openMicrophoneSystemSettings; + const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)"); + const phase = state.phase; + const active = phase === "preparing" || phase === "recording" || phase === "transcribing"; + const error = resolveVoiceInputErrorPresentation(state, errorContext); + const shortcutSuffix = shortcutLabel ? ` (${shortcutLabel})` : ""; + const toggleLabel = + phase === "recording" + ? "Stop and transcribe" + : phase === "transcribing" + ? "Transcribing" + : phase === "preparing" + ? "Starting voice input" + : "Voice input"; + + return ( +
+ {active ? ( + <> + + + } + > + + + Cancel voice input (Esc) + +
+ {phase === "transcribing" ? ( + + ) : phase === "recording" && !prefersReducedMotion ? ( + + ) : ( + + )} +
+ + + ) : error ? ( +
+ + } + > + + {error.message} + + {error.message} + + {error.action === "open-settings" ? ( + + ) : error.action === "retry" ? ( + + ) : null} + +
+ ) : null} + + + } + > + + + {`${toggleLabel}${shortcutSuffix}`} + +
+ ); +}); diff --git a/apps/web/src/components/chat/useComposerVoiceInput.ts b/apps/web/src/components/chat/useComposerVoiceInput.ts new file mode 100644 index 0000000000000..1fdb77b7a7fd7 --- /dev/null +++ b/apps/web/src/components/chat/useComposerVoiceInput.ts @@ -0,0 +1,135 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { + VoiceInputController, + voiceInputBlocksSubmission, + type VoiceDraftSnapshot, + type VoiceInputState, +} from "@t3tools/client-runtime/voice-input"; +import { useEffect, useLayoutEffect, useState } from "react"; + +import { createBrowserVoiceRecorderEnvironment, createWebVoiceRecorder } from "~/lib/voiceRecorder"; +import { createWebVoiceTranscriber } from "~/state/voiceTranscription"; + +const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null }; + +export interface ComposerVoiceInputInput { + readonly environmentId: EnvironmentId; + readonly ownerKey: string; + readonly language: string; + /** The controller treats a draft that changed since recording started as stale. */ + readonly draftText: string; + readonly readDraft: () => Omit; + readonly commitDraft: (text: string, selection: VoiceDraftSnapshot["selection"]) => void; +} + +export interface ComposerVoiceInput { + readonly state: VoiceInputState; + readonly busy: boolean; + readonly readStartedAt: () => number | null; + readonly readLevel: () => number; + /** Starts from idle or an error, stops and transcribes while recording. */ + readonly toggle: () => void; + readonly cancel: () => void; +} + +interface VoiceInputRuntime extends Omit { + readonly setInput: (input: ComposerVoiceInputInput) => void; + readonly setOwner: (ownerKey: string) => void; + readonly noteDraftChanged: (draftText: string) => void; + readonly dispose: () => void; +} + +/** + * Everything the controller reads at event time lives here rather than in React + * state, so the hook re-renders only when the voice input phase changes. + */ +function createRuntime( + initialInput: ComposerVoiceInputInput, + onStateChange: (state: VoiceInputState) => void, +): VoiceInputRuntime { + let latest = initialInput; + let revision = 0; + let ownerKey: string | null = null; + let controller: VoiceInputController | null = null; + const recorder = createWebVoiceRecorder(createBrowserVoiceRecorderEnvironment(), (status) => { + void controller?.handleRecorderStatus(status); + }); + const active = new VoiceInputController({ + recorder: recorder.recorder, + getTranscriber: () => createWebVoiceTranscriber(latest.environmentId, () => latest.language), + requestPermission: recorder.requestPermission, + configureRecording: recorder.configureRecording, + releaseRecording: recorder.releaseRecording, + deleteRecording: recorder.deleteRecording, + readDraft: () => ({ ...latest.readDraft(), revision }), + commitDraft: (text, selection) => latest.commitDraft(text, selection), + onStateChange: (state) => { + onStateChange(state); + // The microphone is on only while voice input is active, whichever path ended it. + if (!voiceInputBlocksSubmission(state)) void recorder.releaseRecording(); + }, + }); + controller = active; + return { + setInput: (input) => { + latest = input; + }, + setOwner: (next) => { + if (ownerKey !== null && ownerKey !== next) active.ownerChanged(); + ownerKey = next; + }, + noteDraftChanged: () => { + revision += 1; + }, + dispose: () => { + active.dispose(); + void recorder.releaseRecording(); + }, + readStartedAt: () => recorder.startedAt, + readLevel: recorder.readLevel, + toggle: () => { + const phase = active.currentState.phase; + if (phase === "recording") void active.stop(); + else if (phase === "idle" || phase === "error") void active.start(); + }, + cancel: () => active.cancel(), + }; +} + +export function useComposerVoiceInput(input: ComposerVoiceInputInput): ComposerVoiceInput { + const [state, setState] = useState(IDLE_STATE); + const [runtime] = useState(() => createRuntime(input, setState)); + const busy = voiceInputBlocksSubmission(state); + + useLayoutEffect(() => { + runtime.setInput(input); + }); + useEffect(() => { + runtime.noteDraftChanged(input.draftText); + }, [runtime, input.draftText]); + useEffect(() => { + runtime.setOwner(input.ownerKey); + }, [runtime, input.ownerKey]); + useEffect(() => () => runtime.dispose(), [runtime]); + + useEffect(() => { + if (!busy) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== "Escape") return; + event.preventDefault(); + event.stopPropagation(); + runtime.cancel(); + }; + window.addEventListener("keydown", onKeyDown, true); + return () => window.removeEventListener("keydown", onKeyDown, true); + }, [busy, runtime]); + + return { + state, + busy, + readStartedAt: runtime.readStartedAt, + readLevel: runtime.readLevel, + toggle: runtime.toggle, + cancel: runtime.cancel, + }; +} diff --git a/apps/web/src/components/chat/voiceInputErrorPresentation.test.ts b/apps/web/src/components/chat/voiceInputErrorPresentation.test.ts new file mode 100644 index 0000000000000..5ca5b27368ba1 --- /dev/null +++ b/apps/web/src/components/chat/voiceInputErrorPresentation.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveVoiceInputErrorPresentation } from "./voiceInputErrorPresentation"; + +const denied = { + phase: "error", + error: "Microphone access is required for voice input.", + errorAction: "settings", +} as const; + +describe("resolveVoiceInputErrorPresentation", () => { + it("routes a blocked microphone to the place that can unblock it", () => { + expect( + resolveVoiceInputErrorPresentation(denied, { + secureContext: true, + canOpenSystemSettings: true, + }), + ).toMatchObject({ action: "open-settings" }); + expect( + resolveVoiceInputErrorPresentation(denied, { + secureContext: true, + canOpenSystemSettings: false, + }), + ).toMatchObject({ action: "retry", message: expect.stringContaining("browser") }); + expect( + resolveVoiceInputErrorPresentation(denied, { + secureContext: false, + canOpenSystemSettings: true, + }), + ).toMatchObject({ action: null, message: expect.stringContaining("HTTPS") }); + }); + + it("shows other failures verbatim with a retry when the controller offers one", () => { + const context = { secureContext: true, canOpenSystemSettings: false }; + expect( + resolveVoiceInputErrorPresentation( + { phase: "error", error: "Groq is down.", errorAction: "retry" }, + context, + ), + ).toEqual({ message: "Groq is down.", action: "retry" }); + expect( + resolveVoiceInputErrorPresentation( + { phase: "error", error: "Voice transcription is not available.", errorAction: null }, + context, + ), + ).toEqual({ message: "Voice transcription is not available.", action: null }); + expect( + resolveVoiceInputErrorPresentation( + { phase: "recording", error: null, errorAction: null }, + context, + ), + ).toBeNull(); + }); +}); diff --git a/apps/web/src/components/chat/voiceInputErrorPresentation.ts b/apps/web/src/components/chat/voiceInputErrorPresentation.ts new file mode 100644 index 0000000000000..3b448d615439d --- /dev/null +++ b/apps/web/src/components/chat/voiceInputErrorPresentation.ts @@ -0,0 +1,38 @@ +import type { VoiceInputState } from "@t3tools/client-runtime/voice-input"; + +export interface VoiceInputErrorContext { + /** getUserMedia exists only on HTTPS and localhost origins. */ + readonly secureContext: boolean; + /** True on macOS desktop builds whose bridge can open the Microphone privacy pane. */ + readonly canOpenSystemSettings: boolean; +} + +export type VoiceInputErrorAction = "retry" | "open-settings"; + +export interface VoiceInputErrorPresentation { + readonly message: string; + readonly action: VoiceInputErrorAction | null; +} + +export function resolveVoiceInputErrorPresentation( + state: VoiceInputState, + context: VoiceInputErrorContext, +): VoiceInputErrorPresentation | null { + if (state.phase !== "error" || state.error === null) return null; + if (state.errorAction === "settings") { + if (!context.secureContext) { + return { message: "Voice input needs an HTTPS or localhost connection.", action: null }; + } + if (context.canOpenSystemSettings) { + return { + message: "Allow the microphone for T3 Code in System Settings, then try again.", + action: "open-settings", + }; + } + return { + message: "Allow the microphone for this site in your browser's settings, then try again.", + action: "retry", + }; + } + return { message: state.error, action: state.errorAction === "retry" ? "retry" : null }; +} diff --git a/apps/web/src/lib/microphoneSettings.ts b/apps/web/src/lib/microphoneSettings.ts new file mode 100644 index 0000000000000..2e1e332c677b6 --- /dev/null +++ b/apps/web/src/lib/microphoneSettings.ts @@ -0,0 +1,22 @@ +import { SystemSettingsPaneSchema } from "@t3tools/contracts"; +import { isMacPlatform } from "@t3tools/shared/keybindings"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { isElectron } from "~/env"; +import { readLocalApi } from "~/localApi"; + +// The desktop bridge accepts only the panes its contract lists. Decoding keeps this +// button off until "microphone" joins SystemSettingsPaneSchema, without a cast. +const microphonePane = Schema.decodeUnknownOption(SystemSettingsPaneSchema)("microphone"); + +export const canOpenMicrophoneSystemSettings = + isElectron && + typeof navigator !== "undefined" && + isMacPlatform(navigator.platform) && + Option.isSome(microphonePane); + +export async function openMicrophoneSystemSettings(): Promise { + if (Option.isNone(microphonePane)) return; + await readLocalApi()?.shell.openSystemSettings(microphonePane.value); +} diff --git a/apps/web/src/lib/voiceRecorder.test.ts b/apps/web/src/lib/voiceRecorder.test.ts index 5bd55f7a02f4d..60be82932bbca 100644 --- a/apps/web/src/lib/voiceRecorder.test.ts +++ b/apps/web/src/lib/voiceRecorder.test.ts @@ -175,7 +175,7 @@ describe("createWebVoiceRecorder", () => { getUserMedia: refusal("SecurityError"), queryMicrophonePermission: async () => null, }); - expect(await insecure.web.requestPermission()).toEqual({ granted: false, canAskAgain: true }); + expect(await insecure.web.requestPermission()).toEqual({ granted: false, canAskAgain: false }); const broken = createHarness({ getUserMedia: async () => { diff --git a/apps/web/src/lib/voiceRecorder.ts b/apps/web/src/lib/voiceRecorder.ts index 63cde1e2000ed..430979358e9ef 100644 --- a/apps/web/src/lib/voiceRecorder.ts +++ b/apps/web/src/lib/voiceRecorder.ts @@ -59,7 +59,7 @@ function stopTracks(stream: MediaStream | null): void { for (const track of stream?.getTracks() ?? []) track.stop(); } -function isPermissionRefusal(error: unknown): boolean { +function isPermissionRefusal(error: unknown): error is DOMException { return ( error instanceof DOMException && (error.name === "NotAllowedError" || error.name === "SecurityError") @@ -167,9 +167,11 @@ export function createWebVoiceRecorder( return { granted: true, canAskAgain: true }; } catch (error) { if (!isPermissionRefusal(error)) throw error; - const state = environment.denialIsPermanent - ? "denied" - : await environment.queryMicrophonePermission(); + // A SecurityError means the origin itself cannot ask, so retrying cannot help. + const state = + environment.denialIsPermanent || error.name === "SecurityError" + ? "denied" + : await environment.queryMicrophonePermission(); return { granted: false, canAskAgain: state !== "denied" }; } }, diff --git a/apps/web/src/lib/voiceWav.browser.test.ts b/apps/web/src/lib/voiceWav.browser.test.ts new file mode 100644 index 0000000000000..509710d829f08 --- /dev/null +++ b/apps/web/src/lib/voiceWav.browser.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { convertRecordingToWav, encodeWavPcm16, VOICE_WAV_SAMPLE_RATE } from "./voiceWav"; + +/** A one-second 440 Hz tone at 48 kHz, as a browser might hand back from a recording. */ +function toneRecording(): Blob { + const sampleRate = 48_000; + const samples = Float32Array.from({ length: sampleRate }, (_, index) => + Math.sin((2 * Math.PI * 440 * index) / sampleRate), + ); + return new Blob([encodeWavPcm16(samples, sampleRate)], { type: "audio/wav" }); +} + +describe("convertRecordingToWav", () => { + it("resamples a recording to 16 kHz mono PCM WAV in Chromium", async () => { + const wav = await convertRecordingToWav(toneRecording()); + const view = new DataView(await wav.arrayBuffer()); + + expect(wav.type).toBe("audio/wav"); + expect(view.getUint32(24, true)).toBe(VOICE_WAV_SAMPLE_RATE); + expect(view.getUint16(22, true)).toBe(1); + const sampleCount = view.getUint32(40, true) / 2; + expect(sampleCount).toBeGreaterThanOrEqual(VOICE_WAV_SAMPLE_RATE - 1); + expect(sampleCount).toBeLessThanOrEqual(VOICE_WAV_SAMPLE_RATE + 1); + + let peak = 0; + for (let index = 0; index < sampleCount; index += 1) { + peak = Math.max(peak, Math.abs(view.getInt16(44 + index * 2, true))); + } + expect(peak).toBeGreaterThan(20_000); + }); +}); diff --git a/apps/web/src/lib/voiceWav.test.ts b/apps/web/src/lib/voiceWav.test.ts new file mode 100644 index 0000000000000..874bbc580530c --- /dev/null +++ b/apps/web/src/lib/voiceWav.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { encodeWavPcm16 } from "./voiceWav"; + +const ascii = (view: DataView, offset: number, length: number) => + String.fromCharCode(...Array.from({ length }, (_, index) => view.getUint8(offset + index))); + +describe("encodeWavPcm16", () => { + it("writes a canonical 16-bit mono PCM header sized to the samples", () => { + const buffer = encodeWavPcm16([0, 1, -1, 0.5], 16_000); + const view = new DataView(buffer); + + expect(buffer.byteLength).toBe(44 + 4 * 2); + expect(ascii(view, 0, 4)).toBe("RIFF"); + expect(view.getUint32(4, true)).toBe(36 + 8); + expect(ascii(view, 8, 4)).toBe("WAVE"); + expect(ascii(view, 12, 4)).toBe("fmt "); + expect(view.getUint32(16, true)).toBe(16); + expect(view.getUint16(20, true)).toBe(1); + expect(view.getUint16(22, true)).toBe(1); + expect(view.getUint32(24, true)).toBe(16_000); + expect(view.getUint32(28, true)).toBe(32_000); + expect(view.getUint16(32, true)).toBe(2); + expect(view.getUint16(34, true)).toBe(16); + expect(ascii(view, 36, 4)).toBe("data"); + expect(view.getUint32(40, true)).toBe(8); + }); + + it("scales and clamps samples to little-endian signed 16-bit", () => { + const view = new DataView(encodeWavPcm16([0, 1, -1, 0.5, 2, -2], 16_000)); + const sample = (index: number) => view.getInt16(44 + index * 2, true); + expect([sample(0), sample(1), sample(2), sample(3), sample(4), sample(5)]).toEqual([ + 0, 32_767, -32_768, 16_383, 32_767, -32_768, + ]); + expect(view.getUint8(44 + 2)).toBe(0xff); + expect(view.getUint8(44 + 3)).toBe(0x7f); + }); +}); diff --git a/apps/web/src/lib/voiceWav.ts b/apps/web/src/lib/voiceWav.ts new file mode 100644 index 0000000000000..bf87c6738109f --- /dev/null +++ b/apps/web/src/lib/voiceWav.ts @@ -0,0 +1,67 @@ +/** Speech models downsample to 16 kHz mono anyway, so the upload carries nothing more. */ +export const VOICE_WAV_SAMPLE_RATE = 16_000; + +const WAV_HEADER_BYTES = 44; + +function writeAscii(view: DataView, offset: number, text: string): void { + for (let index = 0; index < text.length; index += 1) { + view.setUint8(offset + index, text.charCodeAt(index)); + } +} + +/** Canonical 44-byte RIFF header followed by little-endian 16-bit mono PCM. */ +export function encodeWavPcm16(samples: ArrayLike, sampleRate: number): ArrayBuffer { + const dataBytes = samples.length * 2; + const buffer = new ArrayBuffer(WAV_HEADER_BYTES + dataBytes); + const view = new DataView(buffer); + writeAscii(view, 0, "RIFF"); + view.setUint32(4, WAV_HEADER_BYTES - 8 + dataBytes, true); + writeAscii(view, 8, "WAVE"); + writeAscii(view, 12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, 1, true); + view.setUint32(24, sampleRate, true); + view.setUint32(28, sampleRate * 2, true); + view.setUint16(32, 2, true); + view.setUint16(34, 16, true); + writeAscii(view, 36, "data"); + view.setUint32(40, dataBytes, true); + for (let index = 0; index < samples.length; index += 1) { + const clamped = Math.max(-1, Math.min(1, samples[index] ?? 0)); + view.setInt16( + WAV_HEADER_BYTES + index * 2, + clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, + true, + ); + } + return buffer; +} + +/** + * Every provider gets the same 16 kHz mono WAV. xAI rejects WebM, which is the only + * container Chromium's MediaRecorder produces, and a local whisper.cpp server would + * otherwise need ffmpeg to read the browser's upload. + */ +export async function convertRecordingToWav(recording: Blob): Promise { + const encoded = await recording.arrayBuffer(); + const decoder = new OfflineAudioContext({ + numberOfChannels: 1, + length: 1, + sampleRate: VOICE_WAV_SAMPLE_RATE, + }); + const decoded = await decoder.decodeAudioData(encoded); + const resampler = new OfflineAudioContext({ + numberOfChannels: 1, + length: Math.max(1, Math.ceil(decoded.duration * VOICE_WAV_SAMPLE_RATE)), + sampleRate: VOICE_WAV_SAMPLE_RATE, + }); + const source = resampler.createBufferSource(); + source.buffer = decoded; + source.connect(resampler.destination); + source.start(); + const rendered = await resampler.startRendering(); + return new Blob([encodeWavPcm16(rendered.getChannelData(0), VOICE_WAV_SAMPLE_RATE)], { + type: "audio/wav", + }); +} diff --git a/apps/web/src/state/voiceTranscription.ts b/apps/web/src/state/voiceTranscription.ts index b5f7fea0ff373..969eadf1c1527 100644 --- a/apps/web/src/state/voiceTranscription.ts +++ b/apps/web/src/state/voiceTranscription.ts @@ -11,6 +11,7 @@ import { } from "@t3tools/client-runtime/voice-input"; import { connectionAtomRuntime } from "../connection/runtime"; +import { convertRecordingToWav } from "../lib/voiceWav"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { readEnvironmentScope, readPreparedConnection } from "./session"; @@ -44,5 +45,6 @@ export function createWebVoiceTranscriber( return connection ? resolveAssetUrl(connection.httpBaseUrl, relativeUrl) : null; }, fetch: (input, init) => fetch(input, init), + prepareAudio: convertRecordingToWav, }); } diff --git a/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts b/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts index 0494c70fda967..10cd6cedbba09 100644 --- a/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts +++ b/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts @@ -16,6 +16,7 @@ function createHarness(options: { readonly post?: PostResponse | ((init: RequestInit) => Promise); readonly createTranscriptionUrl?: EnvironmentVoiceTranscriberDependencies["createTranscriptionUrl"]; readonly resolveUrl?: EnvironmentVoiceTranscriberDependencies["resolveUrl"]; + readonly prepareAudio?: EnvironmentVoiceTranscriberDependencies["prepareAudio"]; }) { const audio = options.audio ?? new Blob(["audio-bytes"], { type: "audio/webm;codecs=opus" }); const posts: Array<{ url: string; init: RequestInit }> = []; @@ -42,6 +43,7 @@ function createHarness(options: { }), resolveUrl: options.resolveUrl ?? ((relativeUrl) => `https://env.example${relativeUrl}`), fetch: fetch as unknown as typeof globalThis.fetch, + ...(options.prepareAudio ? { prepareAudio: options.prepareAudio } : {}), }); return { transcriber, posts, mintInputs }; } @@ -77,6 +79,26 @@ describe("createEnvironmentVoiceTranscriber", () => { expect(await new Response(post?.init.body as Blob).text()).toBe("audio-bytes"); }); + it("uploads the prepared audio in place of the raw recording", async () => { + const harness = createHarness({ + prepareAudio: async (recording) => + new Blob([`wav:${await recording.text()}`], { type: "audio/wav" }), + }); + await expect(transcribe(harness)).resolves.toBe("hello world"); + expect(harness.mintInputs).toEqual([{ mimeType: "audio/wav", sizeBytes: 15 }]); + expect(harness.posts[0]?.init.headers).toEqual({ "content-type": "audio/wav" }); + expect(await new Response(harness.posts[0]?.init.body as Blob).text()).toBe("wav:audio-bytes"); + + const broken = createHarness({ + prepareAudio: async () => { + throw new Error("decode failed"); + }, + }); + const error = await transcriptionError(transcribe(broken)); + expect(error.code).toBe("transcription-failed"); + expect(broken.mintInputs).toHaveLength(0); + }); + it("uses the configured language as the locale and falls back to the device locale", async () => { const signal = new AbortController().signal; expect((await createHarness({ language: "de" }).transcriber.prepare({ signal })).locale).toBe( diff --git a/packages/client-runtime/src/voice-input/environmentTranscriber.ts b/packages/client-runtime/src/voice-input/environmentTranscriber.ts index 96c6ed9842ba1..aa9e473f74500 100644 --- a/packages/client-runtime/src/voice-input/environmentTranscriber.ts +++ b/packages/client-runtime/src/voice-input/environmentTranscriber.ts @@ -27,6 +27,8 @@ export type EnvironmentVoiceTranscriberDependencies = { /** Null when the environment has no reachable HTTP base, such as while disconnected. */ readonly resolveUrl: (relativeUrl: string) => string | null; readonly fetch: typeof globalThis.fetch; + /** Re-encodes the recording before upload, such as to the WAV every provider accepts. */ + readonly prepareAudio?: (recording: Blob) => Promise; }; const decodeMimeType = Schema.decodeUnknownOption(VoiceTranscriptionAudioMimeType); @@ -93,6 +95,18 @@ export function createEnvironmentVoiceTranscriber( ); } throwIfVoiceTranscriptionAborted(signal); + if (dependencies.prepareAudio && blob.size > 0) { + try { + blob = await dependencies.prepareAudio(blob); + } catch (error) { + throw new VoiceTranscriptionError( + "transcription-failed", + "Could not convert the recording for upload.", + { cause: error }, + ); + } + throwIfVoiceTranscriptionAborted(signal); + } const mimeType = containerMimeType(blob.type); if (!mimeType) { From ebbc00b8c4562c53a73ae69439a180345cc9c07c Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 22:05:27 -0400 Subject: [PATCH 10/55] feat(desktop): microphone privacy pane and usage description for voice input The macOS microphone usage description now covers dictation in the composer. The System Settings opener knows the Microphone privacy pane and checks the microphone media access status instead of Safari's full disk access when it shows the permission helper for that pane. The IPC payload schema in contracts still lists only full-disk-access, so the web client offers the button once that schema includes "microphone". Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/ipc/methods/window.ts | 5 ++++- apps/desktop/src/permissions/MacPermission.ts | 2 ++ scripts/build-desktop-artifact.ts | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 9066cf6f1a67c..235d109330e90 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -311,7 +311,10 @@ export const openSystemSettings = DesktopIpc.makeIpcMethod({ const opened = yield* shell.openSystemSettings(pane); if (opened && environment.isPackaged) { const permissions = yield* MacPermissions.MacPermissions; - const isGranted = yield* safariPermissionCheck; + const isGranted = + pane === "full-disk-access" + ? yield* safariPermissionCheck + : () => Electron.systemPreferences.getMediaAccessStatus("microphone") === "granted"; yield* permissions.showHelper(pane, owner, isGranted); } return opened; diff --git a/apps/desktop/src/permissions/MacPermission.ts b/apps/desktop/src/permissions/MacPermission.ts index e72d796c876ad..7699b4af9ee39 100644 --- a/apps/desktop/src/permissions/MacPermission.ts +++ b/apps/desktop/src/permissions/MacPermission.ts @@ -4,6 +4,7 @@ export const MAC_PERMISSION_SETTINGS_URLS = { accessibility: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility", "full-disk-access": "x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles", + microphone: "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone", }; export type MacPermission = keyof typeof MAC_PERMISSION_SETTINGS_URLS; @@ -12,4 +13,5 @@ export const MAC_PERMISSION_TITLES: Record = { "screen-recording": "Screen Recording", accessibility: "Accessibility", "full-disk-access": "Full Disk Access", + microphone: "Microphone", }; diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index d2cff47263455..2c16afac8b27b 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -2894,7 +2894,7 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* ( NSCameraUsageDescription: "T3 Code lets commands run by terminals and coding agents use the camera.", NSMicrophoneUsageDescription: - "T3 Code lets commands run by terminals and coding agents use the microphone.", + "T3 Code records your voice when you dictate a message in the composer, and lets commands run by terminals and coding agents use the microphone.", // macOS lists an app under Default web browser only when it opens web // pages as documents as well as http and https links (see protocols). CFBundleDocumentTypes: [ From 841413796e2f84a848f643b3902af4434235faad Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 22:12:00 -0400 Subject: [PATCH 11/55] feat(contracts): add the apple-on-device voice transcription provider Splits HttpVoiceTranscriptionProvider out of VoiceTranscriptionProvider so the hosted defaults table stays keyed by HTTP providers only, advertises appleOnDeviceTranscription in the environment capabilities, and lets the desktop bootstrap hand appleSpeechHelperPath to its backend. Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/desktopBootstrap.ts | 1 + packages/contracts/src/environment.ts | 2 ++ packages/contracts/src/settings.ts | 15 +++++++++++++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/contracts/src/desktopBootstrap.ts b/packages/contracts/src/desktopBootstrap.ts index bc0a723b57b02..3cb33530c3392 100644 --- a/packages/contracts/src/desktopBootstrap.ts +++ b/packages/contracts/src/desktopBootstrap.ts @@ -34,6 +34,7 @@ export const DesktopBackendBootstrap = Schema.Struct({ desktopBrowserFd: Schema.optionalKey(PositiveInt), desktopBrowserControlFd: Schema.optionalKey(PositiveInt), resourceMonitorPath: Schema.optionalKey(TrimmedNonEmptyString), + appleSpeechHelperPath: Schema.optionalKey(TrimmedNonEmptyString), }); export type DesktopBackendBootstrap = typeof DesktopBackendBootstrap.Type; diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 4272c9d12d94b..c0cfbf9e92c83 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -95,6 +95,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ databaseStorage: Schema.optionalKey(Schema.Boolean), /** Server checks OTLP endpoints for the telemetry export settings. */ otlpEndpointCheck: Schema.optionalKey(Schema.Boolean), + /** The host is macOS 26 or later with the Apple speech helper, and SpeechAnalyzer is available. */ + appleOnDeviceTranscription: Schema.optionalKey(Schema.Boolean), projectWorktreeCleanup: Schema.optionalKey(Schema.Boolean), settledWorktreeCleanup: Schema.optionalKey(Schema.Boolean), worktreesDirectory: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index a8747947649bb..4b19f3b961b74 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -782,14 +782,25 @@ export type AntigravitySettings = typeof AntigravitySettings.Type; * `openai-compatible` posts to `/audio/transcriptions` (OpenAI, Groq, a whisper.cpp * server); `xai` posts to `/stt`, whose form fields differ. */ -export const VoiceTranscriptionProvider = Schema.Literals(["openai-compatible", "xai"]); +export const HttpVoiceTranscriptionProvider = Schema.Literals(["openai-compatible", "xai"]); +export type HttpVoiceTranscriptionProvider = typeof HttpVoiceTranscriptionProvider.Type; + +/** + * `apple-on-device` runs Apple's SpeechAnalyzer on the environment's own Mac and ignores + * `baseUrl`, `model`, and `apiKey`. Offer it only when the environment advertises + * `capabilities.appleOnDeviceTranscription`. + */ +export const VoiceTranscriptionProvider = Schema.Literals([ + ...HttpVoiceTranscriptionProvider.literals, + "apple-on-device", +]); export type VoiceTranscriptionProvider = typeof VoiceTranscriptionProvider.Type; /** A key is required whenever `baseUrl` is still the provider's hosted default. */ export const VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS = { "openai-compatible": { baseUrl: "https://api.openai.com/v1", model: "gpt-transcribe" }, xai: { baseUrl: "https://api.x.ai/v1", model: "grok-voice-transcribe-2.0" }, -} as const satisfies Record; +} as const satisfies Record; export const VoiceTranscriptionSettings = Schema.Struct({ enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), From 121ad2f530779d39d329b6c085ed6fcc696e7e28 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 22:25:45 -0400 Subject: [PATCH 12/55] fix(web): voice input survives cancelled prompts, unplugged microphones, and stuck mints Stops the microphone stream a permission prompt grants after voice input was already cancelled, and hands over the captured audio when the tracks end on their own instead of recording forever. A cancelled transcription no longer waits on a hung URL mint. Escape leaves open dialogs and the command palette alone, the composer handle sees the current voice state, the draft selection is trusted only against the text it came from, and the palette says when the composer cannot take voice input. Drops comments that restated their code. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/CommandPalette.tsx | 7 ++- apps/web/src/components/chat/ChatComposer.tsx | 25 ++++----- ...ComposerVoiceInputControl.browser.test.tsx | 2 +- .../chat/ComposerVoiceInputControl.tsx | 4 +- .../components/chat/useComposerVoiceInput.ts | 33 +++++++----- .../chat/voiceInputErrorPresentation.ts | 2 - apps/web/src/lib/microphoneSettings.ts | 5 +- apps/web/src/lib/voiceRecorder.test.ts | 52 ++++++++++++++++--- apps/web/src/lib/voiceRecorder.ts | 48 +++++++++-------- apps/web/src/lib/voiceWav.browser.test.ts | 1 - apps/web/src/lib/voiceWav.ts | 35 ++++++------- .../src/voice-input/controller.ts | 2 - .../environmentTranscriber.test.ts | 18 +++++++ .../src/voice-input/environmentTranscriber.ts | 33 +++++++++--- .../src/voice-input/transcription.ts | 1 + 15 files changed, 175 insertions(+), 93 deletions(-) diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 508fed9176650..d2a230f47d482 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -711,7 +711,12 @@ function CommandPaletteDialog(props: { } function toggleComposerDictation(composerHandleRef: ComposerHandleRef | null): void { - composerHandleRef?.current?.toggleDictation(); + if (composerHandleRef?.current?.toggleDictation() === true) return; + toastManager.add({ + type: "warning", + title: "Voice input is not available right now", + description: "The composer is not accepting text at the moment.", + }); } function OpenCommandPaletteDialog(props: { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 95ed31d16afbf..651dcfc12fbe6 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1460,7 +1460,6 @@ export interface ChatComposerHandle { isModelPickerOpen: () => boolean; isCaretAtStart: () => boolean; compactContext: () => void; - /** Starts dictation, or stops and transcribes. False when voice input is not offered here. */ toggleDictation: () => boolean; readSnapshot: () => { value: string; @@ -2085,18 +2084,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerEditorRef = useRef(null); const readVoiceDraftStable = useStableCallback(() => { const text = promptRef.current; - return { - ownerKey: composerDraftTargetKey, - text, - selection: composerEditorRef.current?.readSelectionRange() ?? { - start: text.length, - end: text.length, - }, - }; + const editor = composerEditorRef.current; + // The editor's selection only indexes the text it was read from. + const selection = + editor && editor.readSnapshot().value === text + ? editor.readSelectionRange() + : { start: text.length, end: text.length }; + return { ownerKey: composerDraftTargetKey, text, selection }; }); - // Voice input must be known before sendDisabledReason, but the commit goes through - // applyPromptReplacement, which is declared further down. The effect below the - // declaration fills this in, since a closure may not capture it earlier. + // sendDisabledReason needs voice input before applyPromptReplacement is declared, and + // the React Compiler rejects a closure that captures a const declared later. The + // layout effect below that declaration fills this in. const voiceCommitRef = useRef< ((text: string, selection: { readonly start: number; readonly end: number }) => void) | null >(null); @@ -6449,6 +6447,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) getTimelineScrollableNode, isTimelineAtLogicalEnd, setIsComposerScrollCollapsed, + showComposerVoiceAction, + voiceInput.busy, + voiceInput.toggle, ], ); diff --git a/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx b/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx index b2d81631b002a..85437e4cd5426 100644 --- a/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx @@ -15,7 +15,7 @@ function control( overrides: Partial> = {}, ) { return ( -
+
number | null; readonly readLevel: () => number; - /** Starts recording, or stops and transcribes. The same button in the same spot does both. */ readonly onToggle: () => void; readonly onCancel: () => void; readonly errorContext?: VoiceInputErrorContext; diff --git a/apps/web/src/components/chat/useComposerVoiceInput.ts b/apps/web/src/components/chat/useComposerVoiceInput.ts index 1fdb77b7a7fd7..6ad3af473f77f 100644 --- a/apps/web/src/components/chat/useComposerVoiceInput.ts +++ b/apps/web/src/components/chat/useComposerVoiceInput.ts @@ -7,6 +7,7 @@ import { } from "@t3tools/client-runtime/voice-input"; import { useEffect, useLayoutEffect, useState } from "react"; +import { isCommandPaletteOpen } from "~/commandPaletteBus"; import { createBrowserVoiceRecorderEnvironment, createWebVoiceRecorder } from "~/lib/voiceRecorder"; import { createWebVoiceTranscriber } from "~/state/voiceTranscription"; @@ -16,7 +17,6 @@ export interface ComposerVoiceInputInput { readonly environmentId: EnvironmentId; readonly ownerKey: string; readonly language: string; - /** The controller treats a draft that changed since recording started as stale. */ readonly draftText: string; readonly readDraft: () => Omit; readonly commitDraft: (text: string, selection: VoiceDraftSnapshot["selection"]) => void; @@ -27,7 +27,6 @@ export interface ComposerVoiceInput { readonly busy: boolean; readonly readStartedAt: () => number | null; readonly readLevel: () => number; - /** Starts from idle or an error, stops and transcribes while recording. */ readonly toggle: () => void; readonly cancel: () => void; } @@ -35,19 +34,16 @@ export interface ComposerVoiceInput { interface VoiceInputRuntime extends Omit { readonly setInput: (input: ComposerVoiceInputInput) => void; readonly setOwner: (ownerKey: string) => void; - readonly noteDraftChanged: (draftText: string) => void; + readonly setDraftText: (draftText: string) => void; readonly dispose: () => void; } -/** - * Everything the controller reads at event time lives here rather than in React - * state, so the hook re-renders only when the voice input phase changes. - */ function createRuntime( initialInput: ComposerVoiceInputInput, onStateChange: (state: VoiceInputState) => void, ): VoiceInputRuntime { let latest = initialInput; + let draftText = initialInput.draftText; let revision = 0; let ownerKey: string | null = null; let controller: VoiceInputController | null = null; @@ -65,7 +61,6 @@ function createRuntime( commitDraft: (text, selection) => latest.commitDraft(text, selection), onStateChange: (state) => { onStateChange(state); - // The microphone is on only while voice input is active, whichever path ended it. if (!voiceInputBlocksSubmission(state)) void recorder.releaseRecording(); }, }); @@ -78,7 +73,9 @@ function createRuntime( if (ownerKey !== null && ownerKey !== next) active.ownerChanged(); ownerKey = next; }, - noteDraftChanged: () => { + setDraftText: (next) => { + if (next === draftText) return; + draftText = next; revision += 1; }, dispose: () => { @@ -105,7 +102,7 @@ export function useComposerVoiceInput(input: ComposerVoiceInputInput): ComposerV runtime.setInput(input); }); useEffect(() => { - runtime.noteDraftChanged(input.draftText); + runtime.setDraftText(input.draftText); }, [runtime, input.draftText]); useEffect(() => { runtime.setOwner(input.ownerKey); @@ -115,13 +112,21 @@ export function useComposerVoiceInput(input: ComposerVoiceInputInput): ComposerV useEffect(() => { if (!busy) return; const onKeyDown = (event: KeyboardEvent) => { - if (event.key !== "Escape") return; + if (event.key !== "Escape" || event.defaultPrevented || isCommandPaletteOpen()) return; + // A dialog or menu that is open owns its own Escape. + if ( + event.target instanceof Element && + event.target.closest( + '[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]', + ) + ) { + return; + } event.preventDefault(); - event.stopPropagation(); runtime.cancel(); }; - window.addEventListener("keydown", onKeyDown, true); - return () => window.removeEventListener("keydown", onKeyDown, true); + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); }, [busy, runtime]); return { diff --git a/apps/web/src/components/chat/voiceInputErrorPresentation.ts b/apps/web/src/components/chat/voiceInputErrorPresentation.ts index 3b448d615439d..75ad448740208 100644 --- a/apps/web/src/components/chat/voiceInputErrorPresentation.ts +++ b/apps/web/src/components/chat/voiceInputErrorPresentation.ts @@ -1,9 +1,7 @@ import type { VoiceInputState } from "@t3tools/client-runtime/voice-input"; export interface VoiceInputErrorContext { - /** getUserMedia exists only on HTTPS and localhost origins. */ readonly secureContext: boolean; - /** True on macOS desktop builds whose bridge can open the Microphone privacy pane. */ readonly canOpenSystemSettings: boolean; } diff --git a/apps/web/src/lib/microphoneSettings.ts b/apps/web/src/lib/microphoneSettings.ts index 2e1e332c677b6..8f3183dab5211 100644 --- a/apps/web/src/lib/microphoneSettings.ts +++ b/apps/web/src/lib/microphoneSettings.ts @@ -1,13 +1,12 @@ import { SystemSettingsPaneSchema } from "@t3tools/contracts"; -import { isMacPlatform } from "@t3tools/shared/keybindings"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { isElectron } from "~/env"; +import { isMacPlatform } from "~/lib/utils"; import { readLocalApi } from "~/localApi"; -// The desktop bridge accepts only the panes its contract lists. Decoding keeps this -// button off until "microphone" joins SystemSettingsPaneSchema, without a cast. +// None until SystemSettingsPaneSchema lists "microphone"; the desktop side already handles it. const microphonePane = Schema.decodeUnknownOption(SystemSettingsPaneSchema)("microphone"); export const canOpenMicrophoneSystemSettings = diff --git a/apps/web/src/lib/voiceRecorder.test.ts b/apps/web/src/lib/voiceRecorder.test.ts index 60be82932bbca..d9dc1c04f7d5f 100644 --- a/apps/web/src/lib/voiceRecorder.test.ts +++ b/apps/web/src/lib/voiceRecorder.test.ts @@ -27,10 +27,17 @@ class FakeMediaRecorder implements MediaRecorderLike { } start(): void { + if (this.state !== "inactive") throw new DOMException("already recording", "InvalidStateError"); this.state = "recording"; } stop(): void { + if (this.state === "inactive") throw new DOMException("not recording", "InvalidStateError"); + this.endRecording(); + } + + /** What the browser does when every track of the stream ends. */ + endRecording(): void { this.state = "inactive"; for (const listener of this.listeners.get("dataavailable") ?? []) { listener({ data: this.chunk } as never); @@ -74,11 +81,11 @@ function createHarness(overrides: Partial = {}) { return { web, environment, tracks, recorders, statuses, created, revoked }; } -async function startRecording(harness: ReturnType) { +async function startRecording(harness: ReturnType, forDuration = 300) { expect(await harness.web.requestPermission()).toEqual({ granted: true, canAskAgain: true }); await harness.web.configureRecording(); await harness.web.recorder.prepareToRecordAsync(); - harness.web.recorder.record({ forDuration: 300 }); + harness.web.recorder.record({ forDuration }); } function refusal(name: "NotAllowedError" | "SecurityError") { @@ -87,6 +94,13 @@ function refusal(name: "NotAllowedError" | "SecurityError") { }; } +const finished = (url: string): VoiceRecorderStatus => ({ + isFinished: true, + hasError: false, + error: null, + url, +}); + describe("createWebVoiceRecorder", () => { afterEach(() => { vi.useRealTimers(); @@ -104,6 +118,7 @@ describe("createWebVoiceRecorder", () => { expect(harness.created[0]?.type).toBe("audio/webm;codecs=opus"); expect(await harness.created[0]?.text()).toBe("pcm"); expect(harness.web.startedAt).toBeNull(); + expect(harness.statuses).toEqual([]); await harness.web.releaseRecording(); for (const track of harness.tracks) expect(track.stop).toHaveBeenCalledTimes(1); @@ -125,15 +140,24 @@ describe("createWebVoiceRecorder", () => { it("stops itself at the duration limit and reports the finished recording", async () => { const harness = createHarness(); - await startRecording(harness); + await harness.web.requestPermission(); + await harness.web.configureRecording(); + await harness.web.recorder.prepareToRecordAsync(); vi.useFakeTimers(); harness.web.recorder.record({ forDuration: 2 }); await vi.advanceTimersByTimeAsync(1_999); expect(harness.statuses).toEqual([]); await vi.advanceTimersByTimeAsync(1); - expect(harness.statuses).toEqual([ - { isFinished: true, hasError: false, error: null, url: "blob:recording-1" }, - ]); + expect(harness.statuses).toEqual([finished("blob:recording-1")]); + }); + + it("hands over what it captured when the microphone ends on its own", async () => { + const harness = createHarness(); + await startRecording(harness); + harness.recorders[0]!.endRecording(); + expect(harness.statuses).toEqual([finished("blob:recording-1")]); + await harness.web.recorder.stop(); + expect(harness.statuses).toHaveLength(1); }); it("resolves stop without a recording when nothing started", async () => { @@ -155,6 +179,22 @@ describe("createWebVoiceRecorder", () => { for (const track of harness.tracks) expect(track.stop).toHaveBeenCalledTimes(1); }); + it("stops a stream the prompt grants after voice input was already released", async () => { + const { stream, tracks } = createFakeStream(); + let grant!: (stream: MediaStream) => void; + const harness = createHarness({ + getUserMedia: () => + new Promise((resolve) => { + grant = resolve; + }), + }); + const permission = harness.web.requestPermission(); + await harness.web.releaseRecording(); + grant(stream); + expect(await permission).toEqual({ granted: true, canAskAgain: true }); + for (const track of tracks) expect(track.stop).toHaveBeenCalledTimes(1); + }); + it("tells a blocked microphone apart from a dismissed prompt", async () => { const dismissed = createHarness({ getUserMedia: refusal("NotAllowedError") }); expect(await dismissed.web.requestPermission()).toEqual({ granted: false, canAskAgain: true }); diff --git a/apps/web/src/lib/voiceRecorder.ts b/apps/web/src/lib/voiceRecorder.ts index 430979358e9ef..a393d5460e57e 100644 --- a/apps/web/src/lib/voiceRecorder.ts +++ b/apps/web/src/lib/voiceRecorder.ts @@ -7,7 +7,6 @@ import { import { isElectron } from "~/env"; -/** Containers the environment accepts, best first. Safari records only mp4. */ const PREFERRED_AUDIO_MIME_TYPES = [ "audio/webm;codecs=opus", "audio/webm", @@ -17,7 +16,6 @@ const PREFERRED_AUDIO_MIME_TYPES = [ ] as const; export interface VoiceLevelMeter { - /** Current microphone level from 0 (silence) to 1 (full scale). */ readLevel(): number; close(): void; } @@ -29,7 +27,6 @@ export type MediaRecorderLike = Pick< export interface VoiceRecorderEnvironment { readonly getUserMedia: (constraints: MediaStreamConstraints) => Promise; - /** Null when the Permissions API cannot answer for the microphone. */ readonly queryMicrophonePermission: () => Promise; readonly isTypeSupported: (mimeType: string) => boolean; readonly createMediaRecorder: ( @@ -39,17 +36,14 @@ export interface VoiceRecorderEnvironment { readonly createLevelMeter: (stream: MediaStream) => VoiceLevelMeter | null; readonly createObjectURL: (blob: Blob) => string; readonly revokeObjectURL: (url: string) => void; - /** True where the page cannot prompt again, so a refusal needs a settings change. */ readonly denialIsPermanent: boolean; } export interface WebVoiceRecorder { readonly recorder: VoiceRecorder; - /** Epoch milliseconds when the current recording started, null otherwise. */ readonly startedAt: number | null; requestPermission(): Promise<{ readonly granted: boolean; readonly canAskAgain: boolean }>; configureRecording(): Promise; - /** Stops every microphone track. Safe to call at any time. */ releaseRecording(): Promise; deleteRecording(uri: string): void; readLevel(): number; @@ -70,18 +64,18 @@ export function createWebVoiceRecorder( environment: VoiceRecorderEnvironment, onStatus: (status: VoiceRecorderStatus) => void, ): WebVoiceRecorder { - // Acquired by requestPermission, because a browser only prompts through - // getUserMedia, and adopted by configureRecording. - let pendingStream: MediaStream | null = null; + let promptedStream: MediaStream | null = null; let stream: MediaStream | null = null; let meter: VoiceLevelMeter | null = null; let mediaRecorder: MediaRecorderLike | null = null; let started = false; + let stopRequested = false; let stopped: Promise | null = null; let chunks: Blob[] = []; let recordingUri: string | null = null; let limitTimer: ReturnType | null = null; let startedAt: number | null = null; + let releases = 0; const clearLimitTimer = () => { if (limitTimer !== null) clearTimeout(limitTimer); @@ -111,6 +105,11 @@ export function createWebVoiceRecorder( clearLimitTimer(); startedAt = null; resolve(); + // A stop nobody asked for means the tracks ended, such as a device + // unplugged, so hand over what was captured instead of recording forever. + if (!stopRequested) { + onStatus({ isFinished: true, hasError: false, error: null, url: recordingUri }); + } }); next.addEventListener("error", () => { onStatus({ @@ -122,10 +121,12 @@ export function createWebVoiceRecorder( }); mediaRecorder = next; started = false; + stopRequested = false; stopped = promise; }, record: ({ forDuration }) => { if (!mediaRecorder) throw new Error("The recorder is not prepared."); + clearLimitTimer(); mediaRecorder.start(); started = true; startedAt = Date.now(); @@ -144,6 +145,7 @@ export function createWebVoiceRecorder( // A recorder that never started fires no stop event, and one whose // tracks ended already fired it. if (started) { + stopRequested = true; if (current.state !== "inactive") current.stop(); await stopped; } @@ -160,10 +162,15 @@ export function createWebVoiceRecorder( return startedAt; }, requestPermission: async () => { - stopTracks(pendingStream); - pendingStream = null; + stopTracks(promptedStream); + promptedStream = null; + const releasesBefore = releases; try { - pendingStream = await environment.getUserMedia({ audio: true }); + const granted = await environment.getUserMedia({ audio: true }); + // A cancel while the prompt was open already released, so this stream + // has no owner left to stop it later. + if (releases !== releasesBefore) stopTracks(granted); + else promptedStream = granted; return { granted: true, canAskAgain: true }; } catch (error) { if (!isPermissionRefusal(error)) throw error; @@ -176,18 +183,19 @@ export function createWebVoiceRecorder( } }, configureRecording: async () => { - stream = pendingStream ?? (await environment.getUserMedia({ audio: true })); - pendingStream = null; + stream = promptedStream ?? (await environment.getUserMedia({ audio: true })); + promptedStream = null; meter = environment.createLevelMeter(stream); }, releaseRecording: async () => { + releases += 1; clearLimitTimer(); meter?.close(); meter = null; stopTracks(stream); stream = null; - stopTracks(pendingStream); - pendingStream = null; + stopTracks(promptedStream); + promptedStream = null; startedAt = null; }, deleteRecording: (uri) => { @@ -222,16 +230,12 @@ export function createBrowserVoiceRecorderEnvironment(): VoiceRecorderEnvironmen getUserMedia: (constraints) => navigator.mediaDevices?.getUserMedia ? navigator.mediaDevices.getUserMedia(constraints) - : // Plain-http origins other than localhost have no mediaDevices at all. - Promise.reject( + : Promise.reject( new DOMException("Microphone access needs a secure context.", "SecurityError"), ), queryMicrophonePermission: async () => { try { - // lib.dom's PermissionName omits "microphone" although every engine answers it. - const status = await navigator.permissions.query({ - name: "microphone" as PermissionName, - }); + const status = await navigator.permissions.query({ name: "microphone" }); return status.state; } catch { return null; diff --git a/apps/web/src/lib/voiceWav.browser.test.ts b/apps/web/src/lib/voiceWav.browser.test.ts index 509710d829f08..8363243afea15 100644 --- a/apps/web/src/lib/voiceWav.browser.test.ts +++ b/apps/web/src/lib/voiceWav.browser.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from "vite-plus/test"; import { convertRecordingToWav, encodeWavPcm16, VOICE_WAV_SAMPLE_RATE } from "./voiceWav"; -/** A one-second 440 Hz tone at 48 kHz, as a browser might hand back from a recording. */ function toneRecording(): Blob { const sampleRate = 48_000; const samples = Float32Array.from({ length: sampleRate }, (_, index) => diff --git a/apps/web/src/lib/voiceWav.ts b/apps/web/src/lib/voiceWav.ts index bf87c6738109f..3328fbea26ca0 100644 --- a/apps/web/src/lib/voiceWav.ts +++ b/apps/web/src/lib/voiceWav.ts @@ -1,4 +1,3 @@ -/** Speech models downsample to 16 kHz mono anyway, so the upload carries nothing more. */ export const VOICE_WAV_SAMPLE_RATE = 16_000; const WAV_HEADER_BYTES = 44; @@ -9,7 +8,6 @@ function writeAscii(view: DataView, offset: number, text: string): void { } } -/** Canonical 44-byte RIFF header followed by little-endian 16-bit mono PCM. */ export function encodeWavPcm16(samples: ArrayLike, sampleRate: number): ArrayBuffer { const dataBytes = samples.length * 2; const buffer = new ArrayBuffer(WAV_HEADER_BYTES + dataBytes); @@ -38,30 +36,31 @@ export function encodeWavPcm16(samples: ArrayLike, sampleRate: number): return buffer; } +export function downmixToMono(audio: AudioBuffer): Float32Array { + const mono = new Float32Array(audio.length); + for (let channel = 0; channel < audio.numberOfChannels; channel += 1) { + const samples = audio.getChannelData(channel); + for (let index = 0; index < samples.length; index += 1) { + mono[index] = (mono[index] ?? 0) + (samples[index] ?? 0) / audio.numberOfChannels; + } + } + return mono; +} + /** - * Every provider gets the same 16 kHz mono WAV. xAI rejects WebM, which is the only - * container Chromium's MediaRecorder produces, and a local whisper.cpp server would - * otherwise need ffmpeg to read the browser's upload. + * Every provider gets the same 16 kHz mono WAV. xAI rejects WebM, Chromium's default + * MediaRecorder container, and a local whisper.cpp server would otherwise need ffmpeg + * to read the browser's upload. decodeAudioData resamples to its context's rate, so a + * 16 kHz offline context does the conversion itself. */ export async function convertRecordingToWav(recording: Blob): Promise { - const encoded = await recording.arrayBuffer(); const decoder = new OfflineAudioContext({ numberOfChannels: 1, length: 1, sampleRate: VOICE_WAV_SAMPLE_RATE, }); - const decoded = await decoder.decodeAudioData(encoded); - const resampler = new OfflineAudioContext({ - numberOfChannels: 1, - length: Math.max(1, Math.ceil(decoded.duration * VOICE_WAV_SAMPLE_RATE)), - sampleRate: VOICE_WAV_SAMPLE_RATE, - }); - const source = resampler.createBufferSource(); - source.buffer = decoded; - source.connect(resampler.destination); - source.start(); - const rendered = await resampler.startRendering(); - return new Blob([encodeWavPcm16(rendered.getChannelData(0), VOICE_WAV_SAMPLE_RATE)], { + const decoded = await decoder.decodeAudioData(await recording.arrayBuffer()); + return new Blob([encodeWavPcm16(downmixToMono(decoded), VOICE_WAV_SAMPLE_RATE)], { type: "audio/wav", }); } diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index 30d7c14d129de..7e7e6f33d477f 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -182,8 +182,6 @@ function transcriptionErrorMessage(error: unknown): string { if (error instanceof Error && error.message === "voice-operation-busy") { return "Voice transcription is still finishing. Try again shortly."; } - // Transcribers phrase their failures for the user, such as the environment's own - // reason for rejecting an upload. Anything else is an unexpected defect. if (error instanceof VoiceTranscriptionError) return error.message; return "Could not transcribe this recording."; } diff --git a/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts b/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts index 10cd6cedbba09..4e316a1e9fab2 100644 --- a/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts +++ b/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts @@ -183,6 +183,24 @@ describe("createEnvironmentVoiceTranscriber", () => { expect(uploadSettled).toBe(true); }); + it("settles as cancelled while a URL mint is still pending", async () => { + const controller = new AbortController(); + let mintSettled = false; + const harness = createHarness({ + createTranscriptionUrl: () => + new Promise(() => { + mintSettled = false; + }), + }); + const pending = transcribe(harness, controller.signal); + await Promise.resolve(); + controller.abort(); + const cancelled = await transcriptionError(pending); + expect(cancelled.code).toBe("cancelled"); + expect(mintSettled).toBe(false); + expect(harness.posts).toHaveLength(0); + }); + it.each([ ["an unsupported container", new Blob(["x"], { type: "audio/flac" })], ["an empty recording", new Blob([], { type: "audio/mp4" })], diff --git a/packages/client-runtime/src/voice-input/environmentTranscriber.ts b/packages/client-runtime/src/voice-input/environmentTranscriber.ts index aa9e473f74500..a37dcfd0094c7 100644 --- a/packages/client-runtime/src/voice-input/environmentTranscriber.ts +++ b/packages/client-runtime/src/voice-input/environmentTranscriber.ts @@ -27,7 +27,6 @@ export type EnvironmentVoiceTranscriberDependencies = { /** Null when the environment has no reachable HTTP base, such as while disconnected. */ readonly resolveUrl: (relativeUrl: string) => string | null; readonly fetch: typeof globalThis.fetch; - /** Re-encodes the recording before upload, such as to the WAV every provider accepts. */ readonly prepareAudio?: (recording: Blob) => Promise; }; @@ -52,6 +51,24 @@ function isAbortError(error: unknown): boolean { return error instanceof Error && error.name === "AbortError"; } +function cancelledError(): VoiceTranscriptionError { + return new VoiceTranscriptionError("cancelled", "Voice transcription was cancelled."); +} + +/** + * Settles as cancelled on abort even though the work continues. Minting a URL and + * decoding audio hold no resource the controller owns, so a stuck RPC must not + * block the next recording. + */ +function abortable(work: Promise, signal: AbortSignal): Promise { + if (signal.aborted) return Promise.reject(cancelledError()); + return new Promise((resolve, reject) => { + const onAbort = () => reject(cancelledError()); + signal.addEventListener("abort", onAbort, { once: true }); + work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)); + }); +} + async function readJson(response: Response): Promise { try { return await response.json(); @@ -74,11 +91,6 @@ function failureFromResponse(status: number, body: unknown): VoiceTranscriptionE ); } -/** - * Uploads the recording to the environment, which forwards it to the configured - * speech-to-text API. The API key never leaves the environment, so the client only - * needs the capability URL the environment mints per recording. - */ export function createEnvironmentVoiceTranscriber( dependencies: EnvironmentVoiceTranscriberDependencies, ): VoiceTranscriber { @@ -97,8 +109,9 @@ export function createEnvironmentVoiceTranscriber( throwIfVoiceTranscriptionAborted(signal); if (dependencies.prepareAudio && blob.size > 0) { try { - blob = await dependencies.prepareAudio(blob); + blob = await abortable(dependencies.prepareAudio(blob), signal); } catch (error) { + if (error instanceof VoiceTranscriptionError) throw error; throw new VoiceTranscriptionError( "transcription-failed", "Could not convert the recording for upload.", @@ -127,8 +140,12 @@ export function createEnvironmentVoiceTranscriber( let minted: VoiceTranscriptionCreateUrlResult; try { - minted = await dependencies.createTranscriptionUrl({ mimeType, sizeBytes: blob.size }); + minted = await abortable( + dependencies.createTranscriptionUrl({ mimeType, sizeBytes: blob.size }), + signal, + ); } catch (error) { + if (error instanceof VoiceTranscriptionError) throw error; if (isNotConfiguredError(error)) { throw new VoiceTranscriptionError( "unavailable", diff --git a/packages/client-runtime/src/voice-input/transcription.ts b/packages/client-runtime/src/voice-input/transcription.ts index 9e927f7caa5b6..2103d2a9d145f 100644 --- a/packages/client-runtime/src/voice-input/transcription.ts +++ b/packages/client-runtime/src/voice-input/transcription.ts @@ -19,6 +19,7 @@ export type VoiceTranscriptionErrorCode = | "transcription-failed" | "cancelled"; +/** `message` is shown to the user as written, so phrase it for them. */ export class VoiceTranscriptionError extends Error { readonly code: VoiceTranscriptionErrorCode; From 542791addd2282b55acefd5a215920b22be7e9b7 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 22:25:45 -0400 Subject: [PATCH 13/55] feat(web): voice input settings Adds a Voice input section to Settings > General for the environment-scoped server settings: an enable switch, a provider select, model presets that set provider, base URL, and model together, editable endpoint fields, a language field, and an API key that shows its saved state and can be cleared. Free options come first: Apple on-device when the environment's Mac advertises it, then a local whisper.cpp server. A saved Apple provider on a machine without the capability stays selected but disabled with a note. Moving the endpoint to another host drops the saved key so it never reaches a different vendor. Co-Authored-By: Claude Opus 5.5 --- .../components/settings/SettingsPanels.tsx | 3 + .../settings/VoiceInputSettings.tsx | 227 ++++++++++++++++++ .../src/components/settings/settingsSearch.ts | 30 +++ .../settings/voiceInputSettings.logic.test.ts | 101 ++++++++ .../settings/voiceInputSettings.logic.ts | 153 ++++++++++++ 5 files changed, 514 insertions(+) create mode 100644 apps/web/src/components/settings/VoiceInputSettings.tsx create mode 100644 apps/web/src/components/settings/voiceInputSettings.logic.test.ts create mode 100644 apps/web/src/components/settings/voiceInputSettings.logic.ts diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 16c6ff3fb8925..26ad91bfe9b90 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -57,6 +57,7 @@ import * as Schema from "effect/Schema"; import { APP_VERSION, HOSTED_APP_CHANNEL, HOSTED_APP_CHANNEL_LABEL } from "../../branding"; import { CliCommandSettingsRow } from "./CliCommandSettingsRow"; import { MobileAppSettingsRow } from "./MobileAppSettingsRow"; +import { VoiceInputSettings } from "./VoiceInputSettings"; import { canCheckForUpdate, getDesktopUpdateButtonTooltip, @@ -3285,6 +3286,8 @@ export function GeneralSettingsPanel() { /> + + {isElectron || HOSTED_APP_CHANNEL ? ( diff --git a/apps/web/src/components/settings/VoiceInputSettings.tsx b/apps/web/src/components/settings/VoiceInputSettings.tsx new file mode 100644 index 0000000000000..3974472e07501 --- /dev/null +++ b/apps/web/src/components/settings/VoiceInputSettings.tsx @@ -0,0 +1,227 @@ +import type { ServerSettingsPatch, VoiceTranscriptionProvider } from "@t3tools/contracts"; +import { XIcon } from "lucide-react"; + +import { Button } from "../ui/button"; +import { DraftInput } from "../ui/draft-input"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { ScopedSwitch } from "./ScopedSwitch"; +import { SecretInput } from "./SecretInput"; +import { SettingsRow, SettingsSection } from "./settingsLayout"; +import { searchableSetting } from "./settingsSearch"; +import { useSettingsScope } from "./SettingsScopeContext"; +import { + useScopedSettings, + useScopedSettingsMixed, + useUpdateScopedSettings, +} from "./useScopedSettings"; +import { + availableVoiceInputPresets, + resolveVoiceInputPreset, + VOICE_INPUT_PROVIDER_LABELS, + voiceInputPresetPatch, + voiceInputProviderPatch, + type VoiceInputPresetId, +} from "./voiceInputSettings.logic"; + +type VoiceTranscriptionPatch = NonNullable; + +const SETTING_KEYS = ["voiceTranscription"] as const; +const CONTROL_CLASSNAME = "w-full max-w-full @min-[32rem]/settings-row:w-72"; + +const APPLE_NOTE = + "Apple on-device transcribes on the Mac running T3 Code. The first use of a new language downloads Apple's language model."; +const APPLE_UNAVAILABLE_NOTE = "Needs macOS 26 or later on the machine running T3 Code."; + +export function VoiceInputSettings() { + const settings = useScopedSettings((unified) => unified.voiceTranscription); + const updateSettings = useUpdateScopedSettings(); + const mixed = useScopedSettingsMixed(SETTING_KEYS); + const { connectedEnvironments } = useSettingsScope(); + const hasServerTargets = connectedEnvironments.length > 0; + const appleOnDeviceAvailable = + hasServerTargets && + connectedEnvironments.every( + (target) => target.serverConfig?.environment.capabilities.appleOnDeviceTranscription === true, + ); + const update = (patch: VoiceTranscriptionPatch) => updateSettings({ voiceTranscription: patch }); + + const appleSelected = settings.provider === "apple-on-device"; + const appleBlocked = appleSelected && !appleOnDeviceAvailable; + const providers: ReadonlyArray = [ + ...(appleOnDeviceAvailable || appleSelected ? (["apple-on-device"] as const) : []), + "openai-compatible", + "xai", + ]; + const presets = availableVoiceInputPresets(appleOnDeviceAvailable); + const presetId = resolveVoiceInputPreset(settings); + const presetLabel = presets.find((preset) => preset.id === presetId)?.label ?? "Custom"; + const keyConfigured = settings.apiKey.length > 0; + + return ( + + update({ enabled: Boolean(checked) })} + aria-label="Enable voice input" + /> + ) : ( + + Connect an environment to set up voice input. + + ) + } + /> + {hasServerTargets ? ( + <> + { + if (value !== null && value !== settings.provider) { + update(voiceInputProviderPatch(value as VoiceTranscriptionProvider, settings)); + } + }} + > + + + {mixed ? "Mixed" : VOICE_INPUT_PROVIDER_LABELS[settings.provider]} + + + + {providers.map((provider) => ( + + {VOICE_INPUT_PROVIDER_LABELS[provider]} + + ))} + + + } + /> + {appleSelected ? null : ( + + + update({ baseUrl: next })} + spellCheck={false} + /> + update({ model: next })} + spellCheck={false} + /> +
+ } + /> + )} + update({ language: next })} + spellCheck={false} + /> + } + /> + {appleSelected ? null : ( + + update({ apiKey: next })} + /> + {keyConfigured ? ( + + ) : null} +
+ } + /> + )} + + ) : null} + + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 38737b2627b06..4244b1f5bc7d9 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -524,6 +524,36 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "project-defaults", searchTerms: ["generated thread titles source control content default provider"], }, + { + id: "voice-input-enabled", + title: "Voice input", + to: "/settings/general", + searchTerms: ["dictation microphone speech to text transcribe whisper record"], + }, + { + id: "voice-input-provider", + title: "Voice input provider", + to: "/settings/general", + searchTerms: ["speech to text model openai groq xai grok whisper.cpp apple on-device"], + }, + { + id: "voice-input-model", + title: "Voice input model", + to: "/settings/general", + searchTerms: ["speech to text preset base url endpoint gpt-transcribe whisper groq"], + }, + { + id: "voice-input-language", + title: "Voice input language", + to: "/settings/general", + searchTerms: ["dictation transcription language locale"], + }, + { + id: "voice-input-api-key", + title: "Voice input API key", + to: "/settings/general", + searchTerms: ["speech to text credential secret token"], + }, { id: "app-version", title: "Version", diff --git a/apps/web/src/components/settings/voiceInputSettings.logic.test.ts b/apps/web/src/components/settings/voiceInputSettings.logic.test.ts new file mode 100644 index 0000000000000..4057e930274c5 --- /dev/null +++ b/apps/web/src/components/settings/voiceInputSettings.logic.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + availableVoiceInputPresets, + resolveVoiceInputPreset, + VOICE_INPUT_PRESETS, + voiceInputPresetPatch, + voiceInputProviderPatch, +} from "./voiceInputSettings.logic"; + +const openai = { provider: "openai-compatible", baseUrl: "https://api.openai.com/v1" } as const; + +describe("voice input presets", () => { + it("recognizes every preset from the settings it writes, ignoring URL case and slashes", () => { + for (const preset of VOICE_INPUT_PRESETS) { + const patch = voiceInputPresetPatch(preset.id, openai); + expect(patch).not.toBeNull(); + const written = { baseUrl: openai.baseUrl, model: "gpt-transcribe", ...patch! }; + expect(resolveVoiceInputPreset(written)).toBe(preset.id); + expect( + resolveVoiceInputPreset({ + ...written, + baseUrl: `${written.baseUrl.toUpperCase()}/`, + model: ` ${written.model} `, + }), + ).toBe(preset.id); + } + expect(voiceInputPresetPatch("custom", openai)).toBeNull(); + }); + + it("treats an edited endpoint or model as custom, except for Apple which has neither", () => { + expect(resolveVoiceInputPreset({ ...openai, model: "gpt-5-transcribe" })).toBe("custom"); + expect( + resolveVoiceInputPreset({ + provider: "xai", + baseUrl: "https://api.openai.com/v1", + model: "gpt-transcribe", + }), + ).toBe("custom"); + expect( + resolveVoiceInputPreset({ + provider: "apple-on-device", + baseUrl: "https://api.groq.com/openai/v1", + model: "whisper-large-v3-turbo", + }), + ).toBe("apple-on-device"); + }); + + it("resets the endpoint for HTTP providers and leaves it alone for Apple", () => { + expect(voiceInputProviderPatch("xai", openai)).toEqual({ + provider: "xai", + baseUrl: "https://api.x.ai/v1", + model: "grok-voice-transcribe-2.0", + apiKey: "", + }); + expect( + voiceInputProviderPatch("openai-compatible", { baseUrl: "https://api.x.ai/v1" }), + ).toEqual({ + provider: "openai-compatible", + baseUrl: "https://api.openai.com/v1", + model: "gpt-transcribe", + apiKey: "", + }); + expect(voiceInputProviderPatch("apple-on-device", openai)).toEqual({ + provider: "apple-on-device", + }); + expect(voiceInputPresetPatch("apple-on-device", openai)).toEqual({ + provider: "apple-on-device", + }); + }); + + it("drops the saved API key only when the endpoint moves to another host", () => { + expect(voiceInputPresetPatch("openai-whisper-1", openai)).toEqual({ + provider: "openai-compatible", + baseUrl: "https://api.openai.com/v1", + model: "whisper-1", + }); + expect(voiceInputPresetPatch("groq-whisper-large-v3-turbo", openai)).toMatchObject({ + baseUrl: "https://api.groq.com/openai/v1", + apiKey: "", + }); + expect(voiceInputPresetPatch("local-whisper-cpp", openai)).toMatchObject({ + baseUrl: "http://127.0.0.1:8080/v1", + apiKey: "", + }); + expect( + voiceInputPresetPatch("openai-gpt-transcribe", { baseUrl: "HTTPS://API.OPENAI.COM/v1/" }), + ).not.toHaveProperty("apiKey"); + }); + + it("offers Apple first only where the environment supports it, then the free local option", () => { + expect( + availableVoiceInputPresets(true) + .map((preset) => preset.id) + .slice(0, 2), + ).toEqual(["apple-on-device", "local-whisper-cpp"]); + const withoutApple = availableVoiceInputPresets(false).map((preset) => preset.id); + expect(withoutApple[0]).toBe("local-whisper-cpp"); + expect(withoutApple).not.toContain("apple-on-device"); + }); +}); diff --git a/apps/web/src/components/settings/voiceInputSettings.logic.ts b/apps/web/src/components/settings/voiceInputSettings.logic.ts new file mode 100644 index 0000000000000..520e36431faae --- /dev/null +++ b/apps/web/src/components/settings/voiceInputSettings.logic.ts @@ -0,0 +1,153 @@ +import { + VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS, + type HttpVoiceTranscriptionProvider, + type VoiceTranscriptionProvider, + type VoiceTranscriptionSettings, +} from "@t3tools/contracts"; + +export type VoiceInputPresetId = + | "apple-on-device" + | "local-whisper-cpp" + | "openai-gpt-transcribe" + | "openai-gpt-4o-mini-transcribe" + | "openai-whisper-1" + | "groq-whisper-large-v3-turbo" + | "xai-grok-voice-transcribe" + | "custom"; + +export type VoiceInputProviderTarget = Pick< + VoiceTranscriptionSettings, + "provider" | "baseUrl" | "model" +>; + +export type VoiceInputTargetPatch = Partial & + Pick & { readonly apiKey?: "" }; + +export interface VoiceInputPreset { + readonly id: Exclude; + readonly label: string; + readonly provider: VoiceTranscriptionProvider; + readonly endpoint?: Pick; +} + +export const VOICE_INPUT_PROVIDER_LABELS: Record = { + "apple-on-device": "Apple on-device (free, private, runs on this Mac)", + "openai-compatible": "OpenAI-compatible (OpenAI, Groq, local whisper.cpp)", + xai: "xAI Grok", +}; + +const OPENAI = VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS["openai-compatible"].baseUrl; + +export const VOICE_INPUT_PRESETS: ReadonlyArray = [ + { + id: "apple-on-device", + label: VOICE_INPUT_PROVIDER_LABELS["apple-on-device"], + provider: "apple-on-device", + }, + { + id: "local-whisper-cpp", + label: "Local whisper.cpp (free, no API key)", + provider: "openai-compatible", + endpoint: { baseUrl: "http://127.0.0.1:8080/v1", model: "whisper-1" }, + }, + { + id: "openai-gpt-transcribe", + label: "OpenAI gpt-transcribe (recommended)", + provider: "openai-compatible", + endpoint: { baseUrl: OPENAI, model: "gpt-transcribe" }, + }, + { + id: "openai-gpt-4o-mini-transcribe", + label: "OpenAI gpt-4o-mini-transcribe", + provider: "openai-compatible", + endpoint: { baseUrl: OPENAI, model: "gpt-4o-mini-transcribe" }, + }, + { + id: "openai-whisper-1", + label: "OpenAI whisper-1", + provider: "openai-compatible", + endpoint: { baseUrl: OPENAI, model: "whisper-1" }, + }, + { + id: "groq-whisper-large-v3-turbo", + label: "Groq whisper-large-v3-turbo", + provider: "openai-compatible", + endpoint: { baseUrl: "https://api.groq.com/openai/v1", model: "whisper-large-v3-turbo" }, + }, + { + id: "xai-grok-voice-transcribe", + label: "xAI grok-voice-transcribe-2.0", + provider: "xai", + endpoint: VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS.xai, + }, +]; + +function normalizeBaseUrl(baseUrl: string): string { + return baseUrl.trim().replace(/\/+$/, "").toLowerCase(); +} + +function originOf(baseUrl: string): string { + try { + return new URL(baseUrl.trim()).origin; + } catch { + return normalizeBaseUrl(baseUrl); + } +} + +export function isHttpVoiceInputProvider( + provider: VoiceTranscriptionProvider, +): provider is HttpVoiceTranscriptionProvider { + return provider !== "apple-on-device"; +} + +function endpointMatches(preset: VoiceInputPreset, target: VoiceInputProviderTarget): boolean { + if (!isHttpVoiceInputProvider(target.provider)) return true; + return ( + preset.endpoint !== undefined && + normalizeBaseUrl(preset.endpoint.baseUrl) === normalizeBaseUrl(target.baseUrl) && + preset.endpoint.model === target.model.trim() + ); +} + +export function resolveVoiceInputPreset(target: VoiceInputProviderTarget): VoiceInputPresetId { + const match = VOICE_INPUT_PRESETS.find( + (preset) => preset.provider === target.provider && endpointMatches(preset, target), + ); + return match?.id ?? "custom"; +} + +/** A key belongs to the host it was issued for, so a new origin starts without one. */ +function withKeyReset( + patch: VoiceInputTargetPatch, + current: Pick, +): VoiceInputTargetPatch { + return patch.baseUrl !== undefined && originOf(patch.baseUrl) !== originOf(current.baseUrl) + ? { ...patch, apiKey: "" } + : patch; +} + +export function voiceInputPresetPatch( + id: VoiceInputPresetId, + current: Pick, +): VoiceInputTargetPatch | null { + const preset = VOICE_INPUT_PRESETS.find((candidate) => candidate.id === id); + if (!preset) return null; + return withKeyReset({ provider: preset.provider, ...preset.endpoint }, current); +} + +export function voiceInputProviderPatch( + provider: VoiceTranscriptionProvider, + current: Pick, +): VoiceInputTargetPatch { + return isHttpVoiceInputProvider(provider) + ? withKeyReset({ provider, ...VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS[provider] }, current) + : { provider }; +} + +export function availableVoiceInputPresets( + appleOnDeviceAvailable: boolean, +): ReadonlyArray { + return appleOnDeviceAvailable + ? VOICE_INPUT_PRESETS + : VOICE_INPUT_PRESETS.filter((preset) => preset.provider !== "apple-on-device"); +} From 86cd109a7451dee608ab135e37dc131dfc7c85b6 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 22:25:46 -0400 Subject: [PATCH 14/55] docs: voice input on desktop and web Describes the environment-backed transcription path in the internals page and adds a user section with the settings path, the shortcut, and the microphone permission steps. Co-Authored-By: Claude Opus 5.5 --- docs/internals/voice-input.md | 11 +++++++++-- docs/user/composer.md | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/docs/internals/voice-input.md b/docs/internals/voice-input.md index 55e3007a48721..3b36702f93a97 100644 --- a/docs/internals/voice-input.md +++ b/docs/internals/voice-input.md @@ -2,8 +2,15 @@ Transcription edits a composer draft. It does not submit an agent turn. Audio is temporary client input, and only normal message submission sends the resulting -text. The current implementation transcribes locally on supported iOS devices; -environment-backed transcription is not implemented. +text. Supported iOS devices transcribe locally. Web and desktop upload the +recording to the environment, which forwards it to the configured speech-to-text +API, because the API key is an environment secret and never reaches a client. +The client asks `voice.createTranscriptionUrl` for a short-lived capability URL +and posts the audio there, so the upload works over every connection mode without +a separate credential. Browsers record whatever container their engine supports, +and the [web transcriber](../../apps/web/src/lib/voiceWav.ts) re-encodes every +recording to 16 kHz mono WAV before upload, since xAI rejects WebM and a local +whisper.cpp server would otherwise need ffmpeg. The [shared controller](../../packages/client-runtime/src/voice-input/controller.ts) owns the operation while the client supplies capture and transcription. Preparation diff --git a/docs/user/composer.md b/docs/user/composer.md index a784b625108c0..ebe1879a515a5 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -49,6 +49,28 @@ also send files to T3 Code through another app's system share sheet. See [images and videos](#images-and-videos-in-messages) for previewing and saving media. +## Voice input on desktop and web + +Dictate a message instead of typing it. Turn it on under **Settings → General → +Voice input**, where you choose who transcribes: a free whisper.cpp server on the +machine running T3 Code, Apple's on-device engine when that machine is a Mac on +macOS 26 or later, or a hosted API from OpenAI, Groq, or xAI with your own API +key. The key stays on that machine. Audio goes to the T3 Code server, which sends +it to the provider you chose, so hosted options bill per use. + +Press the microphone button in the composer, or `Cmd+Shift+Space` on macOS and +`Ctrl+Shift+Space` elsewhere, to start recording. Press the same button, or the +shortcut, again to stop. The transcript is inserted at your cursor for you to +review and edit; nothing is sent until you send the message. Press Esc to discard +a recording. A recording stops on its own after 5 minutes. Change +`composer.toggleDictation` in **Settings → Keybindings** to use another shortcut. + +The browser asks for microphone access the first time. If you decline, allow the +microphone for this site in your browser's settings. On the desktop app for macOS, +allow it under **System Settings → Privacy & Security → Microphone**. Voice input +is unavailable on plain `http://` connections other than localhost, because +browsers only expose the microphone on secure origins. + ## Send while the agent is working On web and desktop, choose **Settings → General → Follow-up behavior** to queue From a4c08d8f773fc78e2e142c10a3eaa005240f4674 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 22:41:01 -0400 Subject: [PATCH 15/55] feat(native): add the Apple speech helper for on-device transcription t3-apple-speech wraps macOS 26 SpeechAnalyzer behind two subcommands that each print one JSON object. `probe` reports availability and locales, and `transcribe --locale ` installs a missing language model on demand and returns the text. build.mjs compiles it with swiftc in Swift 6 mode for arm64, x86_64, or a lipo universal binary with a 26.0 deployment target. Co-Authored-By: Claude Opus 5.5 --- native/apple-speech/build.mjs | 80 +++++++++++++++++++++++ native/apple-speech/main.swift | 113 +++++++++++++++++++++++++++++++++ 2 files changed, 193 insertions(+) create mode 100644 native/apple-speech/build.mjs create mode 100644 native/apple-speech/main.swift diff --git a/native/apple-speech/build.mjs b/native/apple-speech/build.mjs new file mode 100644 index 0000000000000..8943d585ca37c --- /dev/null +++ b/native/apple-speech/build.mjs @@ -0,0 +1,80 @@ +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import * as NodeURL from "node:url"; +import * as NodeUtil from "node:util"; + +// oxlint-disable-next-line t3code/no-global-process-runtime -- The Swift compiler targets the actual host; this script has no Effect runtime. +const hostArch = process.arch; +// oxlint-disable-next-line t3code/no-global-process-runtime -- SpeechAnalyzer only links against the macOS 26 SDK, so this only builds on a Mac. +const hostPlatform = process.platform; + +const { values } = NodeUtil.parseArgs({ + options: { output: { type: "string" }, arch: { type: "string", default: hostArch } }, +}); + +const SWIFT_ARCHES = { arm64: ["arm64"], x64: ["x86_64"], universal: ["arm64", "x86_64"] }; +const DEPLOYMENT_TARGET = "26.0"; + +if (hostPlatform !== "darwin") { + throw new Error("The Apple speech helper can only be built on macOS."); +} +const arches = SWIFT_ARCHES[values.arch]; +if (arches === undefined) throw new Error(`Unsupported macOS architecture: ${values.arch}`); + +const root = NodeURL.fileURLToPath(new URL("./", import.meta.url)); +const source = NodePath.resolve(root, "main.swift"); +const output = values.output ?? NodePath.resolve(root, "build", "t3-apple-speech"); + +const builtArches = (file) => { + try { + return NodeChildProcess.execFileSync("lipo", ["-archs", file], { encoding: "utf8" }) + .trim() + .split(/\s+/) + .sort(); + } catch { + return []; + } +}; +let current = false; +try { + current = + NodeFS.statSync(output).mtimeMs >= + Math.max( + NodeFS.statSync(source).mtimeMs, + NodeFS.statSync(NodeURL.fileURLToPath(import.meta.url)).mtimeMs, + ) && builtArches(output).join(" ") === [...arches].sort().join(" "); +} catch {} + +if (!current) { + NodeFS.mkdirSync(NodePath.dirname(output), { recursive: true }); + const temporaries = arches.map((arch) => `${output}.${arch}.${process.pid}.tmp`); + try { + arches.forEach((arch, index) => { + NodeChildProcess.execFileSync( + "swiftc", + [ + "-parse-as-library", + "-swift-version", + "6", + "-O", + "-target", + `${arch}-apple-macos${DEPLOYMENT_TARGET}`, + "-o", + temporaries[index], + source, + ], + { stdio: "inherit" }, + ); + }); + if (temporaries.length === 1) { + NodeFS.renameSync(temporaries[0], output); + } else { + NodeChildProcess.execFileSync("lipo", ["-create", ...temporaries, "-output", output], { + stdio: "inherit", + }); + } + } finally { + for (const temporary of temporaries) NodeFS.rmSync(temporary, { force: true }); + } +} diff --git a/native/apple-speech/main.swift b/native/apple-speech/main.swift new file mode 100644 index 0000000000000..2aa3beb7f57bb --- /dev/null +++ b/native/apple-speech/main.swift @@ -0,0 +1,113 @@ +import AVFoundation +import Foundation +import Speech + +struct ProbeOutput: Encodable { + let available: Bool + let supportedLocales: [String] + let installedLocales: [String] +} + +struct TranscribeOutput: Encodable { + let text: String + let locale: String +} + +struct ErrorOutput: Encodable { + struct Body: Encodable { + let code: String + let message: String + } + + let error: Body +} + +func emit(_ output: Output) { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + guard let data = try? encoder.encode(output) else { + FileHandle.standardOutput.write(Data("{\"error\":{\"code\":\"failed\",\"message\":\"Could not encode the helper output.\"}}\n".utf8)) + exit(1) + } + FileHandle.standardOutput.write(data) + FileHandle.standardOutput.write(Data("\n".utf8)) +} + +func fail(_ code: String, _ message: String) -> Never { + emit(ErrorOutput(error: .init(code: code, message: message))) + exit(1) +} + +func probe() async { + let supported = await SpeechTranscriber.supportedLocales + let installed = await SpeechTranscriber.installedLocales + emit( + ProbeOutput( + available: SpeechTranscriber.isAvailable, + supportedLocales: supported.map(\.identifier).sorted(), + installedLocales: installed.map(\.identifier).sorted())) +} + +func transcribe(localeIdentifier: String, wavPath: String) async { + guard SpeechTranscriber.isAvailable else { + fail("unavailable", "SpeechTranscriber is not available on this Mac.") + } + let requested = localeIdentifier.isEmpty ? Locale.current : Locale(identifier: localeIdentifier) + guard let locale = await SpeechTranscriber.supportedLocale(equivalentTo: requested) else { + fail("unsupported_locale", "No speech model supports the locale '\(requested.identifier)'.") + } + let transcriber = SpeechTranscriber(locale: locale, preset: .transcription) + do { + if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) { + try await request.downloadAndInstall() + } + } catch { + fail("assets_failed", "Could not install the speech model for '\(locale.identifier)': \(error)") + } + let analyzer = SpeechAnalyzer(modules: [transcriber]) + // An unstructured task, so a throw below exits the process instead of + // waiting for a results stream that may never finish. + let transcript = Task { try await transcriber.results.reduce("") { $0 + String($1.text.characters) } } + do { + let file = try AVAudioFile(forReading: URL(fileURLWithPath: wavPath)) + if let last = try await analyzer.analyzeSequence(from: file) { + try await analyzer.finalizeAndFinish(through: last) + } else { + await analyzer.cancelAndFinishNow() + } + emit(TranscribeOutput(text: try await transcript.value, locale: locale.identifier)) + } catch { + fail("failed", "Transcription failed: \(error)") + } +} + +@main +struct Main { + static func main() async { + let usage = "usage: t3-apple-speech probe | transcribe --locale " + var arguments = Array(CommandLine.arguments.dropFirst()) + guard let command = arguments.first else { fail("failed", usage) } + arguments.removeFirst() + switch command { + case "probe": + await probe() + case "transcribe": + var locale = "" + var wavPath: String? + var index = 0 + while index < arguments.count { + if arguments[index] == "--locale" { + locale = index + 1 < arguments.count ? arguments[index + 1] : "" + index += 2 + } else { + wavPath = arguments[index] + index += 1 + } + } + guard let wavPath else { fail("failed", usage) } + await transcribe(localeIdentifier: locale, wavPath: wavPath) + default: + fail("failed", usage) + } + } +} From 31e60e95ca2d17fbc0aa7171dd355c6b592b69d9 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 22:41:01 -0400 Subject: [PATCH 16/55] feat(server): transcribe voice recordings with Apple on-device speech AppleSpeechHelper resolves the t3-apple-speech binary (T3CODE_APPLE_SPEECH_PATH, the appleSpeechHelperPath config, the bundled copy next to dist, or the dev build), only on Darwin 25 or later, and probes it once per process. The probe is forked at layer construction so the startup descriptor read overlaps it, and a probe that times out is retried after a minute instead of being cached for the process lifetime. transcribe writes the WAV to a scoped temp directory that is removed on every exit path and maps the helper's error codes to typed errors. VoiceTranscription's provider table becomes a discriminated union with a `kind` of "http" or "apple". The Apple backend needs no key, URL, or model, accepts audio/wav only, and is refused at mint time unless the host advertises capabilities.appleOnDeviceTranscription, which ServerEnvironment now reads from the helper. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/cli/config.ts | 2 + apps/server/src/config.ts | 2 + .../src/environment/ServerEnvironment.test.ts | 8 +- .../src/environment/ServerEnvironment.ts | 23 +- apps/server/src/http.ts | 6 + apps/server/src/server.ts | 14 +- .../AppleSpeechHelper.test.ts | 302 ++++++++++++++++++ .../voiceTranscription/AppleSpeechHelper.ts | 250 +++++++++++++++ .../VoiceTranscription.test.ts | 77 +++++ .../voiceTranscription/VoiceTranscription.ts | 104 ++++-- docs/internals/voice-input.md | 18 +- 11 files changed, 759 insertions(+), 47 deletions(-) create mode 100644 apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts create mode 100644 apps/server/src/voiceTranscription/AppleSpeechHelper.ts diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index c7271b795b555..d670d13acbd18 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -370,6 +370,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct const desktopBrowserFd = bootstrap?.desktopBrowserFd; const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd; const resourceMonitorPath = bootstrap?.resourceMonitorPath; + const appleSpeechHelperPath = bootstrap?.appleSpeechHelperPath; const autoBootstrapProjectFromCwd = Option.getOrElse( resolveOptionPrecedence( Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd), @@ -477,6 +478,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct desktopBrowserFd, desktopBrowserControlFd, resourceMonitorPath, + appleSpeechHelperPath, autoBootstrapProjectFromCwd, logWebSocketEvents, tailscaleServeEnabled, diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index ef6f71a46a2e2..1fc01b6039b78 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -81,6 +81,7 @@ export class ServerConfig extends Context.Service< readonly desktopBrowserFd?: number | undefined; readonly desktopBrowserControlFd?: number | undefined; readonly resourceMonitorPath?: string | undefined; + readonly appleSpeechHelperPath?: string | undefined; readonly autoBootstrapProjectFromCwd: boolean; readonly logWebSocketEvents: boolean; readonly tailscaleServeEnabled: boolean; @@ -221,6 +222,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* ( desktopBrowserFd: undefined, desktopBrowserControlFd: undefined, resourceMonitorPath: undefined, + appleSpeechHelperPath: undefined, staticDir: undefined, devUrl, devAllowedOrigins: [], diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index 7cebccb2a1f7c..27be44ae89f26 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -18,11 +18,13 @@ import { RELAY_URL_SECRET, } from "../cloud/config.ts"; import * as ServerConfig from "../config.ts"; +import * as AppleSpeechHelper from "../voiceTranscription/AppleSpeechHelper.ts"; import * as ServerEnvironment from "./ServerEnvironment.ts"; const layerServerEnvironment = (baseDir: string) => ServerEnvironment.layer.pipe( Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layerUnavailable), Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)), ); @@ -98,6 +100,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { Effect.provide( ServerEnvironment.layer.pipe( Layer.provide(layerEmptySecretStore), + Layer.provide(AppleSpeechHelper.layerUnavailable), Layer.provide(ServerConfig.layer({ ...config, mode })), ), ), @@ -235,7 +238,10 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { prefix: "t3-server-environment-publish-test-", }); const layerTest = Layer.mergeAll( - ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)), + ServerEnvironment.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layerUnavailable), + ), ServerSecretStore.layer, ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir))); diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index fbb5970560bc6..4b57e28ac69da 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -21,6 +21,7 @@ import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts"; import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; +import * as AppleSpeechHelper from "../voiceTranscription/AppleSpeechHelper.ts"; import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts"; import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts"; @@ -185,6 +186,7 @@ export const make = Effect.gen(function* () { const path = yield* Path.Path; const serverConfig = yield* ServerConfig.ServerConfig; const secrets = yield* ServerSecretStore.ServerSecretStore; + const appleSpeech = yield* AppleSpeechHelper.AppleSpeechHelper; const identity = yield* ServerEnvironmentIdentity; const hostPlatform = yield* HostProcess.Platform; const hostArchitecture = yield* HostProcess.Architecture; @@ -269,17 +271,20 @@ export const make = Effect.gen(function* () { }, }; + // The publish opt-in and relay link change at runtime (`t3 connect + // publish`, the client settings toggle), so the capability is read per + // descriptor request rather than baked in at startup. + const runtimeCapabilities = Effect.all({ + agentActivityPublishing: readAgentActivityPublishingActive(secrets), + appleOnDeviceTranscription: appleSpeech.available, + }); + return ServerEnvironment.of({ getEnvironmentId: Effect.succeed(environmentId), - // The publish opt-in and relay link change at runtime (`t3 connect - // publish`, the client settings toggle), so the capability is read per - // descriptor request rather than baked in at startup. - getDescriptor: readAgentActivityPublishingActive(secrets).pipe( - Effect.map((agentActivityPublishing) => ({ - ...descriptor, - capabilities: { ...descriptor.capabilities, agentActivityPublishing }, - })), - ), + getDescriptor: Effect.map(runtimeCapabilities, (capabilities) => ({ + ...descriptor, + capabilities: { ...descriptor.capabilities, ...capabilities }, + })), }); }); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index e3493ad7e73f1..6444af7f729c4 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -565,6 +565,12 @@ export const layerVoiceTranscriptionRoute = HttpRouter.add( Effect.logWarning("Voice transcription failed upstream.", { cause: error }).pipe( Effect.as(voiceTranscriptionFailure("upstream_failed", error.message)), ), + AppleSpeechUnsupportedLocaleError: (error) => + Effect.succeed(voiceTranscriptionFailure("not_configured", error.message)), + AppleSpeechHelperError: (error) => + Effect.logWarning("Voice transcription failed in the Apple speech helper.", { + cause: error, + }).pipe(Effect.as(voiceTranscriptionFailure("upstream_failed", error.message))), }), ); }), diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 053efbe97314d..51d2fae746405 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -93,6 +93,7 @@ import * as ProviderAdapterRegistry from "./orchestration-v2/ProviderAdapterRegi import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; import * as ProviderUsageLimitsIngestion from "./provider/ProviderUsageLimitsIngestion.ts"; import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; +import * as AppleSpeechHelper from "./voiceTranscription/AppleSpeechHelper.ts"; import * as VoiceTranscription from "./voiceTranscription/VoiceTranscription.ts"; import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts"; import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts"; @@ -281,6 +282,7 @@ const layerUsage = UsageService.layer.pipe( const layerVoiceTranscription = VoiceTranscription.layer.pipe( Layer.provide(layerServerSettings), Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layer), ); const layerResourceDiagnostics = Layer.mergeAll( @@ -462,7 +464,10 @@ const layerProjectFaviconResolver = ProjectFaviconResolver.layer.pipe( Layer.provide(T3ProjectFileLoader.layer), ); -const layerServerEnvironment = ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)); +const layerServerEnvironment = ServerEnvironment.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layer), +); const layerAuth = EnvironmentAuth.layer.pipe( Layer.provideMerge(layerPersistence), @@ -1060,7 +1065,12 @@ const layerMakeServer = Layer.unwrap( Layer.provideMerge(layerRuntimeServices), Layer.provideMerge( McpSessionRegistry.layer.pipe( - Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))), + Layer.provide( + ServerEnvironment.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layer), + ), + ), ), ), Layer.provide(layerActivation), diff --git a/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts b/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts new file mode 100644 index 0000000000000..883630d54d0d3 --- /dev/null +++ b/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts @@ -0,0 +1,302 @@ +// @effect-diagnostics nodeBuiltinImport:off - The skip gate for the real helper runs before any Effect runtime exists. +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { assert, describe, expect, it } from "@effect/vitest"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as NodeFS from "node:fs"; +import * as TestClock from "effect/testing/TestClock"; +import { ChildProcessSpawner } from "effect/process"; + +import * as ServerConfig from "../config.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import * as AppleSpeechHelper from "./AppleSpeechHelper.ts"; + +const devHelperPath = `${import.meta.dirname}/../../../../native/apple-speech/build/t3-apple-speech`; +const realHelperUsable = + HostProcess.Platform.defaultValue() === "darwin" && + Number.parseInt(AppleSpeechHelper.AppleSpeechHostKernelRelease.defaultValue(), 10) >= 25 && + NodeFS.existsSync(devHelperPath); + +const audio = new Uint8Array([82, 73, 70, 70, 1, 2, 3, 4]); +const probeAvailable = + '{"available":true,"supportedLocales":["en_US"],"installedLocales":["en_US"]}'; + +const output = ( + fields: Partial = {}, +): ProcessRunner.ProcessRunOutput => ({ + stdout: "", + stderr: "", + code: ChildProcessSpawner.ExitCode(0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + ...fields, +}); + +const failed = (stdout: string) => output({ code: ChildProcessSpawner.ExitCode(1), stdout }); + +const timedOut = (input: ProcessRunner.ProcessRunInput) => + new ProcessRunner.ProcessTimeoutError({ + command: input.command, + argumentCount: input.args.length, + timeoutMs: 1, + }); + +type Handler = ( + input: ProcessRunner.ProcessRunInput, +) => Effect.Effect; + +const setup = Effect.fn(function* ( + host: { readonly platform: NodeJS.Platform; readonly kernelRelease: string }, + handle: Handler, +) { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-apple-speech-test-" }); + const helperPath = `${baseDir}/t3-apple-speech`; + yield* fileSystem.writeFileString(helperPath, "helper"); + const runs: Array = []; + const service = yield* AppleSpeechHelper.make.pipe( + Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)), + Effect.provideService( + ProcessRunner.ProcessRunner, + ProcessRunner.ProcessRunner.of({ + run: (input) => + Effect.suspend(() => { + runs.push(input); + return handle(input); + }), + }), + ), + Effect.provideService(HostProcess.Platform, host.platform), + Effect.provideService(HostProcess.Environment, { T3CODE_APPLE_SPEECH_PATH: helperPath }), + Effect.provideService(AppleSpeechHelper.AppleSpeechHostKernelRelease, host.kernelRelease), + ); + return { service, runs, helperPath }; +}); + +const macOS26 = { platform: "darwin", kernelRelease: "25.0.0" } as const; + +const helperThat = + (onTranscribe: Handler): Handler => + (input) => + input.args[0] === "probe" + ? Effect.succeed(output({ stdout: probeAvailable })) + : onTranscribe(input); + +describe("AppleSpeechHelper", () => { + it.effect.skipIf(!realHelperUsable)("probes the built helper through the real layer", () => + Effect.gen(function* () { + const service = yield* AppleSpeechHelper.AppleSpeechHelper; + expect(yield* service.available).toBe(true); + }).pipe( + Effect.provide( + AppleSpeechHelper.layer.pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-apple-speech-real-" })), + Layer.provide(NodeServices.layer), + ), + ), + Effect.provideService(HostProcess.Environment, { T3CODE_APPLE_SPEECH_PATH: devHelperPath }), + ), + ); + + it.effect.each([ + { platform: "linux", kernelRelease: "6.8.0" }, + { platform: "win32", kernelRelease: "10.0.22631" }, + { platform: "darwin", kernelRelease: "24.6.0" }, + ] as const)("never spawns the helper on $platform $kernelRelease", (host) => + Effect.gen(function* () { + const { service, runs } = yield* setup(host, () => Effect.die("must not spawn")); + expect(yield* service.available).toBe(false); + const error = yield* Effect.flip(service.transcribe({ audio, locale: "en" })); + assert.instanceOf(error, AppleSpeechHelper.AppleSpeechHelperError); + expect(error.reason).toBe("unavailable"); + expect(runs).toHaveLength(0); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect.each([ + { name: "available", probe: output({ stdout: probeAvailable }), available: true }, + { + name: "unavailable", + probe: output({ stdout: '{"available":false,"supportedLocales":[],"installedLocales":[]}' }), + available: false, + }, + { + name: "malformed", + probe: output({ stdout: "Speech framework crashed\n" }), + available: false, + }, + { + name: "failing", + probe: failed('{"error":{"code":"failed","message":"boom"}}'), + available: false, + }, + { name: "hung", probe: output({ code: null, timedOut: true }), available: false }, + ])("reads a $name probe once and caches it", ({ probe, available }) => + Effect.gen(function* () { + const { service, runs, helperPath } = yield* setup(macOS26, () => Effect.succeed(probe)); + expect(yield* service.available).toBe(available); + expect(yield* service.available).toBe(available); + expect(runs).toHaveLength(1); + expect(runs[0]).toMatchObject({ command: helperPath, args: ["probe"] }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("retries a probe that timed out, but not before a minute has passed", () => + Effect.gen(function* () { + let probes = 0; + const { service, runs } = yield* setup(macOS26, () => + Effect.sync(() => + probes++ === 0 + ? output({ code: null, timedOut: true }) + : output({ stdout: probeAvailable }), + ), + ); + expect(yield* service.available).toBe(false); + expect(yield* service.available).toBe(false); + expect(runs).toHaveLength(1); + yield* TestClock.adjust("1 minute"); + expect(yield* service.available).toBe(true); + expect(runs).toHaveLength(2); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("treats a helper that fails to launch as unavailable", () => + Effect.gen(function* () { + const { service, runs } = yield* setup(macOS26, (input) => + Effect.fail( + new ProcessRunner.ProcessSpawnError({ + command: input.command, + argumentCount: input.args.length, + cause: new Error("dyld: Symbol not found"), + }), + ), + ); + expect(yield* service.available).toBe(false); + expect(runs).toHaveLength(1); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("transcribes a WAV through a temp file that is gone afterwards", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + let wavPath = ""; + const { service, runs, helperPath } = yield* setup( + macOS26, + helperThat((input) => + Effect.gen(function* () { + wavPath = input.args.at(-1)!; + expect(new Uint8Array(yield* Effect.orDie(fileSystem.readFile(wavPath)))).toEqual( + audio, + ); + return output({ stdout: '{"text":"hello apple","locale":"en_US"}\n' }); + }), + ), + ); + const transcript = yield* service.transcribe({ audio, locale: "en" }); + expect(transcript).toEqual({ text: "hello apple", locale: "en_US" }); + expect(runs).toHaveLength(2); + const run = runs[1]!; + expect(run.command).toBe(helperPath); + expect(run.args).toEqual(["transcribe", "--locale", "en", wavPath]); + expect(Duration.toMillis(Duration.fromInputUnsafe(run.timeout!))).toBe(120_000); + expect(yield* fileSystem.exists(wavPath)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("passes an empty locale through so the helper uses the system language", () => + Effect.gen(function* () { + const { service, runs } = yield* setup( + macOS26, + helperThat(() => Effect.succeed(output({ stdout: '{"text":"","locale":"en_US"}' }))), + ); + expect(yield* service.transcribe({ audio, locale: "" })).toEqual({ + text: "", + locale: "en_US", + }); + expect(runs[1]!.args.slice(0, 3)).toEqual(["transcribe", "--locale", ""]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect.each([ + { + name: "unsupported_locale", + result: () => + Effect.succeed(failed('{"error":{"code":"unsupported_locale","message":"no model"}}')), + tag: "AppleSpeechUnsupportedLocaleError", + reason: undefined, + message: "does not support the language 'xx-YY'", + }, + { + name: "assets_failed", + result: () => + Effect.succeed(failed('{"error":{"code":"assets_failed","message":"offline"}}')), + tag: "AppleSpeechHelperError", + reason: "assets_failed", + message: "language model could not be downloaded", + }, + { + name: "unavailable", + result: () => Effect.succeed(failed('{"error":{"code":"unavailable","message":"off"}}')), + tag: "AppleSpeechHelperError", + reason: "unavailable", + message: "not available on this Mac", + }, + { + name: "failed", + result: () => Effect.succeed(failed('{"error":{"code":"failed","message":"bad wav"}}')), + tag: "AppleSpeechHelperError", + reason: "failed", + message: "transcription failed", + }, + { + name: "crash without JSON", + result: () => Effect.succeed(failed("Segmentation fault")), + tag: "AppleSpeechHelperError", + reason: "failed", + message: "transcription failed", + }, + { + name: "unexpected success output", + result: () => Effect.succeed(output({ stdout: '{"transcript":"wrong shape"}' })), + tag: "AppleSpeechHelperError", + reason: "failed", + message: "transcription failed", + }, + { + name: "timeout", + result: (input: ProcessRunner.ProcessRunInput) => Effect.fail(timedOut(input)), + tag: "AppleSpeechHelperError", + reason: "timeout", + message: "did not finish within 120 seconds", + }, + ])( + "maps a $name helper result and still deletes the temp file", + ({ result, tag, reason, message }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + let wavPath = ""; + const { service } = yield* setup( + macOS26, + helperThat((input) => { + wavPath = input.args.at(-1)!; + return result(input); + }), + ); + const error = yield* Effect.flip(service.transcribe({ audio, locale: "xx-YY" })); + expect(error._tag).toBe(tag); + if (reason !== undefined) { + assert.instanceOf(error, AppleSpeechHelper.AppleSpeechHelperError); + expect(error.reason).toBe(reason); + } + expect(error.message).toContain(message); + expect(wavPath).not.toBe(""); + expect(yield* fileSystem.exists(wavPath)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/voiceTranscription/AppleSpeechHelper.ts b/apps/server/src/voiceTranscription/AppleSpeechHelper.ts new file mode 100644 index 0000000000000..5e47c74aa526e --- /dev/null +++ b/apps/server/src/voiceTranscription/AppleSpeechHelper.ts @@ -0,0 +1,250 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as NodeOS from "node:os"; + +import * as ServerConfig from "../config.ts"; +import * as ProcessRunner from "../processRunner.ts"; + +const HELPER_NAME = "t3-apple-speech"; +// Darwin 25 is macOS 26, the first release with SpeechAnalyzer. +const MIN_DARWIN_MAJOR = 25; +const PROBE_TIMEOUT = "10 seconds"; +const PROBE_RETRY_DELAY = Duration.minutes(1); +// The first transcription in a language downloads its model through AssetInventory. +const TRANSCRIBE_TIMEOUT_SECONDS = 120; +const CAUSE_MAX_LENGTH = 300; + +const ProbeOutput = Schema.Struct({ available: Schema.Boolean }); + +const TranscribeOutput = Schema.Struct({ + text: Schema.String, + locale: Schema.String, +}); +type AppleSpeechTranscript = typeof TranscribeOutput.Type; + +const HelperErrorOutput = Schema.Struct({ + error: Schema.Struct({ + code: Schema.Literals(["unsupported_locale", "unavailable", "assets_failed", "failed"]), + message: Schema.String, + }), +}); + +const decodeProbe = Schema.decodeUnknownOption(Schema.fromJsonString(ProbeOutput)); +const decodeTranscript = Schema.decodeUnknownOption(Schema.fromJsonString(TranscribeOutput)); +const decodeHelperError = Schema.decodeUnknownOption(Schema.fromJsonString(HelperErrorOutput)); + +export class AppleSpeechUnsupportedLocaleError extends Schema.TaggedError()( + "AppleSpeechUnsupportedLocaleError", + { + locale: Schema.String, + }, +) { + override get message(): string { + return this.locale + ? `Apple on-device transcription does not support the language '${this.locale}'.` + : "Apple on-device transcription does not support this Mac's system language."; + } +} + +export class AppleSpeechHelperError extends Schema.TaggedError()( + "AppleSpeechHelperError", + { + reason: Schema.Literals(["unavailable", "assets_failed", "timeout", "failed"]), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + switch (this.reason) { + case "unavailable": + return "Apple on-device transcription is not available on this Mac."; + case "assets_failed": + return "The Apple speech language model could not be downloaded."; + case "timeout": + return `Apple on-device transcription did not finish within ${TRANSCRIBE_TIMEOUT_SECONDS} seconds.`; + case "failed": + return "Apple on-device transcription failed."; + } + } +} + +class AppleSpeechProbeTimedOut extends Schema.TaggedError()( + "AppleSpeechProbeTimedOut", + { + helperPath: Schema.String, + }, +) { + override get message(): string { + return `The Apple speech helper at '${this.helperPath}' did not answer its probe within ${PROBE_TIMEOUT}.`; + } +} + +export class AppleSpeechHelper extends Context.Service< + AppleSpeechHelper, + { + /** Probed once per process and cached. Never spawns off macOS 26 or later. */ + readonly available: Effect.Effect; + readonly transcribe: (input: { + readonly audio: Uint8Array; + readonly locale: string; + }) => Effect.Effect< + AppleSpeechTranscript, + AppleSpeechHelperError | AppleSpeechUnsupportedLocaleError + >; + } +>()("t3/voiceTranscription/AppleSpeechHelper") {} + +export const AppleSpeechHostKernelRelease = Context.Reference( + "t3/voiceTranscription/AppleSpeechHostKernelRelease", + { + defaultValue: () => NodeOS.release(), + }, +); + +const hostSupportsSpeechAnalyzer = (platform: NodeJS.Platform, kernelRelease: string) => + platform === "darwin" && Number.parseInt(kernelRelease, 10) >= MIN_DARWIN_MAJOR; + +export const make = Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processRunner = yield* ProcessRunner.ProcessRunner; + const platform = yield* HostProcess.Platform; + const environment = yield* HostProcess.Environment; + const kernelRelease = yield* AppleSpeechHostKernelRelease; + + const candidates = [ + environment.T3CODE_APPLE_SPEECH_PATH, + config.appleSpeechHelperPath, + path.resolve(import.meta.dirname, "apple-speech", HELPER_NAME), + path.resolve(import.meta.dirname, "../apple-speech", HELPER_NAME), + path.resolve(import.meta.dirname, "../../../../native/apple-speech/build", HELPER_NAME), + path.resolve(import.meta.dirname, "../../../native/apple-speech/build", HELPER_NAME), + ].filter((candidate): candidate is string => Boolean(candidate)); + + const locate = Effect.gen(function* () { + for (const candidate of candidates) { + if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { + return Option.some(candidate); + } + } + yield* Effect.logDebug("No Apple speech helper found.", { candidates }); + return Option.none(); + }); + + const probe = Effect.fn("AppleSpeechHelper.probe")(function* (helperPath: string) { + const result = yield* processRunner + .run({ + command: helperPath, + args: ["probe"], + timeout: PROBE_TIMEOUT, + timeoutBehavior: "timedOutResult", + }) + .pipe(Effect.option); + if (Option.isSome(result) && result.value.timedOut) { + return yield* new AppleSpeechProbeTimedOut({ helperPath }); + } + const available = + Option.isSome(result) && + result.value.code === 0 && + Option.exists(decodeProbe(result.value.stdout), (output) => output.available); + if (!available) { + yield* Effect.logWarning("The Apple speech helper is present but unusable.", { helperPath }); + } + return available ? Option.some(helperPath) : Option.none(); + }); + + let helper: Effect.Effect, AppleSpeechProbeTimedOut> = Effect.succeedNone; + if (hostSupportsSpeechAnalyzer(platform, kernelRelease)) { + helper = yield* Effect.cachedWithTTL( + locate.pipe( + Effect.flatMap(Option.match({ onNone: () => Effect.succeedNone, onSome: probe })), + ), + // A probe that hangs during a slow boot must not disable Apple transcription until restart. + (exit) => (Exit.isSuccess(exit) ? Duration.infinity : PROBE_RETRY_DELAY), + ); + // The startup sequence reads the environment descriptor, so the spawn + // starts now and overlaps the rest of startup instead of delaying it. + yield* Effect.forkScoped(Effect.ignore(helper)); + } + const helperPath = helper.pipe(Effect.orElseSucceed(() => Option.none())); + + const transcribe = Effect.fn("AppleSpeechHelper.transcribe")(function* (input: { + readonly audio: Uint8Array; + readonly locale: string; + }) { + const command = yield* helperPath; + if (Option.isNone(command)) { + return yield* new AppleSpeechHelperError({ reason: "unavailable" }); + } + const directory = yield* fileSystem + .makeTempDirectoryScoped({ prefix: "t3-apple-speech-" }) + .pipe(Effect.mapError((cause) => new AppleSpeechHelperError({ reason: "failed", cause }))); + const wavPath = path.join(directory, "recording.wav"); + yield* fileSystem + .writeFile(wavPath, input.audio) + .pipe(Effect.mapError((cause) => new AppleSpeechHelperError({ reason: "failed", cause }))); + const result = yield* processRunner + .run({ + command: command.value, + args: ["transcribe", "--locale", input.locale, wavPath], + timeout: `${TRANSCRIBE_TIMEOUT_SECONDS} seconds`, + }) + .pipe( + Effect.mapError( + (cause) => + new AppleSpeechHelperError({ + reason: cause._tag === "ProcessTimeoutError" ? "timeout" : "failed", + cause, + }), + ), + ); + if (result.code !== 0) { + const reported = decodeHelperError(result.stdout); + if (Option.isNone(reported)) { + return yield* new AppleSpeechHelperError({ + reason: "failed", + cause: new Error(result.stderr.slice(0, CAUSE_MAX_LENGTH)), + }); + } + const { code, message } = reported.value.error; + return yield* code === "unsupported_locale" + ? new AppleSpeechUnsupportedLocaleError({ locale: input.locale }) + : new AppleSpeechHelperError({ + reason: code, + cause: new Error(message.slice(0, CAUSE_MAX_LENGTH)), + }); + } + return yield* Option.match(decodeTranscript(result.stdout), { + // The output may hold the user's words, so the cause records only its size. + onNone: () => + new AppleSpeechHelperError({ + reason: "failed", + cause: new Error(`The helper printed ${result.stdout.length} bytes, not a transcript.`), + }), + onSome: Effect.succeed, + }); + }, Effect.scoped); + + return AppleSpeechHelper.of({ + available: Effect.map(helperPath, Option.isSome), + transcribe, + }); +}); + +export const layer = Layer.effect(AppleSpeechHelper, make).pipe(Layer.provide(ProcessRunner.layer)); + +export const layerUnavailable = Layer.succeed( + AppleSpeechHelper, + AppleSpeechHelper.of({ + available: Effect.succeed(false), + transcribe: () => new AppleSpeechHelperError({ reason: "unavailable" }), + }), +); diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts index b6d72e35db90e..e8e4503c56c7a 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -24,14 +24,25 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerConfig from "../config.ts"; import * as ServerHttp from "../http.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as AppleSpeechHelper from "./AppleSpeechHelper.ts"; import * as VoiceTranscription from "./VoiceTranscription.ts"; const audio = new Uint8Array([1, 2, 3, 4, 5, 6]); +const appleSpeechUnavailable = AppleSpeechHelper.AppleSpeechHelper.of({ + available: Effect.succeed(false), + transcribe: () => Effect.die("the Apple speech helper is unavailable"), +}); + +const appleSpeechAvailable = ( + transcribe: AppleSpeechHelper.AppleSpeechHelper["Service"]["transcribe"], +) => AppleSpeechHelper.AppleSpeechHelper.of({ available: Effect.succeed(true), transcribe }); + function setup( settings: Partial, upstream: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect = () => Effect.succeed(Response.json({ text: "hello world" })), + appleSpeech = appleSpeechUnavailable, ) { const requests: Array = []; const client = HttpClient.make((request) => @@ -47,6 +58,7 @@ function setup( }), ), Layer.provide(Layer.succeed(HttpClient.HttpClient, client)), + Layer.provide(Layer.succeed(AppleSpeechHelper.AppleSpeechHelper, appleSpeech)), Layer.provideMerge(ServerSecretStore.layer), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-voice-test-" })), Layer.provideMerge(NodeServices.layer), @@ -67,6 +79,8 @@ const xai = { model: "grok-voice-transcribe-2.0", } as const; +const apple = { provider: "apple-on-device", baseUrl: "", model: "", apiKey: "" } as const; + const post = ( relativeUrl: string, options: { readonly body?: Uint8Array; readonly contentLength?: number } = {}, @@ -168,6 +182,7 @@ describe("VoiceTranscription", () => { { settings: { apiKey: "" }, message: "OpenAI API key" }, { settings: { ...xai, apiKey: "" }, message: "xAI API key" }, { settings: xai, message: "xAI does not accept audio/webm recordings." }, + { settings: apple, message: "Apple on-device transcription needs macOS 26 or later" }, { settings: { model: "" }, message: "model name" }, { settings: { baseUrl: "" }, message: "endpoint URL" }, { settings: { baseUrl: "ftp://whisper.local" }, message: "not valid" }, @@ -261,6 +276,68 @@ describe("VoiceTranscription", () => { }, ); + it.effect("mints WAV but not WebM for Apple on-device without a key, URL, or model", () => { + const { layer } = setup( + apple, + undefined, + appleSpeechAvailable(() => Effect.die("unused")), + ); + return Effect.gen(function* () { + const error = yield* Effect.flip(mint); + expect(error.message).toBe( + "Apple on-device transcription does not accept audio/webm recordings.", + ); + const issued = yield* mintAs("audio/wav"); + expect(issued.relativeUrl.startsWith("/api/voice/transcriptions/")).toBe(true); + }).pipe(Effect.provide(layer)); + }); + + it.effect("transcribes WAV through the Apple speech helper without an HTTP request", () => { + const transcribed: Array<{ readonly audio: Uint8Array; readonly locale: string }> = []; + const { layer, requests } = setup( + { ...apple, language: "en" }, + undefined, + appleSpeechAvailable((input) => { + transcribed.push(input); + return Effect.succeed({ text: "hello apple", locale: "en_US" }); + }), + ); + return Effect.gen(function* () { + const response = yield* post((yield* mintAs("audio/wav")).relativeUrl); + expect(response).toEqual({ status: 200, body: { text: "hello apple" } }); + expect(requests).toHaveLength(0); + expect(transcribed).toEqual([{ audio, locale: "en" }]); + }).pipe(Effect.provide(layer)); + }); + + it.effect.each([ + { + failure: new AppleSpeechHelper.AppleSpeechUnsupportedLocaleError({ locale: "xx-YY" }), + status: 409, + code: "not_configured", + message: "Apple on-device transcription does not support the language 'xx-YY'.", + }, + { + failure: new AppleSpeechHelper.AppleSpeechHelperError({ reason: "assets_failed" }), + status: 502, + code: "upstream_failed", + message: "The Apple speech language model could not be downloaded.", + }, + ])("answers $code when the Apple speech helper fails with $failure._tag", (expected) => { + const { layer } = setup( + apple, + undefined, + appleSpeechAvailable(() => expected.failure), + ); + return Effect.gen(function* () { + const response = yield* post((yield* mintAs("audio/wav")).relativeUrl); + expect(response).toEqual({ + status: expected.status, + body: { code: expected.code, message: expected.message }, + }); + }).pipe(Effect.provide(layer)); + }); + it.effect("refuses a WebM upload minted before switching to xAI without calling upstream", () => { const { layer, requests } = setup({}); return Effect.gen(function* () { diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts index 06c193c10456e..cdb343fc59bc5 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -28,6 +28,7 @@ import { timingSafeEqualBase64Url, } from "../auth/utils.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as AppleSpeechHelper from "./AppleSpeechHelper.ts"; export const VOICE_TRANSCRIPTION_ROUTE_PREFIX = "/api/voice/transcriptions"; @@ -49,17 +50,30 @@ interface TranscriptionFormInput { readonly fileName: string; } -interface ProviderProtocol { +interface ProviderBackendBase { readonly name: string; - readonly path: string; readonly acceptedMimeTypes: ReadonlyArray; +} + +interface HttpProviderBackend extends ProviderBackendBase { + readonly kind: "http"; + readonly path: string; + readonly hostedBaseUrl: string; readonly form: (input: TranscriptionFormInput) => FormData; } -const PROVIDER_PROTOCOLS = { +interface AppleProviderBackend extends ProviderBackendBase { + readonly kind: "apple"; +} + +type ProviderBackend = HttpProviderBackend | AppleProviderBackend; + +const PROVIDER_BACKENDS = { "openai-compatible": { + kind: "http", name: "OpenAI", path: "audio/transcriptions", + hostedBaseUrl: VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS["openai-compatible"].baseUrl, acceptedMimeTypes: VoiceTranscriptionAudioMimeType.literals, form: ({ model, language, file, fileName }) => { const form = new FormData(); @@ -74,8 +88,10 @@ const PROVIDER_PROTOCOLS = { }, }, xai: { + kind: "http", name: "xAI", path: "stt", + hostedBaseUrl: VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS.xai.baseUrl, acceptedMimeTypes: ["audio/ogg", "audio/mp4", "audio/mpeg", "audio/wav"], form: ({ model, language, file, fileName }) => { const form = new FormData(); @@ -86,7 +102,12 @@ const PROVIDER_PROTOCOLS = { return form; }, }, -} as const satisfies Record; + "apple-on-device": { + kind: "apple", + name: "Apple on-device transcription", + acceptedMimeTypes: ["audio/wav"], + }, +} as const satisfies Record; const VoiceTranscriptionClaims = Schema.Struct({ version: Schema.Literal(1), @@ -203,55 +224,65 @@ export class VoiceTranscription extends Context.Service< | VoiceTranscriptionUnsupportedFormatError | VoiceTranscriptionCredentialsRejectedError | VoiceTranscriptionUpstreamError + | AppleSpeechHelper.AppleSpeechHelperError + | AppleSpeechHelper.AppleSpeechUnsupportedLocaleError >; } >()("t3/voiceTranscription/VoiceTranscription") {} -interface TranscriptionEndpoint { - readonly protocol: ProviderProtocol; +type HttpTranscriptionEndpoint = HttpProviderBackend & { readonly url: string; readonly host: string; readonly model: string; readonly language: string; readonly apiKey: string; -} +}; + +type TranscriptionEndpoint = + | HttpTranscriptionEndpoint + | (AppleProviderBackend & { readonly language: string }); -function resolveEndpoint( +const resolveEndpoint = Effect.fn("VoiceTranscription.resolveEndpoint")(function* ( settings: VoiceTranscriptionSettings, -): Effect.Effect { - const notConfigured = (message: string) => - Effect.fail(new VoiceTranscriptionNotConfiguredError({ message })); + appleSpeechAvailable: Effect.Effect, +): Effect.fn.Return { + const notConfigured = (message: string) => new VoiceTranscriptionNotConfiguredError({ message }); if (!settings.enabled) { - return notConfigured("Voice transcription is turned off for this environment."); + return yield* notConfigured("Voice transcription is turned off for this environment."); + } + const backend = PROVIDER_BACKENDS[settings.provider]; + if (backend.kind === "apple") { + if (!(yield* appleSpeechAvailable)) { + return yield* notConfigured( + "Apple on-device transcription needs macOS 26 or later on the machine running T3 Code.", + ); + } + return { ...backend, language: settings.language }; } const baseUrl = settings.baseUrl.replace(/\/+$/, ""); - if (!baseUrl) return notConfigured("Voice transcription needs an endpoint URL."); - if (!settings.model) return notConfigured("Voice transcription needs a model name."); - const protocol = PROVIDER_PROTOCOLS[settings.provider]; + if (!baseUrl) return yield* notConfigured("Voice transcription needs an endpoint URL."); + if (!settings.model) return yield* notConfigured("Voice transcription needs a model name."); // Local whisper.cpp-style servers take no key, but the hosted defaults always do. - if ( - !settings.apiKey && - baseUrl === VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS[settings.provider].baseUrl - ) { - return notConfigured(`Add an ${protocol.name} API key to use voice transcription.`); + if (!settings.apiKey && baseUrl === backend.hostedBaseUrl) { + return yield* notConfigured(`Add an ${backend.name} API key to use voice transcription.`); } - const url = URL.parse(`${baseUrl}/${protocol.path}`); + const url = URL.parse(`${baseUrl}/${backend.path}`); if (!url || (url.protocol !== "https:" && url.protocol !== "http:")) { - return notConfigured("The voice transcription endpoint URL is not valid."); + return yield* notConfigured("The voice transcription endpoint URL is not valid."); } - return Effect.succeed({ - protocol, + return { + ...backend, url: url.toString(), host: url.host, model: settings.model, language: settings.language, apiKey: settings.apiKey, - }); -} + }; +}); const readUpstreamMessage = ( response: HttpClientResponse.HttpClientResponse, - endpoint: TranscriptionEndpoint, + endpoint: HttpTranscriptionEndpoint, ) => response.text.pipe( Effect.map((body) => @@ -270,6 +301,7 @@ const make = Effect.gen(function* () { const settingsService = yield* ServerSettings.ServerSettingsService; const secretStore = yield* ServerSecretStore.ServerSecretStore; const client = yield* HttpClient.HttpClient; + const appleSpeech = yield* AppleSpeechHelper.AppleSpeechHelper; const signingSecret = loadUploadSigningSecret.pipe( Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore), @@ -285,16 +317,18 @@ const make = Effect.gen(function* () { message: "Could not read the voice transcription settings.", }), ), - Effect.flatMap((settings) => resolveEndpoint(settings.voiceTranscription)), + Effect.flatMap((settings) => + resolveEndpoint(settings.voiceTranscription, appleSpeech.available), + ), ); const createUploadUrl = Effect.fn("VoiceTranscription.createUploadUrl")(function* ( input: VoiceTranscriptionCreateUrlInput, ) { const endpoint = yield* loadEndpoint; - if (!endpoint.protocol.acceptedMimeTypes.includes(input.mimeType)) { + if (!endpoint.acceptedMimeTypes.includes(input.mimeType)) { return yield* new VoiceTranscriptionNotConfiguredError({ - message: unsupportedFormatMessage(endpoint.protocol.name, input.mimeType), + message: unsupportedFormatMessage(endpoint.name, input.mimeType), }); } const secret = yield* signingSecret.pipe( @@ -355,19 +389,23 @@ const make = Effect.gen(function* () { } const endpoint = yield* loadEndpoint; // The provider can change between minting and uploading. - if (!endpoint.protocol.acceptedMimeTypes.includes(claims.mimeType)) { + if (!endpoint.acceptedMimeTypes.includes(claims.mimeType)) { return yield* new VoiceTranscriptionUnsupportedFormatError({ - providerName: endpoint.protocol.name, + providerName: endpoint.name, mimeType: claims.mimeType, }); } + if (endpoint.kind === "apple") { + const { text } = yield* appleSpeech.transcribe({ audio, locale: endpoint.language }); + return { text } satisfies VoiceTranscriptionResult; + } const upstreamError = ( fields: Omit[0], "host">, ) => new VoiceTranscriptionUpstreamError({ host: endpoint.host, ...fields }); const request = HttpClientRequest.post(endpoint.url).pipe( HttpClientRequest.bodyFormData( - endpoint.protocol.form({ + endpoint.form({ model: endpoint.model, language: endpoint.language, file: new Blob([audio], { type: claims.mimeType }), diff --git a/docs/internals/voice-input.md b/docs/internals/voice-input.md index 55e3007a48721..476a0d9c224f0 100644 --- a/docs/internals/voice-input.md +++ b/docs/internals/voice-input.md @@ -2,8 +2,22 @@ Transcription edits a composer draft. It does not submit an agent turn. Audio is temporary client input, and only normal message submission sends the resulting -text. The current implementation transcribes locally on supported iOS devices; -environment-backed transcription is not implemented. +text. Supported iOS devices transcribe locally. Other clients upload the +recording to the environment, whose +[`VoiceTranscription`](../../apps/server/src/voiceTranscription/VoiceTranscription.ts) +service picks the provider. + +Apple on-device transcription runs on the environment host, not on the client. +A browser cannot reach SpeechAnalyzer, and a remote web or mobile client +connected to a Mac should get the same provider the desktop app gets. The server +spawns [`t3-apple-speech`](../../native/apple-speech/main.swift) through +[`AppleSpeechHelper`](../../apps/server/src/voiceTranscription/AppleSpeechHelper.ts), +which probes the helper once per process and advertises +`capabilities.appleOnDeviceTranscription` only on macOS 26 or later with a +working helper. That capability is the client's signal to offer the provider. +The server also refuses to mint an upload URL for it when the capability is +absent, so a client that skips the check, or settings copied to a Linux host, +fail with a clear message instead of a missing binary. The [shared controller](../../packages/client-runtime/src/voice-input/controller.ts) owns the operation while the client supplies capture and transcription. Preparation From 48d5049909db27e8e6b0852e4eeceb5c5ca29d56 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 22:41:02 -0400 Subject: [PATCH 17/55] feat(desktop): bundle the Apple speech helper in mac builds build-desktop-artifact.ts builds t3-apple-speech on mac targets, ships it as the apple-speech extra resource outside the asar, and checks for a macOS 26 SDK in the mac preflight. The desktop backend passes the bundled helper path to its server the way it passes the resource monitor. build-cli-archive.ts accepts --apple-speech-dir and signs the helper. CI does not provide that directory yet, so CLI archives still ship without it. Co-Authored-By: Claude Opus 5.5 --- .../DesktopBackendConfiguration.test.ts | 36 ++++++++ .../backend/DesktopBackendConfiguration.ts | 84 +++++++++++++------ scripts/build-cli-archive.ts | 28 ++++++- scripts/build-desktop-artifact.test.ts | 51 +++++++++++ scripts/build-desktop-artifact.ts | 50 +++++++++++ 5 files changed, 222 insertions(+), 27 deletions(-) diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 15e7be0a6181c..75d6ea218fe0e 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -991,6 +991,42 @@ describe("DesktopBackendConfiguration", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + it.effect("hands the packaged Apple speech helper only to a macOS backend", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-backend-config-test-", + }); + const resourcesPath = path.join(baseDir, "resources"); + const helperPath = path.join(resourcesPath, "apple-speech/t3-apple-speech"); + yield* fileSystem.makeDirectory(path.dirname(helperPath), { recursive: true }); + yield* fileSystem.writeFileString(helperPath, "binary"); + yield* fileSystem.chmod(helperPath, 0o755); + + const resolveBootstrap = (platform: NodeJS.Platform) => + Effect.gen(function* () { + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + return (yield* configuration.resolvePrimary).bootstrap; + }).pipe( + Effect.provide( + layerBackendConfiguration().pipe( + Layer.provideMerge(layerServerExposure), + Layer.provideMerge(DesktopAppSettings.layerTest()), + Layer.provideMerge(DesktopWslServerTree.layerTest()), + Layer.provideMerge(DesktopWslEnvironment.layerTest()), + Layer.provideMerge( + layerEnvironment(baseDir, { platform, isPackaged: true, resourcesPath }), + ), + ), + ), + ); + + assert.equal((yield* resolveBootstrap("darwin")).appleSpeechHelperPath, helperPath); + assert.notProperty(yield* resolveBootstrap("linux"), "appleSpeechHelperPath"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => { // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it. const runtime = ManagedRuntime.make( diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index dadbe8acc743b..68f43a0c17004 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -170,38 +170,60 @@ function resourceMonitorBinaryName(platform: NodeJS.Platform): string { return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor"; } +const resolveBundledHelperPath = Effect.fn("desktop.backendConfiguration.resolveBundledHelperPath")( + function* (input: { + readonly directory: string; + readonly binaryName: string; + readonly devBuildDirectories: ReadonlyArray; + }) { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const candidates = environment.isDevelopment + ? input.devBuildDirectories.map((directory) => + environment.path.join(environment.rootDir, directory, input.binaryName), + ) + : environment.isPackaged + ? [environment.path.join(environment.resourcesPath, input.directory, input.binaryName)] + : environment.resolveResourcePathCandidates( + environment.path.join(input.directory, input.binaryName), + ); + + for (const candidate of candidates) { + if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { + return Option.some(candidate); + } + } + + return Option.none(); + }, +); + const resolveResourceMonitorPath = Effect.fn( "desktop.backendConfiguration.resolveResourceMonitorPath", )(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const binaryName = resourceMonitorBinaryName(environment.platform); - const candidates = environment.isDevelopment - ? [ - environment.path.join( - environment.rootDir, - "native/resource-monitor/target/release", - binaryName, - ), - environment.path.join( - environment.rootDir, - "native/resource-monitor/target/debug", - binaryName, - ), - ] - : environment.isPackaged - ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)] - : environment.resolveResourcePathCandidates( - environment.path.join("resource-monitor", binaryName), - ); + return yield* resolveBundledHelperPath({ + directory: "resource-monitor", + binaryName: resourceMonitorBinaryName(environment.platform), + devBuildDirectories: [ + "native/resource-monitor/target/release", + "native/resource-monitor/target/debug", + ], + }); +}); - for (const candidate of candidates) { - if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { - return Option.some(candidate); - } +const resolveAppleSpeechHelperPath = Effect.fn( + "desktop.backendConfiguration.resolveAppleSpeechHelperPath", +)(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + if (environment.platform !== "darwin") { + return Option.none(); } - - return Option.none(); + return yield* resolveBundledHelperPath({ + directory: "apple-speech", + binaryName: "t3-apple-speech", + devBuildDirectories: ["native/apple-speech/build"], + }); }); const readPersistedBackendObservabilitySettings = Effect.gen(function* () { @@ -500,6 +522,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv function* ( input: SharedBootstrapInput & { readonly resourceMonitorPath: Option.Option; + readonly appleSpeechHelperPath: Option.Option; readonly cliPath: Option.Option; readonly shellEnvironmentPrepared: boolean; }, @@ -532,6 +555,10 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv onNone: () => ({}), onSome: (resourceMonitorPath) => ({ resourceMonitorPath }), }), + ...Option.match(input.appleSpeechHelperPath, { + onNone: () => ({}), + onSome: (appleSpeechHelperPath) => ({ appleSpeechHelperPath }), + }), ...buildObservabilityFragment(input.observabilitySettings), }; @@ -817,6 +844,10 @@ export const make = Effect.gen(function* () { Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), ); + const appleSpeechHelperPath = yield* resolveAppleSpeechHelperPath().pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), + ); const cliPath = yield* DesktopCliShim.install.pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), @@ -825,6 +856,7 @@ export const make = Effect.gen(function* () { return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath, + appleSpeechHelperPath, cliPath, shellEnvironmentPrepared, }).pipe( diff --git a/scripts/build-cli-archive.ts b/scripts/build-cli-archive.ts index 1367c27c180d5..9a0a4a239bda9 100644 --- a/scripts/build-cli-archive.ts +++ b/scripts/build-cli-archive.ts @@ -291,7 +291,8 @@ const signMacArchiveContents = Effect.fn("signMacArchiveContents")(function* (in entry.endsWith(".node") || entry.endsWith(".dylib") || entry.endsWith("spawn-helper") || - entry.endsWith("t3-resource-monitor"), + entry.endsWith("t3-resource-monitor") || + entry.endsWith("t3-apple-speech"), ) .map((entry) => path.join(input.contentDir, entry)); @@ -438,6 +439,7 @@ const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: { readonly version: string; readonly outputDir: string; readonly resourceMonitorDir: Option.Option; + readonly appleSpeechDir: Option.Option; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -485,6 +487,24 @@ const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: { yield* fs.copyFile(builtExecutable, path.join(contentDir, executableName)); yield* stageWebClient(webClient, path.join(contentDir, "client")); yield* fs.copy(resourceMonitorDir, path.join(contentDir, "resource-monitor")); + if (input.platform === "mac") { + const appleSpeechDir = Option.getOrElse(input.appleSpeechDir, () => + path.join(serverDir, "dist/apple-speech"), + ); + if (Option.isSome(input.appleSpeechDir)) { + yield* requireInput( + appleSpeechDir, + "Build it with `node native/apple-speech/build.mjs --arch --output /t3-apple-speech`.", + ); + } + if (yield* fs.exists(appleSpeechDir)) { + yield* fs.copy(appleSpeechDir, path.join(contentDir, "apple-speech")); + } else { + yield* Effect.log( + `[cli-archive] No Apple speech helper at ${appleSpeechDir}; the archive ships without on-device transcription.`, + ); + } + } yield* stageRuntimeExternals({ repoRoot, stageDir: contentDir, @@ -562,6 +582,12 @@ const command = Command.make( ), Flag.optional, ), + appleSpeechDir: Flag.String("apple-speech-dir").pipe( + Flag.withDescription( + "Directory holding t3-apple-speech for macOS archives (defaults to apps/server/dist/apple-speech when it exists).", + ), + Flag.optional, + ), }, (input) => buildCliArchive(input).pipe(Effect.scoped), ).pipe(Command.withDescription("Package the t3 single-executable into a per-platform archive.")); diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index 6ad4413adb567..2fb01b7a569a9 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -45,6 +45,7 @@ import { ancestorNodeModulesPaths, copyDirectoryPreservingSymlinks, LinuxBrowserSecretHostError, + stageAppleSpeechHelper, stageBrowserSecret, validateWindowsPackagedPayload, verifyPackagedBundleIsSelfContained, @@ -473,6 +474,56 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { }), ); + it.effect("ships the Apple speech helper only with mac builds and outside the asar", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const appleSpeech = { + from: "apps/desktop/prod-resources/apple-speech", + to: "apple-speech", + }; + for (const platform of ["mac", "linux", "win"] as const) { + const config = yield* createBuildConfig( + platform, + platform === "mac" ? "dmg" : platform === "linux" ? "AppImage" : "nsis", + "0.0.33", + false, + false, + undefined, + undefined, + ); + const extraResources = config.extraResources as ReadonlyArray; + if (platform === "mac") { + assert.deepInclude(extraResources, appleSpeech); + } else { + assert.notDeepInclude(extraResources, appleSpeech); + } + } + assert.isTrue( + DESKTOP_FILE_EXCLUSIONS.some((glob) => + NodePath.matchesGlob( + "apps/desktop/prod-resources/apple-speech/t3-apple-speech", + glob.slice(1), + ), + ), + ); + + const stageResourcesDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-apple-speech-" }); + for (const platform of ["linux", "win"] as const) { + yield* stageAppleSpeechHelper({ + repoRoot: stageResourcesDir, + stageResourcesDir, + platform, + arch: "x64", + verbose: false, + }); + } + assert.isFalse(yield* fs.exists(path.join(stageResourcesDir, "apple-speech"))); + }), + ), + ); + it.effect("omits update feeds for pull request preview builds", () => Effect.gen(function* () { const preview = yield* createBuildConfig( diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index d2cff47263455..eb5957fb30539 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -398,6 +398,10 @@ const MAC_DESKTOP_BUILD_PREREQUISITES = [ { id: "sips", description: "macOS image tool (sips)" }, { id: "iconutil", description: "macOS icon tool (iconutil)" }, { id: "lipo", description: "Xcode universal-binary tool (lipo)" }, + { + id: "macosSdk26", + description: "Xcode 26 or later (the macOS 26 SDK builds the Apple speech helper)", + }, ] as const; export class MacDesktopBuildPrerequisitesMissingError extends Schema.TaggedError()( @@ -997,6 +1001,8 @@ export const DESKTOP_FILE_EXCLUSIONS = [ "!apps/desktop/resources/browser-secret/**/*", "!apps/desktop/prod-resources/browser-secret", "!apps/desktop/prod-resources/browser-secret/**/*", + "!apps/desktop/prod-resources/apple-speech", + "!apps/desktop/prod-resources/apple-speech/**/*", // Windows stages the server sidecar below prod-resources so electron-builder // can copy it using project-relative extraResources matchers. Keep those // staging inputs out of app.asar; they are emitted once at resources/. @@ -1131,6 +1137,9 @@ export const LINUX_CAPTURE_EXTRA_RESOURCES = [ export const LINUX_BROWSER_SECRET_EXTRA_RESOURCES = [ { from: "apps/desktop/prod-resources/browser-secret", to: "browser-secret" }, ] as const; +export const MAC_APPLE_SPEECH_EXTRA_RESOURCES = [ + { from: "apps/desktop/prod-resources/apple-speech", to: "apple-speech" }, +] as const; export interface MacPasskeySigningConfiguration { readonly appId: string; @@ -1949,6 +1958,13 @@ const rustTargetIsInstalled = Effect.fn("rustTargetIsInstalled")(function* (targ return entries.some((entry) => entry.startsWith("libstd-") && entry.endsWith(".rlib")); }); +const macSdkSupportsSpeechAnalyzer = Effect.fn("macSdkSupportsSpeechAnalyzer")(function* () { + const result = yield* spawnAndCollectOutput( + ChildProcess.make("xcrun", ["--sdk", "macosx", "--show-sdk-version"]), + ).pipe(Effect.orElseSucceed(() => null)); + return result !== null && result.exitCode === 0 && Number.parseInt(result.stdout, 10) >= 26; +}); + export const preflightLinuxDesktopBuild = Effect.fn("preflightLinuxDesktopBuild")(function* ( arch: typeof BuildArch.Type = "x64", ) { @@ -2017,6 +2033,7 @@ export const preflightMacDesktopBuild = Effect.fn("preflightMacDesktopBuild")(fu arch === "universal" ? desktopBuildProbeSucceeds(ChildProcess.make("lipo", ["-version"]), "lipo") : Effect.succeed(true), + macosSdk26: macSdkSupportsSpeechAnalyzer(), }, { concurrency: "unbounded" }, ); @@ -2507,6 +2524,31 @@ export const stageBrowserSecret = Effect.fn("stageBrowserSecret")(function* (inp ); }); +export const stageAppleSpeechHelper = Effect.fn("stageAppleSpeechHelper")(function* (input: { + readonly repoRoot: string; + readonly stageResourcesDir: string; + readonly platform: typeof BuildPlatform.Type; + readonly arch: typeof BuildArch.Type; + readonly verbose: boolean; +}) { + if (input.platform !== "mac") return; + const path = yield* Path.Path; + yield* runCommand( + ChildProcess.make( + "node", + [ + path.join(input.repoRoot, "native/apple-speech/build.mjs"), + "--arch", + input.arch, + "--output", + path.join(input.stageResourcesDir, "apple-speech", "t3-apple-speech"), + ], + { cwd: input.repoRoot }, + ), + { label: "build Apple speech helper", verbose: input.verbose }, + ); +}); + const generateMacIconSet = Effect.fn("build-desktop-artifact.generateMacIconSet")(function* ( sourcePng: string, targetIcns: string, @@ -2854,6 +2896,7 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* ( ...DESKTOP_EXTRA_RESOURCES, ...(platform === "linux" ? LINUX_CAPTURE_EXTRA_RESOURCES : []), ...(platform === "linux" ? LINUX_BROWSER_SECRET_EXTRA_RESOURCES : []), + ...(platform === "mac" ? MAC_APPLE_SPEECH_EXTRA_RESOURCES : []), ...(platform === "win" ? WINDOWS_SERVER_EXTRA_RESOURCES : []), ...(platform === "win" && wslRuntimeBundled ? WSL_RUNTIME_EXTRA_RESOURCES : []), ], @@ -3829,6 +3872,13 @@ const buildDesktopArtifactUnlocked = Effect.fn("buildDesktopArtifactUnlocked")(f arch: options.arch, verbose: options.verbose, }); + yield* stageAppleSpeechHelper({ + repoRoot, + stageResourcesDir, + platform: options.platform, + arch: options.arch, + verbose: options.verbose, + }); yield* assertPlatformBuildResources( options.platform, From 8c80aeafc1b41d779a21797599205fc33783184f Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 22:43:39 -0400 Subject: [PATCH 18/55] feat(desktop): open the macOS microphone privacy pane from voice input Voice input's denied-microphone state offers to open System Settings on macOS. The desktop shell already knew the pane; the IPC contract now lists it. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/lib/microphoneSettings.ts | 15 ++------------- packages/contracts/src/ipc.ts | 2 +- 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/apps/web/src/lib/microphoneSettings.ts b/apps/web/src/lib/microphoneSettings.ts index 8f3183dab5211..d8d68dfa3e03b 100644 --- a/apps/web/src/lib/microphoneSettings.ts +++ b/apps/web/src/lib/microphoneSettings.ts @@ -1,21 +1,10 @@ -import { SystemSettingsPaneSchema } from "@t3tools/contracts"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; - import { isElectron } from "~/env"; import { isMacPlatform } from "~/lib/utils"; import { readLocalApi } from "~/localApi"; -// None until SystemSettingsPaneSchema lists "microphone"; the desktop side already handles it. -const microphonePane = Schema.decodeUnknownOption(SystemSettingsPaneSchema)("microphone"); - export const canOpenMicrophoneSystemSettings = - isElectron && - typeof navigator !== "undefined" && - isMacPlatform(navigator.platform) && - Option.isSome(microphonePane); + isElectron && typeof navigator !== "undefined" && isMacPlatform(navigator.platform); export async function openMicrophoneSystemSettings(): Promise { - if (Option.isNone(microphonePane)) return; - await readLocalApi()?.shell.openSystemSettings(microphonePane.value); + await readLocalApi()?.shell.openSystemSettings("microphone"); } diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index d1f6b349397ee..1ccc1112e9488 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1023,7 +1023,7 @@ export const DesktopPreviewRecordingSaveInputSchema = Schema.Struct({ data: Schema.Uint8Array, }); -export const SystemSettingsPaneSchema = Schema.Literals(["full-disk-access"]); +export const SystemSettingsPaneSchema = Schema.Literals(["full-disk-access", "microphone"]); export type SystemSettingsPane = typeof SystemSettingsPaneSchema.Type; export interface DesktopBridge { From f47b8bee4023dfc224dbd900d2fcb79da1cb5efd Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:08:22 -0400 Subject: [PATCH 19/55] fix(native): Apple speech helper answers empty recordings instead of hanging A zero-frame WAV made analyzeSequence return nil, and the helper then waited forever on a results stream that never finished. It now answers an empty transcript for an empty file or an empty analysis, opens the recording before downloading a model, and gives the first model download 90 seconds so a stall reports assets_failed instead of the server's generic timeout. Co-Authored-By: Claude Opus 5.5 --- native/apple-speech/main.swift | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/native/apple-speech/main.swift b/native/apple-speech/main.swift index 2aa3beb7f57bb..cbc52c1dcd44c 100644 --- a/native/apple-speech/main.swift +++ b/native/apple-speech/main.swift @@ -33,6 +33,8 @@ func emit(_ output: Output) { FileHandle.standardOutput.write(Data("\n".utf8)) } +let assetDownloadTimeoutSeconds = 90 + func fail(_ code: String, _ message: String) -> Never { emit(ErrorOutput(error: .init(code: code, message: message))) exit(1) @@ -56,7 +58,25 @@ func transcribe(localeIdentifier: String, wavPath: String) async { guard let locale = await SpeechTranscriber.supportedLocale(equivalentTo: requested) else { fail("unsupported_locale", "No speech model supports the locale '\(requested.identifier)'.") } + let file: AVAudioFile + do { + file = try AVAudioFile(forReading: URL(fileURLWithPath: wavPath)) + } catch { + fail("failed", "Could not read the recording: \(error)") + } + guard file.length > 0 else { + emit(TranscribeOutput(text: "", locale: locale.identifier)) + return + } let transcriber = SpeechTranscriber(locale: locale, preset: .transcription) + // The server's own timeout is longer, so a stalled first download reports + // as a model download failure instead of a generic timeout. + let assetWatchdog = Task { + try await Task.sleep(for: .seconds(assetDownloadTimeoutSeconds)) + fail( + "assets_failed", + "The speech model for '\(locale.identifier)' did not download within \(assetDownloadTimeoutSeconds) seconds.") + } do { if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) { try await request.downloadAndInstall() @@ -64,17 +84,19 @@ func transcribe(localeIdentifier: String, wavPath: String) async { } catch { fail("assets_failed", "Could not install the speech model for '\(locale.identifier)': \(error)") } + assetWatchdog.cancel() let analyzer = SpeechAnalyzer(modules: [transcriber]) // An unstructured task, so a throw below exits the process instead of // waiting for a results stream that may never finish. let transcript = Task { try await transcriber.results.reduce("") { $0 + String($1.text.characters) } } do { - let file = try AVAudioFile(forReading: URL(fileURLWithPath: wavPath)) - if let last = try await analyzer.analyzeSequence(from: file) { - try await analyzer.finalizeAndFinish(through: last) - } else { + guard let last = try await analyzer.analyzeSequence(from: file) else { await analyzer.cancelAndFinishNow() + transcript.cancel() + emit(TranscribeOutput(text: "", locale: locale.identifier)) + return } + try await analyzer.finalizeAndFinish(through: last) emit(TranscribeOutput(text: try await transcript.value, locale: locale.identifier)) } catch { fail("failed", "Transcription failed: \(error)") From eefa01fe04e552d802e8cac6e8182eaa5296473c Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:08:23 -0400 Subject: [PATCH 20/55] fix(native): write the universal Apple speech helper atomically lipo -create wrote straight to the output path, so an interrupted build left a partial binary that the freshness check could treat as current. Co-Authored-By: Claude Opus 5.5 --- native/apple-speech/build.mjs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/native/apple-speech/build.mjs b/native/apple-speech/build.mjs index 8943d585ca37c..a0d0ee9a0a1ca 100644 --- a/native/apple-speech/build.mjs +++ b/native/apple-speech/build.mjs @@ -49,6 +49,7 @@ try { if (!current) { NodeFS.mkdirSync(NodePath.dirname(output), { recursive: true }); const temporaries = arches.map((arch) => `${output}.${arch}.${process.pid}.tmp`); + const universal = `${output}.universal.${process.pid}.tmp`; try { arches.forEach((arch, index) => { NodeChildProcess.execFileSync( @@ -70,11 +71,12 @@ if (!current) { if (temporaries.length === 1) { NodeFS.renameSync(temporaries[0], output); } else { - NodeChildProcess.execFileSync("lipo", ["-create", ...temporaries, "-output", output], { + NodeChildProcess.execFileSync("lipo", ["-create", ...temporaries, "-output", universal], { stdio: "inherit", }); + NodeFS.renameSync(universal, output); } } finally { - for (const temporary of temporaries) NodeFS.rmSync(temporary, { force: true }); + for (const temporary of [...temporaries, universal]) NodeFS.rmSync(temporary, { force: true }); } } From 469b9121de20c1cea9922d1cbef737a3958bd935 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:09:30 -0400 Subject: [PATCH 21/55] fix(desktop): build mac apps on an older SDK without the Apple speech helper The macOS 26 SDK preflight failed every mac desktop build on an older Xcode. The helper is optional, so staging it is now skipped with a log line when the SDK is older, and the app ships without Apple on-device transcription. Co-Authored-By: Claude Opus 5.5 --- scripts/build-desktop-artifact.test.ts | 35 ++++++++++++++++++++++++++ scripts/build-desktop-artifact.ts | 11 ++++---- 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index 2fb01b7a569a9..0345113a2d8b4 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -524,6 +524,41 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { ), ); + it.effect.each(["15.5", "26.0"])( + "stages the Apple speech helper on mac only with a macOS 26 SDK (SDK %s)", + (sdkVersion) => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const stageResourcesDir = yield* fs.makeTempDirectoryScoped({ + prefix: "t3-apple-speech-sdk-", + }); + const commands: Array = []; + yield* stageAppleSpeechHelper({ + repoRoot: stageResourcesDir, + stageResourcesDir, + platform: "mac", + arch: "arm64", + verbose: false, + }).pipe( + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + const { command: name, args } = command as unknown as { + readonly command: string; + readonly args: ReadonlyArray; + }; + commands.push([name, ...args].join(" ")); + return Effect.succeed(mockProcess(0, name === "xcrun" ? `${sdkVersion}\n` : "")); + }), + ), + ); + const builds = commands.filter((command) => command.includes("build.mjs")); + assert.lengthOf(builds, sdkVersion === "26.0" ? 1 : 0); + }), + ), + ); + it.effect("omits update feeds for pull request preview builds", () => Effect.gen(function* () { const preview = yield* createBuildConfig( diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 575aa6505568e..fd9b07938ea10 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -398,10 +398,6 @@ const MAC_DESKTOP_BUILD_PREREQUISITES = [ { id: "sips", description: "macOS image tool (sips)" }, { id: "iconutil", description: "macOS icon tool (iconutil)" }, { id: "lipo", description: "Xcode universal-binary tool (lipo)" }, - { - id: "macosSdk26", - description: "Xcode 26 or later (the macOS 26 SDK builds the Apple speech helper)", - }, ] as const; export class MacDesktopBuildPrerequisitesMissingError extends Schema.TaggedError()( @@ -2033,7 +2029,6 @@ export const preflightMacDesktopBuild = Effect.fn("preflightMacDesktopBuild")(fu arch === "universal" ? desktopBuildProbeSucceeds(ChildProcess.make("lipo", ["-version"]), "lipo") : Effect.succeed(true), - macosSdk26: macSdkSupportsSpeechAnalyzer(), }, { concurrency: "unbounded" }, ); @@ -2532,6 +2527,12 @@ export const stageAppleSpeechHelper = Effect.fn("stageAppleSpeechHelper")(functi readonly verbose: boolean; }) { if (input.platform !== "mac") return; + if (!(yield* macSdkSupportsSpeechAnalyzer())) { + yield* Effect.log( + "[desktop-artifact] Building the Apple speech helper needs the macOS 26 SDK (Xcode 26 or Command Line Tools 26); the app ships without Apple on-device transcription.", + ); + return; + } const path = yield* Path.Path; yield* runCommand( ChildProcess.make( From e21854560ea7c919385498acad217f738efcfef8 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:09:31 -0400 Subject: [PATCH 22/55] chore(cli): stop plumbing the Apple speech helper into CLI archives Nothing in CI builds the --apple-speech-dir input, so the archive never shipped the helper. Apple on-device transcription is desktop-only for now. Co-Authored-By: Claude Opus 5.5 --- scripts/build-cli-archive.ts | 28 +--------------------------- 1 file changed, 1 insertion(+), 27 deletions(-) diff --git a/scripts/build-cli-archive.ts b/scripts/build-cli-archive.ts index 9a0a4a239bda9..1367c27c180d5 100644 --- a/scripts/build-cli-archive.ts +++ b/scripts/build-cli-archive.ts @@ -291,8 +291,7 @@ const signMacArchiveContents = Effect.fn("signMacArchiveContents")(function* (in entry.endsWith(".node") || entry.endsWith(".dylib") || entry.endsWith("spawn-helper") || - entry.endsWith("t3-resource-monitor") || - entry.endsWith("t3-apple-speech"), + entry.endsWith("t3-resource-monitor"), ) .map((entry) => path.join(input.contentDir, entry)); @@ -439,7 +438,6 @@ const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: { readonly version: string; readonly outputDir: string; readonly resourceMonitorDir: Option.Option; - readonly appleSpeechDir: Option.Option; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -487,24 +485,6 @@ const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: { yield* fs.copyFile(builtExecutable, path.join(contentDir, executableName)); yield* stageWebClient(webClient, path.join(contentDir, "client")); yield* fs.copy(resourceMonitorDir, path.join(contentDir, "resource-monitor")); - if (input.platform === "mac") { - const appleSpeechDir = Option.getOrElse(input.appleSpeechDir, () => - path.join(serverDir, "dist/apple-speech"), - ); - if (Option.isSome(input.appleSpeechDir)) { - yield* requireInput( - appleSpeechDir, - "Build it with `node native/apple-speech/build.mjs --arch --output /t3-apple-speech`.", - ); - } - if (yield* fs.exists(appleSpeechDir)) { - yield* fs.copy(appleSpeechDir, path.join(contentDir, "apple-speech")); - } else { - yield* Effect.log( - `[cli-archive] No Apple speech helper at ${appleSpeechDir}; the archive ships without on-device transcription.`, - ); - } - } yield* stageRuntimeExternals({ repoRoot, stageDir: contentDir, @@ -582,12 +562,6 @@ const command = Command.make( ), Flag.optional, ), - appleSpeechDir: Flag.String("apple-speech-dir").pipe( - Flag.withDescription( - "Directory holding t3-apple-speech for macOS archives (defaults to apps/server/dist/apple-speech when it exists).", - ), - Flag.optional, - ), }, (input) => buildCliArchive(input).pipe(Effect.scoped), ).pipe(Command.withDescription("Package the t3 single-executable into a per-platform archive.")); From c81b920cd61e1b63717887b1ffb5bd11b2fef14e Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:12:14 -0400 Subject: [PATCH 23/55] fix(server): read Apple speech availability without waiting for the probe ServerEnvironment.getDescriptor awaited the cached helper probe, which could take its full 10 second timeout, so startup, server.getConfig on every connect, CloudLink health proofs, and MCP all stalled behind it. The probe now runs in the background and publishes its answer to a Ref that defaults to false; the descriptor only reads it. Minting and transcribing still wait for the first answer. A probe that times out is retried every minute, at most five times, instead of on every descriptor read. The helper also stops looking in the CLI archive layout, which never shipped it. Co-Authored-By: Claude Opus 5.5 --- .../src/environment/ServerEnvironment.test.ts | 33 +++++++++ .../src/environment/ServerEnvironment.ts | 3 - .../AppleSpeechHelper.test.ts | 43 ++++++++++-- .../voiceTranscription/AppleSpeechHelper.ts | 68 ++++++++++++------- .../VoiceTranscription.test.ts | 18 +++-- .../voiceTranscription/VoiceTranscription.ts | 6 +- 6 files changed, 131 insertions(+), 40 deletions(-) diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index 27be44ae89f26..1077f839d606f 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -231,6 +231,39 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { }), ); + it.effect.each([true, false])( + "advertises Apple on-device transcription as %s from the helper's latest answer", + (available) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-server-environment-apple-speech-test-", + }); + const descriptor = yield* Effect.gen(function* () { + const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; + return yield* serverEnvironment.getDescriptor; + }).pipe( + Effect.provide( + ServerEnvironment.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide( + Layer.succeed( + AppleSpeechHelper.AppleSpeechHelper, + AppleSpeechHelper.AppleSpeechHelper.of({ + available: Effect.succeed(available), + availability: Effect.die("the descriptor must not wait for a probe"), + transcribe: () => Effect.die("unused"), + }), + ), + ), + Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)), + ), + ), + ); + expect(descriptor.capabilities.appleOnDeviceTranscription).toBe(available); + }), + ); + it.effect("reports agent activity publishing from the current secret state", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 4b57e28ac69da..61216716e16d9 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -271,9 +271,6 @@ export const make = Effect.gen(function* () { }, }; - // The publish opt-in and relay link change at runtime (`t3 connect - // publish`, the client settings toggle), so the capability is read per - // descriptor request rather than baked in at startup. const runtimeCapabilities = Effect.all({ agentActivityPublishing: readAgentActivityPublishingActive(secrets), appleOnDeviceTranscription: appleSpeech.available, diff --git a/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts b/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts index 883630d54d0d3..8f9f6ce9ff572 100644 --- a/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts +++ b/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts @@ -2,7 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { assert, describe, expect, it } from "@effect/vitest"; -import * as Duration from "effect/Duration"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -92,6 +92,7 @@ describe("AppleSpeechHelper", () => { it.effect.skipIf(!realHelperUsable)("probes the built helper through the real layer", () => Effect.gen(function* () { const service = yield* AppleSpeechHelper.AppleSpeechHelper; + expect(yield* service.availability).toBe("available"); expect(yield* service.available).toBe(true); }).pipe( Effect.provide( @@ -111,6 +112,7 @@ describe("AppleSpeechHelper", () => { ] as const)("never spawns the helper on $platform $kernelRelease", (host) => Effect.gen(function* () { const { service, runs } = yield* setup(host, () => Effect.die("must not spawn")); + expect(yield* service.availability).toBe("unsupported-host"); expect(yield* service.available).toBe(false); const error = yield* Effect.flip(service.transcribe({ audio, locale: "en" })); assert.instanceOf(error, AppleSpeechHelper.AppleSpeechHelperError); @@ -140,6 +142,7 @@ describe("AppleSpeechHelper", () => { ])("reads a $name probe once and caches it", ({ probe, available }) => Effect.gen(function* () { const { service, runs, helperPath } = yield* setup(macOS26, () => Effect.succeed(probe)); + expect(yield* service.availability).toBe(available ? "available" : "unavailable"); expect(yield* service.available).toBe(available); expect(yield* service.available).toBe(available); expect(runs).toHaveLength(1); @@ -147,6 +150,19 @@ describe("AppleSpeechHelper", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + it.effect("reports unavailable without waiting while the first probe is still running", () => + Effect.gen(function* () { + const release = yield* Deferred.make(); + const { service } = yield* setup(macOS26, () => + Deferred.await(release).pipe(Effect.as(output({ stdout: probeAvailable }))), + ); + expect(yield* service.available).toBe(false); + yield* Deferred.succeed(release, undefined); + expect(yield* service.availability).toBe("available"); + expect(yield* service.available).toBe(true); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("retries a probe that timed out, but not before a minute has passed", () => Effect.gen(function* () { let probes = 0; @@ -157,12 +173,29 @@ describe("AppleSpeechHelper", () => { : output({ stdout: probeAvailable }), ), ); + expect(yield* service.availability).toBe("unavailable"); expect(yield* service.available).toBe(false); - expect(yield* service.available).toBe(false); + yield* TestClock.adjust("59 seconds"); expect(runs).toHaveLength(1); - yield* TestClock.adjust("1 minute"); - expect(yield* service.available).toBe(true); + yield* TestClock.adjust("1 second"); expect(runs).toHaveLength(2); + expect(yield* service.available).toBe(true); + expect(yield* service.availability).toBe("available"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("stops retrying a probe that keeps timing out", () => + Effect.gen(function* () { + const { service, runs } = yield* setup(macOS26, () => + Effect.succeed(output({ code: null, timedOut: true })), + ); + expect(yield* service.availability).toBe("unavailable"); + yield* TestClock.adjust("1 hour"); + const attempts = runs.length; + expect(attempts).toBeGreaterThan(1); + yield* TestClock.adjust("1 hour"); + expect(runs).toHaveLength(attempts); + expect(yield* service.available).toBe(false); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -177,6 +210,7 @@ describe("AppleSpeechHelper", () => { }), ), ); + expect(yield* service.availability).toBe("unavailable"); expect(yield* service.available).toBe(false); expect(runs).toHaveLength(1); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), @@ -204,7 +238,6 @@ describe("AppleSpeechHelper", () => { const run = runs[1]!; expect(run.command).toBe(helperPath); expect(run.args).toEqual(["transcribe", "--locale", "en", wavPath]); - expect(Duration.toMillis(Duration.fromInputUnsafe(run.timeout!))).toBe(120_000); expect(yield* fileSystem.exists(wavPath)).toBe(false); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/voiceTranscription/AppleSpeechHelper.ts b/apps/server/src/voiceTranscription/AppleSpeechHelper.ts index 5e47c74aa526e..046c8603bdb6d 100644 --- a/apps/server/src/voiceTranscription/AppleSpeechHelper.ts +++ b/apps/server/src/voiceTranscription/AppleSpeechHelper.ts @@ -1,12 +1,14 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Ref from "effect/Ref"; +import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as NodeOS from "node:os"; @@ -18,6 +20,7 @@ const HELPER_NAME = "t3-apple-speech"; const MIN_DARWIN_MAJOR = 25; const PROBE_TIMEOUT = "10 seconds"; const PROBE_RETRY_DELAY = Duration.minutes(1); +const PROBE_RETRY_LIMIT = 5; // The first transcription in a language downloads its model through AssetInventory. const TRANSCRIBE_TIMEOUT_SECONDS = 120; const CAUSE_MAX_LENGTH = 300; @@ -86,11 +89,16 @@ class AppleSpeechProbeTimedOut extends Schema.TaggedError; + /** Waits for the first probe to answer. */ + readonly availability: Effect.Effect; readonly transcribe: (input: { readonly audio: Uint8Array; readonly locale: string; @@ -111,6 +119,10 @@ export const AppleSpeechHostKernelRelease = Context.Reference( const hostSupportsSpeechAnalyzer = (platform: NodeJS.Platform, kernelRelease: string) => platform === "darwin" && Number.parseInt(kernelRelease, 10) >= MIN_DARWIN_MAJOR; +/** The helper's stdout may hold the user's words, so a cause built from it records only its size. */ +const sizeOnlyCause = (stdout: string) => + new Error(`The helper printed ${stdout.length} bytes, not a transcript.`); + export const make = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const fileSystem = yield* FileSystem.FileSystem; @@ -123,8 +135,6 @@ export const make = Effect.gen(function* () { const candidates = [ environment.T3CODE_APPLE_SPEECH_PATH, config.appleSpeechHelperPath, - path.resolve(import.meta.dirname, "apple-speech", HELPER_NAME), - path.resolve(import.meta.dirname, "../apple-speech", HELPER_NAME), path.resolve(import.meta.dirname, "../../../../native/apple-speech/build", HELPER_NAME), path.resolve(import.meta.dirname, "../../../native/apple-speech/build", HELPER_NAME), ].filter((candidate): candidate is string => Boolean(candidate)); @@ -161,26 +171,38 @@ export const make = Effect.gen(function* () { return available ? Option.some(helperPath) : Option.none(); }); - let helper: Effect.Effect, AppleSpeechProbeTimedOut> = Effect.succeedNone; - if (hostSupportsSpeechAnalyzer(platform, kernelRelease)) { - helper = yield* Effect.cachedWithTTL( - locate.pipe( - Effect.flatMap(Option.match({ onNone: () => Effect.succeedNone, onSome: probe })), - ), - // A probe that hangs during a slow boot must not disable Apple transcription until restart. - (exit) => (Exit.isSuccess(exit) ? Duration.infinity : PROBE_RETRY_DELAY), - ); - // The startup sequence reads the environment descriptor, so the spawn - // starts now and overlaps the rest of startup instead of delaying it. - yield* Effect.forkScoped(Effect.ignore(helper)); + const hostSupported = hostSupportsSpeechAnalyzer(platform, kernelRelease); + const helperPath = yield* Ref.make(Option.none()); + const firstProbeAnswered = yield* Deferred.make(); + const locateOnce = yield* Effect.cached(locate); + + const probeInBackground = locateOnce.pipe( + Effect.flatMap(Option.match({ onNone: () => Effect.succeedNone, onSome: probe })), + Effect.flatMap((found) => Ref.set(helperPath, found)), + Effect.ensuring(Deferred.succeed(firstProbeAnswered, undefined)), + Effect.retry({ schedule: Schedule.spaced(PROBE_RETRY_DELAY), times: PROBE_RETRY_LIMIT }), + Effect.ignore({ log: true }), + ); + if (hostSupported) { + yield* Effect.forkScoped(probeInBackground); + } else { + yield* Deferred.succeed(firstProbeAnswered, undefined); } - const helperPath = helper.pipe(Effect.orElseSucceed(() => Option.none())); + + const answeredHelperPath = Deferred.await(firstProbeAnswered).pipe( + Effect.andThen(Ref.get(helperPath)), + ); + const availability: Effect.Effect = hostSupported + ? Effect.map(answeredHelperPath, (found) => + Option.isSome(found) ? "available" : "unavailable", + ) + : Effect.succeed("unsupported-host"); const transcribe = Effect.fn("AppleSpeechHelper.transcribe")(function* (input: { readonly audio: Uint8Array; readonly locale: string; }) { - const command = yield* helperPath; + const command = yield* answeredHelperPath; if (Option.isNone(command)) { return yield* new AppleSpeechHelperError({ reason: "unavailable" }); } @@ -223,18 +245,15 @@ export const make = Effect.gen(function* () { }); } return yield* Option.match(decodeTranscript(result.stdout), { - // The output may hold the user's words, so the cause records only its size. onNone: () => - new AppleSpeechHelperError({ - reason: "failed", - cause: new Error(`The helper printed ${result.stdout.length} bytes, not a transcript.`), - }), + new AppleSpeechHelperError({ reason: "failed", cause: sizeOnlyCause(result.stdout) }), onSome: Effect.succeed, }); }, Effect.scoped); return AppleSpeechHelper.of({ - available: Effect.map(helperPath, Option.isSome), + available: Effect.map(Ref.get(helperPath), Option.isSome), + availability, transcribe, }); }); @@ -245,6 +264,7 @@ export const layerUnavailable = Layer.succeed( AppleSpeechHelper, AppleSpeechHelper.of({ available: Effect.succeed(false), + availability: Effect.succeed("unavailable"), transcribe: () => new AppleSpeechHelperError({ reason: "unavailable" }), }), ); diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts index e8e4503c56c7a..5239296e3b07c 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -29,14 +29,22 @@ import * as VoiceTranscription from "./VoiceTranscription.ts"; const audio = new Uint8Array([1, 2, 3, 4, 5, 6]); -const appleSpeechUnavailable = AppleSpeechHelper.AppleSpeechHelper.of({ - available: Effect.succeed(false), - transcribe: () => Effect.die("the Apple speech helper is unavailable"), -}); +const appleSpeechWith = ( + availability: AppleSpeechHelper.AppleSpeechAvailability, + transcribe: AppleSpeechHelper.AppleSpeechHelper["Service"]["transcribe"] = () => + Effect.die("the Apple speech helper is unavailable"), +) => + AppleSpeechHelper.AppleSpeechHelper.of({ + available: Effect.succeed(availability === "available"), + availability: Effect.succeed(availability), + transcribe, + }); + +const appleSpeechUnavailable = appleSpeechWith("unsupported-host"); const appleSpeechAvailable = ( transcribe: AppleSpeechHelper.AppleSpeechHelper["Service"]["transcribe"], -) => AppleSpeechHelper.AppleSpeechHelper.of({ available: Effect.succeed(true), transcribe }); +) => appleSpeechWith("available", transcribe); function setup( settings: Partial, diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts index cdb343fc59bc5..3d84fbed06de8 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -244,7 +244,7 @@ type TranscriptionEndpoint = const resolveEndpoint = Effect.fn("VoiceTranscription.resolveEndpoint")(function* ( settings: VoiceTranscriptionSettings, - appleSpeechAvailable: Effect.Effect, + appleSpeechAvailability: Effect.Effect, ): Effect.fn.Return { const notConfigured = (message: string) => new VoiceTranscriptionNotConfiguredError({ message }); if (!settings.enabled) { @@ -252,7 +252,7 @@ const resolveEndpoint = Effect.fn("VoiceTranscription.resolveEndpoint")(function } const backend = PROVIDER_BACKENDS[settings.provider]; if (backend.kind === "apple") { - if (!(yield* appleSpeechAvailable)) { + if ((yield* appleSpeechAvailability) !== "available") { return yield* notConfigured( "Apple on-device transcription needs macOS 26 or later on the machine running T3 Code.", ); @@ -318,7 +318,7 @@ const make = Effect.gen(function* () { }), ), Effect.flatMap((settings) => - resolveEndpoint(settings.voiceTranscription, appleSpeech.available), + resolveEndpoint(settings.voiceTranscription, appleSpeech.availability), ), ); From 6997ff52479f2d509ede92f292103b3f42086c6a Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:16:45 -0400 Subject: [PATCH 24/55] fix(server): structured voice transcription errors with an internal failure code VoiceTranscriptionNotConfiguredError now carries a reason literal plus the provider name, MIME type, and locale, and derives its message, so the wording lives in one place for the RPC and the upload route. Upstream error text moves into the error's cause and the route's log, and no longer reaches the client message. A settings read failure answered 409 not_configured and a signing-key failure answered 400 invalid link. Both are now VoiceTranscriptionInternalError and the new internal failure code (HTTP 500), logged with their cause. Minting refused after a probe timeout or with no helper now says Apple on-device transcription is unavailable on the host, keeping the macOS 26 message for older hosts. A recording minted before the provider stopped accepting its format answers not_configured, like minting it would. The module now reads errors, schemas, the provider table, the tag, then make. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/assets/AttachmentUpload.ts | 1 - apps/server/src/http.ts | 58 +-- .../VoiceTranscription.test.ts | 108 ++++- .../voiceTranscription/VoiceTranscription.ts | 382 ++++++++---------- .../contracts/src/clientRpcPermissions.ts | 1 - packages/contracts/src/rpc.ts | 4 +- packages/contracts/src/voiceTranscription.ts | 59 ++- 7 files changed, 350 insertions(+), 263 deletions(-) diff --git a/apps/server/src/assets/AttachmentUpload.ts b/apps/server/src/assets/AttachmentUpload.ts index 51c2ecb29c7df..f50fdc3f0b1ef 100644 --- a/apps/server/src/assets/AttachmentUpload.ts +++ b/apps/server/src/assets/AttachmentUpload.ts @@ -64,7 +64,6 @@ function decodeClaims(encodedPayload: string): AttachmentUploadClaims | null { } } -/** Shared with voice transcription upload tokens; each token's `kind` keeps the two apart. */ export const loadUploadSigningSecret = Effect.gen(function* () { const secretStore = yield* ServerSecretStore.ServerSecretStore; return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 6444af7f729c4..8620ee8bfff83 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -504,6 +504,7 @@ const VOICE_TRANSCRIPTION_FAILURE_STATUS = { not_configured: 409, upstream_rejected_credentials: 502, upstream_failed: 502, + internal: 500, } as const satisfies Record; const voiceTranscriptionFailure = (code: VoiceTranscriptionFailureCode, message: string) => @@ -548,32 +549,37 @@ export const layerVoiceTranscriptionRoute = HttpRouter.add( return voiceTranscriptionFailure("invalid_upload", "Could not read the recording."); } - return yield* voiceTranscription.transcribe(claims.value, audio.value).pipe( - Effect.map((result) => - HttpServerResponse.jsonUnsafe(result, { headers: { "cache-control": "no-store" } }), - ), - Effect.catchTags({ - VoiceTranscriptionNotConfiguredError: (error) => - Effect.succeed(voiceTranscriptionFailure("not_configured", error.message)), - VoiceTranscriptionInvalidUploadError: (error) => - Effect.succeed(voiceTranscriptionFailure("invalid_upload", error.message)), - VoiceTranscriptionUnsupportedFormatError: (error) => - Effect.succeed(voiceTranscriptionFailure("invalid_upload", error.message)), - VoiceTranscriptionCredentialsRejectedError: (error) => - Effect.succeed(voiceTranscriptionFailure("upstream_rejected_credentials", error.message)), - VoiceTranscriptionUpstreamError: (error) => - Effect.logWarning("Voice transcription failed upstream.", { cause: error }).pipe( - Effect.as(voiceTranscriptionFailure("upstream_failed", error.message)), - ), - AppleSpeechUnsupportedLocaleError: (error) => - Effect.succeed(voiceTranscriptionFailure("not_configured", error.message)), - AppleSpeechHelperError: (error) => - Effect.logWarning("Voice transcription failed in the Apple speech helper.", { - cause: error, - }).pipe(Effect.as(voiceTranscriptionFailure("upstream_failed", error.message))), - }), - ); - }), + return yield* voiceTranscription + .transcribe(claims.value, audio.value) + .pipe( + Effect.map((result) => + HttpServerResponse.jsonUnsafe(result, { headers: { "cache-control": "no-store" } }), + ), + ); + }).pipe( + Effect.catchTags({ + VoiceTranscriptionNotConfiguredError: (error) => + Effect.succeed(voiceTranscriptionFailure("not_configured", error.message)), + VoiceTranscriptionInvalidUploadError: (error) => + Effect.succeed(voiceTranscriptionFailure("invalid_upload", error.message)), + VoiceTranscriptionInternalError: (error) => + Effect.succeed(voiceTranscriptionFailure("internal", error.message)), + VoiceTranscriptionCredentialsRejectedError: (error) => + Effect.logWarning("Voice transcription credentials were rejected upstream.", { + cause: error, + }).pipe( + Effect.as(voiceTranscriptionFailure("upstream_rejected_credentials", error.message)), + ), + VoiceTranscriptionUpstreamError: (error) => + Effect.logWarning("Voice transcription failed upstream.", { cause: error }).pipe( + Effect.as(voiceTranscriptionFailure("upstream_failed", error.message)), + ), + AppleSpeechHelperError: (error) => + Effect.logWarning("Voice transcription failed in the Apple speech helper.", { + cause: error, + }).pipe(Effect.as(voiceTranscriptionFailure("upstream_failed", error.message))), + }), + ), ); const decodeBuildManifest = Schema.decodeUnknownEffect( diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts index 5239296e3b07c..67ec0b1a79cbe 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -1,14 +1,16 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; -import type { - VoiceTranscriptionAudioMimeType, - VoiceTranscriptionSettings, +import { + ServerSettingsError, + type VoiceTranscriptionAudioMimeType, + type VoiceTranscriptionSettings, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as TestClock from "effect/testing/TestClock"; import { HttpClient, @@ -51,6 +53,10 @@ function setup( upstream: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect = () => Effect.succeed(Response.json({ text: "hello world" })), appleSpeech = appleSpeechUnavailable, + overrides: { + readonly settingsService?: Layer.Layer; + readonly secretStore?: Layer.Layer; + } = {}, ) { const requests: Array = []; const client = HttpClient.make((request) => @@ -61,13 +67,14 @@ function setup( ); const layer = VoiceTranscription.layer.pipe( Layer.provideMerge( - ServerSettings.layerTest({ - voiceTranscription: { enabled: true, apiKey: "sk-test", ...settings }, - }), + overrides.settingsService ?? + ServerSettings.layerTest({ + voiceTranscription: { enabled: true, apiKey: "sk-test", ...settings }, + }), ), Layer.provide(Layer.succeed(HttpClient.HttpClient, client)), Layer.provide(Layer.succeed(AppleSpeechHelper.AppleSpeechHelper, appleSpeech)), - Layer.provideMerge(ServerSecretStore.layer), + Layer.provideMerge(overrides.secretStore ?? ServerSecretStore.layer), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-voice-test-" })), Layer.provideMerge(NodeServices.layer), ); @@ -191,11 +198,21 @@ describe("VoiceTranscription", () => { { settings: { ...xai, apiKey: "" }, message: "xAI API key" }, { settings: xai, message: "xAI does not accept audio/webm recordings." }, { settings: apple, message: "Apple on-device transcription needs macOS 26 or later" }, + { + settings: apple, + appleSpeech: appleSpeechWith("unavailable"), + message: "Apple on-device transcription is unavailable on the machine running T3 Code.", + }, { settings: { model: "" }, message: "model name" }, { settings: { baseUrl: "" }, message: "endpoint URL" }, { settings: { baseUrl: "ftp://whisper.local" }, message: "not valid" }, - ] as const)("refuses to mint an upload URL when $message", ({ settings, message }) => { - const { layer } = setup(settings); + ] as const)("refuses to mint an upload URL when $message", (expected) => { + const { settings, message } = expected; + const { layer } = setup( + settings, + undefined, + "appleSpeech" in expected ? expected.appleSpeech : undefined, + ); return Effect.gen(function* () { const error = yield* Effect.flip(mint); expect(error._tag).toBe("VoiceTranscriptionNotConfiguredError"); @@ -351,11 +368,11 @@ describe("VoiceTranscription", () => { return Effect.gen(function* () { const issued = yield* mint; const settings = yield* ServerSettings.ServerSettingsService; - yield* settings.updateSettings({ voiceTranscription: xai }); + yield* settings.updateSettings({ voiceTranscription: { ...xai, apiKey: "sk-xai" } }); const response = yield* post(issued.relativeUrl); expect(response).toEqual({ - status: 400, - body: { code: "invalid_upload", message: "xAI does not accept audio/webm recordings." }, + status: 409, + body: { code: "not_configured", message: "xAI does not accept audio/webm recordings." }, }); expect(requests).toHaveLength(0); }).pipe(Effect.provide(layer)); @@ -368,37 +385,84 @@ describe("VoiceTranscription", () => { { status: 401 }, ), code: "upstream_rejected_credentials", - message: "api.openai.com rejected the API key (HTTP 401): Incorrect API key provided: [key].", + message: "The transcription service at api.openai.com rejected the API key (HTTP 401).", + cause: "Incorrect API key provided: [key].", }, { upstream: Response.json({ error: "model not loaded" }, { status: 500 }), code: "upstream_failed", - message: "api.openai.com answered HTTP 500: model not loaded", + message: "The transcription service at api.openai.com answered HTTP 500.", + cause: "model not loaded", }, { upstream: new Response("bad gateway", { status: 503 }), code: "upstream_failed", - message: "api.openai.com answered HTTP 503.", + message: "The transcription service at api.openai.com answered HTTP 503.", + cause: undefined, }, { upstream: Response.json({ transcript: "wrong shape" }), code: "upstream_failed", - message: "api.openai.com returned an unexpected response.", + message: "The transcription service at api.openai.com returned an unexpected response.", + cause: undefined, }, ])( "answers $code with a 502 for upstream HTTP $upstream.status", - ({ upstream, code, message }) => { - const { layer } = setup({}, () => Effect.succeed(upstream)); + ({ upstream, code, message, cause }) => { + const { layer } = setup({}, () => Effect.succeed(upstream.clone())); return Effect.gen(function* () { const response = yield* post((yield* mint).relativeUrl); - expect(response.status).toBe(502); - expect(response.body.code).toBe(code); - expect(response.body.message).toContain(message); - expect(JSON.stringify(response.body)).not.toContain("sk-test"); + expect(response).toEqual({ status: 502, body: { code, message } }); + + const voice = yield* VoiceTranscription.VoiceTranscription; + const token = (yield* mint).relativeUrl.split("/").at(-1)!; + const claims = Option.getOrThrow(yield* voice.verifyUploadToken(token)); + const error = yield* Effect.flip(voice.transcribe(claims, audio)); + if (cause !== undefined) { + expect(error.cause).toBeInstanceOf(Error); + expect((error.cause as Error).message).toBe(cause); + } }).pipe(Effect.provide(layer)); }, ); + it.effect("answers internal when the settings cannot be read", () => { + const { layer } = setup({}, undefined, undefined, { + settingsService: Layer.mock(ServerSettings.ServerSettingsService)({ + getSettings: Effect.fail( + new ServerSettingsError({ settingsPath: "settings.json", operation: "read-file" }), + ), + }), + }); + return Effect.gen(function* () { + const error = yield* Effect.flip(mint); + expect(error._tag).toBe("VoiceTranscriptionInternalError"); + expect(error.message).toBe("Voice transcription hit a server error."); + }).pipe(Effect.provide(layer)); + }); + + it.effect("answers internal instead of an invalid link when the signing key cannot load", () => { + const { layer, requests } = setup({}, undefined, undefined, { + secretStore: Layer.mock(ServerSecretStore.ServerSecretStore)({ + getOrCreateRandom: () => + Effect.fail( + new ServerSecretStore.SecretStoreReadError({ + resource: "upload signing key", + cause: new Error("disk unreadable"), + }), + ), + }), + }); + return Effect.gen(function* () { + const response = yield* post("/api/voice/transcriptions/payload.signature"); + expect(response).toEqual({ + status: 500, + body: { code: "internal", message: "Voice transcription hit a server error." }, + }); + expect(requests).toHaveLength(0); + }).pipe(Effect.provide(layer)); + }); + it.effect("answers upstream_failed when the service does not answer in time", () => Effect.gen(function* () { const reached = yield* Deferred.make(); diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts index 3d84fbed06de8..d862b5d9847e5 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -4,11 +4,12 @@ import { VoiceTranscriptionAudioMimeType, type VoiceTranscriptionCreateUrlInput, type VoiceTranscriptionCreateUrlResult, + VoiceTranscriptionInternalError, VoiceTranscriptionNotConfiguredError, + type VoiceTranscriptionNotConfiguredReason, type VoiceTranscriptionProvider, type VoiceTranscriptionResult, type VoiceTranscriptionSettings, - VoiceTranscriptionSigningKeyError, } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; @@ -35,6 +36,77 @@ export const VOICE_TRANSCRIPTION_ROUTE_PREFIX = "/api/voice/transcriptions"; const UPSTREAM_TIMEOUT_SECONDS = 90; const UPSTREAM_MESSAGE_MAX_LENGTH = 300; +export class VoiceTranscriptionInvalidUploadError extends Schema.TaggedError()( + "VoiceTranscriptionInvalidUploadError", + { + expectedBytes: Schema.Number, + receivedBytes: Schema.Number, + }, +) { + override get message(): string { + return `The recording was ${this.receivedBytes} bytes, expected ${this.expectedBytes}.`; + } +} + +export class VoiceTranscriptionCredentialsRejectedError extends Schema.TaggedError()( + "VoiceTranscriptionCredentialsRejectedError", + { + host: Schema.String, + status: Schema.Number, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return `The transcription service at ${this.host} rejected the API key (HTTP ${this.status}).`; + } +} + +export class VoiceTranscriptionUpstreamError extends Schema.TaggedError()( + "VoiceTranscriptionUpstreamError", + { + host: Schema.String, + stage: Schema.Literals(["request", "timeout", "status", "response"]), + status: Schema.optional(Schema.Number), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + switch (this.stage) { + case "request": + return `Could not reach the transcription service at ${this.host}.`; + case "timeout": + return `The transcription service at ${this.host} did not answer within ${UPSTREAM_TIMEOUT_SECONDS} seconds.`; + case "status": + return `The transcription service at ${this.host} answered HTTP ${this.status}.`; + case "response": + return `The transcription service at ${this.host} returned an unexpected response.`; + } + } +} + +const VoiceTranscriptionClaims = Schema.Struct({ + version: Schema.Literal(1), + kind: Schema.Literal("voice-transcription"), + mimeType: VoiceTranscriptionAudioMimeType, + sizeBytes: Schema.Number, + expiresAt: Schema.Number, +}); +export type VoiceTranscriptionClaims = typeof VoiceTranscriptionClaims.Type; + +const claimsJson = Schema.fromJsonString(VoiceTranscriptionClaims); +const decodeClaims = Schema.decodeUnknownOption(claimsJson); +const encodeClaims = Schema.encodeSync(claimsJson); + +const decodeTranscript = Schema.decodeUnknownEffect(Schema.Struct({ text: Schema.String })); +// OpenAI nests the message under `error`; some compatible servers send `error` as a plain string. +const decodeUpstreamError = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + error: Schema.Union([Schema.Struct({ message: Schema.String }), Schema.String]), + }), + ), +); + const AUDIO_FILE_EXTENSIONS = { "audio/webm": "webm", "audio/ogg": "ogg", @@ -109,98 +181,30 @@ const PROVIDER_BACKENDS = { }, } as const satisfies Record; -const VoiceTranscriptionClaims = Schema.Struct({ - version: Schema.Literal(1), - kind: Schema.Literal("voice-transcription"), - mimeType: VoiceTranscriptionAudioMimeType, - sizeBytes: Schema.Number, - expiresAt: Schema.Number, -}); -export type VoiceTranscriptionClaims = typeof VoiceTranscriptionClaims.Type; - -const claimsJson = Schema.fromJsonString(VoiceTranscriptionClaims); -const decodeClaims = Schema.decodeUnknownOption(claimsJson); -const encodeClaims = Schema.encodeSync(claimsJson); - -const decodeTranscript = Schema.decodeUnknownEffect(Schema.Struct({ text: Schema.String })); -// OpenAI nests the message under `error`; some compatible servers send `error` as a plain string. -const decodeUpstreamError = Schema.decodeUnknownOption( - Schema.fromJsonString( - Schema.Struct({ - error: Schema.Union([Schema.Struct({ message: Schema.String }), Schema.String]), - }), - ), -); - -export class VoiceTranscriptionInvalidUploadError extends Schema.TaggedError()( - "VoiceTranscriptionInvalidUploadError", - { - expectedBytes: Schema.Number, - receivedBytes: Schema.Number, - }, -) { - override get message(): string { - return `The recording was ${this.receivedBytes} bytes, expected ${this.expectedBytes}.`; - } -} - -export class VoiceTranscriptionUnsupportedFormatError extends Schema.TaggedError()( - "VoiceTranscriptionUnsupportedFormatError", - { - providerName: Schema.String, - mimeType: VoiceTranscriptionAudioMimeType, - }, -) { - override get message(): string { - return unsupportedFormatMessage(this.providerName, this.mimeType); - } -} +type HttpTranscriptionEndpoint = HttpProviderBackend & { + readonly url: string; + readonly host: string; + readonly model: string; + readonly language: string; + readonly apiKey: string; +}; -const unsupportedFormatMessage = ( - providerName: string, - mimeType: VoiceTranscriptionAudioMimeType, -) => `${providerName} does not accept ${mimeType} recordings.`; +type TranscriptionEndpoint = + | HttpTranscriptionEndpoint + | (AppleProviderBackend & { readonly language: string }); -export class VoiceTranscriptionCredentialsRejectedError extends Schema.TaggedError()( - "VoiceTranscriptionCredentialsRejectedError", - { - host: Schema.String, - status: Schema.Number, - upstreamMessage: Schema.optional(Schema.String), - }, -) { - override get message(): string { - return `The transcription service at ${this.host} rejected the API key (HTTP ${this.status})${ - this.upstreamMessage ? `: ${this.upstreamMessage}` : "." - }`; - } -} +const acceptsMimeType = (backend: ProviderBackend, mimeType: VoiceTranscriptionAudioMimeType) => + backend.acceptedMimeTypes.includes(mimeType); -export class VoiceTranscriptionUpstreamError extends Schema.TaggedError()( - "VoiceTranscriptionUpstreamError", - { - host: Schema.String, - stage: Schema.Literals(["request", "timeout", "status", "response"]), - status: Schema.optional(Schema.Number), - upstreamMessage: Schema.optional(Schema.String), - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - switch (this.stage) { - case "request": - return `Could not reach the transcription service at ${this.host}.`; - case "timeout": - return `The transcription service at ${this.host} did not answer within ${UPSTREAM_TIMEOUT_SECONDS} seconds.`; - case "status": - return `The transcription service at ${this.host} answered HTTP ${this.status}${ - this.upstreamMessage ? `: ${this.upstreamMessage}` : "." - }`; - case "response": - return `The transcription service at ${this.host} returned an unexpected response.`; - } - } -} +const orInternalError = + (stage: VoiceTranscriptionInternalError["stage"]) => + (effect: Effect.Effect) => + effect.pipe( + Effect.tapError((cause) => + Effect.logError("Voice transcription hit a server error.", { stage, cause }), + ), + Effect.mapError((cause) => new VoiceTranscriptionInternalError({ stage, cause })), + ); export class VoiceTranscription extends Context.Service< VoiceTranscription, @@ -209,11 +213,11 @@ export class VoiceTranscription extends Context.Service< input: VoiceTranscriptionCreateUrlInput, ) => Effect.Effect< VoiceTranscriptionCreateUrlResult, - VoiceTranscriptionNotConfiguredError | VoiceTranscriptionSigningKeyError + VoiceTranscriptionNotConfiguredError | VoiceTranscriptionInternalError >; readonly verifyUploadToken: ( token: string, - ) => Effect.Effect>; + ) => Effect.Effect, VoiceTranscriptionInternalError>; readonly transcribe: ( claims: VoiceTranscriptionClaims, audio: Uint8Array, @@ -221,82 +225,14 @@ export class VoiceTranscription extends Context.Service< VoiceTranscriptionResult, | VoiceTranscriptionNotConfiguredError | VoiceTranscriptionInvalidUploadError - | VoiceTranscriptionUnsupportedFormatError | VoiceTranscriptionCredentialsRejectedError | VoiceTranscriptionUpstreamError + | VoiceTranscriptionInternalError | AppleSpeechHelper.AppleSpeechHelperError - | AppleSpeechHelper.AppleSpeechUnsupportedLocaleError >; } >()("t3/voiceTranscription/VoiceTranscription") {} -type HttpTranscriptionEndpoint = HttpProviderBackend & { - readonly url: string; - readonly host: string; - readonly model: string; - readonly language: string; - readonly apiKey: string; -}; - -type TranscriptionEndpoint = - | HttpTranscriptionEndpoint - | (AppleProviderBackend & { readonly language: string }); - -const resolveEndpoint = Effect.fn("VoiceTranscription.resolveEndpoint")(function* ( - settings: VoiceTranscriptionSettings, - appleSpeechAvailability: Effect.Effect, -): Effect.fn.Return { - const notConfigured = (message: string) => new VoiceTranscriptionNotConfiguredError({ message }); - if (!settings.enabled) { - return yield* notConfigured("Voice transcription is turned off for this environment."); - } - const backend = PROVIDER_BACKENDS[settings.provider]; - if (backend.kind === "apple") { - if ((yield* appleSpeechAvailability) !== "available") { - return yield* notConfigured( - "Apple on-device transcription needs macOS 26 or later on the machine running T3 Code.", - ); - } - return { ...backend, language: settings.language }; - } - const baseUrl = settings.baseUrl.replace(/\/+$/, ""); - if (!baseUrl) return yield* notConfigured("Voice transcription needs an endpoint URL."); - if (!settings.model) return yield* notConfigured("Voice transcription needs a model name."); - // Local whisper.cpp-style servers take no key, but the hosted defaults always do. - if (!settings.apiKey && baseUrl === backend.hostedBaseUrl) { - return yield* notConfigured(`Add an ${backend.name} API key to use voice transcription.`); - } - const url = URL.parse(`${baseUrl}/${backend.path}`); - if (!url || (url.protocol !== "https:" && url.protocol !== "http:")) { - return yield* notConfigured("The voice transcription endpoint URL is not valid."); - } - return { - ...backend, - url: url.toString(), - host: url.host, - model: settings.model, - language: settings.language, - apiKey: settings.apiKey, - }; -}); - -const readUpstreamMessage = ( - response: HttpClientResponse.HttpClientResponse, - endpoint: HttpTranscriptionEndpoint, -) => - response.text.pipe( - Effect.map((body) => - Option.getOrUndefined( - Option.map(decodeUpstreamError(body), ({ error }) => { - const message = typeof error === "string" ? error : error.message; - const redacted = endpoint.apiKey ? message.replaceAll(endpoint.apiKey, "[key]") : message; - return redacted.slice(0, UPSTREAM_MESSAGE_MAX_LENGTH); - }), - ), - ), - Effect.orElseSucceed(() => undefined), - ); - const make = Effect.gen(function* () { const settingsService = yield* ServerSettings.ServerSettingsService; const secretStore = yield* ServerSecretStore.ServerSecretStore; @@ -305,35 +241,77 @@ const make = Effect.gen(function* () { const signingSecret = loadUploadSigningSecret.pipe( Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore), + orInternalError("load-signing-key"), ); - const loadEndpoint = settingsService.getSettings.pipe( - Effect.tapError((cause) => - Effect.logError("Failed to read voice transcription settings.", { cause }), - ), - Effect.mapError( - () => - new VoiceTranscriptionNotConfiguredError({ - message: "Could not read the voice transcription settings.", - }), - ), - Effect.flatMap((settings) => - resolveEndpoint(settings.voiceTranscription, appleSpeech.availability), - ), - ); + const resolveEndpoint = Effect.fn("VoiceTranscription.resolveEndpoint")(function* ( + settings: VoiceTranscriptionSettings, + ): Effect.fn.Return { + const backend = PROVIDER_BACKENDS[settings.provider]; + const notConfigured = (reason: VoiceTranscriptionNotConfiguredReason) => + new VoiceTranscriptionNotConfiguredError({ reason, providerName: backend.name }); + if (!settings.enabled) return yield* notConfigured("disabled"); + if (backend.kind === "apple") { + const availability = yield* appleSpeech.availability; + if (availability !== "available") { + return yield* notConfigured( + availability === "unsupported-host" ? "apple-unsupported-host" : "apple-unavailable", + ); + } + return { ...backend, language: settings.language }; + } + const baseUrl = settings.baseUrl.replace(/\/+$/, ""); + if (!baseUrl) return yield* notConfigured("missing-base-url"); + if (!settings.model) return yield* notConfigured("missing-model"); + if (!settings.apiKey && baseUrl === backend.hostedBaseUrl) { + return yield* notConfigured("missing-api-key"); + } + const url = URL.parse(`${baseUrl}/${backend.path}`); + if (!url || (url.protocol !== "https:" && url.protocol !== "http:")) { + return yield* notConfigured("invalid-base-url"); + } + return { + ...backend, + url: url.toString(), + host: url.host, + model: settings.model, + language: settings.language, + apiKey: settings.apiKey, + }; + }); - const createUploadUrl = Effect.fn("VoiceTranscription.createUploadUrl")(function* ( - input: VoiceTranscriptionCreateUrlInput, + const loadEndpoint = Effect.fn("VoiceTranscription.loadEndpoint")(function* ( + mimeType: VoiceTranscriptionAudioMimeType, ) { - const endpoint = yield* loadEndpoint; - if (!endpoint.acceptedMimeTypes.includes(input.mimeType)) { + const settings = yield* settingsService.getSettings.pipe(orInternalError("read-settings")); + const endpoint = yield* resolveEndpoint(settings.voiceTranscription); + if (!acceptsMimeType(endpoint, mimeType)) { return yield* new VoiceTranscriptionNotConfiguredError({ - message: unsupportedFormatMessage(endpoint.name, input.mimeType), + reason: "unsupported-format", + providerName: endpoint.name, + mimeType, }); } - const secret = yield* signingSecret.pipe( - Effect.mapError((cause) => new VoiceTranscriptionSigningKeyError({ cause })), - ); + return endpoint; + }); + + const readUpstreamCause = Effect.fn("VoiceTranscription.readUpstreamCause")(function* ( + response: HttpClientResponse.HttpClientResponse, + apiKey: string, + ) { + const body = yield* response.text.pipe(Effect.option); + const reported = Option.getOrUndefined(Option.flatMap(body, decodeUpstreamError)); + if (reported === undefined) return undefined; + const message = typeof reported.error === "string" ? reported.error : reported.error.message; + const redacted = apiKey ? message.replaceAll(apiKey, "[key]") : message; + return new Error(redacted.slice(0, UPSTREAM_MESSAGE_MAX_LENGTH)); + }); + + const createUploadUrl = Effect.fn("VoiceTranscription.createUploadUrl")(function* ( + input: VoiceTranscriptionCreateUrlInput, + ) { + yield* loadEndpoint(input.mimeType); + const secret = yield* signingSecret; const expiresAt = (yield* Clock.currentTimeMillis) + VOICE_TRANSCRIPTION_URL_TTL_MS; const encodedPayload = base64UrlEncode( encodeClaims({ @@ -357,16 +335,8 @@ const make = Effect.gen(function* () { if (!encodedPayload || !signature || unexpectedSegment !== undefined) { return Option.none(); } - const secret = yield* signingSecret.pipe( - Effect.tapError((cause) => - Effect.logError("Failed to load the voice transcription signing key.", { cause }), - ), - Effect.option, - ); - if ( - Option.isNone(secret) || - !timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret.value)) - ) { + const secret = yield* signingSecret; + if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) { return Option.none(); } const claims = Option.flatMap( @@ -387,16 +357,18 @@ const make = Effect.gen(function* () { receivedBytes: audio.byteLength, }); } - const endpoint = yield* loadEndpoint; - // The provider can change between minting and uploading. - if (!endpoint.acceptedMimeTypes.includes(claims.mimeType)) { - return yield* new VoiceTranscriptionUnsupportedFormatError({ - providerName: endpoint.name, - mimeType: claims.mimeType, - }); - } + const endpoint = yield* loadEndpoint(claims.mimeType); if (endpoint.kind === "apple") { - const { text } = yield* appleSpeech.transcribe({ audio, locale: endpoint.language }); + const { text } = yield* appleSpeech.transcribe({ audio, locale: endpoint.language }).pipe( + Effect.catchTags({ + AppleSpeechUnsupportedLocaleError: ({ locale }) => + new VoiceTranscriptionNotConfiguredError({ + reason: "unsupported-locale", + providerName: endpoint.name, + locale, + }), + }), + ); return { text } satisfies VoiceTranscriptionResult; } const upstreamError = ( @@ -420,19 +392,17 @@ const make = Effect.gen(function* () { .execute(request) .pipe(Effect.mapError((cause) => upstreamError({ stage: "request", cause }))); if (response.status === 401 || response.status === 403) { - const upstreamMessage = yield* readUpstreamMessage(response, endpoint); return yield* new VoiceTranscriptionCredentialsRejectedError({ host: endpoint.host, status: response.status, - ...(upstreamMessage ? { upstreamMessage } : {}), + cause: yield* readUpstreamCause(response, endpoint.apiKey), }); } if (response.status < 200 || response.status >= 300) { - const upstreamMessage = yield* readUpstreamMessage(response, endpoint); return yield* upstreamError({ stage: "status", status: response.status, - ...(upstreamMessage ? { upstreamMessage } : {}), + cause: yield* readUpstreamCause(response, endpoint.apiKey), }); } const { text } = yield* response.json.pipe( diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index a24cf48e43a1a..ab28898ad5d54 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -43,7 +43,6 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.vcsSwitchRef]: AuthSourceControlWriteScope, [WS_METHODS.vcsInit]: AuthSourceControlWriteScope, - // Transcribing spends this environment's speech-to-text credentials. [WS_METHODS.voiceCreateTranscriptionUrl]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksUpsert]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 81ed208831112..737c2d7ad5c15 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -104,8 +104,8 @@ import { import { VoiceTranscriptionCreateUrlInput, VoiceTranscriptionCreateUrlResult, + VoiceTranscriptionInternalError, VoiceTranscriptionNotConfiguredError, - VoiceTranscriptionSigningKeyError, } from "./voiceTranscription.ts"; import { PersistChatAttachmentsError, @@ -1322,7 +1322,7 @@ const WsVoiceCreateTranscriptionUrlRpc = Rpc.make(WS_METHODS.voiceCreateTranscri success: VoiceTranscriptionCreateUrlResult, error: Schema.Union([ VoiceTranscriptionNotConfiguredError, - VoiceTranscriptionSigningKeyError, + VoiceTranscriptionInternalError, EnvironmentAuthorizationError, ]), }); diff --git a/packages/contracts/src/voiceTranscription.ts b/packages/contracts/src/voiceTranscription.ts index 4be7fd99ec798..a29442ce013bd 100644 --- a/packages/contracts/src/voiceTranscription.ts +++ b/packages/contracts/src/voiceTranscription.ts @@ -42,6 +42,7 @@ export const VoiceTranscriptionFailureCode = Schema.Literals([ "invalid_upload", "upstream_rejected_credentials", "upstream_failed", + "internal", ]); export type VoiceTranscriptionFailureCode = typeof VoiceTranscriptionFailureCode.Type; @@ -52,20 +53,68 @@ export const VoiceTranscriptionFailure = Schema.Struct({ }); export type VoiceTranscriptionFailure = typeof VoiceTranscriptionFailure.Type; +export const VoiceTranscriptionNotConfiguredReason = Schema.Literals([ + "disabled", + "missing-base-url", + "missing-model", + "missing-api-key", + "invalid-base-url", + "insecure-base-url", + "apple-unsupported-host", + "apple-unavailable", + "unsupported-format", + "unsupported-locale", +]); +export type VoiceTranscriptionNotConfiguredReason = + typeof VoiceTranscriptionNotConfiguredReason.Type; + export class VoiceTranscriptionNotConfiguredError extends Schema.TaggedError()( "VoiceTranscriptionNotConfiguredError", { - message: Schema.String, + reason: VoiceTranscriptionNotConfiguredReason, + providerName: Schema.String, + mimeType: Schema.optional(VoiceTranscriptionAudioMimeType), + locale: Schema.optional(Schema.String), }, -) {} +) { + override get message(): string { + switch (this.reason) { + case "disabled": + return "Voice transcription is turned off for this environment."; + case "missing-base-url": + return "Voice transcription needs an endpoint URL."; + case "missing-model": + return "Voice transcription needs a model name."; + case "missing-api-key": + return `Add an ${this.providerName} API key to use voice transcription.`; + case "invalid-base-url": + return "The voice transcription endpoint URL is not valid."; + case "insecure-base-url": + return "Voice transcription sends an API key only over https, unless the endpoint is on this machine or a private network."; + case "apple-unsupported-host": + return "Apple on-device transcription needs macOS 26 or later on the machine running T3 Code."; + case "apple-unavailable": + return "Apple on-device transcription is unavailable on the machine running T3 Code."; + case "unsupported-format": + return this.mimeType + ? `${this.providerName} does not accept ${this.mimeType} recordings.` + : `${this.providerName} does not accept this recording format.`; + case "unsupported-locale": + return this.locale + ? `${this.providerName} does not support the language '${this.locale}'.` + : `${this.providerName} does not support this Mac's system language.`; + } + } +} -export class VoiceTranscriptionSigningKeyError extends Schema.TaggedError()( - "VoiceTranscriptionSigningKeyError", +export class VoiceTranscriptionInternalError extends Schema.TaggedError()( + "VoiceTranscriptionInternalError", { + stage: Schema.Literals(["read-settings", "load-signing-key"]), cause: Schema.Defect(), }, ) { override get message(): string { - return "Failed to load the voice transcription signing key."; + return "Voice transcription hit a server error."; } } From 7e0efe9e1cc4b1d5e3f0b4edf555e69af1edb963 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:18:08 -0400 Subject: [PATCH 25/55] fix(server): accept each voice upload link once and keep it out of traces The capability URL could be posted again until it expired, and its token reached request traces. The route is now on the untraced path list beside the webhook routes, and the service remembers each accepted signature until its expiry, so a second POST answers 400 invalid_upload. Each link carries a nonce so two identical recordings minted in the same millisecond stay distinct. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/http.ts | 8 ++- .../VoiceTranscription.test.ts | 52 +++++++++++++++++-- .../voiceTranscription/VoiceTranscription.ts | 16 +++++- 3 files changed, 68 insertions(+), 8 deletions(-) diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 8620ee8bfff83..6e61626dc2f08 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -401,8 +401,12 @@ const UNTRACED_REQUEST_PATHS: ReadonlySet = new Set([OTLP_TRACES_PROXY_P const layerUntracedRequests = Layer.succeed(HttpMiddleware.TracerDisabledWhen)((request) => { const queryIndex = request.url.indexOf("?"); const path = queryIndex === -1 ? request.url : request.url.slice(0, queryIndex); - // Webhook URLs carry their secret token in the path, so they never reach a trace. - return UNTRACED_REQUEST_PATHS.has(path) || path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`); + // Webhook and voice upload URLs carry their secret token in the path, so they never reach a trace. + return ( + UNTRACED_REQUEST_PATHS.has(path) || + path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`) || + path.startsWith(`${VoiceTranscription.VOICE_TRANSCRIPTION_ROUTE_PREFIX}/`) + ); }); export const withUntracedRequests = Layer.provide(layerUntracedRequests); diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts index 67ec0b1a79cbe..d270100b3e5d8 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -16,6 +16,7 @@ import { HttpClient, type HttpClientRequest, HttpClientResponse, + HttpMiddleware, HttpRouter, HttpServerRequest, HttpServerResponse, @@ -149,6 +150,7 @@ describe("VoiceTranscription", () => { Effect.succeedSome({ version: 1, kind: "voice-transcription", + nonce: "nonce", mimeType: "audio/webm", sizeBytes: audio.byteLength, expiresAt: Number.MAX_SAFE_INTEGER, @@ -488,7 +490,6 @@ describe("VoiceTranscription", () => { () => { const { layer, requests } = setup({}); return Effect.gen(function* () { - const issued = yield* mint; const attachment = yield* issueAttachmentUploadUrl({ type: "file", name: "audio.webm", @@ -497,16 +498,17 @@ describe("VoiceTranscription", () => { }); const attachmentToken = attachment.relativeUrl.split("/").at(-1)!; const rejected = [ - yield* post(`${issued.relativeUrl}x`), + yield* post(`${(yield* mint).relativeUrl}x`), yield* post(`/api/voice/transcriptions/${attachmentToken}`), - yield* post(issued.relativeUrl, { contentLength: audio.byteLength + 1 }), - yield* post(issued.relativeUrl, { + yield* post((yield* mint).relativeUrl, { contentLength: audio.byteLength + 1 }), + yield* post((yield* mint).relativeUrl, { body: audio.slice(1), contentLength: audio.byteLength - 1, }), ]; + const expiring = yield* mint; yield* TestClock.adjust("2 minutes"); - rejected.push(yield* post(issued.relativeUrl)); + rejected.push(yield* post(expiring.relativeUrl)); for (const response of rejected) { expect(response.status).toBe(400); @@ -517,6 +519,46 @@ describe("VoiceTranscription", () => { }, ); + it.effect("accepts each upload link once", () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + const issued = yield* mint; + expect((yield* post(issued.relativeUrl)).status).toBe(200); + expect(yield* post(issued.relativeUrl)).toEqual({ + status: 400, + body: { + code: "invalid_upload", + message: "This transcription link is invalid or has expired.", + }, + }); + expect((yield* post((yield* mint).relativeUrl)).status).toBe(200); + expect(requests).toHaveLength(2); + }).pipe(Effect.provide(layer)); + }); + + it.effect("keeps upload links out of traces", () => + Effect.gen(function* () { + const traced = yield* Deferred.make<(path: string) => boolean>(); + yield* Layer.build( + ServerHttp.withUntracedRequests( + Layer.effectDiscard( + Effect.gen(function* () { + const disabled = yield* HttpMiddleware.TracerDisabledWhen; + yield* Deferred.succeed( + traced, + (path) => + !disabled(HttpServerRequest.fromWeb(new Request(`http://t3.test${path}`))), + ); + }), + ), + ), + ); + const isTraced = yield* Deferred.await(traced); + expect(isTraced("/api/voice/transcriptions/payload.signature")).toBe(false); + expect(isTraced("/api/attachments/upload/payload.signature")).toBe(true); + }).pipe(Effect.scoped), + ); + it.effect("answers not_configured when transcription is turned off after minting", () => { const { layer, requests } = setup({}); return Effect.gen(function* () { diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts index d862b5d9847e5..cab86c84b6719 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -13,10 +13,12 @@ import { } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import { identity } from "effect/Function"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http"; @@ -87,6 +89,8 @@ export class VoiceTranscriptionUpstreamError extends Schema.TaggedError()); const signingSecret = loadUploadSigningSecret.pipe( Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore), @@ -317,6 +323,7 @@ const make = Effect.gen(function* () { encodeClaims({ version: 1, kind: "voice-transcription", + nonce: yield* crypto.randomUUIDv4().pipe(Effect.orDie), mimeType: input.mimeType, sizeBytes: input.sizeBytes, expiresAt, @@ -344,7 +351,14 @@ const make = Effect.gen(function* () { decodeClaims, ); const nowMs = yield* Clock.currentTimeMillis; - return Option.filter(claims, (decoded) => decoded.expiresAt > nowMs); + if (Option.isNone(claims) || claims.value.expiresAt <= nowMs) return Option.none(); + const firstUse = yield* Ref.modify(consumedSignatures, (consumed) => { + const live = new Map([...consumed].filter(([, expiresAt]) => expiresAt > nowMs)); + if (live.has(signature)) return [false, live]; + live.set(signature, claims.value.expiresAt); + return [true, live]; + }); + return firstUse ? claims : Option.none(); }); const transcribe = Effect.fn("VoiceTranscription.transcribe")(function* ( From ee75ec26681c207d4cfdb584c789df98e367811a Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:18:35 -0400 Subject: [PATCH 26/55] fix(server): refuse to send the voice transcription key over public http An http: base URL sent the bearer key in cleartext to any host. A key now goes over http only to a loopback, private, link-local, or .local endpoint, which covers a whisper.cpp server on the same machine or network. A keyless http endpoint stays allowed anywhere. Co-Authored-By: Claude Opus 5.5 --- .../VoiceTranscription.test.ts | 22 +++++++++++++++++++ .../voiceTranscription/VoiceTranscription.ts | 4 ++++ 2 files changed, 26 insertions(+) diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts index d270100b3e5d8..caf512ed302e4 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -208,6 +208,7 @@ describe("VoiceTranscription", () => { { settings: { model: "" }, message: "model name" }, { settings: { baseUrl: "" }, message: "endpoint URL" }, { settings: { baseUrl: "ftp://whisper.local" }, message: "not valid" }, + { settings: { baseUrl: "http://api.example.com/v1" }, message: "only over https" }, ] as const)("refuses to mint an upload URL when $message", (expected) => { const { settings, message } = expected; const { layer } = setup( @@ -251,6 +252,27 @@ describe("VoiceTranscription", () => { }).pipe(Effect.provide(layer)); }); + it.effect.each([ + { baseUrl: "http://localhost:8080/v1", apiKey: "sk-test" }, + { baseUrl: "http://127.0.0.2:8080/v1", apiKey: "sk-test" }, + { baseUrl: "http://[::1]:8080/v1", apiKey: "sk-test" }, + { baseUrl: "http://192.168.1.20/v1", apiKey: "sk-test" }, + { baseUrl: "http://10.0.0.5/v1", apiKey: "sk-test" }, + { baseUrl: "http://172.20.0.5/v1", apiKey: "sk-test" }, + { baseUrl: "http://169.254.10.1/v1", apiKey: "sk-test" }, + { baseUrl: "http://[fd12::5]/v1", apiKey: "sk-test" }, + { baseUrl: "http://gpu-box.local/v1", apiKey: "sk-test" }, + { baseUrl: "http://api.example.com/v1", apiKey: "" }, + ])("allows http to a private endpoint, or anywhere without a key: $baseUrl", (settings) => { + const { layer, requests } = setup({ ...settings, model: "whisper-1" }); + return Effect.gen(function* () { + expect((yield* post((yield* mint).relativeUrl)).status).toBe(200); + expect(requests[0]!.headers.authorization).toBe( + settings.apiKey ? `Bearer ${settings.apiKey}` : undefined, + ); + }).pipe(Effect.provide(layer)); + }); + it.effect.each([ { language: "fr", languages: ["fr"] }, { language: "", languages: [] }, diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts index cab86c84b6719..ec378059dc28f 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -11,6 +11,7 @@ import { type VoiceTranscriptionResult, type VoiceTranscriptionSettings, } from "@t3tools/contracts"; +import { isPrivateNetworkHost } from "@t3tools/shared/hostClassification"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; @@ -276,6 +277,9 @@ const make = Effect.gen(function* () { if (!url || (url.protocol !== "https:" && url.protocol !== "http:")) { return yield* notConfigured("invalid-base-url"); } + if (url.protocol === "http:" && settings.apiKey && !isPrivateNetworkHost(url.hostname)) { + return yield* notConfigured("insecure-base-url"); + } return { ...backend, url: url.toString(), From 347a6aff3041866c00d1c17e554a6383aa095ae0 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:19:41 -0400 Subject: [PATCH 27/55] fix(server): cap voice transcription upstream responses at 1 MiB The transcript and error bodies were read whole, so a misbehaving endpoint could make the server buffer an unbounded response. Both reads now stop past 1 MiB and answer upstream_failed. Co-Authored-By: Claude Opus 5.5 --- .../VoiceTranscription.test.ts | 33 +++++++++++++++ .../voiceTranscription/VoiceTranscription.ts | 40 +++++++++++++++++-- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts index caf512ed302e4..1ea36f272fa95 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -450,6 +450,39 @@ describe("VoiceTranscription", () => { }, ); + it.effect.each([200, 500])("stops reading an upstream HTTP %s body past 1 MiB", (status) => { + const chunk = new Uint8Array(64 * 1024).fill(0x61); + let sentBytes = 0; + const { layer } = setup({}, () => + Effect.succeed( + new Response( + new ReadableStream({ + pull: (controller) => { + if (sentBytes > 2 * 1024 * 1024) return new Promise(() => {}); + sentBytes += chunk.byteLength; + controller.enqueue(chunk); + }, + }), + { status }, + ), + ), + ); + return Effect.gen(function* () { + const response = yield* post((yield* mint).relativeUrl); + expect(response).toEqual({ + status: 502, + body: { + code: "upstream_failed", + message: + status === 200 + ? "The transcription service at api.openai.com returned an unexpected response." + : "The transcription service at api.openai.com answered HTTP 500.", + }, + }); + expect(sentBytes).toBeLessThan(2 * 1024 * 1024); + }).pipe(Effect.provide(layer)); + }); + it.effect("answers internal when the settings cannot be read", () => { const { layer } = setup({}, undefined, undefined, { settingsService: Layer.mock(ServerSettings.ServerSettingsService)({ diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts index ec378059dc28f..9da119b4921f7 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -21,6 +21,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http"; import { loadUploadSigningSecret } from "../assets/AttachmentUpload.ts"; @@ -38,6 +39,7 @@ export const VOICE_TRANSCRIPTION_ROUTE_PREFIX = "/api/voice/transcriptions"; const UPSTREAM_TIMEOUT_SECONDS = 90; const UPSTREAM_MESSAGE_MAX_LENGTH = 300; +const UPSTREAM_BODY_MAX_BYTES = 1024 * 1024; export class VoiceTranscriptionInvalidUploadError extends Schema.TaggedError()( "VoiceTranscriptionInvalidUploadError", @@ -87,6 +89,17 @@ export class VoiceTranscriptionUpstreamError extends Schema.TaggedError()( + "VoiceTranscriptionUpstreamBodyTooLargeError", + { + maxBytes: Schema.Number, + }, +) { + override get message(): string { + return `The transcription service answered with more than ${this.maxBytes} bytes.`; + } +} + const VoiceTranscriptionClaims = Schema.Struct({ version: Schema.Literal(1), kind: Schema.Literal("voice-transcription"), @@ -102,7 +115,9 @@ const claimsJson = Schema.fromJsonString(VoiceTranscriptionClaims); const decodeClaims = Schema.decodeUnknownOption(claimsJson); const encodeClaims = Schema.encodeSync(claimsJson); -const decodeTranscript = Schema.decodeUnknownEffect(Schema.Struct({ text: Schema.String })); +const decodeTranscript = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ text: Schema.String })), +); // OpenAI nests the message under `error`; some compatible servers send `error` as a plain string. const decodeUpstreamError = Schema.decodeUnknownOption( Schema.fromJsonString( @@ -305,11 +320,30 @@ const make = Effect.gen(function* () { return endpoint; }); + const readUpstreamText = Effect.fn("VoiceTranscription.readUpstreamText")(function* ( + response: HttpClientResponse.HttpClientResponse, + ) { + const decoder = new TextDecoder(); + let text = ""; + let receivedBytes = 0; + yield* Stream.runForEach(response.stream, (chunk) => { + receivedBytes += chunk.byteLength; + if (receivedBytes > UPSTREAM_BODY_MAX_BYTES) { + return new VoiceTranscriptionUpstreamBodyTooLargeError({ + maxBytes: UPSTREAM_BODY_MAX_BYTES, + }); + } + text += decoder.decode(chunk, { stream: true }); + return Effect.void; + }); + return text + decoder.decode(); + }); + const readUpstreamCause = Effect.fn("VoiceTranscription.readUpstreamCause")(function* ( response: HttpClientResponse.HttpClientResponse, apiKey: string, ) { - const body = yield* response.text.pipe(Effect.option); + const body = yield* readUpstreamText(response).pipe(Effect.option); const reported = Option.getOrUndefined(Option.flatMap(body, decodeUpstreamError)); if (reported === undefined) return undefined; const message = typeof reported.error === "string" ? reported.error : reported.error.message; @@ -423,7 +457,7 @@ const make = Effect.gen(function* () { cause: yield* readUpstreamCause(response, endpoint.apiKey), }); } - const { text } = yield* response.json.pipe( + const { text } = yield* readUpstreamText(response).pipe( Effect.flatMap(decodeTranscript), Effect.mapError((cause) => upstreamError({ stage: "response", cause })), ); From 4525b056b050ce37b4a99d4edd5721afe880153b Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:19:45 -0400 Subject: [PATCH 28/55] fix(voice): keep a failed recording for retry and report refused commits A transcription that fails after the recording succeeded no longer throws the audio away. The controller holds the recording URI behind a new `retry-transcription` error action, re-sends the same audio from `retryTranscription()`, and deletes it on cancel, dispose, owner change, or a fresh start, so audio is never kept past the next user action. Mobile keeps its behaviour: its start path always records anew. `commitDraft` now reports whether the draft took the text. The web composer returns `applyPromptReplacement`'s result, so a transcript that a choice-only agent question refuses surfaces as "draft changed" instead of vanishing. The composer also folds the pending request and question identity into the voice owner key, so a question taking over the composer cancels the recording that started on the draft. Recorder dependencies can throw `VoiceRecorderError` to show their own message in place of the generic start failure. Co-Authored-By: Claude Fable 5.1 --- .../voice-input/lazyVoiceRecorder.test.ts | 2 +- .../features/voice-input/voiceInputSession.ts | 8 +- apps/web/src/components/chat/ChatComposer.tsx | 18 +- .../components/chat/useComposerVoiceInput.ts | 3 +- .../src/voice-input/controller.test.ts | 121 ++++++++- .../src/voice-input/controller.ts | 248 +++++++++++++----- .../client-runtime/src/voice-input/index.ts | 1 + 7 files changed, 324 insertions(+), 77 deletions(-) diff --git a/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts b/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts index d3236bc7c992b..5c5ac1c168bfc 100644 --- a/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts +++ b/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts @@ -94,7 +94,7 @@ describe("createLazyVoiceRecorder", () => { selection: { start: 0, end: 0 }, revision: 0, }), - commitDraft: () => undefined, + commitDraft: () => true, onStateChange: () => undefined, }); return { ...harness, controller, deleted }; diff --git a/apps/mobile/src/features/voice-input/voiceInputSession.ts b/apps/mobile/src/features/voice-input/voiceInputSession.ts index 372c1081d6747..14d3fe1085b84 100644 --- a/apps/mobile/src/features/voice-input/voiceInputSession.ts +++ b/apps/mobile/src/features/voice-input/voiceInputSession.ts @@ -9,7 +9,7 @@ export type VoiceInputTarget = { readonly ownerKey: string; readonly label?: string; readonly readDraft: () => VoiceDraftSnapshot | null; - readonly commitDraft: VoiceInputControllerDependencies["commitDraft"]; + readonly commitDraft: (text: string, selection: VoiceDraftSnapshot["selection"]) => void; readonly subscribe: () => () => void; }; @@ -58,7 +58,11 @@ export class VoiceInputSession { dependencies.onStateChange(state); }, readDraft: () => this.target?.readDraft() ?? null, - commitDraft: (text, selection) => this.target?.commitDraft(text, selection), + commitDraft: (text, selection) => { + if (!this.target) return false; + this.target.commitDraft(text, selection); + return true; + }, }); } diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 651dcfc12fbe6..210c890a26c5b 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2096,16 +2096,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // the React Compiler rejects a closure that captures a const declared later. The // layout effect below that declaration fills this in. const voiceCommitRef = useRef< - ((text: string, selection: { readonly start: number; readonly end: number }) => void) | null + ((text: string, selection: { readonly start: number; readonly end: number }) => boolean) | null >(null); const commitVoiceDraftStable = useStableCallback( - (text: string, selection: { readonly start: number; readonly end: number }) => { - voiceCommitRef.current?.(text, selection); - }, + (text: string, selection: { readonly start: number; readonly end: number }) => + voiceCommitRef.current?.(text, selection) ?? false, ); + // A pending question swaps the composer's text for its answer, so a recording that + // started on the draft must not land there. + const voiceOwnerKey = + pendingUserInputs[0] && activePendingProgress?.activeQuestion + ? `${composerDraftTargetKey}:${pendingUserInputs[0].requestId}:${activePendingProgress.activeQuestion.id}` + : composerDraftTargetKey; const voiceInput = useComposerVoiceInput({ environmentId, - ownerKey: composerDraftTargetKey, + ownerKey: voiceOwnerKey, language: settings.voiceTranscription.language, draftText: prompt, readDraft: readVoiceDraftStable, @@ -3826,11 +3831,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const applyPromptReplacementStable = useStableCallback(applyPromptReplacement); useLayoutEffect(() => { - voiceCommitRef.current = (text, selection) => { + voiceCommitRef.current = (text, selection) => applyPromptReplacement(0, promptRef.current.length, text, { expandedCursorAfterReplace: selection.start, }); - }; }); const readComposerSnapshot = (): { diff --git a/apps/web/src/components/chat/useComposerVoiceInput.ts b/apps/web/src/components/chat/useComposerVoiceInput.ts index 6ad3af473f77f..c27c0df91d23a 100644 --- a/apps/web/src/components/chat/useComposerVoiceInput.ts +++ b/apps/web/src/components/chat/useComposerVoiceInput.ts @@ -19,7 +19,8 @@ export interface ComposerVoiceInputInput { readonly language: string; readonly draftText: string; readonly readDraft: () => Omit; - readonly commitDraft: (text: string, selection: VoiceDraftSnapshot["selection"]) => void; + /** False when the composer refused the text, for example while a choice-only question owns it. */ + readonly commitDraft: (text: string, selection: VoiceDraftSnapshot["selection"]) => boolean; } export interface ComposerVoiceInput { diff --git a/packages/client-runtime/src/voice-input/controller.test.ts b/packages/client-runtime/src/voice-input/controller.test.ts index d433748e5bdbb..e6078af97f735 100644 --- a/packages/client-runtime/src/voice-input/controller.test.ts +++ b/packages/client-runtime/src/voice-input/controller.test.ts @@ -4,6 +4,7 @@ import { resetVoiceInputGlobalsForTests, resolveTranscriptCommit, VoiceInputController, + VoiceRecorderError, VOICE_RECORDING_LIMIT_SECONDS, type VoiceDraftSnapshot, type VoiceInputControllerDependencies, @@ -60,7 +61,10 @@ function createHarness( releaseRecording: async () => undefined, deleteRecording: (uri) => deleted.push(uri), readDraft: () => currentDraft, - commitDraft: (text, selection) => commits.push({ text, selection }), + commitDraft: (text, selection) => { + commits.push({ text, selection }); + return true; + }, onStateChange: vi.fn(), ...overrides, }; @@ -144,7 +148,7 @@ describe("VoiceInputController", () => { expect(harness.controller.currentState).toMatchObject({ phase: "error", error: expect.any(String), - errorAction: failure === "permission" ? "settings" : "retry", + errorAction: failure === "permission" ? "settings" : "retry-transcription", }); harness.setDraft(draft({ ownerKey: "environment:other-thread" })); @@ -156,9 +160,122 @@ describe("VoiceInputController", () => { errorAction: null, }); expect(harness.commits).toEqual([]); + if (failure === "transcription") expect(harness.deleted).toEqual(["file:///voice.m4a"]); }, ); + it("keeps the recording after transcription fails and sends the same audio on retry", async () => { + const transcribe = vi + .fn() + .mockRejectedValueOnce(new Error("Upload failed")) + .mockResolvedValue("new text"); + const prepare = vi.fn(async () => preparedTranscription(transcribe)); + const harness = createHarness({ getTranscriber: () => ({ prepare }) }); + await harness.controller.start(); + await harness.controller.stop(); + expect(harness.controller.currentState).toMatchObject({ + phase: "error", + errorAction: "retry-transcription", + }); + expect(harness.deleted).toEqual([]); + + await harness.controller.retryTranscription(); + + expect(transcribe.mock.calls.map(([uri]) => uri)).toEqual([ + "file:///voice.m4a", + "file:///voice.m4a", + ]); + expect(prepare).toHaveBeenCalledTimes(2); + expect(harness.recorder.record).toHaveBeenCalledTimes(1); + expect(harness.commits).toEqual([ + { text: "hello new text", selection: { start: 14, end: 14 } }, + ]); + expect(harness.controller.currentState.phase).toBe("idle"); + expect(harness.deleted).toEqual(["file:///voice.m4a"]); + }); + + it("keeps holding the recording when the retried transcription fails again", async () => { + const harness = createHarness({ + getTranscriber: () => ({ + prepare: async () => + preparedTranscription(async () => { + throw new Error("Upload failed"); + }), + }), + }); + await harness.controller.start(); + await harness.controller.stop(); + await harness.controller.retryTranscription(); + + expect(harness.controller.currentState.errorAction).toBe("retry-transcription"); + expect(harness.deleted).toEqual([]); + harness.controller.cancel(); + expect(harness.deleted).toEqual(["file:///voice.m4a"]); + }); + + it.each(["cancel", "dispose", "start"] as const)( + "deletes a kept recording on %s instead of keeping audio around", + async (action) => { + const harness = createHarness({ + getTranscriber: () => ({ + prepare: async () => + preparedTranscription(async () => { + throw new Error("Upload failed"); + }), + }), + }); + await harness.controller.start(); + await harness.controller.stop(); + expect(harness.deleted).toEqual([]); + + await harness.controller[action](); + + expect(harness.deleted[0]).toBe("file:///voice.m4a"); + if (action === "start") { + expect(harness.controller.currentState.phase).toBe("recording"); + expect(harness.recorder.record).toHaveBeenCalledTimes(2); + await harness.controller.interruptRecording(); + } else if (action === "cancel") { + expect(harness.controller.currentState.phase).toBe("idle"); + } + }, + ); + + it("reports a refused commit as a changed draft and discards the recording", async () => { + const harness = createHarness({ commitDraft: () => false }); + await harness.controller.start(); + await harness.controller.stop(); + + expect(harness.controller.currentState).toMatchObject({ + phase: "error", + error: expect.stringContaining("draft changed"), + errorAction: "retry", + }); + expect(harness.deleted).toEqual(["file:///voice.m4a"]); + }); + + it("shows the recorder's own message when the microphone cannot start", async () => { + const harness = createHarness({ + requestPermission: async () => { + throw new VoiceRecorderError("No microphone was found."); + }, + }); + await harness.controller.start(); + expect(harness.controller.currentState).toEqual({ + phase: "error", + error: "No microphone was found.", + errorAction: "retry", + }); + + const opaque = createHarness({ + requestPermission: async () => { + throw new Error("boom"); + }, + }); + await opaque.controller.start(); + expect(opaque.controller.currentState.error).toBe("Could not start voice recording."); + }); + it.each(["permission", "preparation", "recording"] as const)( "keeps the selected transcriber when preferences change during %s", async (changeDuring) => { diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index 7e7e6f33d477f..69350d3fb4d52 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -10,10 +10,14 @@ export const VOICE_RECORDING_LIMIT_SECONDS = 5 * 60; export type VoiceInputPhase = "idle" | "preparing" | "recording" | "transcribing" | "error"; +/** + * `retry-transcription` means the recording was kept: `retryTranscription()` sends the + * same audio again, while `start()`, `cancel()`, and `dispose()` delete it. + */ export type VoiceInputState = { readonly phase: VoiceInputPhase; readonly error: string | null; - readonly errorAction: "retry" | "settings" | null; + readonly errorAction: "retry" | "retry-transcription" | "settings" | null; }; export function voiceInputBlocksSubmission(state: VoiceInputState): boolean { @@ -43,6 +47,14 @@ export interface VoiceRecorder { stop(): Promise; } +/** Thrown by recorder dependencies. `message` is shown to the user as written. */ +export class VoiceRecorderError extends Error { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = "VoiceRecorderError"; + } +} + export type VoiceInputControllerDependencies = { readonly recorder: VoiceRecorder; readonly getTranscriber: () => VoiceTranscriber | null; @@ -54,10 +66,11 @@ export type VoiceInputControllerDependencies = { readonly releaseRecording: () => Promise; readonly deleteRecording: (uri: string) => void; readonly readDraft: () => VoiceDraftSnapshot | null; + /** False when the draft refused the text, which the controller reports as a changed draft. */ readonly commitDraft: ( text: string, selection: { readonly start: number; readonly end: number }, - ) => void; + ) => boolean; readonly onStateChange: (state: VoiceInputState) => void; }; @@ -186,7 +199,18 @@ function transcriptionErrorMessage(error: unknown): string { return "Could not transcribe this recording."; } +function startErrorMessage(error: unknown): string { + return error instanceof VoiceRecorderError ? error.message : "Could not start voice recording."; +} + const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null }; +const DRAFT_CHANGED_MESSAGE = + "The draft changed while voice input was running. The transcript was not added."; + +type SessionClaim = + | { readonly kind: "claimed"; readonly session: VoiceInputSession; readonly signal: AbortSignal } + | { readonly kind: "busy" } + | { readonly kind: "stale" }; export class VoiceInputController { private readonly dependencies: VoiceInputControllerDependencies; @@ -198,6 +222,7 @@ export class VoiceInputController { private capturedDraft: VoiceDraftSnapshot | null = null; private recordingUri: string | null = null; private readonly ownedRecordingUris = new Set(); + private heldRecordingUri: string | null = null; private recordingConfigured = false; private finishing = false; @@ -211,6 +236,7 @@ export class VoiceInputController { async start(): Promise { if (this.state.phase !== "idle" && this.state.phase !== "error") return; + this.discardHeldRecording(); const initiatingDraft = this.dependencies.readDraft(); if (!initiatingDraft) { this.setError("This draft is no longer available.", "retry"); @@ -221,22 +247,14 @@ export class VoiceInputController { this.setState({ phase: "preparing", error: null, errorAction: null }); try { - for ( - let previousSession = activeSession; - previousSession?.abandoned; - previousSession = activeSession - ) { - await previousSession.released; - if (!this.isCurrent(operationToken)) return; - } - sessionToken = acquireSession(); - if (!sessionToken) { + const claim = await this.claimSession(operationToken); + if (claim.kind === "stale") return; + if (claim.kind === "busy") { this.setError("Another voice recording is already active.", "retry"); return; } - this.sessionToken = sessionToken; - const abortController = new AbortController(); - this.transcriptionAbortController = abortController; + sessionToken = claim.session; + const { signal } = claim; const transcriber = this.dependencies.getTranscriber(); if (!transcriber) { @@ -255,9 +273,7 @@ export class VoiceInputController { } try { - this.transcription = await runTranscriptionOperation(() => - transcriber.prepare({ signal: abortController.signal }), - ); + this.transcription = await runTranscriptionOperation(() => transcriber.prepare({ signal })); } catch (error) { if (this.isCurrent(operationToken)) this.setError(preparationErrorMessage(error), "retry"); return; @@ -280,9 +296,8 @@ export class VoiceInputController { this.capturedDraft = capturedDraft; this.dependencies.recorder.record({ forDuration: VOICE_RECORDING_LIMIT_SECONDS }); this.setState({ phase: "recording", error: null, errorAction: null }); - } catch { - if (this.isCurrent(operationToken)) - this.setError("Could not start voice recording.", "retry"); + } catch (error) { + if (this.isCurrent(operationToken)) this.setError(startErrorMessage(error), "retry"); } finally { if (sessionToken && this.sessionToken === sessionToken) { if (this.isCurrent(operationToken) && this.state.phase === "error") { @@ -299,11 +314,69 @@ export class VoiceInputController { return this.finishRecording(false, null); } + /** Sends the recording kept by a failed transcription again. No-op without one. */ + async retryTranscription(): Promise { + const recordingUri = this.heldRecordingUri; + if (this.state.phase !== "error" || recordingUri === null) return; + this.heldRecordingUri = null; + this.rememberRecordingUri(recordingUri); + let sessionToken: VoiceInputSession | null = null; + const operationToken = ++this.operationToken; + this.setState({ phase: "transcribing", error: null, errorAction: null }); + + try { + const claim = await this.claimSession(operationToken); + if (claim.kind === "stale") return; + if (claim.kind === "busy") { + this.holdRecordingForRetry(recordingUri, "Another voice recording is already active."); + return; + } + sessionToken = claim.session; + const { signal } = claim; + + const transcriber = this.dependencies.getTranscriber(); + if (!transcriber) { + this.setError("Voice transcription is not available.", null); + return; + } + let transcription: PreparedVoiceTranscription; + try { + transcription = await runTranscriptionOperation(() => transcriber.prepare({ signal })); + } catch (error) { + if (this.isCurrent(operationToken)) { + this.holdRecordingForRetry(recordingUri, preparationErrorMessage(error)); + } + return; + } + if (!this.isCurrent(operationToken)) return; + const capturedDraft = this.dependencies.readDraft(); + if (!capturedDraft) { + this.setError("This draft is no longer available.", "retry"); + return; + } + await this.transcribeAndCommit({ + operationToken, + recordingUri, + transcription, + signal, + capturedDraft, + }); + } catch { + if (this.isCurrent(operationToken)) { + this.setError("Could not finish voice recording.", "retry"); + } + } finally { + if (sessionToken === null) this.deleteOwnedRecordings(); + else if (this.sessionToken === sessionToken) await this.releaseResources(); + } + } + cancel(): void { switch (this.state.phase) { case "idle": return; case "error": + this.discardHeldRecording(); this.setState(IDLE_STATE); return; case "preparing": @@ -365,12 +438,30 @@ export class VoiceInputController { this.discardRecording(null); return; } + this.discardHeldRecording(); if (this.state.phase === "preparing" || this.state.phase === "transcribing") { this.invalidateOperation(); this.setState(IDLE_STATE); } } + private async claimSession(operationToken: number): Promise { + for ( + let previousSession = activeSession; + previousSession?.abandoned; + previousSession = activeSession + ) { + await previousSession.released; + if (!this.isCurrent(operationToken)) return { kind: "stale" }; + } + const session = acquireSession(); + if (!session) return { kind: "busy" }; + this.sessionToken = session; + const abortController = new AbortController(); + this.transcriptionAbortController = abortController; + return { kind: "claimed", session, signal: abortController.signal }; + } + private async finishRecording( alreadyStopped: boolean, completedUri: string | null, @@ -396,43 +487,13 @@ export class VoiceInputController { return; } - const recordingUri = this.recordingUri; - const transcription = this.transcription; - const signal = this.transcriptionAbortController.signal; - const capturedDraft = this.capturedDraft; - let transcript: string; - try { - transcript = await runTranscriptionOperation(() => - transcription.transcribe(recordingUri, { signal }), - ); - } catch (error) { - if (this.isCurrent(operationToken)) { - this.setError(transcriptionErrorMessage(error), "retry"); - } - return; - } - if (!this.isCurrent(operationToken)) return; - - const result = resolveTranscriptCommit( - capturedDraft, - this.dependencies.readDraft(), - transcript, - transcription.locale, - ); - if (result.kind === "stale") { - this.setError( - "The draft changed while voice input was running. The transcript was not added.", - "retry", - ); - return; - } - if (result.kind === "empty") { - this.setError("No speech was detected.", "retry"); - return; - } - - this.dependencies.commitDraft(result.text, result.selection); - this.setState(IDLE_STATE); + await this.transcribeAndCommit({ + operationToken, + recordingUri: this.recordingUri, + transcription: this.transcription, + signal: this.transcriptionAbortController.signal, + capturedDraft: this.capturedDraft, + }); } catch { if (this.isCurrent(operationToken)) { this.setError("Could not finish voice recording.", "retry"); @@ -443,6 +504,70 @@ export class VoiceInputController { } } + private async transcribeAndCommit(input: { + readonly operationToken: number; + readonly recordingUri: string; + readonly transcription: PreparedVoiceTranscription; + readonly signal: AbortSignal; + readonly capturedDraft: VoiceDraftSnapshot; + }): Promise { + const { operationToken, recordingUri, transcription } = input; + let transcript: string; + try { + transcript = await runTranscriptionOperation(() => + transcription.transcribe(recordingUri, { signal: input.signal }), + ); + } catch (error) { + if (this.isCurrent(operationToken)) { + this.holdRecordingForRetry(recordingUri, transcriptionErrorMessage(error)); + } + return; + } + if (!this.isCurrent(operationToken)) return; + + const result = resolveTranscriptCommit( + input.capturedDraft, + this.dependencies.readDraft(), + transcript, + transcription.locale, + ); + if (result.kind === "empty") { + this.setError("No speech was detected.", "retry"); + return; + } + const committed = + result.kind === "commit" && this.dependencies.commitDraft(result.text, result.selection); + if (!committed) { + this.setError(DRAFT_CHANGED_MESSAGE, "retry"); + return; + } + this.setState(IDLE_STATE); + } + + private holdRecordingForRetry(uri: string, error: string): void { + this.heldRecordingUri = uri; + this.setError(error, "retry-transcription"); + } + + private discardHeldRecording(): void { + const uri = this.heldRecordingUri; + if (uri === null) return; + this.heldRecordingUri = null; + try { + this.dependencies.deleteRecording(uri); + } catch {} + } + + private deleteOwnedRecordings(): void { + if (this.heldRecordingUri !== null) this.ownedRecordingUris.delete(this.heldRecordingUri); + for (const uri of this.ownedRecordingUris) { + try { + this.dependencies.deleteRecording(uri); + } catch {} + } + this.ownedRecordingUris.clear(); + } + private async discardRecording(error: string | null): Promise { this.invalidateOperation(); this.setState( @@ -464,12 +589,7 @@ export class VoiceInputController { this.rememberRecordingUri(this.dependencies.recorder.uri); } catch {} this.recordingUri = null; - for (const uri of this.ownedRecordingUris) { - try { - this.dependencies.deleteRecording(uri); - } catch {} - } - this.ownedRecordingUris.clear(); + this.deleteOwnedRecordings(); await this.releaseAudioSession(); releaseSession(this.sessionToken); this.sessionToken = null; diff --git a/packages/client-runtime/src/voice-input/index.ts b/packages/client-runtime/src/voice-input/index.ts index e746a7da833d1..c340128cf645e 100644 --- a/packages/client-runtime/src/voice-input/index.ts +++ b/packages/client-runtime/src/voice-input/index.ts @@ -1,5 +1,6 @@ export { VoiceInputController, + VoiceRecorderError, VOICE_RECORDING_LIMIT_SECONDS, voiceInputBlocksSubmission, type VoiceDraftSnapshot, From 59833bead5959ec9320181c0d607da3dba38661a Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:19:46 -0400 Subject: [PATCH 29/55] fix(voice): preflight transcription settings and keep the server's reason `prepare` now checks what the environment already told the client, enabled, the Apple capability for apple-on-device, and a key for a hosted default URL, and fails with the server's own wording before the microphone opens. A refused URL mint keeps the environment's message instead of a generic one. `abortable` becomes `settleOnAbort`, and the transcription contract now says what it does: resource-holding work settles after it stops, while a URL mint or an in-memory decode may settle as cancelled while it finishes. Co-Authored-By: Claude Fable 5.1 --- apps/web/src/state/voiceTranscription.ts | 11 ++ .../environmentTranscriber.test.ts | 101 ++++++++++++++++-- .../src/voice-input/environmentTranscriber.ts | 79 ++++++++++---- .../client-runtime/src/voice-input/index.ts | 2 + .../src/voice-input/transcription.ts | 7 +- 5 files changed, 167 insertions(+), 33 deletions(-) diff --git a/apps/web/src/state/voiceTranscription.ts b/apps/web/src/state/voiceTranscription.ts index 969eadf1c1527..1bc34ce356c27 100644 --- a/apps/web/src/state/voiceTranscription.ts +++ b/apps/web/src/state/voiceTranscription.ts @@ -13,6 +13,7 @@ import { import { connectionAtomRuntime } from "../connection/runtime"; import { convertRecordingToWav } from "../lib/voiceWav"; import { appAtomRegistry } from "../rpc/atomRegistry"; +import { serverEnvironment } from "./server"; import { readEnvironmentScope, readPreparedConnection } from "./session"; export const voiceTranscriptionEnvironment = { @@ -29,6 +30,16 @@ export function createWebVoiceTranscriber( return createEnvironmentVoiceTranscriber({ language, fallbackLocale: () => navigator.language || "en-US", + readConfiguration: () => { + const config = appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId)); + return config + ? { + settings: config.settings.voiceTranscription, + appleOnDeviceTranscription: + config.environment.capabilities.appleOnDeviceTranscription === true, + } + : null; + }, createTranscriptionUrl: async (input) => { const result = await runAtomCommand( appAtomRegistry, diff --git a/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts b/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts index 4e316a1e9fab2..2f936be358957 100644 --- a/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts +++ b/packages/client-runtime/src/voice-input/environmentTranscriber.test.ts @@ -2,17 +2,40 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { createEnvironmentVoiceTranscriber, + voiceTranscriptionUnavailableReason, type EnvironmentVoiceTranscriberDependencies, + type VoiceTranscriptionConfiguration, } from "./environmentTranscriber.ts"; import { VoiceTranscriptionError } from "./transcription.ts"; const RECORDING_URI = "blob:https://app.example/recording"; +const HOSTED_OPENAI: VoiceTranscriptionConfiguration = { + settings: { + enabled: true, + provider: "openai-compatible", + baseUrl: "https://api.openai.com/v1", + model: "gpt-transcribe", + language: "", + apiKey: "••••", + }, + appleOnDeviceTranscription: false, +}; + type PostResponse = { readonly status: number; readonly body: unknown }; +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + function createHarness(options: { readonly audio?: Blob; readonly language?: string; + readonly configuration?: VoiceTranscriptionConfiguration | null; readonly post?: PostResponse | ((init: RequestInit) => Promise); readonly createTranscriptionUrl?: EnvironmentVoiceTranscriberDependencies["createTranscriptionUrl"]; readonly resolveUrl?: EnvironmentVoiceTranscriberDependencies["resolveUrl"]; @@ -35,6 +58,8 @@ function createHarness(options: { const transcriber = createEnvironmentVoiceTranscriber({ language: () => options.language ?? "", fallbackLocale: () => "fr-FR", + readConfiguration: () => + options.configuration === undefined ? HOSTED_OPENAI : options.configuration, createTranscriptionUrl: options.createTranscriptionUrl ?? (async (input) => { @@ -132,17 +157,34 @@ describe("createEnvironmentVoiceTranscriber", () => { expect(opaque.code).toBe("transcription-failed"); }); - it("maps a refused URL mint to unavailable when the environment is not configured", async () => { + it("maps a refused URL mint to unavailable with the environment's own reason", async () => { const unconfigured = await transcriptionError( transcribe( createHarness({ createTranscriptionUrl: async () => { - throw { _tag: "VoiceTranscriptionNotConfiguredError", message: "no key" }; + throw { + _tag: "VoiceTranscriptionNotConfiguredError", + message: "Add an OpenAI API key to use voice transcription.", + }; + }, + }), + ), + ); + expect(unconfigured).toMatchObject({ + code: "unavailable", + message: "Add an OpenAI API key to use voice transcription.", + }); + + const silent = await transcriptionError( + transcribe( + createHarness({ + createTranscriptionUrl: async () => { + throw { _tag: "VoiceTranscriptionNotConfiguredError", message: "" }; }, }), ), ); - expect(unconfigured.code).toBe("unavailable"); + expect(silent).toMatchObject({ code: "unavailable", message: expect.stringContaining("not") }); const offline = await transcriptionError( transcribe( @@ -163,6 +205,7 @@ describe("createEnvironmentVoiceTranscriber", () => { it("settles as cancelled only after the upload itself has been aborted", async () => { const controller = new AbortController(); + const uploadEntered = deferred(); let uploadSettled = false; const harness = createHarness({ post: (init) => @@ -173,10 +216,11 @@ describe("createEnvironmentVoiceTranscriber", () => { reject(new DOMException("aborted", "AbortError")); }); }); + uploadEntered.resolve(undefined); }), }); const pending = transcribe(harness, controller.signal); - await vi.waitFor(() => expect(harness.posts).toHaveLength(1)); + await uploadEntered.promise; controller.abort(); const cancelled = await transcriptionError(pending); expect(cancelled.code).toBe("cancelled"); @@ -185,22 +229,57 @@ describe("createEnvironmentVoiceTranscriber", () => { it("settles as cancelled while a URL mint is still pending", async () => { const controller = new AbortController(); - let mintSettled = false; + const mintEntered = deferred(); const harness = createHarness({ - createTranscriptionUrl: () => - new Promise(() => { - mintSettled = false; - }), + createTranscriptionUrl: () => { + mintEntered.resolve(undefined); + return new Promise(() => {}); + }, }); const pending = transcribe(harness, controller.signal); - await Promise.resolve(); + await mintEntered.promise; controller.abort(); const cancelled = await transcriptionError(pending); expect(cancelled.code).toBe("cancelled"); - expect(mintSettled).toBe(false); expect(harness.posts).toHaveLength(0); }); + it("refuses to prepare when the environment's own settings cannot transcribe", async () => { + const signal = new AbortController().signal; + const configured = ( + settings: Partial, + appleOnDeviceTranscription = false, + ): VoiceTranscriptionConfiguration => ({ + settings: { ...HOSTED_OPENAI.settings, ...settings }, + appleOnDeviceTranscription, + }); + const prepare = (configuration: VoiceTranscriptionConfiguration | null) => + createHarness({ configuration }).transcriber.prepare({ signal }); + + const disabled = await transcriptionError(prepare(configured({ enabled: false }))); + expect(disabled).toMatchObject({ + code: "unavailable", + message: expect.stringContaining("off"), + }); + const keyless = await transcriptionError(prepare(configured({ apiKey: "" }))); + expect(keyless.message).toBe("Add an OpenAI API key to use voice transcription."); + const keylessXai = await transcriptionError( + prepare(configured({ provider: "xai", baseUrl: "https://api.x.ai/v1/", apiKey: "" })), + ); + expect(keylessXai.message).toBe("Add an xAI API key to use voice transcription."); + const appleElsewhere = await transcriptionError( + prepare(configured({ provider: "apple-on-device" })), + ); + expect(appleElsewhere.message).toContain("macOS 26"); + + await expect(prepare(configured({ provider: "apple-on-device" }, true))).resolves.toBeDefined(); + await expect( + prepare(configured({ baseUrl: "http://127.0.0.1:8080/v1", apiKey: "" })), + ).resolves.toBeDefined(); + await expect(prepare(null)).resolves.toBeDefined(); + expect(voiceTranscriptionUnavailableReason(HOSTED_OPENAI)).toBeNull(); + }); + it.each([ ["an unsupported container", new Blob(["x"], { type: "audio/flac" })], ["an empty recording", new Blob([], { type: "audio/mp4" })], diff --git a/packages/client-runtime/src/voice-input/environmentTranscriber.ts b/packages/client-runtime/src/voice-input/environmentTranscriber.ts index a37dcfd0094c7..2073302b1804b 100644 --- a/packages/client-runtime/src/voice-input/environmentTranscriber.ts +++ b/packages/client-runtime/src/voice-input/environmentTranscriber.ts @@ -1,10 +1,13 @@ import { VOICE_TRANSCRIPTION_MAX_AUDIO_BYTES, + VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS, VoiceTranscriptionAudioMimeType, VoiceTranscriptionFailure, VoiceTranscriptionResult, + type HttpVoiceTranscriptionProvider, type VoiceTranscriptionCreateUrlInput, type VoiceTranscriptionCreateUrlResult, + type VoiceTranscriptionSettings, } from "@t3tools/contracts"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -15,11 +18,20 @@ import { type VoiceTranscriber, } from "./transcription.ts"; +/** What the environment already told the client about its transcription setup. */ +export type VoiceTranscriptionConfiguration = { + /** `apiKey` arrives redacted; only its presence is meaningful. */ + readonly settings: VoiceTranscriptionSettings; + readonly appleOnDeviceTranscription: boolean; +}; + export type EnvironmentVoiceTranscriberDependencies = { /** Configured ISO-639-1 code. Empty lets the model detect the language. */ readonly language: () => string; /** Locale used for transcript spacing when no language is configured. */ readonly fallbackLocale: () => string; + /** Null while the environment's config is unknown, in which case the server decides. */ + readonly readConfiguration: () => VoiceTranscriptionConfiguration | null; /** Rejects with the RPC's tagged error when the environment refuses to mint a URL. */ readonly createTranscriptionUrl: ( input: VoiceTranscriptionCreateUrlInput, @@ -34,17 +46,47 @@ const decodeMimeType = Schema.decodeUnknownOption(VoiceTranscriptionAudioMimeTyp const decodeResult = Schema.decodeUnknownOption(VoiceTranscriptionResult); const decodeFailure = Schema.decodeUnknownOption(VoiceTranscriptionFailure); +const HOSTED_PROVIDER_NAMES: Record = { + "openai-compatible": "OpenAI", + xai: "xAI", +}; + +/** + * The checks the server runs before minting an upload URL, so a misconfigured + * environment fails before the microphone opens. Messages match the server's. + */ +export function voiceTranscriptionUnavailableReason({ + settings, + appleOnDeviceTranscription, +}: VoiceTranscriptionConfiguration): string | null { + if (!settings.enabled) return "Voice transcription is turned off for this environment."; + if (settings.provider === "apple-on-device") { + return appleOnDeviceTranscription + ? null + : "Apple on-device transcription needs macOS 26 or later on the machine running T3 Code."; + } + const hostedBaseUrl = VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS[settings.provider].baseUrl; + if (!settings.apiKey && settings.baseUrl.replace(/\/+$/, "") === hostedBaseUrl) { + return `Add an ${HOSTED_PROVIDER_NAMES[settings.provider]} API key to use voice transcription.`; + } + return null; +} + function containerMimeType(blobType: string): VoiceTranscriptionAudioMimeType | null { return Option.getOrNull(decodeMimeType(blobType.split(";")[0]?.trim().toLowerCase())); } -function isNotConfiguredError(error: unknown): boolean { - return ( - typeof error === "object" && - error !== null && - "_tag" in error && - error._tag === "VoiceTranscriptionNotConfiguredError" - ); +function notConfiguredMessage(error: unknown): string | null { + if ( + typeof error !== "object" || + error === null || + !("_tag" in error) || + error._tag !== "VoiceTranscriptionNotConfiguredError" + ) { + return null; + } + const message = "message" in error && typeof error.message === "string" ? error.message : ""; + return message.length > 0 ? message : "Voice input is not configured on this environment."; } function isAbortError(error: unknown): boolean { @@ -55,12 +97,7 @@ function cancelledError(): VoiceTranscriptionError { return new VoiceTranscriptionError("cancelled", "Voice transcription was cancelled."); } -/** - * Settles as cancelled on abort even though the work continues. Minting a URL and - * decoding audio hold no resource the controller owns, so a stuck RPC must not - * block the next recording. - */ -function abortable(work: Promise, signal: AbortSignal): Promise { +function settleOnAbort(work: Promise, signal: AbortSignal): Promise { if (signal.aborted) return Promise.reject(cancelledError()); return new Promise((resolve, reject) => { const onAbort = () => reject(cancelledError()); @@ -109,7 +146,7 @@ export function createEnvironmentVoiceTranscriber( throwIfVoiceTranscriptionAborted(signal); if (dependencies.prepareAudio && blob.size > 0) { try { - blob = await abortable(dependencies.prepareAudio(blob), signal); + blob = await settleOnAbort(dependencies.prepareAudio(blob), signal); } catch (error) { if (error instanceof VoiceTranscriptionError) throw error; throw new VoiceTranscriptionError( @@ -140,18 +177,15 @@ export function createEnvironmentVoiceTranscriber( let minted: VoiceTranscriptionCreateUrlResult; try { - minted = await abortable( + minted = await settleOnAbort( dependencies.createTranscriptionUrl({ mimeType, sizeBytes: blob.size }), signal, ); } catch (error) { if (error instanceof VoiceTranscriptionError) throw error; - if (isNotConfiguredError(error)) { - throw new VoiceTranscriptionError( - "unavailable", - "Voice input is not configured on this environment.", - { cause: error }, - ); + const notConfigured = notConfiguredMessage(error); + if (notConfigured !== null) { + throw new VoiceTranscriptionError("unavailable", notConfigured, { cause: error }); } throw new VoiceTranscriptionError( "transcription-failed", @@ -207,6 +241,9 @@ export function createEnvironmentVoiceTranscriber( return { prepare: async ({ signal }) => { throwIfVoiceTranscriptionAborted(signal); + const configuration = dependencies.readConfiguration(); + const unavailable = configuration && voiceTranscriptionUnavailableReason(configuration); + if (unavailable) throw new VoiceTranscriptionError("unavailable", unavailable); const language = dependencies.language().trim(); return { locale: language.length > 0 ? language : dependencies.fallbackLocale(), diff --git a/packages/client-runtime/src/voice-input/index.ts b/packages/client-runtime/src/voice-input/index.ts index c340128cf645e..cbdf67079cecb 100644 --- a/packages/client-runtime/src/voice-input/index.ts +++ b/packages/client-runtime/src/voice-input/index.ts @@ -12,7 +12,9 @@ export { } from "./controller.ts"; export { createEnvironmentVoiceTranscriber, + voiceTranscriptionUnavailableReason, type EnvironmentVoiceTranscriberDependencies, + type VoiceTranscriptionConfiguration, } from "./environmentTranscriber.ts"; export { normalizeVoiceInputDecibels, diff --git a/packages/client-runtime/src/voice-input/transcription.ts b/packages/client-runtime/src/voice-input/transcription.ts index 2103d2a9d145f..8b1329c26a63f 100644 --- a/packages/client-runtime/src/voice-input/transcription.ts +++ b/packages/client-runtime/src/voice-input/transcription.ts @@ -1,4 +1,9 @@ -/** Cancellation is cooperative: settle only after the underlying work has stopped. */ +/** + * Cancellation is cooperative. Work that holds a resource the controller owns, such as a + * native speech session or the recording file, settles only after that work has stopped. + * Work that holds nothing of the controller's, such as a URL mint or an in-memory decode, + * may settle as cancelled while it finishes in the background. + */ export type VoiceTranscriptionOptions = { readonly signal: AbortSignal; }; From efa94ad1e6fd8c1756d28c04ef340d76e4a5b88c Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:20:04 -0400 Subject: [PATCH 30/55] fix(server): accept voice uploads without a Content-Length header A proxy or tunnel that re-chunks the body drops Content-Length, and the voice route rejected those uploads while the attachment route accepts them. The body read is still capped at the signed size and transcribe still checks the exact byte count; a present but mismatched Content-Length is still 400. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/http.ts | 4 ++- .../VoiceTranscription.test.ts | 29 +++++++++++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 6e61626dc2f08..796238cbc1ec4 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -538,7 +538,9 @@ export const layerVoiceTranscriptionRoute = HttpRouter.add( ); } const { sizeBytes } = claims.value; - if (Number(request.headers["content-length"]) !== sizeBytes) { + const contentLength = request.headers["content-length"]; + // Tunnels may re-chunk the body. The read cap and transcribe's exact byte count still apply. + if (contentLength !== undefined && Number(contentLength) !== sizeBytes) { return voiceTranscriptionFailure( "invalid_upload", `Content-Length must match the recording size of ${sizeBytes} bytes.`, diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts index 1ea36f272fa95..31d7c68dd36ed 100644 --- a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -99,7 +99,7 @@ const apple = { provider: "apple-on-device", baseUrl: "", model: "", apiKey: "" const post = ( relativeUrl: string, - options: { readonly body?: Uint8Array; readonly contentLength?: number } = {}, + options: { readonly body?: Uint8Array; readonly contentLength?: number | null } = {}, ) => Effect.gen(function* () { const body = options.body ?? audio; @@ -109,7 +109,9 @@ const post = ( body: new Blob([new Uint8Array(body)]), headers: { "content-type": "audio/webm", - "content-length": String(options.contentLength ?? body.byteLength), + ...(options.contentLength === null + ? {} + : { "content-length": String(options.contentLength ?? body.byteLength) }), }, }); const response = HttpServerResponse.toWeb( @@ -574,6 +576,29 @@ describe("VoiceTranscription", () => { }, ); + it.effect("accepts a re-chunked upload without Content-Length but still checks its size", () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + expect(yield* post((yield* mint).relativeUrl, { contentLength: null })).toEqual({ + status: 200, + body: { text: "hello world" }, + }); + const longer = yield* post((yield* mint).relativeUrl, { + body: new Uint8Array([...audio, 7]), + contentLength: null, + }); + const shorter = yield* post((yield* mint).relativeUrl, { + body: audio.slice(1), + contentLength: null, + }); + for (const response of [longer, shorter]) { + expect(response.status).toBe(400); + expect(response.body.code).toBe("invalid_upload"); + } + expect(requests).toHaveLength(1); + }).pipe(Effect.provide(layer)); + }); + it.effect("accepts each upload link once", () => { const { layer, requests } = setup({}); return Effect.gen(function* () { From bec64093b9b054f51de6f7aaadce3a141fab350b Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:21:13 -0400 Subject: [PATCH 31/55] fix(server): drop the saved voice transcription key when the endpoint moves Only the web client cleared the key when the base URL changed, so any other writer could send the saved key to a new host. The settings merge now clears it, and the secret store entry with it, when a patch changes the provider or the base URL's origin without sending a key. A path change on the same origin keeps the key, and a key sent in the same patch wins. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/serverSettings.test.ts | 40 ++++++++++++++++++++++++++ packages/shared/src/serverSettings.ts | 24 ++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index f009c70286a7c..df3bdf23a1a2d 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1353,6 +1353,46 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettingsWithSecrets())), ); + it.effect.each([ + { + name: "a base URL on another origin", + patch: { baseUrl: "https://transcribe.example.com/v1" }, + keeps: false, + }, + { name: "another provider", patch: { provider: "xai" }, keeps: false }, + { + name: "a path on the same origin", + patch: { baseUrl: "https://api.openai.com/v2" }, + keeps: true, + }, + { name: "a model change", patch: { model: "whisper-1" }, keeps: true }, + ] as const)("keeps the voice transcription key across $name: $keeps", ({ patch, keeps }) => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + const store = yield* ServerSecretStore.ServerSecretStore; + yield* service.updateSettings({ + voiceTranscription: { enabled: true, apiKey: "sk-voice-secret" }, + }); + const moved = yield* service.updateSettings({ voiceTranscription: patch }); + assert.strictEqual(moved.voiceTranscription.apiKey, keeps ? "sk-voice-secret" : ""); + assert.strictEqual(Option.isSome(yield* store.get("voice-transcription-api-key")), keeps); + }).pipe(Effect.provide(layerServerSettingsWithSecrets())), + ); + + it.effect("saves a key sent together with a move to another origin", () => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + yield* service.updateSettings({ + voiceTranscription: { enabled: true, apiKey: "sk-voice-secret" }, + }); + const moved = yield* service.updateSettings({ + voiceTranscription: { baseUrl: "https://transcribe.example.com/v1", apiKey: "sk-new" }, + }); + assert.strictEqual(moved.voiceTranscription.apiKey, "sk-new"); + assert.strictEqual((yield* service.getSettings).voiceTranscription.apiKey, "sk-new"); + }).pipe(Effect.provide(layerServerSettingsWithSecrets())), + ); + it.effect("moves saved provider credentials to the secret store when settings load", () => Effect.gen(function* () { const service = yield* ServerSettingsModule.ServerSettingsService; diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 5371cf76e8a79..ba605591c838c 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -359,6 +359,25 @@ function translateLegacyProjectOverridePatch( } as ServerSettingsPatch; } +function endpointOrigin(baseUrl: string): string { + try { + return new URL(baseUrl).origin; + } catch { + return baseUrl; + } +} + +/** A saved key belongs to the service it was entered for, so it never follows a move to another. */ +function movesVoiceTranscriptionEndpoint( + current: ServerSettings["voiceTranscription"], + next: ServerSettings["voiceTranscription"], +): boolean { + return ( + current.provider !== next.provider || + endpointOrigin(current.baseUrl) !== endpointOrigin(next.baseUrl) + ); +} + export function applyServerSettingsPatch( current: ServerSettings, rawPatch: ServerSettingsPatch, @@ -590,6 +609,11 @@ export function applyServerSettingsPatch( : {}), ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}), ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}), + ...(patch.voiceTranscription !== undefined && + patch.voiceTranscription.apiKey === undefined && + movesVoiceTranscriptionEndpoint(current.voiceTranscription, next.voiceTranscription) + ? { voiceTranscription: { ...next.voiceTranscription, apiKey: "" } } + : {}), }; const normalizedBackgroundActivity = normalizeBackgroundActivitySettings( nextWithReplacementsBase.backgroundActivity, From 0f6942ac0c1a73e42b5717e41ee6c62239e5956c Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:22:44 -0400 Subject: [PATCH 32/55] fix(web): name the microphone failure and the place to unblock it A denied microphone on the Windows or Linux desktop app pointed at browser settings. The error context now carries where the permission lives (browser, macOS, Windows, Linux) and each gets its own instruction; macOS keeps the System Settings button. NotFoundError and NotReadableError from getUserMedia become VoiceRecorderError messages about a missing or busy microphone. The recorder's `denialIsPermanent` flag is now `deniedBy`, and its internals are named for what they track: a pending stop event, a release generation, and a handler for tracks that ended on their own. Co-Authored-By: Claude Fable 5.1 --- ...ComposerVoiceInputControl.browser.test.tsx | 4 +- .../chat/ComposerVoiceInputControl.tsx | 7 +- .../chat/voiceInputErrorPresentation.test.ts | 25 ++++--- .../chat/voiceInputErrorPresentation.ts | 42 +++++++---- apps/web/src/lib/microphoneSettings.ts | 14 +++- apps/web/src/lib/voiceRecorder.test.ts | 52 ++++++++------ apps/web/src/lib/voiceRecorder.ts | 71 ++++++++++++------- .../src/voice-input/metering.test.ts | 2 +- 8 files changed, 142 insertions(+), 75 deletions(-) diff --git a/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx b/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx index 85437e4cd5426..9f3ca30a5727e 100644 --- a/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx @@ -19,7 +19,7 @@ function control( null} readLevel={() => 0} onToggle={() => {}} @@ -98,7 +98,7 @@ describe("ComposerVoiceInputControl", () => { await using screen = await render( control(denied, { onOpenSettings, - errorContext: { secureContext: true, canOpenSystemSettings: true }, + errorContext: { secureContext: true, permissionHost: "macos" }, }), ); expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( diff --git a/apps/web/src/components/chat/ComposerVoiceInputControl.tsx b/apps/web/src/components/chat/ComposerVoiceInputControl.tsx index 077f52feb0b5b..278da32f5ee35 100644 --- a/apps/web/src/components/chat/ComposerVoiceInputControl.tsx +++ b/apps/web/src/components/chat/ComposerVoiceInputControl.tsx @@ -3,10 +3,7 @@ import { CircleAlertIcon, MicIcon, XIcon } from "lucide-react"; import { memo, useEffect, useLayoutEffect, useRef, useState } from "react"; import { useMediaQuery } from "~/hooks/useMediaQuery"; -import { - canOpenMicrophoneSystemSettings, - openMicrophoneSystemSettings, -} from "~/lib/microphoneSettings"; +import { microphonePermissionHost, openMicrophoneSystemSettings } from "~/lib/microphoneSettings"; import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; import { Spinner } from "../ui/spinner"; @@ -22,7 +19,7 @@ const VOICE_METER_REST_SCALE = 0.15; const BROWSER_ERROR_CONTEXT: VoiceInputErrorContext = { secureContext: typeof window !== "undefined" && window.isSecureContext, - canOpenSystemSettings: canOpenMicrophoneSystemSettings, + permissionHost: microphonePermissionHost, }; export function formatVoiceElapsed(seconds: number): string { diff --git a/apps/web/src/components/chat/voiceInputErrorPresentation.test.ts b/apps/web/src/components/chat/voiceInputErrorPresentation.test.ts index 5ca5b27368ba1..2d890b36a7c2a 100644 --- a/apps/web/src/components/chat/voiceInputErrorPresentation.test.ts +++ b/apps/web/src/components/chat/voiceInputErrorPresentation.test.ts @@ -10,34 +10,43 @@ const denied = { describe("resolveVoiceInputErrorPresentation", () => { it("routes a blocked microphone to the place that can unblock it", () => { + expect( + resolveVoiceInputErrorPresentation(denied, { secureContext: true, permissionHost: "macos" }), + ).toMatchObject({ action: "open-settings", message: expect.stringContaining("System") }); expect( resolveVoiceInputErrorPresentation(denied, { secureContext: true, - canOpenSystemSettings: true, + permissionHost: "windows", }), - ).toMatchObject({ action: "open-settings" }); + ).toMatchObject({ action: "retry", message: expect.stringContaining("Privacy & security") }); + expect( + resolveVoiceInputErrorPresentation(denied, { secureContext: true, permissionHost: "linux" }), + ).toMatchObject({ action: "retry", message: expect.stringContaining("system") }); expect( resolveVoiceInputErrorPresentation(denied, { secureContext: true, - canOpenSystemSettings: false, + permissionHost: "browser", }), ).toMatchObject({ action: "retry", message: expect.stringContaining("browser") }); expect( - resolveVoiceInputErrorPresentation(denied, { - secureContext: false, - canOpenSystemSettings: true, - }), + resolveVoiceInputErrorPresentation(denied, { secureContext: false, permissionHost: "macos" }), ).toMatchObject({ action: null, message: expect.stringContaining("HTTPS") }); }); it("shows other failures verbatim with a retry when the controller offers one", () => { - const context = { secureContext: true, canOpenSystemSettings: false }; + const context = { secureContext: true, permissionHost: "browser" } as const; expect( resolveVoiceInputErrorPresentation( { phase: "error", error: "Groq is down.", errorAction: "retry" }, context, ), ).toEqual({ message: "Groq is down.", action: "retry" }); + expect( + resolveVoiceInputErrorPresentation( + { phase: "error", error: "Upload failed.", errorAction: "retry-transcription" }, + context, + ), + ).toEqual({ message: "Upload failed.", action: "retry" }); expect( resolveVoiceInputErrorPresentation( { phase: "error", error: "Voice transcription is not available.", errorAction: null }, diff --git a/apps/web/src/components/chat/voiceInputErrorPresentation.ts b/apps/web/src/components/chat/voiceInputErrorPresentation.ts index 75ad448740208..203acfd7dbc79 100644 --- a/apps/web/src/components/chat/voiceInputErrorPresentation.ts +++ b/apps/web/src/components/chat/voiceInputErrorPresentation.ts @@ -1,8 +1,10 @@ import type { VoiceInputState } from "@t3tools/client-runtime/voice-input"; +import type { MicrophonePermissionHost } from "~/lib/microphoneSettings"; + export interface VoiceInputErrorContext { readonly secureContext: boolean; - readonly canOpenSystemSettings: boolean; + readonly permissionHost: MicrophonePermissionHost; } export type VoiceInputErrorAction = "retry" | "open-settings"; @@ -12,6 +14,27 @@ export interface VoiceInputErrorPresentation { readonly action: VoiceInputErrorAction | null; } +const BLOCKED_MICROPHONE: Record = { + browser: { + message: "Allow the microphone for this site in your browser's settings, then try again.", + action: "retry", + }, + macos: { + message: "Allow the microphone for T3 Code in System Settings, then try again.", + action: "open-settings", + }, + windows: { + message: + "Allow the microphone for T3 Code under Settings > Privacy & security > Microphone, then try again.", + action: "retry", + }, + linux: { + message: + "Allow the microphone for T3 Code in your system's sound or privacy settings, then try again.", + action: "retry", + }, +}; + export function resolveVoiceInputErrorPresentation( state: VoiceInputState, context: VoiceInputErrorContext, @@ -21,16 +44,11 @@ export function resolveVoiceInputErrorPresentation( if (!context.secureContext) { return { message: "Voice input needs an HTTPS or localhost connection.", action: null }; } - if (context.canOpenSystemSettings) { - return { - message: "Allow the microphone for T3 Code in System Settings, then try again.", - action: "open-settings", - }; - } - return { - message: "Allow the microphone for this site in your browser's settings, then try again.", - action: "retry", - }; + return BLOCKED_MICROPHONE[context.permissionHost]; } - return { message: state.error, action: state.errorAction === "retry" ? "retry" : null }; + return { + message: state.error, + action: + state.errorAction === "retry" || state.errorAction === "retry-transcription" ? "retry" : null, + }; } diff --git a/apps/web/src/lib/microphoneSettings.ts b/apps/web/src/lib/microphoneSettings.ts index d8d68dfa3e03b..8c8cdf782786f 100644 --- a/apps/web/src/lib/microphoneSettings.ts +++ b/apps/web/src/lib/microphoneSettings.ts @@ -1,9 +1,17 @@ import { isElectron } from "~/env"; -import { isMacPlatform } from "~/lib/utils"; +import { isMacPlatform, isWindowsPlatform } from "~/lib/utils"; import { readLocalApi } from "~/localApi"; -export const canOpenMicrophoneSystemSettings = - isElectron && typeof navigator !== "undefined" && isMacPlatform(navigator.platform); +/** Where a user unblocks the microphone. Electron grants page requests itself, so only the OS can refuse. */ +export type MicrophonePermissionHost = "browser" | "macos" | "windows" | "linux"; + +function detectMicrophonePermissionHost(): MicrophonePermissionHost { + if (!isElectron || typeof navigator === "undefined") return "browser"; + if (isMacPlatform(navigator.platform)) return "macos"; + return isWindowsPlatform(navigator.platform) ? "windows" : "linux"; +} + +export const microphonePermissionHost = detectMicrophonePermissionHost(); export async function openMicrophoneSystemSettings(): Promise { await readLocalApi()?.shell.openSystemSettings("microphone"); diff --git a/apps/web/src/lib/voiceRecorder.test.ts b/apps/web/src/lib/voiceRecorder.test.ts index d9dc1c04f7d5f..e7e74a47e04b6 100644 --- a/apps/web/src/lib/voiceRecorder.test.ts +++ b/apps/web/src/lib/voiceRecorder.test.ts @@ -1,5 +1,5 @@ import type { VoiceRecorderStatus } from "@t3tools/client-runtime/voice-input"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; import { createWebVoiceRecorder, @@ -33,11 +33,10 @@ class FakeMediaRecorder implements MediaRecorderLike { stop(): void { if (this.state === "inactive") throw new DOMException("not recording", "InvalidStateError"); - this.endRecording(); + this.simulateTracksEnded(); } - /** What the browser does when every track of the stream ends. */ - endRecording(): void { + simulateTracksEnded(): void { this.state = "inactive"; for (const listener of this.listeners.get("dataavailable") ?? []) { listener({ data: this.chunk } as never); @@ -46,6 +45,11 @@ class FakeMediaRecorder implements MediaRecorderLike { } } +function fakeTimers(): Disposable { + vi.useFakeTimers(); + return { [Symbol.dispose]: () => void vi.useRealTimers() }; +} + function createFakeStream() { const tracks = [{ stop: vi.fn() }, { stop: vi.fn() }]; return { stream: { getTracks: () => tracks } as unknown as MediaStream, tracks }; @@ -74,7 +78,7 @@ function createHarness(overrides: Partial = {}) { revokeObjectURL: (url) => { revoked.push(url); }, - denialIsPermanent: false, + deniedBy: "browser", ...overrides, }; const web = createWebVoiceRecorder(environment, (status) => statuses.push(status)); @@ -88,7 +92,7 @@ async function startRecording(harness: ReturnType, forDura harness.web.recorder.record({ forDuration }); } -function refusal(name: "NotAllowedError" | "SecurityError") { +function refusal(name: "NotAllowedError" | "SecurityError" | "NotFoundError" | "NotReadableError") { return async () => { throw new DOMException("refused", name); }; @@ -102,15 +106,12 @@ const finished = (url: string): VoiceRecorderStatus => ({ }); describe("createWebVoiceRecorder", () => { - afterEach(() => { - vi.useRealTimers(); - }); - it("records into a blob URL that exists only after stop, then turns the microphone off", async () => { + using _now = vi.spyOn(Date, "now").mockReturnValue(1_000); const harness = createHarness(); await startRecording(harness); expect(harness.web.recorder.uri).toBeNull(); - expect(harness.web.startedAt).not.toBeNull(); + expect(harness.web.startedAt).toBe(1_000); expect(harness.recorders[0]?.options).toEqual({ mimeType: "audio/webm;codecs=opus" }); await harness.web.recorder.stop(); @@ -143,7 +144,7 @@ describe("createWebVoiceRecorder", () => { await harness.web.requestPermission(); await harness.web.configureRecording(); await harness.web.recorder.prepareToRecordAsync(); - vi.useFakeTimers(); + using _timers = fakeTimers(); harness.web.recorder.record({ forDuration: 2 }); await vi.advanceTimersByTimeAsync(1_999); expect(harness.statuses).toEqual([]); @@ -154,7 +155,7 @@ describe("createWebVoiceRecorder", () => { it("hands over what it captured when the microphone ends on its own", async () => { const harness = createHarness(); await startRecording(harness); - harness.recorders[0]!.endRecording(); + harness.recorders[0]!.simulateTracksEnded(); expect(harness.statuses).toEqual([finished("blob:recording-1")]); await harness.web.recorder.stop(); expect(harness.statuses).toHaveLength(1); @@ -205,10 +206,7 @@ describe("createWebVoiceRecorder", () => { }); expect(await blocked.web.requestPermission()).toEqual({ granted: false, canAskAgain: false }); - const desktop = createHarness({ - getUserMedia: refusal("NotAllowedError"), - denialIsPermanent: true, - }); + const desktop = createHarness({ getUserMedia: refusal("NotAllowedError"), deniedBy: "os" }); expect(await desktop.web.requestPermission()).toEqual({ granted: false, canAskAgain: false }); const insecure = createHarness({ @@ -216,12 +214,26 @@ describe("createWebVoiceRecorder", () => { queryMicrophonePermission: async () => null, }); expect(await insecure.web.requestPermission()).toEqual({ granted: false, canAskAgain: false }); + }); + + it("names a missing or busy microphone instead of a generic failure", async () => { + const missing = createHarness({ getUserMedia: refusal("NotFoundError") }); + await expect(missing.web.requestPermission()).rejects.toMatchObject({ + name: "VoiceRecorderError", + message: expect.stringContaining("No microphone"), + }); + + const busy = createHarness({ getUserMedia: refusal("NotReadableError") }); + await expect(busy.web.requestPermission()).rejects.toMatchObject({ + name: "VoiceRecorderError", + message: expect.stringContaining("Another app"), + }); - const broken = createHarness({ + const unknown = createHarness({ getUserMedia: async () => { - throw new DOMException("no device", "NotFoundError"); + throw new DOMException("odd", "AbortError"); }, }); - await expect(broken.web.requestPermission()).rejects.toMatchObject({ name: "NotFoundError" }); + await expect(unknown.web.requestPermission()).rejects.toMatchObject({ name: "AbortError" }); }); }); diff --git a/apps/web/src/lib/voiceRecorder.ts b/apps/web/src/lib/voiceRecorder.ts index a393d5460e57e..a958faac62db5 100644 --- a/apps/web/src/lib/voiceRecorder.ts +++ b/apps/web/src/lib/voiceRecorder.ts @@ -1,6 +1,7 @@ import { normalizeVoiceInputDecibels, voiceInputDecibelsFromByteSamples, + VoiceRecorderError, type VoiceRecorder, type VoiceRecorderStatus, } from "@t3tools/client-runtime/voice-input"; @@ -36,7 +37,8 @@ export interface VoiceRecorderEnvironment { readonly createLevelMeter: (stream: MediaStream) => VoiceLevelMeter | null; readonly createObjectURL: (blob: Blob) => string; readonly revokeObjectURL: (url: string) => void; - readonly denialIsPermanent: boolean; + /** Who refused a microphone request. The OS cannot be asked again from the page. */ + readonly deniedBy: "os" | "browser"; } export interface WebVoiceRecorder { @@ -60,6 +62,32 @@ function isPermissionRefusal(error: unknown): error is DOMException { ); } +function describeMicrophoneFailure(error: unknown): VoiceRecorderError | null { + if (!(error instanceof DOMException)) return null; + switch (error.name) { + case "NotFoundError": + case "OverconstrainedError": + return new VoiceRecorderError("No microphone was found. Connect one and try again.", { + cause: error, + }); + case "NotReadableError": + return new VoiceRecorderError( + "The microphone could not be started. Another app may be using it.", + { cause: error }, + ); + default: + return null; + } +} + +async function openMicrophone(environment: VoiceRecorderEnvironment): Promise { + try { + return await environment.getUserMedia({ audio: true }); + } catch (error) { + throw describeMicrophoneFailure(error) ?? error; + } +} + export function createWebVoiceRecorder( environment: VoiceRecorderEnvironment, onStatus: (status: VoiceRecorderStatus) => void, @@ -68,20 +96,24 @@ export function createWebVoiceRecorder( let stream: MediaStream | null = null; let meter: VoiceLevelMeter | null = null; let mediaRecorder: MediaRecorderLike | null = null; - let started = false; + let stopEventPending = false; let stopRequested = false; let stopped: Promise | null = null; let chunks: Blob[] = []; let recordingUri: string | null = null; let limitTimer: ReturnType | null = null; let startedAt: number | null = null; - let releases = 0; + let releaseGeneration = 0; const clearLimitTimer = () => { if (limitTimer !== null) clearTimeout(limitTimer); limitTimer = null; }; + const handleTracksEnded = () => { + onStatus({ isFinished: true, hasError: false, error: null, url: recordingUri }); + }; + const recorder: VoiceRecorder = { get uri() { return recordingUri; @@ -105,11 +137,7 @@ export function createWebVoiceRecorder( clearLimitTimer(); startedAt = null; resolve(); - // A stop nobody asked for means the tracks ended, such as a device - // unplugged, so hand over what was captured instead of recording forever. - if (!stopRequested) { - onStatus({ isFinished: true, hasError: false, error: null, url: recordingUri }); - } + if (!stopRequested) handleTracksEnded(); }); next.addEventListener("error", () => { onStatus({ @@ -120,7 +148,7 @@ export function createWebVoiceRecorder( }); }); mediaRecorder = next; - started = false; + stopEventPending = false; stopRequested = false; stopped = promise; }, @@ -128,7 +156,7 @@ export function createWebVoiceRecorder( if (!mediaRecorder) throw new Error("The recorder is not prepared."); clearLimitTimer(); mediaRecorder.start(); - started = true; + stopEventPending = true; startedAt = Date.now(); limitTimer = setTimeout(() => { void recorder @@ -142,16 +170,14 @@ export function createWebVoiceRecorder( clearLimitTimer(); const current = mediaRecorder; if (!current) return; - // A recorder that never started fires no stop event, and one whose - // tracks ended already fired it. - if (started) { + if (stopEventPending) { stopRequested = true; if (current.state !== "inactive") current.stop(); await stopped; } mediaRecorder = null; stopped = null; - started = false; + stopEventPending = false; startedAt = null; }, }; @@ -164,31 +190,29 @@ export function createWebVoiceRecorder( requestPermission: async () => { stopTracks(promptedStream); promptedStream = null; - const releasesBefore = releases; + const generationAtPrompt = releaseGeneration; try { - const granted = await environment.getUserMedia({ audio: true }); - // A cancel while the prompt was open already released, so this stream - // has no owner left to stop it later. - if (releases !== releasesBefore) stopTracks(granted); + const granted = await openMicrophone(environment); + if (releaseGeneration !== generationAtPrompt) stopTracks(granted); else promptedStream = granted; return { granted: true, canAskAgain: true }; } catch (error) { if (!isPermissionRefusal(error)) throw error; // A SecurityError means the origin itself cannot ask, so retrying cannot help. const state = - environment.denialIsPermanent || error.name === "SecurityError" + environment.deniedBy === "os" || error.name === "SecurityError" ? "denied" : await environment.queryMicrophonePermission(); return { granted: false, canAskAgain: state !== "denied" }; } }, configureRecording: async () => { - stream = promptedStream ?? (await environment.getUserMedia({ audio: true })); + stream = promptedStream ?? (await openMicrophone(environment)); promptedStream = null; meter = environment.createLevelMeter(stream); }, releaseRecording: async () => { - releases += 1; + releaseGeneration += 1; clearLimitTimer(); meter?.close(); meter = null; @@ -247,7 +271,6 @@ export function createBrowserVoiceRecorderEnvironment(): VoiceRecorderEnvironmen createLevelMeter: createAnalyserLevelMeter, createObjectURL: (blob) => URL.createObjectURL(blob), revokeObjectURL: (url) => URL.revokeObjectURL(url), - // Electron grants the page's request itself, so a refusal can only come from the OS. - denialIsPermanent: isElectron, + deniedBy: isElectron ? "os" : "browser", }; } diff --git a/packages/client-runtime/src/voice-input/metering.test.ts b/packages/client-runtime/src/voice-input/metering.test.ts index a067f57b7d7d6..da10a671f00b2 100644 --- a/packages/client-runtime/src/voice-input/metering.test.ts +++ b/packages/client-runtime/src/voice-input/metering.test.ts @@ -14,7 +14,7 @@ describe("voice input metering", () => { it("grows with the signal between the noise floor and full scale", () => { const quiet = normalizeVoiceInputDecibels(voiceInputDecibelsFromByteSamples([129, 127])); const speech = normalizeVoiceInputDecibels(voiceInputDecibelsFromByteSamples([160, 96])); - expect(quiet).toBeGreaterThanOrEqual(0); + expect(quiet).toBeGreaterThan(0); expect(speech).toBeGreaterThan(quiet); expect(speech).toBeLessThan(1); }); From 0a1fa2aed69107af9881e7f81574e65f2b1c1292 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:22:46 -0400 Subject: [PATCH 33/55] style(server): fit the untraced path comment on one line Co-Authored-By: Claude Opus 5.5 --- apps/server/src/http.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 796238cbc1ec4..1d5c96c42a60a 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -401,7 +401,7 @@ const UNTRACED_REQUEST_PATHS: ReadonlySet = new Set([OTLP_TRACES_PROXY_P const layerUntracedRequests = Layer.succeed(HttpMiddleware.TracerDisabledWhen)((request) => { const queryIndex = request.url.indexOf("?"); const path = queryIndex === -1 ? request.url : request.url.slice(0, queryIndex); - // Webhook and voice upload URLs carry their secret token in the path, so they never reach a trace. + // Webhook and voice upload URLs carry a secret token in the path, so they never reach a trace. return ( UNTRACED_REQUEST_PATHS.has(path) || path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`) || From 09ba807b8e0b08905c640038a1b189f020dc5f2a Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:25:16 -0400 Subject: [PATCH 34/55] perf(web): write WAV samples through an Int16Array and skip the mono copy Mono recordings no longer get copied sample by sample before encoding, and the PCM body is written through an Int16Array view instead of per-sample DataView calls. The encoder asserts the little-endian platform that makes that correct. The browser test now also feeds a stereo recording, so the downmix runs: opposite channels cancel and equal channels keep their level. downmixToMono is no longer exported; nothing imported it. Co-Authored-By: Claude Fable 5.1 --- apps/web/src/lib/voiceWav.browser.test.ts | 70 +++++++++++++++++------ apps/web/src/lib/voiceWav.ts | 13 +++-- 2 files changed, 60 insertions(+), 23 deletions(-) diff --git a/apps/web/src/lib/voiceWav.browser.test.ts b/apps/web/src/lib/voiceWav.browser.test.ts index 8363243afea15..1ef613d46788b 100644 --- a/apps/web/src/lib/voiceWav.browser.test.ts +++ b/apps/web/src/lib/voiceWav.browser.test.ts @@ -2,30 +2,66 @@ import { describe, expect, it } from "vite-plus/test"; import { convertRecordingToWav, encodeWavPcm16, VOICE_WAV_SAMPLE_RATE } from "./voiceWav"; -function toneRecording(): Blob { - const sampleRate = 48_000; - const samples = Float32Array.from({ length: sampleRate }, (_, index) => - Math.sin((2 * Math.PI * 440 * index) / sampleRate), +const SOURCE_SAMPLE_RATE = 48_000; + +function tone(gain: number): Float32Array { + return Float32Array.from( + { length: SOURCE_SAMPLE_RATE }, + (_, index) => gain * Math.sin((2 * Math.PI * 440 * index) / SOURCE_SAMPLE_RATE), ); - return new Blob([encodeWavPcm16(samples, sampleRate)], { type: "audio/wav" }); +} + +function monoRecording(samples: Float32Array): Blob { + return new Blob([encodeWavPcm16(samples, SOURCE_SAMPLE_RATE)], { type: "audio/wav" }); +} + +/** Interleaves two channels and patches the mono header into a stereo one. */ +function stereoRecording(left: Float32Array, right: Float32Array): Blob { + const interleaved = new Float32Array(left.length * 2); + for (let index = 0; index < left.length; index += 1) { + interleaved[index * 2] = left[index] ?? 0; + interleaved[index * 2 + 1] = right[index] ?? 0; + } + const buffer = encodeWavPcm16(interleaved, SOURCE_SAMPLE_RATE); + const view = new DataView(buffer); + view.setUint16(22, 2, true); + view.setUint32(28, SOURCE_SAMPLE_RATE * 4, true); + view.setUint16(32, 4, true); + return new Blob([buffer], { type: "audio/wav" }); +} + +async function decodeMonoWav(wav: Blob): Promise<{ sampleCount: number; peak: number }> { + const view = new DataView(await wav.arrayBuffer()); + expect(wav.type).toBe("audio/wav"); + expect(view.getUint32(24, true)).toBe(VOICE_WAV_SAMPLE_RATE); + expect(view.getUint16(22, true)).toBe(1); + const sampleCount = view.getUint32(40, true) / 2; + let peak = 0; + for (let index = 0; index < sampleCount; index += 1) { + peak = Math.max(peak, Math.abs(view.getInt16(44 + index * 2, true))); + } + return { sampleCount, peak }; } describe("convertRecordingToWav", () => { it("resamples a recording to 16 kHz mono PCM WAV in Chromium", async () => { - const wav = await convertRecordingToWav(toneRecording()); - const view = new DataView(await wav.arrayBuffer()); - - expect(wav.type).toBe("audio/wav"); - expect(view.getUint32(24, true)).toBe(VOICE_WAV_SAMPLE_RATE); - expect(view.getUint16(22, true)).toBe(1); - const sampleCount = view.getUint32(40, true) / 2; + const { sampleCount, peak } = await decodeMonoWav( + await convertRecordingToWav(monoRecording(tone(1))), + ); expect(sampleCount).toBeGreaterThanOrEqual(VOICE_WAV_SAMPLE_RATE - 1); expect(sampleCount).toBeLessThanOrEqual(VOICE_WAV_SAMPLE_RATE + 1); - - let peak = 0; - for (let index = 0; index < sampleCount; index += 1) { - peak = Math.max(peak, Math.abs(view.getInt16(44 + index * 2, true))); - } expect(peak).toBeGreaterThan(20_000); }); + + it("averages stereo channels, so opposite channels cancel and equal ones keep their level", async () => { + const opposite = await decodeMonoWav( + await convertRecordingToWav(stereoRecording(tone(1), tone(-1))), + ); + expect(opposite.peak).toBeLessThan(50); + + const identical = await decodeMonoWav( + await convertRecordingToWav(stereoRecording(tone(1), tone(1))), + ); + expect(identical.peak).toBeGreaterThan(20_000); + }); }); diff --git a/apps/web/src/lib/voiceWav.ts b/apps/web/src/lib/voiceWav.ts index 3328fbea26ca0..0f8d03f851127 100644 --- a/apps/web/src/lib/voiceWav.ts +++ b/apps/web/src/lib/voiceWav.ts @@ -1,6 +1,7 @@ export const VOICE_WAV_SAMPLE_RATE = 16_000; const WAV_HEADER_BYTES = 44; +const PLATFORM_IS_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; function writeAscii(view: DataView, offset: number, text: string): void { for (let index = 0; index < text.length; index += 1) { @@ -9,6 +10,8 @@ function writeAscii(view: DataView, offset: number, text: string): void { } export function encodeWavPcm16(samples: ArrayLike, sampleRate: number): ArrayBuffer { + // Int16Array writes in platform byte order, and WAV requires little-endian. + if (!PLATFORM_IS_LITTLE_ENDIAN) throw new Error("WAV encoding needs a little-endian platform."); const dataBytes = samples.length * 2; const buffer = new ArrayBuffer(WAV_HEADER_BYTES + dataBytes); const view = new DataView(buffer); @@ -25,18 +28,16 @@ export function encodeWavPcm16(samples: ArrayLike, sampleRate: number): view.setUint16(34, 16, true); writeAscii(view, 36, "data"); view.setUint32(40, dataBytes, true); + const pcm = new Int16Array(buffer, WAV_HEADER_BYTES, samples.length); for (let index = 0; index < samples.length; index += 1) { const clamped = Math.max(-1, Math.min(1, samples[index] ?? 0)); - view.setInt16( - WAV_HEADER_BYTES + index * 2, - clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, - true, - ); + pcm[index] = clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff; } return buffer; } -export function downmixToMono(audio: AudioBuffer): Float32Array { +function downmixToMono(audio: AudioBuffer): Float32Array { + if (audio.numberOfChannels === 1) return audio.getChannelData(0); const mono = new Float32Array(audio.length); for (let channel = 0; channel < audio.numberOfChannels; channel += 1) { const samples = audio.getChannelData(channel); From f2701e0704ea0e1da27bfe8691bcf596c417a1d5 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:31:36 -0400 Subject: [PATCH 35/55] fix(web): leave Escape to other editables and expose retry from the voice hook Escape pressed inside an input, textarea, or contenteditable outside the composer's own root no longer cancels a recording; the overlay check for dialogs, menus, and listboxes stays and now lives in one named predicate. The hook takes the composer root as a ref for that check. The hook also returns `retry`, which re-sends a kept recording when the error offers it and records anew otherwise, and `announcement`, live-region text for the phase and for a transcript that landed. A browser test drives the hook through a fake recorder environment and transcriber: Escape ownership, owner changes, microphone release on cancel and unmount, and toggles during preparation. In ChatComposer the selection fallback becomes `editorSelectionFor`, and the `voiceCommitRef` bridge stays with its reason: the React Compiler reports "Cannot access variable while it is being initialized" for a closure over a const declared later. Co-Authored-By: Claude Fable 5.1 --- apps/web/src/components/chat/ChatComposer.tsx | 42 ++-- .../useComposerVoiceInput.browser.test.tsx | 199 ++++++++++++++++++ .../components/chat/useComposerVoiceInput.ts | 82 ++++++-- 3 files changed, 288 insertions(+), 35 deletions(-) create mode 100644 apps/web/src/components/chat/useComposerVoiceInput.browser.test.tsx diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 210c890a26c5b..70fe43d0712ff 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1896,6 +1896,16 @@ function useComposerImageGroups( const NO_PROVIDER_SKILLS: ServerProvider["skills"] = []; const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = []; +/** The editor's selection indexes only the text it was read from. */ +function editorSelectionFor( + editor: ComposerPromptEditorHandle | null, + text: string, +): { start: number; end: number } { + return editor && editor.readSnapshot().value === text + ? editor.readSelectionRange() + : { start: text.length, end: text.length }; +} + export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) { const { composerDraftTarget, @@ -2082,19 +2092,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const questionPreparations = useQuestionAttachmentPreparation((state) => state.counts); const prompt = composerDraft.prompt; const composerEditorRef = useRef(null); + const composerFormRef = useRef(null); + // A pending question swaps the composer's text for its answer, so a recording that + // started on the draft must not land there. + const voiceOwnerKey = + pendingUserInputs[0] && activePendingProgress?.activeQuestion + ? `${composerDraftTargetKey}:${pendingUserInputs[0].requestId}:${activePendingProgress.activeQuestion.id}` + : composerDraftTargetKey; const readVoiceDraftStable = useStableCallback(() => { const text = promptRef.current; - const editor = composerEditorRef.current; - // The editor's selection only indexes the text it was read from. - const selection = - editor && editor.readSnapshot().value === text - ? editor.readSelectionRange() - : { start: text.length, end: text.length }; - return { ownerKey: composerDraftTargetKey, text, selection }; + return { + ownerKey: voiceOwnerKey, + text, + selection: editorSelectionFor(composerEditorRef.current, text), + }; }); - // sendDisabledReason needs voice input before applyPromptReplacement is declared, and - // the React Compiler rejects a closure that captures a const declared later. The - // layout effect below that declaration fills this in. + // The React Compiler rejects a closure over applyPromptReplacement, a const declared + // after this hook, so the layout effect below that declaration fills in the ref. const voiceCommitRef = useRef< ((text: string, selection: { readonly start: number; readonly end: number }) => boolean) | null >(null); @@ -2102,17 +2116,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (text: string, selection: { readonly start: number; readonly end: number }) => voiceCommitRef.current?.(text, selection) ?? false, ); - // A pending question swaps the composer's text for its answer, so a recording that - // started on the draft must not land there. - const voiceOwnerKey = - pendingUserInputs[0] && activePendingProgress?.activeQuestion - ? `${composerDraftTargetKey}:${pendingUserInputs[0].requestId}:${activePendingProgress.activeQuestion.id}` - : composerDraftTargetKey; const voiceInput = useComposerVoiceInput({ environmentId, ownerKey: voiceOwnerKey, language: settings.voiceTranscription.language, draftText: prompt, + composerRef: composerFormRef, readDraft: readVoiceDraftStable, commitDraft: commitVoiceDraftStable, }); @@ -2525,7 +2534,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) names: new Set(), }); const attachmentInputRef = useRef(null); - const composerFormRef = useRef(null); const composerSurfaceRef = useRef(null); const providerInputRejectedRef = useRef(false); const composerSelectLockRef = useRef(false); diff --git a/apps/web/src/components/chat/useComposerVoiceInput.browser.test.tsx b/apps/web/src/components/chat/useComposerVoiceInput.browser.test.tsx new file mode 100644 index 0000000000000..001cd81eae362 --- /dev/null +++ b/apps/web/src/components/chat/useComposerVoiceInput.browser.test.tsx @@ -0,0 +1,199 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import type { + PreparedVoiceTranscription, + VoiceTranscriber, +} from "@t3tools/client-runtime/voice-input"; +import { useEffect, useRef } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import type { MediaRecorderLike, VoiceRecorderEnvironment } from "~/lib/voiceRecorder"; + +const fakes = vi.hoisted(() => ({ + environment: null as VoiceRecorderEnvironment | null, + transcriber: null as VoiceTranscriber | null, +})); +vi.mock(import("~/lib/voiceRecorder"), async (original) => ({ + ...(await original()), + createBrowserVoiceRecorderEnvironment: () => fakes.environment!, +})); +vi.mock(import("~/state/voiceTranscription"), () => ({ + createWebVoiceTranscriber: () => fakes.transcriber!, +})); + +import { useComposerVoiceInput, type ComposerVoiceInput } from "./useComposerVoiceInput"; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +class FakeMediaRecorder implements MediaRecorderLike { + state: RecordingState = "inactive"; + readonly mimeType = "audio/webm"; + private readonly listeners = new Map void>>(); + + constructor(private readonly onStart: () => void) {} + + addEventListener(type: string, listener: unknown): void { + this.listeners.set(type, [ + ...(this.listeners.get(type) ?? []), + listener as (event: never) => void, + ]); + } + + start(): void { + this.state = "recording"; + this.onStart(); + } + + stop(): void { + this.state = "inactive"; + for (const listener of this.listeners.get("dataavailable") ?? []) { + listener({ data: new Blob(["pcm"]) } as never); + } + for (const listener of this.listeners.get("stop") ?? []) listener(undefined as never); + } +} + +const prepared: PreparedVoiceTranscription = { locale: "en-US", transcribe: async () => "spoken" }; + +function setup(prepare: VoiceTranscriber["prepare"] = async () => prepared) { + const tracks = [{ stop: vi.fn() }]; + const stream = { getTracks: () => tracks } as unknown as MediaStream; + const pendingStarts: Array<() => void> = []; + fakes.environment = { + getUserMedia: async () => stream, + queryMicrophonePermission: async () => "granted", + isTypeSupported: () => true, + createMediaRecorder: () => new FakeMediaRecorder(() => pendingStarts.shift()?.()), + createLevelMeter: () => null, + createObjectURL: () => "blob:recording", + revokeObjectURL: () => {}, + deniedBy: "browser", + }; + const prepareSpy = vi.fn(prepare); + fakes.transcriber = { prepare: prepareSpy }; + const armStart = () => { + const started = deferred(); + pendingStarts.push(() => started.resolve()); + return started.promise; + }; + const startRecording = async () => { + const started = armStart(); + await act(async () => { + voice.toggle(); + await started; + }); + expect(voice.state.phase).toBe("recording"); + }; + return { tracks, prepare: prepareSpy, armStart, startRecording }; +} + +let voice!: ComposerVoiceInput; +function Host({ ownerKey }: { ownerKey: string }) { + const rootRef = useRef(null); + const next = useComposerVoiceInput({ + environmentId: EnvironmentId.make("environment"), + ownerKey, + language: "", + draftText: "hello", + composerRef: rootRef, + readDraft: () => ({ ownerKey, text: "hello", selection: { start: 5, end: 5 } }), + commitDraft: () => true, + }); + useEffect(() => { + voice = next; + }, [next]); + return ( +
+
+
+ ); +} + +function Page({ ownerKey = "thread-1" }: { ownerKey?: string }) { + return ( + <> + + +
+ +
+ + ); +} + +function pressEscape(target: Element) { + return act(async () => { + target.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }), + ); + }); +} + +describe("useComposerVoiceInput", () => { + it("leaves Escape to an open dialog or another editable and cancels from the composer", async () => { + const { tracks, startRecording } = setup(); + await using screen = await render(); + await startRecording(); + + await pressEscape(screen.getByRole("button", { name: "Close" }).element()); + expect(voice.state.phase).toBe("recording"); + await pressEscape(screen.getByRole("textbox", { name: "Sidebar search" }).element()); + expect(voice.state.phase).toBe("recording"); + expect(tracks[0]!.stop).not.toHaveBeenCalled(); + + await pressEscape(screen.container.querySelector('[aria-label="Composer editor"]')!); + expect(voice.state.phase).toBe("idle"); + expect(tracks[0]!.stop).toHaveBeenCalledTimes(1); + }); + + it("cancels the recording when the composer's owner changes", async () => { + const { tracks, startRecording } = setup(); + await using screen = await render(); + await startRecording(); + + await screen.rerender(); + expect(voice.state.phase).toBe("idle"); + expect(tracks[0]!.stop).toHaveBeenCalledTimes(1); + }); + + it("releases the microphone on cancel and on unmount", async () => { + const { tracks, startRecording } = setup(); + await using screen = await render(); + await startRecording(); + await act(async () => voice.cancel()); + expect(voice.state.phase).toBe("idle"); + expect(tracks[0]!.stop).toHaveBeenCalledTimes(1); + + await startRecording(); + await screen.unmount(); + expect(tracks[0]!.stop).toHaveBeenCalledTimes(2); + }); + + it("ignores toggle while voice input is still starting", async () => { + const preparation = deferred(); + const { prepare, armStart } = setup(() => preparation.promise); + await using screen = await render(); + const started = armStart(); + await act(async () => voice.toggle()); + expect(voice.state.phase).toBe("preparing"); + expect(voice.busy).toBe(true); + expect(prepare).toHaveBeenCalledTimes(1); + + await act(async () => voice.toggle()); + expect(voice.state.phase).toBe("preparing"); + expect(prepare).toHaveBeenCalledTimes(1); + + await act(async () => { + preparation.resolve(prepared); + await started; + }); + expect(voice.state.phase).toBe("recording"); + await screen.unmount(); + }); +}); diff --git a/apps/web/src/components/chat/useComposerVoiceInput.ts b/apps/web/src/components/chat/useComposerVoiceInput.ts index c27c0df91d23a..78ce65aecb517 100644 --- a/apps/web/src/components/chat/useComposerVoiceInput.ts +++ b/apps/web/src/components/chat/useComposerVoiceInput.ts @@ -5,7 +5,7 @@ import { type VoiceDraftSnapshot, type VoiceInputState, } from "@t3tools/client-runtime/voice-input"; -import { useEffect, useLayoutEffect, useState } from "react"; +import { useEffect, useLayoutEffect, useState, type RefObject } from "react"; import { isCommandPaletteOpen } from "~/commandPaletteBus"; import { createBrowserVoiceRecorderEnvironment, createWebVoiceRecorder } from "~/lib/voiceRecorder"; @@ -18,6 +18,8 @@ export interface ComposerVoiceInputInput { readonly ownerKey: string; readonly language: string; readonly draftText: string; + /** Escape inside an editable element outside this root belongs to that element. */ + readonly composerRef: RefObject; readonly readDraft: () => Omit; /** False when the composer refused the text, for example while a choice-only question owns it. */ readonly commitDraft: (text: string, selection: VoiceDraftSnapshot["selection"]) => boolean; @@ -26,27 +28,67 @@ export interface ComposerVoiceInputInput { export interface ComposerVoiceInput { readonly state: VoiceInputState; readonly busy: boolean; + /** Live-region text: the phase while running, then whether a transcript landed. */ + readonly announcement: string; readonly readStartedAt: () => number | null; readonly readLevel: () => number; readonly toggle: () => void; + /** Sends a kept recording again when the error offers it, otherwise records anew. */ + readonly retry: () => void; readonly cancel: () => void; } -interface VoiceInputRuntime extends Omit { +interface VoiceInputSnapshot { + readonly state: VoiceInputState; + readonly announcement: string; +} + +const IDLE_SNAPSHOT: VoiceInputSnapshot = { state: IDLE_STATE, announcement: "" }; + +interface VoiceInputRuntime extends Omit { readonly setInput: (input: ComposerVoiceInputInput) => void; readonly setOwner: (ownerKey: string) => void; readonly setDraftText: (draftText: string) => void; + readonly composerRoot: () => Element | null; readonly dispose: () => void; } +function announcementFor(state: VoiceInputState, transcriptInserted: boolean): string { + switch (state.phase) { + case "preparing": + return "Starting voice input."; + case "recording": + return "Recording."; + case "transcribing": + return "Transcribing."; + case "idle": + return transcriptInserted ? "Transcript inserted." : ""; + case "error": + // The error banner is an alert and announces itself. + return ""; + } +} + +const OVERLAY_SELECTOR = '[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]'; +const EDITABLE_SELECTOR = + 'input, textarea, select, [contenteditable]:not([contenteditable="false"])'; + +function escapeBelongsElsewhere(target: EventTarget | null, composerRoot: Element | null): boolean { + if (!(target instanceof Element)) return false; + if (target.closest(OVERLAY_SELECTOR)) return true; + const editable = target.closest(EDITABLE_SELECTOR); + return editable !== null && !(composerRoot?.contains(editable) ?? false); +} + function createRuntime( initialInput: ComposerVoiceInputInput, - onStateChange: (state: VoiceInputState) => void, + onSnapshot: (snapshot: VoiceInputSnapshot) => void, ): VoiceInputRuntime { let latest = initialInput; let draftText = initialInput.draftText; let revision = 0; let ownerKey: string | null = null; + let transcriptInserted = false; let controller: VoiceInputController | null = null; const recorder = createWebVoiceRecorder(createBrowserVoiceRecorderEnvironment(), (status) => { void controller?.handleRecorderStatus(status); @@ -59,9 +101,13 @@ function createRuntime( releaseRecording: recorder.releaseRecording, deleteRecording: recorder.deleteRecording, readDraft: () => ({ ...latest.readDraft(), revision }), - commitDraft: (text, selection) => latest.commitDraft(text, selection), + commitDraft: (text, selection) => { + transcriptInserted = latest.commitDraft(text, selection); + return transcriptInserted; + }, onStateChange: (state) => { - onStateChange(state); + onSnapshot({ state, announcement: announcementFor(state, transcriptInserted) }); + transcriptInserted = false; if (!voiceInputBlocksSubmission(state)) void recorder.releaseRecording(); }, }); @@ -79,6 +125,7 @@ function createRuntime( draftText = next; revision += 1; }, + composerRoot: () => latest.composerRef.current, dispose: () => { active.dispose(); void recorder.releaseRecording(); @@ -90,14 +137,19 @@ function createRuntime( if (phase === "recording") void active.stop(); else if (phase === "idle" || phase === "error") void active.start(); }, + retry: () => { + const { phase, errorAction } = active.currentState; + if (errorAction === "retry-transcription") void active.retryTranscription(); + else if (phase === "idle" || phase === "error") void active.start(); + }, cancel: () => active.cancel(), }; } export function useComposerVoiceInput(input: ComposerVoiceInputInput): ComposerVoiceInput { - const [state, setState] = useState(IDLE_STATE); - const [runtime] = useState(() => createRuntime(input, setState)); - const busy = voiceInputBlocksSubmission(state); + const [snapshot, setSnapshot] = useState(IDLE_SNAPSHOT); + const [runtime] = useState(() => createRuntime(input, setSnapshot)); + const busy = voiceInputBlocksSubmission(snapshot.state); useLayoutEffect(() => { runtime.setInput(input); @@ -114,15 +166,7 @@ export function useComposerVoiceInput(input: ComposerVoiceInputInput): ComposerV if (!busy) return; const onKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape" || event.defaultPrevented || isCommandPaletteOpen()) return; - // A dialog or menu that is open owns its own Escape. - if ( - event.target instanceof Element && - event.target.closest( - '[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]', - ) - ) { - return; - } + if (escapeBelongsElsewhere(event.target, runtime.composerRoot())) return; event.preventDefault(); runtime.cancel(); }; @@ -131,11 +175,13 @@ export function useComposerVoiceInput(input: ComposerVoiceInputInput): ComposerV }, [busy, runtime]); return { - state, + state: snapshot.state, busy, + announcement: snapshot.announcement, readStartedAt: runtime.readStartedAt, readLevel: runtime.readLevel, toggle: runtime.toggle, + retry: runtime.retry, cancel: runtime.cancel, }; } From 181a490c2b30697ce16e5d0d3641ca17ecfbc069 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:37:14 -0400 Subject: [PATCH 36/55] fix(web): show voice input errors as a composer banner and keep the footer stable The voice error no longer renders inline in the footer, where it pushed the composer controls into the overflow menu at desktop widths. It is now a ComposerBanner stack item built by voiceInputBannerItem: the message, Retry or Open settings, and a dismiss. A System Settings launch that fails shows a toast instead of leaving a rejected promise. Retry re-sends a kept recording. The footer keeps only the mic or the recording pill, and the compaction breakpoints reserve the pill's width while voice input runs so Send never clips. The mic uses aria-disabled while preparing or transcribing so focus survives, drops aria-pressed, shows the shortcut only in states where it acts, and carries a visually hidden status region that announces the phase and an inserted transcript; the banner is an alert and announces errors. Voice availability in the composer, the palette, and the upload URL resolver now reads the createTranscriptionUrl command's permissionAtom, and the mic hides when the environment is unavailable rather than consulting the always false isConnecting flag. Co-Authored-By: Claude Fable 5.1 --- apps/web/src/components/CommandPalette.tsx | 10 +- apps/web/src/components/chat/ChatComposer.tsx | 29 ++- .../ComposerVoiceInputBanner.browser.test.tsx | 61 +++++++ .../chat/ComposerVoiceInputBanner.tsx | 81 +++++++++ ...ComposerVoiceInputControl.browser.test.tsx | 167 +++++++----------- .../chat/ComposerVoiceInputControl.tsx | 102 +++-------- .../useComposerVoiceInput.browser.test.tsx | 20 ++- .../components/composerFooterLayout.test.ts | 21 +++ .../src/components/composerFooterLayout.ts | 27 ++- apps/web/src/state/voiceTranscription.ts | 9 +- 10 files changed, 331 insertions(+), 196 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerVoiceInputBanner.browser.test.tsx create mode 100644 apps/web/src/components/chat/ComposerVoiceInputBanner.tsx diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index d2a230f47d482..e31642ceb8844 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -124,6 +124,7 @@ import { useEnvironmentQuery } from "../state/query"; import { serverEnvironment } from "../state/server"; import { threadEnvironment } from "../state/threads"; import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; +import { voiceTranscriptionEnvironment } from "~/state/voiceTranscription"; import { sourceControlEnvironment } from "../state/sourceControl"; import { useAtomCommand } from "../state/use-atom-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; @@ -1022,12 +1023,13 @@ function OpenCommandPaletteDialog(props: { const currentProjectEnvironmentId = activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null; const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null; - const canOperateCurrentEnvironment = useEnvironmentScope( - currentProjectEnvironmentId, - AuthOrchestrationOperateScope, + const canCreateTranscriptionUrl = useAtomValue( + voiceTranscriptionEnvironment.createTranscriptionUrl.permissionAtom( + currentProjectEnvironmentId, + ), ); const voiceInputAvailable = - canOperateCurrentEnvironment && + canCreateTranscriptionUrl && environments.find((environment) => environment.environmentId === currentProjectEnvironmentId) ?.serverConfig?.settings.voiceTranscription.enabled === true; const composerHandleRef = useComposerHandleContext(); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 70fe43d0712ff..87c0454d88192 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,3 +1,4 @@ +import { useAtomValue } from "@effect/atom-react"; import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills"; import { useComposerTypingGuard } from "./useComposerTypingGuard"; import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences"; @@ -5,6 +6,7 @@ import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; import { runtimeModeConfig, runtimeModeOptions as runtimeModes } from "./runtimeModeConfig"; import { isLocalEnvironmentDisabled } from "../../localEnvironment"; import { usePrimaryEnvironmentId } from "../../state/environments"; +import { voiceTranscriptionEnvironment } from "~/state/voiceTranscription"; import { useRightPanelStore } from "~/rightPanelStore"; import { AttachmentFilePreview } from "../files/AttachmentFilePreview"; import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; @@ -1066,6 +1068,7 @@ import { } from "lucide-react"; import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText"; import { hasProviderSetup } from "./ProviderStatusBanner"; +import { voiceInputBannerItem } from "./ComposerVoiceInputBanner"; import { ComposerVoiceInputControl } from "./ComposerVoiceInputControl"; import { useComposerVoiceInput } from "./useComposerVoiceInput"; import { @@ -2116,6 +2119,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (text: string, selection: { readonly start: number; readonly end: number }) => voiceCommitRef.current?.(text, selection) ?? false, ); + const canCreateTranscriptionUrl = useAtomValue( + voiceTranscriptionEnvironment.createTranscriptionUrl.permissionAtom(environmentId), + ); const voiceInput = useComposerVoiceInput({ environmentId, ownerKey: voiceOwnerKey, @@ -2891,13 +2897,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion?.allowCustomAnswer !== false)); const showComposerVoiceAction = settings.voiceTranscription.enabled && - canOperateThread && - !isConnecting && + canCreateTranscriptionUrl && + environmentUnavailable === null && !isComposerApprovalState && !projectSelectionRequired && !isChoiceOnlyPendingQuestion && !activePendingIsResponding; const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; + const composerFooterHasActiveVoiceControl = voiceInput.busy; const isComposerMenuLoading = (composerTriggerKind === "path" && pathTriggerQuery.length > 0 && workspaceEntries.isPending) || @@ -3534,11 +3541,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerFormWidth = measureComposerFormWidth(); const footerCompact = shouldUseCompactComposerFooter(composerFormWidth, { hasWideActions: composerFooterHasWideActions, + hasActiveVoiceControl: composerFooterHasActiveVoiceControl, }); const primaryActionsCompact = footerCompact && shouldUseCompactComposerPrimaryActions(composerFormWidth, { hasWideActions: composerFooterHasWideActions, + hasActiveVoiceControl: composerFooterHasActiveVoiceControl, }); return { primaryActionsCompact, @@ -3560,7 +3569,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact, ); }); - }, [composerFooterHasWideActions]); + }, [composerFooterHasWideActions, composerFooterHasActiveVoiceControl]); useEffect(() => { let cancelled = false; @@ -5394,9 +5403,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) content: activityStackContent, } : null; - const bannerStackItems = activityStackItem - ? [activityStackItem, ...props.bannerItems] - : props.bannerItems; + const voiceBannerItem = voiceInputBannerItem({ + state: voiceInput.state, + onRetry: voiceInput.retry, + onDismiss: voiceInput.cancel, + }); + const bannerStackItems = [ + ...(voiceBannerItem ? [voiceBannerItem] : []), + ...(activityStackItem ? [activityStackItem] : []), + ...props.bannerItems, + ]; const [tasksDrawerThreadId, setTasksDrawerThreadId] = useState(activeThreadId); if ( isTasksDrawerOpen && @@ -7398,6 +7414,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) keybindings, "composer.toggleDictation", )} + announcement={voiceInput.announcement} readStartedAt={voiceInput.readStartedAt} readLevel={voiceInput.readLevel} onToggle={voiceInput.toggle} diff --git a/apps/web/src/components/chat/ComposerVoiceInputBanner.browser.test.tsx b/apps/web/src/components/chat/ComposerVoiceInputBanner.browser.test.tsx new file mode 100644 index 0000000000000..8447a1edcec96 --- /dev/null +++ b/apps/web/src/components/chat/ComposerVoiceInputBanner.browser.test.tsx @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import "~/index.css"; +import { act, render } from "../../../test/render"; +import { toastManager } from "../ui/toast"; +import { ComposerBannerStack } from "./ComposerBannerStack"; +import { voiceInputBannerItem } from "./ComposerVoiceInputBanner"; + +const denied = { + phase: "error", + error: "Microphone access is required for voice input.", + errorAction: "settings", +} as const; + +function click(element: Element) { + return act(async () => (element as HTMLElement).click()); +} + +describe("voiceInputBannerItem", () => { + it("explains a failed System Settings launch instead of leaving a rejected promise", async () => { + using add = vi.spyOn(toastManager, "add").mockImplementation(() => "toast"); + const item = voiceInputBannerItem({ + state: denied, + errorContext: { secureContext: true, permissionHost: "macos" }, + openSettings: async () => { + throw new Error("Unable to open System Settings."); + }, + onRetry: () => {}, + onDismiss: () => {}, + }); + await using screen = await render(); + expect(screen.getByRole("alert").element().textContent).toContain("System Settings"); + + await click(screen.getByRole("button", { name: "Open settings" }).element()); + expect(add).toHaveBeenCalledWith( + expect.objectContaining({ type: "error", description: "Unable to open System Settings." }), + ); + }); + + it("offers Retry for a kept recording and nothing while voice input runs", async () => { + const onRetry = vi.fn(); + const item = voiceInputBannerItem({ + state: { phase: "error", error: "Upload failed.", errorAction: "retry-transcription" }, + errorContext: { secureContext: true, permissionHost: "browser" }, + onRetry, + onDismiss: () => {}, + }); + await using screen = await render(); + expect(screen.getByRole("alert").element().textContent).toContain("Upload failed."); + await click(screen.getByRole("button", { name: "Retry" }).element()); + expect(onRetry).toHaveBeenCalledTimes(1); + + expect( + voiceInputBannerItem({ + state: { phase: "recording", error: null, errorAction: null }, + onRetry, + onDismiss: () => {}, + }), + ).toBeNull(); + }); +}); diff --git a/apps/web/src/components/chat/ComposerVoiceInputBanner.tsx b/apps/web/src/components/chat/ComposerVoiceInputBanner.tsx new file mode 100644 index 0000000000000..18fdc4abe91ab --- /dev/null +++ b/apps/web/src/components/chat/ComposerVoiceInputBanner.tsx @@ -0,0 +1,81 @@ +import type { VoiceInputState } from "@t3tools/client-runtime/voice-input"; +import { MicOffIcon } from "lucide-react"; + +import { microphonePermissionHost, openMicrophoneSystemSettings } from "~/lib/microphoneSettings"; +import { Button } from "../ui/button"; +import { toastManager } from "../ui/toast"; +import type { ComposerBannerStackItem } from "./ComposerBannerStack"; +import { + resolveVoiceInputErrorPresentation, + type VoiceInputErrorContext, +} from "./voiceInputErrorPresentation"; + +const BROWSER_ERROR_CONTEXT: VoiceInputErrorContext = { + secureContext: typeof window !== "undefined" && window.isSecureContext, + permissionHost: microphonePermissionHost, +}; + +function keepEditorSelection(event: React.PointerEvent) { + event.preventDefault(); +} + +async function openSettingsOrExplain(openSettings: () => Promise): Promise { + try { + await openSettings(); + } catch (error) { + toastManager.add({ + type: "error", + title: "Could not open System Settings", + description: + error instanceof Error && error.message + ? error.message + : "Open System Settings > Privacy & Security > Microphone and allow T3 Code.", + }); + } +} + +export function voiceInputBannerItem(input: { + readonly state: VoiceInputState; + readonly onRetry: () => void; + readonly onDismiss: () => void; + readonly errorContext?: VoiceInputErrorContext; + readonly openSettings?: () => Promise; +}): ComposerBannerStackItem | null { + const error = resolveVoiceInputErrorPresentation( + input.state, + input.errorContext ?? BROWSER_ERROR_CONTEXT, + ); + if (!error) return null; + const openSettings = input.openSettings ?? openMicrophoneSystemSettings; + const actions = + error.action === "open-settings" ? ( + + ) : error.action === "retry" ? ( + + ) : null; + return { + id: "voice-input-error", + variant: "error", + priority: "urgent", + icon: , + title: error.message, + ...(actions ? { actions } : {}), + dismissLabel: "Dismiss voice input error", + onDismiss: input.onDismiss, + }; +} diff --git a/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx b/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx index 9f3ca30a5727e..deae25af66653 100644 --- a/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerVoiceInputControl.browser.test.tsx @@ -1,129 +1,96 @@ -import type { VoiceInputState } from "@t3tools/client-runtime/voice-input"; +import type { VoiceInputPhase, VoiceInputState } from "@t3tools/client-runtime/voice-input"; +import { useState } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; import "~/index.css"; -import { act, render } from "../../../test/render"; +import { act, fakeTimers, render } from "../../../test/render"; import { ComposerVoiceInputControl } from "./ComposerVoiceInputControl"; -const IDLE: VoiceInputState = { phase: "idle", error: null, errorAction: null }; -const PREPARING: VoiceInputState = { phase: "preparing", error: null, errorAction: null }; -const RECORDING: VoiceInputState = { phase: "recording", error: null, errorAction: null }; -const TRANSCRIBING: VoiceInputState = { phase: "transcribing", error: null, errorAction: null }; +const phaseState = (phase: VoiceInputPhase): VoiceInputState => ({ + phase, + error: null, + errorAction: null, +}); + +// Every toggle moves the phase, so a click the control should have ignored shows up. +const TOGGLED: Record = { + idle: "recording", + error: "recording", + preparing: "idle", + recording: "transcribing", + transcribing: "idle", +}; + +const notStarted = () => null; -function control( - state: VoiceInputState, - overrides: Partial> = {}, -) { +function Host({ + initialPhase, + readStartedAt = notStarted, +}: { + initialPhase: VoiceInputPhase; + readStartedAt?: () => number | null; +}) { + const [phase, setPhase] = useState(initialPhase); return (
null} + announcement="" + readStartedAt={readStartedAt} readLevel={() => 0} - onToggle={() => {}} - onCancel={() => {}} - onOpenSettings={() => {}} - {...overrides} + onToggle={() => setPhase((current) => TOGGLED[current])} + onCancel={() => setPhase("idle")} />
); } -const toggleButton = (container: HTMLElement) => - [...container.querySelectorAll("button")].at(-1)!; +function click(element: Element) { + return act(async () => (element as HTMLElement).click()); +} describe("ComposerVoiceInputControl", () => { it("keeps the stop control exactly where the mic button was, so a second click in the same spot stops", async () => { - const onToggle = vi.fn(); - await using screen = await render(control(IDLE, { onToggle })); - const idleButton = toggleButton(screen.container); - expect(idleButton.getAttribute("aria-label")).toBe("Voice input"); - const idleRect = idleButton.getBoundingClientRect(); - await act(async () => idleButton.click()); - expect(onToggle).toHaveBeenCalledTimes(1); + await using screen = await render(); + const mic = screen.getByRole("button", { name: "Voice input" }).element(); + const idleRect = mic.getBoundingClientRect(); + await click(mic); - await screen.rerender(control(RECORDING, { onToggle })); - const stopButton = toggleButton(screen.container); - expect(stopButton.getAttribute("aria-label")).toBe("Stop and transcribe"); - const recordingRect = stopButton.getBoundingClientRect(); - expect(recordingRect.left).toBe(idleRect.left); - expect(recordingRect.top).toBe(idleRect.top); - expect(recordingRect.width).toBe(idleRect.width); - expect(recordingRect.height).toBe(idleRect.height); - expect(screen.container.querySelector('[aria-label="Cancel voice input"]')).not.toBeNull(); + const stop = screen.getByRole("button", { name: "Stop and transcribe" }).element(); + expect(stop.getBoundingClientRect()).toEqual(idleRect); + screen.getByRole("button", { name: "Cancel voice input" }).element(); - await act(async () => stopButton.click()); - expect(onToggle).toHaveBeenCalledTimes(2); + await click(stop); + screen.getByRole("button", { name: "Transcribing" }).element(); }); - it("disables the stop control while transcribing but keeps cancel available", async () => { - const onCancel = vi.fn(); - await using screen = await render(control(TRANSCRIBING, { onCancel })); - expect(toggleButton(screen.container).disabled).toBe(true); - expect(screen.container.querySelector('[role="status"]')).not.toBeNull(); - const cancel = screen.container.querySelector( - '[aria-label="Cancel voice input"]', - )!; - expect(cancel.disabled).toBe(false); - await act(async () => cancel.click()); - expect(onCancel).toHaveBeenCalledTimes(1); + it("keeps the mic focusable but inert while transcribing and leaves cancel live", async () => { + await using screen = await render(); + const mic = screen.getByRole("button", { name: "Transcribing" }).element() as HTMLButtonElement; + expect(mic.disabled).toBe(false); + expect(mic.getAttribute("aria-disabled")).toBe("true"); + mic.focus(); + expect(document.activeElement).toBe(mic); + + await click(mic); + expect(screen.getByRole("button", { name: "Transcribing" }).query()).toBe(mic); + + await click(screen.getByRole("button", { name: "Cancel voice input" }).element()); + screen.getByRole("button", { name: "Voice input" }).element(); + expect(screen.getByRole("button", { name: "Cancel voice input" }).query()).toBeNull(); }); it("counts recording time from the recorder's start", async () => { let startedAt: number | null = null; - await using screen = await render(control(PREPARING, { readStartedAt: () => startedAt })); - vi.useFakeTimers(); - try { - startedAt = Date.now(); - await screen.rerender(control(RECORDING, { readStartedAt: () => startedAt })); - expect(screen.container.textContent).toContain("0:00"); - await act(async () => { - await vi.advanceTimersByTimeAsync(62_000); - }); - expect(screen.container.textContent).toContain("1:02"); - } finally { - vi.useRealTimers(); - } - }); - - it("explains a blocked microphone and offers the fix the platform has", async () => { - const denied: VoiceInputState = { - phase: "error", - error: "Microphone access is required for voice input.", - errorAction: "settings", - }; - const onOpenSettings = vi.fn(); - await using screen = await render( - control(denied, { - onOpenSettings, - errorContext: { secureContext: true, permissionHost: "macos" }, - }), - ); - expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( - "System Settings", - ); - const open = [...screen.container.querySelectorAll("button")].find( - (button) => button.textContent === "Open settings", - )!; - await act(async () => open.click()); - expect(onOpenSettings).toHaveBeenCalledTimes(1); - - const onToggle = vi.fn(); - await screen.rerender( - control( - { phase: "error", error: "No speech was detected.", errorAction: "retry" }, - { onToggle }, - ), - ); - expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( - "No speech was detected.", - ); - const retry = [...screen.container.querySelectorAll("button")].find( - (button) => button.textContent === "Retry", - )!; - await act(async () => retry.click()); - expect(onToggle).toHaveBeenCalledTimes(1); + await using screen = await render( startedAt} />); + using _timers = fakeTimers(); + startedAt = Date.now(); + await click(screen.getByRole("button", { name: "Voice input" }).element()); + expect(screen.container.textContent).toContain("0:00"); + await act(async () => { + await vi.advanceTimersByTimeAsync(62_000); + }); + expect(screen.container.textContent).toContain("1:02"); }); }); diff --git a/apps/web/src/components/chat/ComposerVoiceInputControl.tsx b/apps/web/src/components/chat/ComposerVoiceInputControl.tsx index 278da32f5ee35..04e2e4c4d4da9 100644 --- a/apps/web/src/components/chat/ComposerVoiceInputControl.tsx +++ b/apps/web/src/components/chat/ComposerVoiceInputControl.tsx @@ -1,28 +1,26 @@ -import type { VoiceInputState } from "@t3tools/client-runtime/voice-input"; -import { CircleAlertIcon, MicIcon, XIcon } from "lucide-react"; +import type { VoiceInputPhase, VoiceInputState } from "@t3tools/client-runtime/voice-input"; +import { MicIcon, XIcon } from "lucide-react"; import { memo, useEffect, useLayoutEffect, useRef, useState } from "react"; import { useMediaQuery } from "~/hooks/useMediaQuery"; -import { microphonePermissionHost, openMicrophoneSystemSettings } from "~/lib/microphoneSettings"; import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; import { Spinner } from "../ui/spinner"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -import { - resolveVoiceInputErrorPresentation, - type VoiceInputErrorContext, -} from "./voiceInputErrorPresentation"; const VOICE_METER_INTERVAL_MS = 66; const VOICE_METER_BAR_COUNT = 5; const VOICE_METER_REST_SCALE = 0.15; -const BROWSER_ERROR_CONTEXT: VoiceInputErrorContext = { - secureContext: typeof window !== "undefined" && window.isSecureContext, - permissionHost: microphonePermissionHost, +const TOGGLE_LABELS: Record = { + idle: "Voice input", + error: "Voice input", + preparing: "Starting voice input", + recording: "Stop and transcribe", + transcribing: "Transcribing", }; -export function formatVoiceElapsed(seconds: number): string { +function formatVoiceElapsed(seconds: number): string { const whole = Math.max(0, Math.floor(seconds)); return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`; } @@ -97,36 +95,33 @@ function VoiceElapsed({ export interface ComposerVoiceInputControlProps { readonly state: VoiceInputState; readonly shortcutLabel: string | null; + /** Read by the visually hidden status region; errors are announced by their banner. */ + readonly announcement: string; readonly readStartedAt: () => number | null; readonly readLevel: () => number; readonly onToggle: () => void; readonly onCancel: () => void; - readonly errorContext?: VoiceInputErrorContext; - readonly onOpenSettings?: () => void; } export const ComposerVoiceInputControl = memo(function ComposerVoiceInputControl( props: ComposerVoiceInputControlProps, ) { - const { state, shortcutLabel, readStartedAt, readLevel, onToggle, onCancel } = props; - const errorContext = props.errorContext ?? BROWSER_ERROR_CONTEXT; - const onOpenSettings = props.onOpenSettings ?? openMicrophoneSystemSettings; + const { state, shortcutLabel, announcement, readStartedAt, readLevel, onToggle, onCancel } = + props; const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)"); const phase = state.phase; const active = phase === "preparing" || phase === "recording" || phase === "transcribing"; - const error = resolveVoiceInputErrorPresentation(state, errorContext); - const shortcutSuffix = shortcutLabel ? ` (${shortcutLabel})` : ""; - const toggleLabel = - phase === "recording" - ? "Stop and transcribe" - : phase === "transcribing" - ? "Transcribing" - : phase === "preparing" - ? "Starting voice input" - : "Voice input"; + // aria-disabled rather than disabled, so keyboard focus survives the transition. + const toggleInert = phase === "preparing" || phase === "transcribing"; + const toggleLabel = TOGGLE_LABELS[phase]; + const toggleTooltip = + shortcutLabel && !toggleInert ? `${toggleLabel} (${shortcutLabel})` : toggleLabel; return (
+ + {announcement} + {active ? ( <> @@ -144,7 +139,7 @@ export const ComposerVoiceInputControl = memo(function ComposerVoiceInputControl > - Cancel voice input (Esc) + Cancel voice input
{phase === "transcribing" ? ( @@ -157,50 +152,6 @@ export const ComposerVoiceInputControl = memo(function ComposerVoiceInputControl
- ) : error ? ( -
- - } - > - - {error.message} - - {error.message} - - {error.action === "open-settings" ? ( - - ) : error.action === "retry" ? ( - - ) : null} - -
) : null} { + if (!toggleInert) onToggle(); + }} /> } > - {`${toggleLabel}${shortcutSuffix}`} + {toggleTooltip}
); diff --git a/apps/web/src/components/chat/useComposerVoiceInput.browser.test.tsx b/apps/web/src/components/chat/useComposerVoiceInput.browser.test.tsx index 001cd81eae362..ac35d3796d47b 100644 --- a/apps/web/src/components/chat/useComposerVoiceInput.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerVoiceInput.browser.test.tsx @@ -62,6 +62,7 @@ class FakeMediaRecorder implements MediaRecorderLike { const prepared: PreparedVoiceTranscription = { locale: "en-US", transcribe: async () => "spoken" }; function setup(prepare: VoiceTranscriber["prepare"] = async () => prepared) { + commits = []; const tracks = [{ stop: vi.fn() }]; const stream = { getTracks: () => tracks } as unknown as MediaStream; const pendingStarts: Array<() => void> = []; @@ -94,6 +95,7 @@ function setup(prepare: VoiceTranscriber["prepare"] = async () => prepared) { } let voice!: ComposerVoiceInput; +let commits: Array<{ text: string; selection: { start: number; end: number } }> = []; function Host({ ownerKey }: { ownerKey: string }) { const rootRef = useRef(null); const next = useComposerVoiceInput({ @@ -103,7 +105,10 @@ function Host({ ownerKey }: { ownerKey: string }) { draftText: "hello", composerRef: rootRef, readDraft: () => ({ ownerKey, text: "hello", selection: { start: 5, end: 5 } }), - commitDraft: () => true, + commitDraft: (text, selection) => { + commits.push({ text, selection }); + return true; + }, }); useEffect(() => { voice = next; @@ -175,6 +180,19 @@ describe("useComposerVoiceInput", () => { expect(tracks[0]!.stop).toHaveBeenCalledTimes(2); }); + it("inserts the transcript at the captured selection and announces each step", async () => { + const { startRecording } = setup(); + await using _screen = await render(); + expect(voice.announcement).toBe(""); + await startRecording(); + expect(voice.announcement).toBe("Recording."); + + await act(async () => voice.toggle()); + expect(voice.state.phase).toBe("idle"); + expect(commits).toEqual([{ text: "hello spoken", selection: { start: 12, end: 12 } }]); + expect(voice.announcement).toBe("Transcript inserted."); + }); + it("ignores toggle while voice input is still starting", async () => { const preparation = deferred(); const { prepare, armStart } = setup(() => preparation.promise); diff --git a/apps/web/src/components/composerFooterLayout.test.ts b/apps/web/src/components/composerFooterLayout.test.ts index 818a99bcf2263..51172178c5169 100644 --- a/apps/web/src/components/composerFooterLayout.test.ts +++ b/apps/web/src/components/composerFooterLayout.test.ts @@ -5,8 +5,29 @@ import { resolveComposerTimelineInset, resolveRestingComposerControlsLayout, resolveRestingComposerControlsNaturalWidth, + shouldUseCompactComposerFooter, + shouldUseCompactComposerPrimaryActions, } from "./composerFooterLayout"; +describe("composer footer compaction", () => { + it("reserves room for the recording pill so the send button never clips", () => { + expect(shouldUseCompactComposerFooter(700)).toBe(false); + expect(shouldUseCompactComposerFooter(700, { hasActiveVoiceControl: true })).toBe(true); + expect(shouldUseCompactComposerFooter(760, { hasActiveVoiceControl: true })).toBe(false); + + expect(shouldUseCompactComposerPrimaryActions(850, { hasWideActions: true })).toBe(false); + expect( + shouldUseCompactComposerPrimaryActions(850, { + hasWideActions: true, + hasActiveVoiceControl: true, + }), + ).toBe(true); + expect(shouldUseCompactComposerPrimaryActions(850, { hasActiveVoiceControl: true })).toBe( + false, + ); + }); +}); + describe("resolveComposerTimelineInset", () => { it("keeps timeline padding stable when the model-only strip appears on collapse", () => { const expanded = resolveComposerTimelineInset({ diff --git a/apps/web/src/components/composerFooterLayout.ts b/apps/web/src/components/composerFooterLayout.ts index cb7efd12afa42..215dffebb5cc4 100644 --- a/apps/web/src/components/composerFooterLayout.ts +++ b/apps/web/src/components/composerFooterLayout.ts @@ -1,7 +1,23 @@ const COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX = 620; const COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX = 780; +/** Cancel, level meter, elapsed time, and the mic while voice input runs. */ +const COMPOSER_FOOTER_ACTIVE_VOICE_CONTROL_PX = 132; const RESTING_COMPOSER_IMAGE_THUMBNAIL_LIMIT = 3; +export interface ComposerFooterCompactnessOptions { + hasWideActions?: boolean; + hasActiveVoiceControl?: boolean; +} + +function composerFooterCompactBreakpoint(options?: ComposerFooterCompactnessOptions): number { + return ( + (options?.hasWideActions + ? COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX + : COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX) + + (options?.hasActiveVoiceControl ? COMPOSER_FOOTER_ACTIVE_VOICE_CONTROL_PX : 0) + ); +} + export function getRestingComposerImagePreviewCounts(imageCount: number): { visibleCount: number; overflowCount: number; @@ -15,12 +31,9 @@ export function getRestingComposerImagePreviewCounts(imageCount: number): { export function shouldUseCompactComposerFooter( width: number | null, - options?: { hasWideActions?: boolean }, + options?: ComposerFooterCompactnessOptions, ): boolean { - const breakpoint = options?.hasWideActions - ? COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX - : COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX; - return width !== null && width < breakpoint; + return width !== null && width < composerFooterCompactBreakpoint(options); } export function shouldUseRestingComposerLayout(input: { @@ -92,12 +105,12 @@ export function shouldAnimateComposerRestingTransition(input: { export function shouldUseCompactComposerPrimaryActions( width: number | null, - options?: { hasWideActions?: boolean }, + options?: ComposerFooterCompactnessOptions, ): boolean { if (!options?.hasWideActions) { return false; } - return width !== null && width < COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX; + return width !== null && width < composerFooterCompactBreakpoint(options); } export interface RestingComposerControlsMeasurement { diff --git a/apps/web/src/state/voiceTranscription.ts b/apps/web/src/state/voiceTranscription.ts index 1bc34ce356c27..416c2822697ca 100644 --- a/apps/web/src/state/voiceTranscription.ts +++ b/apps/web/src/state/voiceTranscription.ts @@ -1,4 +1,4 @@ -import { AuthOrchestrationOperateScope, WS_METHODS, type EnvironmentId } from "@t3tools/contracts"; +import { WS_METHODS, type EnvironmentId } from "@t3tools/contracts"; import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; import { createEnvironmentRpcCommand, @@ -14,7 +14,7 @@ import { connectionAtomRuntime } from "../connection/runtime"; import { convertRecordingToWav } from "../lib/voiceWav"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { serverEnvironment } from "./server"; -import { readEnvironmentScope, readPreparedConnection } from "./session"; +import { readPreparedConnection } from "./session"; export const voiceTranscriptionEnvironment = { createTranscriptionUrl: createEnvironmentRpcCommand(connectionAtomRuntime, { @@ -51,7 +51,10 @@ export function createWebVoiceTranscriber( return result.value; }, resolveUrl: (relativeUrl) => { - if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return null; + const permitted = appAtomRegistry.get( + voiceTranscriptionEnvironment.createTranscriptionUrl.permissionAtom(environmentId), + ); + if (!permitted) return null; const connection = readPreparedConnection(environmentId); return connection ? resolveAssetUrl(connection.httpBaseUrl, relativeUrl) : null; }, From c1a9a7f188b9711a214188fdc9cb4979bf0aafc4 Mon Sep 17 00:00:00 2001 From: Charles Tennent Date: Tue, 20 Oct 2026 23:39:56 -0400 Subject: [PATCH 37/55] fix(web): voice settings name the shortcut, not the command id The enable row shows the resolved shortcut label, or the palette command when it is unbound, instead of the raw `composer.toggleDictation` id. The model row loses the dated OpenAI retirement note and the shell command, and points at the user guide, which now carries the whisper.cpp setup line. isHttpVoiceInputProvider is no longer exported, and the key-reset helper is named for what it does. Co-Authored-By: Claude Fable 5.1 --- .../src/components/settings/VoiceInputSettings.tsx | 9 +++++++-- .../components/settings/voiceInputSettings.logic.ts | 12 +++++++----- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/settings/VoiceInputSettings.tsx b/apps/web/src/components/settings/VoiceInputSettings.tsx index 3974472e07501..f7584cf9a32fd 100644 --- a/apps/web/src/components/settings/VoiceInputSettings.tsx +++ b/apps/web/src/components/settings/VoiceInputSettings.tsx @@ -1,6 +1,9 @@ +import { useAtomValue } from "@effect/atom-react"; import type { ServerSettingsPatch, VoiceTranscriptionProvider } from "@t3tools/contracts"; import { XIcon } from "lucide-react"; +import { primaryServerKeybindingsAtom } from "~/state/server"; +import { shortcutLabelForCommand } from "../../keybindings"; import { Button } from "../ui/button"; import { DraftInput } from "../ui/draft-input"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; @@ -36,6 +39,8 @@ export function VoiceInputSettings() { const settings = useScopedSettings((unified) => unified.voiceTranscription); const updateSettings = useUpdateScopedSettings(); const mixed = useScopedSettingsMixed(SETTING_KEYS); + const keybindings = useAtomValue(primaryServerKeybindingsAtom); + const shortcutLabel = shortcutLabelForCommand(keybindings, "composer.toggleDictation"); const { connectedEnvironments } = useSettingsScope(); const hasServerTargets = connectedEnvironments.length > 0; const appleOnDeviceAvailable = @@ -63,7 +68,7 @@ export function VoiceInputSettings() { serverScoped settingKeys={SETTING_KEYS} {...searchableSetting("voice-input-enabled")} - description="Dictate into the composer with the microphone button or the composer.toggleDictation shortcut. The recording goes to this environment, which transcribes it with the provider below, and the text is inserted for you to review before sending." + description={`Dictate into the composer with the microphone button or ${shortcutLabel ? `the ${shortcutLabel} shortcut` : "the Voice input command in the palette"}. The recording goes to this environment, which transcribes it with the provider below, and the text is inserted for you to review before sending.`} control={ hasServerTargets ? (