diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index dc719ed93c41..599b295fc216 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -126,9 +126,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmen it.effect.each([ { platform: "darwin", architecture: "arm64", supported: true }, { platform: "linux", architecture: "x64", supported: true }, - { platform: "linux", architecture: "x64", libc: "musl", supported: false }, - { platform: "win32", architecture: "arm64", supported: false }, - { platform: "linux", architecture: "arm", supported: false }, + { platform: "linux", architecture: "x64", libc: "musl", supported: true }, + { platform: "win32", architecture: "arm64", supported: true }, + { platform: "linux", architecture: "arm", supported: true }, ] as const)("advertises voice transcription on $platform-$architecture: $supported", (host) => 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 3e780298d70a..6d75a6f2bbfd 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -22,7 +22,6 @@ import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts"; import * as ProcessRunner from "../processRunner.ts"; -import { isSpeechPlatformSupported } from "../speech/platform.ts"; import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts"; import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts"; @@ -190,7 +189,6 @@ export const make = Effect.gen(function* () { const identity = yield* ServerEnvironmentIdentity; const hostPlatform = yield* HostProcess.Platform; const hostArchitecture = yield* HostProcess.Architecture; - const hostLibc = hostPlatform === "linux" ? yield* HostProcess.LinuxLibc : undefined; const environmentId = yield* identity.getEnvironmentId; const cwdBaseName = path.basename(serverConfig.cwd).trim(); const label = yield* resolveServerEnvironmentLabel({ cwdBaseName }); @@ -273,7 +271,8 @@ export const make = Effect.gen(function* () { freshContext: true, scheduledTaskThreadModes: true, npmReleaseLookup: true, - voiceTranscription: isSpeechPlatformSupported(hostPlatform, hostArchitecture, hostLibc), + // Custom speech endpoints work even where the native speech engine is unavailable. + voiceTranscription: true, ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }), ...(serverInstallation === null ? {} : { serverInstallation }), ...(serverSelfUpdate === "boot-service" || desktopAppUpdate diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 0e7ce34df0ea..846991597d15 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1311,7 +1311,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" ); it.effect( - "uses the same secret lifecycle for provider config, environment, host tokens, and quota keys", + "uses the same secret lifecycle for provider config, environment, host tokens, quota keys, and speech", () => Effect.gen(function* () { const service = yield* ServerSettingsModule.ServerSettingsService; @@ -1319,7 +1319,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" const fs = yield* FileSystem.FileSystem; const store = yield* ServerSecretStore.ServerSecretStore; const instanceId = ProviderInstanceId.make("antigravity_secrets"); + const speechEndpoint = { + url: `https://speech.example.test/${"a".repeat(300)}/transcribe`, + model: "whisper", + apiKey: "speech-secret", + }; const saved = yield* service.updateSettings({ + speechEndpoint, providerInstances: { [instanceId]: { driver: ProviderDriverKind.make("antigravity"), @@ -1363,6 +1369,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" "gitcafe-secret", "quota-secret", "expo-secret", + "speech-secret", ]; const client = ServerSettingsModule.redactServerSettingsForClient(saved, { secretReferences: true, @@ -1380,8 +1387,29 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" sourceControlHosts: client.sourceControlHosts, usageLimitSources: client.usageLimitSources, easDeviceHosts: client.easDeviceHosts, + speechEndpoint: client.speechEndpoint, }); for (const value of values) assert.include(JSON.stringify(echoed), value); + // An echoed placeholder must never carry another destination's credentials. + const moved = yield* service.updateSettings({ + speechEndpoint: { + ...client.speechEndpoint!, + url: "https://other.example.test/transcribe", + }, + }); + assert.equal(moved.speechEndpoint?.apiKey, ""); + for (const apiKey of ["replacement-speech-secret", ""]) { + const changed = yield* service.updateSettings({ + speechEndpoint: { ...speechEndpoint, apiKey }, + }); + assert.equal(changed.speechEndpoint?.apiKey, apiKey); + assert.equal( + ServerSettingsModule.redactServerSettingsForClient(changed, { secretReferences: true }) + .speechEndpoint?.apiKey, + apiKey ? "••••••" : "", + ); + } + yield* service.updateSettings({ speechEndpoint }); const renamed = yield* service.updateProviderInstance({ operation: "upsert", instanceId, @@ -1432,6 +1460,16 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" sourceControlHostSecretName({ kind: "gitcafe", field: "token", serverHost: null }), "usage-limit-source-aHVi", ]; + const files = yield* fs.readDirectory(config.secretsDir); + secretNames.push( + ...files + .filter((name) => name.startsWith("speech-endpoint-")) + .map((name) => name.replace(/\.bin$/, "")), + ); + assert.lengthOf( + secretNames.filter((name) => name.startsWith("speech-endpoint-")), + 1, + ); for (const name of secretNames) { assert.isTrue(Option.isSome(yield* store.get(name)), name); } @@ -1463,6 +1501,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" gitcafe: { token: "" }, }, usageLimitSources: { [UsageLimitSourceId.make("hub")]: null }, + speechEndpoint: null, }); for (const name of secretNames) { assert.isTrue(Option.isNone(yield* store.get(name))); diff --git a/apps/server/src/settingsSecrets.ts b/apps/server/src/settingsSecrets.ts index 17640237ff5c..ab9ec6181acd 100644 --- a/apps/server/src/settingsSecrets.ts +++ b/apps/server/src/settingsSecrets.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - Secret slot mapping is synchronous; URL hashes keep filenames bounded. +import * as NodeCrypto from "node:crypto"; import { AntigravitySettings, ClaudeSettings, @@ -7,6 +9,7 @@ import { type ServerSettings, type SettingsSecretValue, SimlockDeviceHostConfig, + SpeechEndpointConfig, UsageLimitSourceConfig, isSecretReference, secretSettingsFields, @@ -47,6 +50,7 @@ const providerSecretFields = new Map([ const usageLimitSecretFields = secretSettingsFields(UsageLimitSourceConfig); const easDeviceHostSecretFields = secretSettingsFields(EasDeviceHostConfig); const simlockDeviceHostSecretFields = secretSettingsFields(SimlockDeviceHostConfig); +const speechEndpointSecretFields = secretSettingsFields(SpeechEndpointConfig); const encode = (value: string) => Buffer.from(value, "utf8").toString("base64url"); export interface SettingsSecret { @@ -232,6 +236,15 @@ function mapSecretFieldGroups( return { ...settings, + speechEndpoint: settings.speechEndpoint + ? (mapFields( + settings.speechEndpoint, + speechEndpointSecretFields, + // Bind credentials to this destination without exceeding filesystem name limits. + (field) => + `speech-endpoint-${NodeCrypto.createHash("sha256").update(settings.speechEndpoint!.url).digest("hex")}-${encode(field)}`, + ) as SpeechEndpointConfig) + : null, providerInstances, sourceControlHosts, usageLimitSources, diff --git a/apps/server/src/speech/SpeechService.test.ts b/apps/server/src/speech/SpeechService.test.ts index 972c401ce309..e677a5e339b3 100644 --- a/apps/server/src/speech/SpeechService.test.ts +++ b/apps/server/src/speech/SpeechService.test.ts @@ -144,6 +144,118 @@ it("rejects empty, misaligned, non-finite, and oversized PCM as invalid audio", } }); +it.effect( + "transcribes through an endpoint without a native engine and preserves dictionary corrections", + () => + Effect.gen(function* () { + const speech = yield* SpeechService.SpeechService; + const settings = yield* ServerSettings.ServerSettingsService; + const endpoint = { + url: "http://localhost:8000/v1/audio/transcriptions", + model: "parakeet", + apiKey: "test-key", + }; + yield* settings.updateSettings({ speechEndpoint: endpoint }); + using network = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue(Response.json({ text: "hello tay three" })); + expect(yield* speech.status).toMatchObject({ + supported: true, + state: "ready", + endpointUrl: endpoint.url, + supportsStreaming: false, + supportsBufferedStreaming: false, + }); + expect(yield* speech.models(false)).toEqual({ models: [] }); + yield* speech.prepareModel; + expect( + yield* speech.transcribe(pcm(), { + ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, + speechEndpointUrl: endpoint.url, + speechCustomWords: [{ term: "T3", aliases: ["tay three"] }], + }), + ).toBe("hello T3"); + expect(network).toHaveBeenCalledTimes(1); + expect(loadNative).not.toHaveBeenCalled(); + expect(download).not.toHaveBeenCalled(); + yield* settings.updateSettings({ speechEndpoint: null }); + expect(yield* speech.status).toMatchObject({ supported: false }); + }).pipe( + Effect.provide(layer), + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Architecture, "arm64"), + ), +); + +it.effect( + "rejects absent or stale endpoint consent before forwarding audio, including streaming", + () => + Effect.gen(function* () { + const speech = yield* SpeechService.SpeechService; + const settings = yield* ServerSettings.ServerSettingsService; + const endpoint = { + url: "https://speech.example.test/v1/audio/transcriptions", + model: "whisper", + apiKey: "", + }; + using network = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue(Response.json({ text: "unused" })); + yield* settings.updateSettings({ speechEndpoint: endpoint }); + for (const speechEndpointUrl of [undefined, "https://previous.example.test/transcribe"]) { + const options = { + ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, + ...(speechEndpointUrl ? { speechEndpointUrl } : {}), + }; + const result = yield* Effect.result(speech.transcribe(pcm(), options)); + expect(Result.isFailure(result) && result.failure).toMatchObject({ + _tag: "SpeechDestinationChangedError", + }); + } + const options = { ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, speechEndpointUrl: endpoint.url }; + const stream = yield* Effect.result(speech.startStream(options).pipe(Effect.scoped)); + expect(Result.isFailure(stream) && stream.failure).toMatchObject({ + _tag: "SpeechDestinationChangedError", + }); + yield* settings.updateSettings({ speechEndpoint: null }); + const local = yield* Effect.result(speech.transcribe(pcm(), options)); + expect(Result.isFailure(local) && local.failure).toMatchObject({ + _tag: "SpeechDestinationChangedError", + }); + expect(network).not.toHaveBeenCalled(); + expect(loadNative).not.toHaveBeenCalled(); + }).pipe(Effect.provide(layer)), +); + +it.effect("reports an endpoint failure without falling back to native transcription", () => + Effect.gen(function* () { + const speech = yield* SpeechService.SpeechService; + const settings = yield* ServerSettings.ServerSettingsService; + const endpoint = { + url: "https://speech.example.test/transcribe", + model: "whisper", + apiKey: "", + }; + yield* settings.updateSettings({ speechEndpoint: endpoint }); + using network = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue(new Response(null, { status: 503 })); + const result = yield* Effect.result( + speech.transcribe(pcm(), { + ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, + speechEndpointUrl: endpoint.url, + }), + ); + expect(Result.isFailure(result) && result.failure).toMatchObject({ + _tag: "SpeechOperationError", + operation: "endpoint transcription", + }); + expect(network).toHaveBeenCalledTimes(1); + expect(loadNative).not.toHaveBeenCalled(); + expect(yield* speech.status).toMatchObject({ state: "ready" }); + }).pipe(Effect.provide(layer)), +); + it.effect("prepares a batch model before audio arrives and reuses it for transcription", () => Effect.gen(function* () { const speech = yield* SpeechService.SpeechService; diff --git a/apps/server/src/speech/SpeechService.ts b/apps/server/src/speech/SpeechService.ts index c1f762f26089..b32171a56202 100644 --- a/apps/server/src/speech/SpeechService.ts +++ b/apps/server/src/speech/SpeechService.ts @@ -24,6 +24,7 @@ import * as Stream from "effect/Stream"; import * as ServerSettings from "../serverSettings.ts"; import { makeSpeechTextCorrector, normalizeSpeechCustomWords } from "./customWords.ts"; import { removeSpeechFillerWords } from "./fillerWords.ts"; +import { transcribeSpeechEndpoint } from "./endpoint.ts"; import { DEFAULT_SPEECH_MODEL_ID, effectiveSpeechLanguage, @@ -89,6 +90,15 @@ export class SpeechBusyError extends Schema.TaggedError()("Spee operation: Schema.String, }) {} +export class SpeechDestinationChangedError extends Schema.TaggedError()( + "SpeechDestinationChangedError", + {}, +) { + override get message(): string { + return "The transcription destination changed. Confirm it in Voice settings before recording."; + } +} + export class SpeechModelNotFoundError extends Schema.TaggedError()( "SpeechModelNotFoundError", { modelId: Schema.String }, @@ -105,6 +115,7 @@ export type SpeechError = | SpeechUnsupportedPlatformError | SpeechModelNotFoundError | SpeechDownloadCancelledError + | SpeechDestinationChangedError | SpeechBusyError; const isSpeechError = Schema.is( @@ -115,6 +126,7 @@ const isSpeechError = Schema.is( SpeechModelNotFoundError, SpeechDownloadCancelledError, SpeechOperationError, + SpeechDestinationChangedError, ]), ); @@ -448,6 +460,23 @@ const make = Effect.gen(function* () { const currentStatus = Effect.fn("SpeechService.currentStatus")(function* ( settings: SettingsSnapshot, ): Effect.fn.Return { + if (settings.speechEndpoint) { + return { + supported: true, + state: activeTranscriptions > 0 ? "transcribing" : "ready", + modelId: settings.speechEndpoint.model, + model: settings.speechEndpoint.model, + endpointUrl: settings.speechEndpoint.url, + size: 0, + supportsStreaming: false, + supportsBufferedStreaming: false, + supportsTranslation: false, + supportsLanguageDetection: true, + acceleration: "cpu", + modelUnloadTimeout: settings.speechModelUnloadTimeout, + gpuDevices: [], + }; + } if (unsupportedReason) return { supported: false, reason: unsupportedReason }; const definition = selectedModel(settings); const ready = yield* store.isReady(definition); @@ -472,6 +501,7 @@ const make = Effect.gen(function* () { settings: SettingsSnapshot, includeBenchmarks: boolean, ): Effect.fn.Return { + if (settings.speechEndpoint) return { models: [] }; const selected = selectedModel(settings); const models = yield* Effect.forEach( SPEECH_MODELS, @@ -537,28 +567,32 @@ const make = Effect.gen(function* () { const prepareModel = readSettings("model preparation").pipe( Effect.flatMap((settings) => - exclusive( - "model preparation", - requireSupported.pipe( - Effect.andThen(installedModelPath(selectedModel(settings))), - Effect.flatMap((modelPath) => - attempt("model preparation", (signal) => - loadModel( - modelPath, - selectedModel(settings), - AbortSignal.any([signal, lifetime.signal]), - settings.speechAcceleration, + settings.speechEndpoint + ? Effect.void + : exclusive( + "model preparation", + requireSupported.pipe( + Effect.andThen(installedModelPath(selectedModel(settings))), + Effect.flatMap((modelPath) => + attempt("model preparation", (signal) => + loadModel( + modelPath, + selectedModel(settings), + AbortSignal.any([signal, lifetime.signal]), + settings.speechAcceleration, + ), + ).pipe( + Effect.timeout("2 minutes"), + Effect.catchTags({ + TimeoutError: (cause) => + Effect.fail( + new SpeechOperationError({ operation: "model preparation", cause }), + ), + }), + ), ), - ).pipe( - Effect.timeout("2 minutes"), - Effect.catchTags({ - TimeoutError: (cause) => - Effect.fail(new SpeechOperationError({ operation: "model preparation", cause })), - }), ), ), - ), - ), ), ); @@ -577,7 +611,10 @@ const make = Effect.gen(function* () { return yield* exclusive( "transcription", Effect.gen(function* () { - yield* requireSupported; + // Older clients have no forwarding consent and must never send audio to a new destination. + if (options.speechEndpointUrl !== settings.speechEndpoint?.url) + return yield* new SpeechDestinationChangedError(); + if (!settings.speechEndpoint) yield* requireSupported; const pcm = yield* Effect.try({ try: () => decodeSpeechPcm(pcmBytes), catch: (cause) => speechError("transcription", cause), @@ -585,6 +622,29 @@ const make = Effect.gen(function* () { if (pcm.length === 0) return ""; activeTranscriptions += 1; return yield* Effect.gen(function* () { + if (settings.speechEndpoint) { + const endpoint = settings.speechEndpoint; + const text = yield* Effect.tryPromise({ + try: (signal) => + transcribeSpeechEndpoint({ + endpoint, + pcm, + language: options.speechLanguage, + signal: AbortSignal.any([signal, lifetime.signal]), + }), + catch: (cause) => speechError("endpoint transcription", cause), + }); + const dictionary = normalizeSpeechCustomWords(options.speechCustomWords); + const correct = makeSpeechTextCorrector( + dictionary.map(({ term }) => term), + dictionary, + ); + return finalizeTranscript( + correct(text), + options, + options.speechLanguage === "auto" ? undefined : options.speechLanguage, + ); + } const definition = selectedModel(settings); const language = effectiveSpeechLanguage(definition, options.speechLanguage); const translateToEnglish = @@ -678,6 +738,9 @@ const make = Effect.gen(function* () { // Stream setup shares the public startStream span. const openStream = Effect.fnUntraced(function* (options: SpeechTranscriptionOptions) { const operation = "streaming transcription"; + const settings = yield* readSettings(operation); + if (settings.speechEndpoint || options.speechEndpointUrl !== undefined) + return yield* new SpeechDestinationChangedError(); yield* requireSupported; const released = Promise.withResolvers(); // @effect-diagnostics-next-line abortControllerInEffect:off - Stream cancellation must abort native work independently of the caller fiber. @@ -726,7 +789,6 @@ const make = Effect.gen(function* () { } }), ); - const settings = yield* readSettings(operation); const definition = selectedModel(settings); const language = effectiveSpeechLanguage(definition, options.speechLanguage); const dictionary = normalizeSpeechCustomWords(options.speechCustomWords); diff --git a/apps/server/src/speech/endpoint.test.ts b/apps/server/src/speech/endpoint.test.ts new file mode 100644 index 000000000000..e900db46d4ae --- /dev/null +++ b/apps/server/src/speech/endpoint.test.ts @@ -0,0 +1,140 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - Exercises the real HTTP wire format, redirects, and cancellation against a local fixture. +import * as NodeHttp from "node:http"; +import { expect, it, vi } from "vite-plus/test"; +import { transcribeSpeechEndpoint } from "./endpoint.ts"; + +const endpoint = { + url: "https://speech.example.test/v1/audio/transcriptions", + model: "parakeet", + apiKey: "", +}; +const input = () => ({ + endpoint, + pcm: new Float32Array([-1, -0.5, 0, 0.5, 1]), + language: "auto", + signal: new AbortController().signal, +}); + +async function serve(handler: NodeHttp.RequestListener) { + const server = NodeHttp.createServer(handler); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing test server address"); + return { + url: `http://127.0.0.1:${address.port}/v1/audio/transcriptions`, + async [Symbol.asyncDispose]() { + server.closeAllConnections(); + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + }, + }; +} + +it("uploads mono PCM16 WAV and returns the endpoint transcript over HTTP", async () => { + const received = Promise.withResolvers<{ headers: Headers; body: FormData }>(); + await using server = await serve((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + const headers = new Headers(); + for (const [name, value] of Object.entries(request.headers)) { + if (typeof value === "string") headers.set(name, value); + } + void new Response(Buffer.concat(chunks), { headers }) + .formData() + .then((body) => received.resolve({ headers, body }), received.reject); + response.writeHead(200, { "Content-Type": "application/json" }); + response.end(JSON.stringify({ text: "Bonjour le monde." })); + }); + }); + const result = await transcribeSpeechEndpoint({ + ...input(), + endpoint: { ...endpoint, url: server.url, apiKey: "test-key" }, + language: "fr", + }); + expect(result).toBe("Bonjour le monde."); + const { headers, body } = await received.promise; + expect(headers.get("authorization")).toBe("Bearer test-key"); + expect(body.get("model")).toBe("parakeet"); + expect(body.get("language")).toBe("fr"); + expect(body.get("response_format")).toBe("json"); + const file = body.get("file") as File; + expect(file.type).toBe("audio/wav"); + expect(file.name).toBe("recording.wav"); + const wav = await file.arrayBuffer(); + const view = new DataView(wav); + expect(new TextDecoder().decode(new Uint8Array(wav, 0, 4))).toBe("RIFF"); + expect(new TextDecoder().decode(new Uint8Array(wav, 8, 8))).toBe("WAVEfmt "); + expect(view.getUint32(4, true)).toBe(wav.byteLength - 8); + expect(view.getUint16(20, true)).toBe(1); + expect(view.getUint16(22, true)).toBe(1); + expect(view.getUint32(24, true)).toBe(16_000); + expect(view.getUint16(34, true)).toBe(16); + expect(view.getUint32(40, true)).toBe(10); + expect(Array.from({ length: 5 }, (_, index) => view.getInt16(44 + index * 2, true))).toEqual([ + -32768, -16384, 0, 16384, 32767, + ]); +}); + +it("omits automatic language and absent credentials", async () => { + using network = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ text: "" })); + expect(await transcribeSpeechEndpoint(input())).toBe(""); + const request = network.mock.calls[0]![1]!; + expect(new Headers(request.headers).has("authorization")).toBe(false); + expect((request.body as FormData).has("language")).toBe(false); +}); + +it.each([ + { response: () => new Response("private error details", { status: 401 }), message: "HTTP 401" }, + { + response: () => new Response("private malformed body"), + message: "JSON object with a text field", + }, + { response: () => Response.json({ text: 123 }), message: "JSON object with a text field" }, + { + response: () => Response.json({ text: "x".repeat(100_001) }), + message: "JSON object with a text field", + }, + { response: () => new Response("x".repeat(1_048_577)), message: "response is too large" }, +])("rejects unsafe or invalid responses: $message", async ({ response, message }) => { + using _network = vi.spyOn(globalThis, "fetch").mockResolvedValue(response()); + await expect(transcribeSpeechEndpoint(input())).rejects.toThrow(message); +}); + +it("does not follow a redirect with audio or credentials", async () => { + let requests = 0; + await using server = await serve((_request, response) => { + requests += 1; + response.writeHead(307, { Location: "/another-destination" }); + response.end(); + }); + await expect( + transcribeSpeechEndpoint({ + ...input(), + endpoint: { ...endpoint, url: server.url, apiKey: "test-key" }, + }), + ).rejects.toThrow(); + expect(requests).toBe(1); +}); + +it.each(["cancellation", "timeout"] as const)("aborts a stalled response on %s", async (reason) => { + const started = Promise.withResolvers(); + await using server = await serve((_request, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + response.write('{"text":"'); + started.resolve(); + }); + const caller = new AbortController(); + const timeout = new AbortController(); + using _timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeout.signal); + const pending = transcribeSpeechEndpoint({ + ...input(), + signal: caller.signal, + endpoint: { ...endpoint, url: server.url }, + }); + const rejected = expect(pending).rejects.toThrow(); + await started.promise; + (reason === "timeout" ? timeout : caller).abort(); + await rejected; +}); diff --git a/apps/server/src/speech/endpoint.ts b/apps/server/src/speech/endpoint.ts new file mode 100644 index 000000000000..dc69970dc66c --- /dev/null +++ b/apps/server/src/speech/endpoint.ts @@ -0,0 +1,90 @@ +import type { SpeechEndpointConfig } from "@t3tools/contracts"; + +const MAX_RESPONSE_BYTES = 1_048_576; +const MAX_TRANSCRIPT_LENGTH = 100_000; + +function encodeWav(pcm: Float32Array): Uint8Array { + const buffer = new ArrayBuffer(44 + pcm.length * 2); + const bytes = new Uint8Array(buffer); + const view = new DataView(buffer); + bytes.set(new TextEncoder().encode("RIFF"), 0); + view.setUint32(4, buffer.byteLength - 8, true); + bytes.set(new TextEncoder().encode("WAVEfmt "), 8); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, 1, true); + view.setUint32(24, 16_000, true); + view.setUint32(28, 32_000, true); + view.setUint16(32, 2, true); + view.setUint16(34, 16, true); + bytes.set(new TextEncoder().encode("data"), 36); + view.setUint32(40, pcm.length * 2, true); + for (let index = 0; index < pcm.length; index += 1) { + const sample = pcm[index]!; + view.setInt16(44 + index * 2, Math.round(sample * (sample < 0 ? 32_768 : 32_767)), true); + } + return bytes; +} + +/** HTTP adapter: the owning SpeechService validates audio and consent before calling it. */ +export async function transcribeSpeechEndpoint(input: { + readonly endpoint: SpeechEndpointConfig; + readonly pcm: Float32Array; + readonly language: string; + readonly signal: AbortSignal; +}): Promise { + const body = new FormData(); + body.set("file", new Blob([encodeWav(input.pcm)], { type: "audio/wav" }), "recording.wav"); + body.set("model", input.endpoint.model); + body.set("response_format", "json"); + if (input.language !== "auto") body.set("language", input.language); + // @effect-diagnostics-next-line globalFetch:off - This Promise adapter preserves fetch's redirect rejection and AbortSignal; SpeechService owns the Effect boundary. + const response = await fetch(input.endpoint.url, { + method: "POST", + body, + headers: input.endpoint.apiKey ? { Authorization: `Bearer ${input.endpoint.apiKey}` } : {}, + redirect: "error", + signal: AbortSignal.any([input.signal, AbortSignal.timeout(120_000)]), + }); + if (!response.ok) { + await response.body?.cancel().catch(() => {}); + throw new Error(`Speech endpoint returned HTTP ${response.status}.`); + } + if (!response.body) throw new Error("Speech endpoint returned an empty response."); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + length += value.byteLength; + if (length > MAX_RESPONSE_BYTES) throw new Error("Speech endpoint response is too large."); + chunks.push(value); + } + } finally { + await reader.cancel().catch(() => {}); + reader.releaseLock(); + } + const bytes = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + let result: unknown; + try { + result = JSON.parse(new TextDecoder().decode(bytes)); + } catch { + throw new Error("Speech endpoint must return a JSON object with a text field."); + } + if ( + typeof result !== "object" || + result === null || + !("text" in result) || + typeof result.text !== "string" || + result.text.length > MAX_TRANSCRIPT_LENGTH + ) + throw new Error("Speech endpoint must return a JSON object with a text field."); + return result.text; +} diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 2e1d1ae71fce..5c9315f4a4dc 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -48,6 +48,7 @@ const mapSpeechError = (effect: Effect.Effect failEnvironmentInvalidRequest("speech_busy"), SpeechDownloadCancelledError: () => failEnvironmentInvalidRequest("speech_busy"), SpeechModelNotFoundError: () => failEnvironmentInvalidRequest("invalid_command"), + SpeechDestinationChangedError: () => failEnvironmentInvalidRequest("invalid_command"), SpeechOperationError: (error) => failEnvironmentInternal("internal_error", error), }), ); diff --git a/apps/web/src/components/settings/SpeechEndpointForm.browser.test.tsx b/apps/web/src/components/settings/SpeechEndpointForm.browser.test.tsx new file mode 100644 index 000000000000..4f859935bd79 --- /dev/null +++ b/apps/web/src/components/settings/SpeechEndpointForm.browser.test.tsx @@ -0,0 +1,90 @@ +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; +import { render } from "../../../test/render"; +import { SpeechEndpointForm } from "./SpeechEndpointForm"; + +const current = { + url: "http://localhost:8000/v1/audio/transcriptions", + model: "whisper", + apiKey: "••••••", +}; + +it("preserves a masked key only for its original URL and clears the replacement after saving", async () => { + const onSave = vi.fn(async () => true); + await using screen = await render( + , + ); + const key = screen.getByLabelText("Speech endpoint API key"); + const save = screen.getByRole("button", { name: "Save and use endpoint" }); + await expect.element(key).toHaveValue(""); + await expect + .element(key) + .toHaveAttribute("placeholder", "Stored secret, enter a new value to replace"); + await userEvent.click(save); + await vi.waitFor(() => expect(onSave).toHaveBeenLastCalledWith(current)); + + const url = "https://other.example.test/v1/audio/transcriptions"; + await userEvent.fill(screen.getByLabelText("Transcription URL"), url); + await expect.element(key).toHaveAttribute("placeholder", "Not set"); + await userEvent.click(save); + await vi.waitFor(() => expect(onSave).toHaveBeenLastCalledWith({ ...current, url, apiKey: "" })); + await userEvent.fill(key, "replacement-key"); + await userEvent.click(save); + await vi.waitFor(() => + expect(onSave).toHaveBeenLastCalledWith({ ...current, url, apiKey: "replacement-key" }), + ); + await expect.element(key).toHaveValue(""); +}); + +it("removes a stored credential and switches back to local models", async () => { + const onSave = vi.fn(async () => true); + await using screen = await render( + , + ); + await userEvent.click(screen.getByRole("button", { name: "Remove stored API key" })); + await userEvent.click(screen.getByRole("button", { name: "Save and use endpoint" })); + await vi.waitFor(() => expect(onSave).toHaveBeenLastCalledWith({ ...current, apiKey: "" })); + await userEvent.click(screen.getByRole("combobox", { name: "Speech engine" })); + await userEvent.click(page.getByRole("option", { name: "Local models", exact: true })); + await userEvent.click(screen.getByRole("button", { name: "Use local models" })); + await vi.waitFor(() => expect(onSave).toHaveBeenLastCalledWith(null)); +}); + +it("rejects URL credentials and keeps an unsuccessful replacement for retry", async () => { + const pending = Promise.withResolvers(); + const onSave = vi.fn(() => pending.promise); + await using screen = await render( + , + ); + await userEvent.fill( + screen.getByLabelText("Transcription URL"), + "https://user:password@example.test/transcribe", + ); + await userEvent.click(screen.getByRole("button", { name: "Save and use endpoint" })); + await expect.element(screen.getByRole("alert")).toBeVisible(); + expect(onSave).not.toHaveBeenCalled(); + await userEvent.fill(screen.getByLabelText("Transcription URL"), current.url); + const key = screen.getByLabelText("Speech endpoint API key"); + await userEvent.fill(key, "retry-key"); + await userEvent.click(screen.getByRole("button", { name: "Save and use endpoint" })); + await expect.element(key).toBeDisabled(); + pending.resolve(false); + await expect.element(screen.getByRole("alert")).toBeVisible(); + await expect.element(key).toHaveValue("retry-key"); + await expect.element(key).toBeEnabled(); +}); diff --git a/apps/web/src/components/settings/SpeechEndpointForm.tsx b/apps/web/src/components/settings/SpeechEndpointForm.tsx new file mode 100644 index 000000000000..8c439cfdd8b3 --- /dev/null +++ b/apps/web/src/components/settings/SpeechEndpointForm.tsx @@ -0,0 +1,140 @@ +import { SpeechEndpointConfig } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { useState } from "react"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { SecretInput } from "./SecretInput"; + +const isSpeechEndpointConfig = Schema.is(SpeechEndpointConfig); + +export function SpeechEndpointForm(props: { + readonly current: SpeechEndpointConfig | null; + readonly disabled: boolean; + readonly environmentLabel: string; + readonly onSave: (endpoint: SpeechEndpointConfig | null) => Promise; +}) { + const [mode, setMode] = useState(props.current ? "endpoint" : "local"); + const [url, setUrl] = useState(props.current?.url ?? ""); + const [model, setModel] = useState(props.current?.model ?? ""); + const [apiKey, setApiKey] = useState(""); + const [clearKey, setClearKey] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const sameDestination = url.trim() === props.current?.url; + const configuredKey = sameDestination && !clearKey && Boolean(props.current?.apiKey); + const disabled = props.disabled || busy; + + const save = async () => { + const endpoint = + mode === "local" + ? null + : { + url: url.trim(), + model: model.trim(), + apiKey: apiKey.trim() || (configuredKey ? props.current!.apiKey : ""), + }; + if (endpoint && !isSpeechEndpointConfig(endpoint)) { + setError( + "Enter a full HTTP or HTTPS transcription URL and a model name. Put credentials in API key, not in the URL.", + ); + return; + } + setBusy(true); + setError(null); + try { + if (await props.onSave(endpoint)) { + setApiKey(""); + setClearKey(false); + } else setError("Could not save the speech endpoint. Reconnect and try again."); + } catch { + setError("Could not save the speech endpoint. Reconnect and try again."); + } finally { + setBusy(false); + } + }; + + return ( +
+ + {mode === "endpoint" ? ( + <> +

+ Use an OpenAI-compatible Whisper or Parakeet server. {props.environmentLabel} sends your + recording to this URL when you finish speaking. Localhost refers to that T3 + environment's machine. +

+ + + + {configuredKey ? ( + + ) : null} +

+ The key is stored securely on {props.environmentLabel}. Saving allows this device's + audio to be forwarded to the URL above; other devices must confirm it separately. +

+ + ) : props.current ? ( +

+ Switch back to a downloaded model on {props.environmentLabel}. +

+ ) : null} + {mode === "endpoint" || props.current ? ( + + ) : null} + {error ? ( +

+ {error} +

+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/settings/SpeechLanguageSelect.tsx b/apps/web/src/components/settings/SpeechLanguageSelect.tsx index 948412184b41..b11388f2556d 100644 --- a/apps/web/src/components/settings/SpeechLanguageSelect.tsx +++ b/apps/web/src/components/settings/SpeechLanguageSelect.tsx @@ -2,17 +2,34 @@ import type { EnvironmentSpeechStatus } from "@t3tools/contracts"; import { effectiveSpeechLanguage } from "@t3tools/shared/speech"; import { updateClientSettings, useClientSettings } from "../../hooks/useSettings"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { DraftInput } from "../ui/draft-input"; const languageNames = new Intl.DisplayNames(["en"], { type: "language" }); export const languageLabel = (code: string) => languageNames.of(code) ?? code; type ModelLanguages = Pick< Extract, - "languages" | "supportsLanguageDetection" + "languages" | "supportsLanguageDetection" | "endpointUrl" >; export function SpeechLanguageSelect({ model }: { readonly model: ModelLanguages | null }) { const preference = useClientSettings((settings) => settings.speechLanguage); + if (model?.endpointUrl) { + return ( + { + const speechLanguage = next.trim(); + if (/^[a-z]{2,3}(?:-[a-z0-9]+)*$|^auto$/i.test(speechLanguage)) + void updateClientSettings({ speechLanguage }); + }} + /> + ); + } const languages = model?.languages ?? []; const resolved = model ? effectiveSpeechLanguage( diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index 8f8507c8f37f..baa466e76279 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx @@ -40,10 +40,15 @@ import { useStableCallback } from "~/hooks/useStableCallback"; import { listBrowserMicrophones, type BrowserMicrophone } from "../../speech/browserMicrophones"; import { chooseAudioDestination, + bindAudioGrant, chooseTranscriptCleanup, useCleanupGrant, } from "../../speech/voiceConsent"; -import { updateClientSettings, useClientSettings } from "../../hooks/useSettings"; +import { + updateClientSettings, + useClientSettings, + useEnvironmentSettings, +} from "../../hooks/useSettings"; import { runtime } from "../../lib/runtime"; import { getCustomModelOptionsByInstance, @@ -52,7 +57,8 @@ import { import { providerInstanceEntriesFor } from "../../providerInstances"; import { useEnvironmentProviders, useEnvironments } from "../../state/environments"; import { useEnvironmentScope } from "../../state/session"; -import { EMPTY_SERVER_PROVIDERS } from "../../state/server"; +import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; import { useEnvironmentSpeechInput, useVoiceTranscriptionDestination, @@ -69,6 +75,7 @@ import { Switch } from "../ui/switch"; import { Textarea } from "../ui/textarea"; import { toastManager } from "../ui/toast"; import { MicrophoneTest } from "./MicrophoneTest"; +import { SpeechEndpointForm } from "./SpeechEndpointForm"; import { LanguageRow, ModelBenchmarks, orderSpeechLanguages } from "./SpeechModelComparison"; import { languageLabel, SpeechLanguageSelect } from "./SpeechLanguageSelect"; import { @@ -596,6 +603,52 @@ function useVoiceModels(prepared: PreparedConnection | null) { type VoiceModels = ReturnType; +function SpeechEndpointSettings(props: { + prepared: PreparedConnection; + catalog: VoiceModels; + grantId: string | null; + environmentLabel: string; +}) { + const endpoint = useEnvironmentSettings( + props.prepared.environmentId, + (settings) => settings.speechEndpoint, + ); + const persist = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false }); + return ( + + { + const canUpdateConsent = props.grantId ? bindAudioGrant(props.grantId) : () => false; + let saved = false; + await props.catalog.run("Could not save speech endpoint", async () => { + const result = await persist({ + environmentId: props.prepared.environmentId, + input: { patch: { speechEndpoint } }, + }); + if (result._tag === "Failure") return; + saved = true; + if (canUpdateConsent()) + chooseAudioDestination({ + kind: "environment", + environmentId: props.prepared.environmentId, + ...(speechEndpoint ? { endpointUrl: speechEndpoint.url } : {}), + }); + }); + return saved; + }} + /> + + ); +} + function AdvancedSpeechSettings({ prepared, catalog, @@ -1031,13 +1084,24 @@ export function VoiceSettingsPanel() { return ( - Microphone audio recorded on this device is sent to the environment you choose here, - where it is transcribed and discarded. Off keeps voice input off on this device. This + Microphone audio is sent to the environment you choose here. A custom endpoint + forwards audio after your confirmation. Off keeps voice input off on this device. This choice is saved on this device only. } @@ -1170,13 +1234,48 @@ export function VoiceSettingsPanel() { ) : null} + {prepared ? ( + + ) : null} + {prepared && model && model.endpointUrl !== destination.endpointUrl ? ( + + chooseAudioDestination({ + kind: "environment", + environmentId: prepared.environmentId, + ...(model.endpointUrl ? { endpointUrl: model.endpointUrl } : {}), + }) + } + > + Use this destination + + } + /> + ) : null} + } /> @@ -1195,7 +1294,7 @@ export function VoiceSettingsPanel() { } /> ) : null} - {prepared ? ( + {prepared && !model?.endpointUrl ? ( void updateClientSettings({ speechSilenceFiltering: checked }) diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 283a5cd46e09..e3686ab0699b 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -495,6 +495,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/voice", searchTerms: ["speech voice dictation stt transcription environment machine consent privacy"], }, + { + id: "speech-endpoint", + title: "Speech engine", + to: "/settings/voice", + searchTerms: ["voice transcription endpoint url api key whisper parakeet openai custom server"], + }, { id: "voice-microphone", title: "Microphone", diff --git a/apps/web/src/speech/browserVoiceInput.ts b/apps/web/src/speech/browserVoiceInput.ts index 1d04f96bba0e..2ae6be725667 100644 --- a/apps/web/src/speech/browserVoiceInput.ts +++ b/apps/web/src/speech/browserVoiceInput.ts @@ -30,6 +30,11 @@ export function createBrowserVoiceInputPlatform(input: { throwIfVoiceTranscriptionAborted(options.signal); if (!status.supported) throw new VoiceTranscriptionError({ code: "unavailable", message: status.reason }); + if (status.endpointUrl !== recordingOptions.speechEndpointUrl) + throw new VoiceTranscriptionError({ + code: "unavailable", + message: "The transcription destination changed. Confirm it in Settings > Voice.", + }); const language = status.languages ? effectiveSpeechLanguage( { @@ -38,7 +43,7 @@ export function createBrowserVoiceInputPlatform(input: { }, recordingOptions.speechLanguage, ) - : "auto"; + : recordingOptions.speechLanguage; const locale = !status.supportsStreaming && status.supportsTranslation && diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index 644edb303aef..806a7f431f33 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -113,6 +113,7 @@ export function useVoiceTranscriptionDestination() { return { environmentId, grantId: grant?.id ?? null, + ...(grant?.destination.endpointUrl ? { endpointUrl: grant.destination.endpointUrl } : {}), label: environment?.label ?? null, prepared: supported && canDictate ? connection : null, }; @@ -122,6 +123,7 @@ export function useEnvironmentSpeechInput(input: HookInput) { const destination = useVoiceTranscriptionDestination(); const prepared = destination.prepared; const grantId = destination.grantId; + const endpointUrl = destination.endpointUrl; const originatingEnvironment = useEnvironment(input.environmentId); const originatingConnection = Option.getOrNull(usePreparedConnection(input.environmentId)); const canCleanUp = useEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope); @@ -259,6 +261,7 @@ export function useEnvironmentSpeechInput(input: HookInput) { : null, }; return { + ...(endpointUrl ? { speechEndpointUrl: endpointUrl } : {}), speechLanguage: settings.speechLanguage, speechTranslateToEnglish: settings.speechTranslateToEnglish, speechCustomWords, @@ -346,7 +349,7 @@ export function useEnvironmentSpeechInput(input: HookInput) { controller.dispose(); if (controllerRef.current === controller) controllerRef.current = null; }; - }, [prepared, grantId]); + }, [prepared, grantId, endpointUrl]); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- probes the chosen environment's speech status once its connection is available useEffect(() => { @@ -458,6 +461,14 @@ export function useEnvironmentSpeechInput(input: HookInput) { }); return; } + if (latestStatus.endpointUrl !== endpointUrl) { + toastManager.add({ + type: "error", + title: "Confirm the transcription destination", + description: "The destination changed. Review it in Settings > Voice before recording.", + }); + return; + } if (latestStatus.state === "missing-model") { setSetup({ ...INITIAL_SETUP, open: true }); return; diff --git a/docs/user/voice-input.md b/docs/user/voice-input.md index 33da1b4ac3aa..833a642308bf 100644 --- a/docs/user/voice-input.md +++ b/docs/user/voice-input.md @@ -10,11 +10,12 @@ On iPhone and Android, voice input transcribes on the device. See ## Choose where audio goes -On web and desktop, transcription runs on one of your T3 Code environments. +On web and desktop, transcription is handled by one of your T3 Code environments. Nothing is sent until you choose one: open **Settings → Voice** and set **Send microphone audio to** the environment that should transcribe for you. Microphone audio recorded on this device is sent to that environment over your -authenticated connection, transcribed there, and discarded. The choice is saved +authenticated connection. By default, it is transcribed there and discarded; a +custom speech endpoint forwards it as described below. The choice is saved on this device only, so every computer and browser you use asks for it once. Set it back to **Off** at any time; a recording in progress is discarded. @@ -37,6 +38,31 @@ is ever retried on another environment. Models marked **Live preview** show text while you speak. Other models can process long recordings in chunks at pauses while you record; models with built-in long-form support transcribe when you stop. +## Use a Whisper or Parakeet endpoint + +In **Settings → Voice → Speech engine**, choose **Custom endpoint**. Enter the +full transcription URL, the model name your server expects, and an optional API +key, then choose **Save and use endpoint**. For example, a local server could use +`http://localhost:8000/v1/audio/transcriptions`. Localhost means the machine running +the chosen T3 environment, which may differ from the computer with your microphone. +T3 stores the key in that environment's protected secret store. + +The server must accept OpenAI-compatible multipart transcription requests with a +WAV `file`, `model`, optional `language`, and `response_format=json`, and return +`{"text":"..."}`. A local Whisper service or a Parakeet service with that API works; +native NVIDIA Riva gRPC endpoints need an adapter. Start and manage the service +separately. T3 does not install an endpoint server or download its model. + +Endpoint settings belong to one environment. Saving authorizes forwarding from +this device to that exact URL; other devices must confirm the destination in Voice +settings. Changing the URL requires fresh confirmation. Audio is sent when you +finish speaking, with no live preview, translation, or T3 silence filtering. The +endpoint controls its own audio retention. Redirects are rejected, and failures +never send the recording to a different destination. Dictionary corrections and +filler removal still apply to the returned text. + +Choose **Local models → Use local models** to return to the built-in engine. + ## Dictate Press the microphone in the composer, or `mod+shift+d` (`mod` is Command on diff --git a/packages/client-runtime/src/state/sharedSettings.test.ts b/packages/client-runtime/src/state/sharedSettings.test.ts index 9d8fc51f960f..04fd7a28fd9f 100644 --- a/packages/client-runtime/src/state/sharedSettings.test.ts +++ b/packages/client-runtime/src/state/sharedSettings.test.ts @@ -5,7 +5,19 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; -import { filterSharedServerPatch } from "./sharedSettings.ts"; +import { filterSharedServerPatch, splitSharedServerPatch } from "./sharedSettings.ts"; + +it("keeps speech endpoint destinations and credentials on their own environment", () => { + const speechEndpoint = { + url: "http://localhost:8000/v1/audio/transcriptions", + model: "whisper", + apiKey: "test-key", + }; + expect(splitSharedServerPatch({ speechEndpoint, sidebarAutoSettleAfterDays: 7 })).toEqual({ + sharedPatch: { sidebarAutoSettleAfterDays: 7 }, + localPatch: { speechEndpoint }, + }); +}); describe("filterSharedServerPatch", () => { it("holds the restart preference until the target's config loads", () => { diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index a5a27235bbe7..52873d0a97b7 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -523,7 +523,28 @@ describe("voice settings", () => { speechModelId: "handy-computer/parakeet-unified-en-0.6b-gguf", speechAcceleration: "auto", speechModelUnloadTimeout: "min_15", + speechEndpoint: null, }); + const endpoint = { url: "http://localhost:8000/v1/audio/transcriptions", model: "whisper" }; + expect(decodeServerSettingsPatch({ speechEndpoint: endpoint })).toEqual({ + speechEndpoint: { ...endpoint, apiKey: "" }, + }); + expect(decodeServerSettingsPatch({ speechEndpoint: null })).toEqual({ speechEndpoint: null }); + expect(PROJECT_SCOPED_SERVER_SETTING_KEYS).not.toContain("speechEndpoint"); + for (const url of [ + "file:///tmp/audio", + "https://user:pass@example.test/transcribe", + "https://example.test/?key=secret", + "https://example.test/#fragment", + "not-a-url", + ]) { + expect(() => decodeServerSettingsPatch({ speechEndpoint: { ...endpoint, url } })).toThrow(); + } + expect(() => + decodeServerSettingsPatch({ + speechEndpoint: { ...endpoint, apiKey: "key\r\nInjected: header" }, + }), + ).toThrow(); }); }); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 30ad120c3e96..bfe8e019a64a 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -56,6 +56,8 @@ import { SpeechAcceleration, SpeechCorrectionCue, SpeechCustomWords, + SpeechEndpointConfig, + SpeechEndpointUrl, SpeechLanguage, SpeechModelUnloadTimeout, SpeechPostProcessingPromptSettings, @@ -362,10 +364,11 @@ export type ModelPreferences = { export const VoiceShortcutMode = Schema.Literals(["auto", "hold", "toggle"]); export type VoiceShortcutMode = typeof VoiceShortcutMode.Type; -/** Where this device sends microphone audio. A later backend adds its own kind here. */ +/** Where this device sends microphone audio, including an explicitly consented forwarding URL. */ export const VoiceTranscriptionDestination = Schema.Struct({ kind: Schema.Literal("environment"), environmentId: EnvironmentId, + endpointUrl: Schema.optionalKey(SpeechEndpointUrl), }); export type VoiceTranscriptionDestination = typeof VoiceTranscriptionDestination.Type; @@ -1243,6 +1246,9 @@ export const ServerSettings = Schema.Struct({ ), enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + speechEndpoint: Schema.NullOr(SpeechEndpointConfig).pipe( + Schema.withDecodingDefault(Effect.succeed(null)), + ), speechModelId: Schema.String.pipe( Schema.withDecodingDefault(Effect.succeed("handy-computer/parakeet-unified-en-0.6b-gguf")), ), @@ -1663,6 +1669,7 @@ export const ServerSettingsPatch = Schema.Struct({ continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean), enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean), speechModelId: Schema.optionalKey(Schema.String), + speechEndpoint: Schema.optionalKey(Schema.NullOr(SpeechEndpointConfig)), speechAcceleration: Schema.optionalKey(SpeechAcceleration), speechModelUnloadTimeout: Schema.optionalKey(SpeechModelUnloadTimeout), speechProjectCustomWords: Schema.optionalKey(SpeechCustomWords), diff --git a/packages/contracts/src/speech.ts b/packages/contracts/src/speech.ts index 5983b6951e07..adb7f17d85c2 100644 --- a/packages/contracts/src/speech.ts +++ b/packages/contracts/src/speech.ts @@ -1,9 +1,39 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import { TrimmedNonEmptyString } from "./baseSchemas.ts"; export const SpeechModelId = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(160)); export type SpeechModelId = typeof SpeechModelId.Type; +export const SpeechEndpointUrl = TrimmedNonEmptyString.check( + Schema.isMaxLength(2_048), + Schema.makeFilter((value) => { + try { + const url = new URL(value); + return ( + (["http:", "https:"].includes(url.protocol) && + !url.username && + !url.password && + !url.search && + !url.hash) || + "Use an HTTP or HTTPS transcription URL without credentials, query parameters, or a fragment." + ); + } catch { + return "Enter a valid HTTP or HTTPS transcription URL."; + } + }), +); + +export const SpeechEndpointConfig = Schema.Struct({ + url: SpeechEndpointUrl, + model: TrimmedNonEmptyString.check(Schema.isMaxLength(160)), + apiKey: Schema.String.check(Schema.isMaxLength(8_192), Schema.isPattern(/^[^\r\n]*$/)).pipe( + Schema.withDecodingDefault(Effect.succeed("")), + Schema.annotateKey({ settingsSecret: true }), + ), +}); +export type SpeechEndpointConfig = typeof SpeechEndpointConfig.Type; + const SpeechCustomWord = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(50)); export const SpeechCustomWords = Schema.Array( Schema.Struct({ @@ -109,6 +139,8 @@ export const EnvironmentSpeechStatus = Schema.Union([ acceleration: SpeechAcceleration, modelUnloadTimeout: SpeechModelUnloadTimeout, gpuDevices: Schema.Array(SpeechGpuDevice), + /** Audio is forwarded here only when the recording explicitly consents to this URL. */ + endpointUrl: Schema.optionalKey(SpeechEndpointUrl), }), ]); export type EnvironmentSpeechStatus = typeof EnvironmentSpeechStatus.Type; @@ -133,6 +165,8 @@ export const SpeechCorrectionCue = Schema.String.check(Schema.isMaxLength(50)); /** Recognition preferences that travel with every recording. */ export const SpeechTranscriptionOptions = Schema.Struct({ + /** Bind consent to the configured external destination; absent means local inference only. */ + speechEndpointUrl: Schema.optionalKey(SpeechEndpointUrl), speechLanguage: SpeechLanguage, speechTranslateToEnglish: Schema.Boolean, speechCustomWords: SpeechCustomWords,