From 7f14d49e5d5371a6acf65684665c14592be55550 Mon Sep 17 00:00:00 2001 From: Drake Stapleton <213298340+drakestapleton@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:44:21 -0600 Subject: [PATCH] feat(speech,web): add local 2-phase voice dictation, hands-free commands, and local STT/cleanup endpoints --- apps/server/src/speech/CloudSpeech.ts | 28 +-- apps/server/src/speech/SpeechService.ts | 165 ++++++++++++++++- apps/server/src/speech/localCleanup.test.ts | 59 ++++++ apps/server/src/speech/localCleanup.ts | 172 +++++++++++++++++ apps/server/src/speech/localEndpoint.test.ts | 62 +++++++ apps/server/src/speech/localEndpoint.ts | 74 ++++++++ apps/server/src/speech/native.ts | 2 +- apps/server/src/speech/postProcessing.ts | 56 +++++- apps/server/src/speech/wav.ts | 25 +++ apps/web/src/components/chat/ChatComposer.tsx | 144 ++++++++++++++- .../settings/VoiceSettingsPanel.tsx | 174 ++++++++++++++++++ apps/web/src/i18n/translations/de.json | 30 ++- apps/web/src/i18n/translations/en.json | 30 ++- apps/web/src/i18n/translations/es.json | 30 ++- apps/web/src/i18n/translations/fr.json | 30 ++- apps/web/src/i18n/translations/ja.json | 30 ++- apps/web/src/i18n/translations/ko.json | 30 ++- apps/web/src/i18n/translations/pt-BR.json | 30 ++- apps/web/src/i18n/translations/ru.json | 30 ++- apps/web/src/i18n/translations/sv.json | 30 ++- apps/web/src/i18n/translations/zh.json | 30 ++- apps/web/src/speech/voiceCommands.test.ts | 82 +++++++++ apps/web/src/speech/voiceCommands.ts | 161 ++++++++++++++++ apps/web/src/speech/voiceInputSession.ts | 14 +- packages/contracts/src/settings.ts | 24 +++ 25 files changed, 1409 insertions(+), 133 deletions(-) create mode 100644 apps/server/src/speech/localCleanup.test.ts create mode 100644 apps/server/src/speech/localCleanup.ts create mode 100644 apps/server/src/speech/localEndpoint.test.ts create mode 100644 apps/server/src/speech/localEndpoint.ts create mode 100644 apps/server/src/speech/wav.ts create mode 100644 apps/web/src/speech/voiceCommands.test.ts create mode 100644 apps/web/src/speech/voiceCommands.ts diff --git a/apps/server/src/speech/CloudSpeech.ts b/apps/server/src/speech/CloudSpeech.ts index 31702c80a87ee..53c653ec3bb27 100644 --- a/apps/server/src/speech/CloudSpeech.ts +++ b/apps/server/src/speech/CloudSpeech.ts @@ -26,6 +26,7 @@ import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts"; import { applySpeechAliases, speechRecognitionWords } from "./customWords.ts"; import { removeSpeechFillerWords } from "./fillerWords.ts"; import { decodeSpeechPcm, SpeechInvalidAudioError } from "./SpeechService.ts"; +import { encodePcm16Wav } from "./wav.ts"; const endpoints = { openai: { url: "https://api.openai.com/v1/audio/transcriptions", model: "gpt-transcribe" }, @@ -41,31 +42,6 @@ const OpenRouterCatalog = Schema.Struct({ data: Schema.Array(Schema.Struct({ id: Schema.String, name: Schema.optionalKey(Schema.String) })), }); -function wave(samples: Float32Array) { - const buffer = new ArrayBuffer(44 + samples.length * 2); - const view = new DataView(buffer); - const tag = (at: number, value: string) => - new Uint8Array(buffer, at, 4).set(new TextEncoder().encode(value)); - tag(0, "RIFF"); - view.setUint32(4, buffer.byteLength - 8, true); - tag(8, "WAVE"); - tag(12, "fmt "); - 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); - tag(36, "data"); - view.setUint32(40, buffer.byteLength - 44, true); - for (let index = 0; index < samples.length; index++) { - const sample = samples[index]!; - view.setInt16(44 + index * 2, Math.round(sample * (sample < 0 ? 32768 : 32767)), true); - } - return buffer; -} - function audioBody( provider: "openai" | "xai", audio: ArrayBuffer, @@ -210,7 +186,7 @@ export const layer = Layer.effect( Effect.mapError(unreadable), ); if (!isApiKey(key)) return yield* unreadable(); - const audio = wave(samples); + const audio = encodePcm16Wav(samples); const request = HttpClientRequest.post(endpoints[provider].url).pipe( HttpClientRequest.bearerToken(Redacted.make(key)), provider === "openrouter" diff --git a/apps/server/src/speech/SpeechService.ts b/apps/server/src/speech/SpeechService.ts index ba25233a32c7e..c18f9b190869f 100644 --- a/apps/server/src/speech/SpeechService.ts +++ b/apps/server/src/speech/SpeechService.ts @@ -24,11 +24,13 @@ import * as Stream from "effect/Stream"; import * as ServerSettings from "../serverSettings.ts"; import { + applySpeechAliases, makeSpeechTextCorrector, normalizeSpeechCustomWords, speechRecognitionWords, } from "./customWords.ts"; import { removeSpeechFillerWords } from "./fillerWords.ts"; +import { parseLocalSpeechEndpoint, transcribeWithLocalEndpoint } from "./localEndpoint.ts"; import { DEFAULT_SPEECH_MODEL_ID, effectiveSpeechLanguage, @@ -458,6 +460,29 @@ const make = Effect.gen(function* () { const currentStatus = Effect.fn("SpeechService.currentStatus")(function* ( settings: SettingsSnapshot, ): Effect.fn.Return { + const localEndpoint = parseLocalSpeechEndpoint( + settings.speechLocalEndpointUrl, + settings.speechLocalEndpointModel, + ); + if (localEndpoint) { + return { + supported: true, + state: activeTranscriptions > 0 ? "transcribing" : "ready", + modelId: localEndpoint.model, + model: `Local STT (${localEndpoint.model})`, + size: 0, + supportsStreaming: true, + supportsBufferedStreaming: true, + supportsModelLinking: !unsupportedReason, + supportsTranslation: false, + languages: ["en"], + supportsLanguageDetection: true, + acceleration: settings.speechAcceleration, + benchmarkTier: "accelerated", + modelUnloadTimeout: settings.speechModelUnloadTimeout, + gpuDevices: [], + }; + } if (unsupportedReason) return { supported: false, reason: unsupportedReason }; const definition = selectedModel(settings); const ready = yield* store.isReady(definition); @@ -560,8 +585,13 @@ const make = Effect.gen(function* () { }; const prepareModel = readSettings("model preparation").pipe( - Effect.flatMap((settings) => - exclusive( + Effect.flatMap((settings) => { + if ( + parseLocalSpeechEndpoint(settings.speechLocalEndpointUrl, settings.speechLocalEndpointModel) + ) { + return Effect.void; + } + return exclusive( "model preparation", requireSupported.pipe( Effect.andThen(installedModelPath(selectedModel(settings))), @@ -582,8 +612,8 @@ const make = Effect.gen(function* () { ), ), ), - ), - ), + ); + }), ); const silenceModelPath = Effect.fn("SpeechService.silenceModelPath")(function* ( @@ -599,16 +629,46 @@ const make = Effect.gen(function* () { const transcribe: SpeechService["Service"]["transcribe"] = Effect.fn("SpeechService.transcribe")( function* (pcmBytes, options) { const settings = yield* readSettings("transcription"); + const localEndpoint = parseLocalSpeechEndpoint( + settings.speechLocalEndpointUrl, + settings.speechLocalEndpointModel, + ); return yield* exclusive( "transcription", Effect.gen(function* () { - yield* requireSupported; + if (!localEndpoint) yield* requireSupported; const pcm = yield* Effect.try({ try: () => decodeSpeechPcm(pcmBytes), catch: (cause) => speechError("transcription", cause), }); if (pcm.length === 0) return ""; activeTranscriptions += 1; + if (localEndpoint) { + return yield* Effect.tryPromise({ + try: (signal) => + transcribeWithLocalEndpoint( + localEndpoint, + pcm, + options, + AbortSignal.any([signal, lifetime.signal]), + ), + catch: (cause) => speechError("local endpoint transcription", cause), + }).pipe( + Effect.map((raw) => { + const corrected = applySpeechAliases(raw, options.speechCustomWords); + return finalizeTranscript( + corrected, + options, + options.speechLanguage === "auto" ? undefined : options.speechLanguage, + ); + }), + Effect.ensuring( + Effect.sync(() => { + activeTranscriptions -= 1; + }), + ), + ); + } return yield* Effect.gen(function* () { const definition = selectedModel(settings); const language = effectiveSpeechLanguage(definition, options.speechLanguage); @@ -707,6 +767,101 @@ const make = Effect.gen(function* () { // Stream setup shares the public startStream span. const openStream = Effect.fnUntraced(function* (options: SpeechTranscriptionOptions) { const operation = "streaming transcription"; + const initialSettings = yield* readSettings(operation); + const localEndpoint = parseLocalSpeechEndpoint( + initialSettings.speechLocalEndpointUrl, + initialSettings.speechLocalEndpointModel, + ); + if (localEndpoint) { + const released = Promise.withResolvers(); + // @effect-diagnostics-next-line abortControllerInEffect:off - Stream cancellation must abort in-flight HTTP fetch independently of the caller fiber. + const controller = new AbortController(); + const signal = AbortSignal.any([controller.signal, lifetime.signal]); + const chunks: Float32Array[] = []; + let totalSamples = 0; + let totalBytes = 0; + let lastPreviewSamples = 0; + let latestPreview: string | null = null; + let previewInFlight = false; + let revision = 0; + let closed = false; + const combineChunks = () => { + const combined = new Float32Array(totalSamples); + let offset = 0; + for (const chunk of chunks) { + combined.set(chunk, offset); + offset += chunk.length; + } + return combined; + }; + yield* Effect.acquireRelease( + Effect.suspend(() => { + if (closing || operationBusy()) return Effect.fail(new SpeechBusyError({ operation })); + activeOperation = released.promise; + activeTranscriptions += 1; + return Effect.void; + }), + () => + Effect.sync(() => { + closed = true; + controller.abort(); + activeTranscriptions -= 1; + if (activeOperation === released.promise) activeOperation = undefined; + released.resolve(); + }), + ); + return { + feed: (bytes: Uint8Array) => + attempt(operation, async () => { + if (closed || signal.aborted) throw new Error("Speech stream is closed."); + if ( + bytes.byteLength > SPEECH_STREAM_MAX_CHUNK_BYTES || + totalBytes + bytes.byteLength > MAX_SPEECH_BYTES + ) { + throw new SpeechInvalidAudioError({ + byteLength: bytes.byteLength, + message: "Speech stream audio limit exceeded.", + }); + } + const pcm = decodeSpeechPcm(bytes); + chunks.push(pcm); + totalSamples += pcm.length; + totalBytes += bytes.byteLength; + revision += 1; + // Phase 1 live preview: refresh interim text roughly every 1.5s of new audio. + if (!previewInFlight && totalSamples - lastPreviewSamples >= 24_000) { + previewInFlight = true; + lastPreviewSamples = totalSamples; + const snapshot = combineChunks(); + void transcribeWithLocalEndpoint(localEndpoint, snapshot, options, signal) + .then((raw) => { + if (closed || signal.aborted) return; + const corrected = applySpeechAliases(raw, options.speechCustomWords).trim(); + if (corrected) latestPreview = corrected; + }) + .catch(() => undefined) + .finally(() => { + previewInFlight = false; + }); + } + return { + revision, + text: latestPreview ? { committed: "", tentative: latestPreview } : null, + }; + }), + finish: attempt(operation, async () => { + if (totalSamples === 0) return ""; + const combined = combineChunks(); + const raw = await transcribeWithLocalEndpoint(localEndpoint, combined, options, signal); + const corrected = applySpeechAliases(raw, options.speechCustomWords); + return finalizeTranscript( + corrected, + options, + options.speechLanguage === "auto" ? undefined : options.speechLanguage, + ); + }), + }; + } yield* requireSupported; const released = Promise.withResolvers(); // @effect-diagnostics-next-line abortControllerInEffect:off - Stream cancellation must abort native work independently of the caller fiber. diff --git a/apps/server/src/speech/localCleanup.test.ts b/apps/server/src/speech/localCleanup.test.ts new file mode 100644 index 0000000000000..bbba3d70b7f8e --- /dev/null +++ b/apps/server/src/speech/localCleanup.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { + cleanTranscriptLocally, + cleanTranscriptWithLocalEndpoint, + parseLocalCleanupEndpoint, +} from "./localCleanup.ts"; + +describe("localCleanup", () => { + it("cleans capitalization, contractions, stutters, punctuation, and spoken corrections locally", () => { + expect( + cleanTranscriptLocally("i dont think the the parser works right", { customWords: [] }), + ).toBe("I don't think the parser works right."); + + expect(cleanTranscriptLocally("can you check why tests fail", { customWords: [] })).toBe( + "Can you check why tests fail?", + ); + + expect(cleanTranscriptLocally("set timeout to 42, scratch that, 24", { customWords: [] })).toBe( + "Set timeout to 24.", + ); + + expect( + cleanTranscriptLocally("use m3 code for local voice", { + customWords: [{ term: "M3 Code", aliases: ["m3 code"] }], + }), + ).toBe("Use M3 Code for local voice."); + }); + + it("parses valid local cleanup endpoints", () => { + expect( + parseLocalCleanupEndpoint("http://127.0.0.1:11434/v1/chat/completions", "qwen2.5:3b"), + ).toEqual({ + url: "http://127.0.0.1:11434/v1/chat/completions", + model: "qwen2.5:3b", + }); + expect(parseLocalCleanupEndpoint("", "")).toBeNull(); + expect(parseLocalCleanupEndpoint("file:///tmp/x", "")).toBeNull(); + }); + + it("calls a local OpenAI-compatible chat completions endpoint for Phase 2 cleanup", async () => { + using _fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response( + JSON.stringify({ + choices: [{ message: { content: "Fix the failing parser tests." } }], + }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ); + + const cleaned = await cleanTranscriptWithLocalEndpoint( + { url: "http://127.0.0.1:11434/v1/chat/completions", model: "qwen2.5:3b" }, + "fix the failing parser tests", + "Clean up punctuation and capitals.", + [], + ); + expect(cleaned).toBe("Fix the failing parser tests."); + }); +}); diff --git a/apps/server/src/speech/localCleanup.ts b/apps/server/src/speech/localCleanup.ts new file mode 100644 index 0000000000000..731d704532df5 --- /dev/null +++ b/apps/server/src/speech/localCleanup.ts @@ -0,0 +1,172 @@ +import type { SpeechCustomWords } from "@t3tools/contracts"; + +import { applySpeechAliases } from "./customWords.ts"; + +export interface LocalCleanupEndpointConfig { + readonly url: string; + readonly model: string; +} + +/** Parses an optional local OpenAI-compatible /v1/chat/completions cleanup endpoint. */ +export function parseLocalCleanupEndpoint( + rawUrl: string | undefined, + rawModel: string | undefined, +): LocalCleanupEndpointConfig | null { + const trimmed = rawUrl?.trim() ?? ""; + if (!trimmed) return null; + let parsed: URL; + try { + parsed = new URL(trimmed); + } catch { + return null; + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; + return { + url: parsed.toString(), + model: rawModel?.trim() || "default", + }; +} + +const CONTRACTION_REPLACEMENTS: ReadonlyArray = [ + [/\bi'm\b/gi, "I'm"], + [/\bi've\b/gi, "I've"], + [/\bi'll\b/gi, "I'll"], + [/\bi'd\b/gi, "I'd"], + [/\bim\b/gi, "I'm"], + [/\bive\b/gi, "I've"], + [/\bdont\b/gi, "don't"], + [/\bcant\b/gi, "can't"], + [/\bwont\b/gi, "won't"], + [/\bdoesnt\b/gi, "doesn't"], + [/\bdidnt\b/gi, "didn't"], + [/\bisnt\b/gi, "isn't"], + [/\barent\b/gi, "aren't"], + [/\bwasnt\b/gi, "wasn't"], + [/\bwerent\b/gi, "weren't"], + [/\bhavent\b/gi, "haven't"], + [/\bhasnt\b/gi, "hasn't"], + [/\bwouldnt\b/gi, "wouldn't"], + [/\bcouldnt\b/gi, "couldn't"], + [/\bshouldnt\b/gi, "shouldn't"], + [/\bthats\b/gi, "that's"], + [/\bwhats\b/gi, "what's"], + [/\btheres\b/gi, "there's"], + [/\bheres\b/gi, "here's"], + [/\byoure\b/gi, "you're"], + [/\btheyre\b/gi, "they're"], + [/\bweve\b/gi, "we've"], + [/\byouve\b/gi, "you've"], + [/\btheyve\b/gi, "they've"], +]; + +const QUESTION_STARTER = + /^(?:what|why|how|where|when|who|which|can|could|would|should|do|does|did|is|are|was|were|will|have|has)\b/i; + +function preserveInitialCase(original: string, replacement: string): string { + if (original.length > 0 && original[0] === original[0]!.toUpperCase()) { + return replacement[0]!.toUpperCase() + replacement.slice(1); + } + return replacement; +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function applySpokenCorrections(text: string, customCue?: string): string { + const cues = ["scratch that", "never mind", "nevermind", "i mean"]; + const trimmedCue = customCue?.trim(); + if (trimmedCue) cues.unshift(trimmedCue); + const cuePattern = cues.map(escapeRegExp).join("|"); + // "make it 42, scratch that, 24" -> "make it 24" + const pattern = new RegExp( + `(\\b\\S+)\\s*[,;:.\\s-]+(?:${cuePattern})\\s*[,;:.\\s-]+(\\S+)`, + "gi", + ); + return text.replace(pattern, "$2"); +} + +/** + * Deterministic, zero-API-call Phase 2 transcript cleaner. + * Fixes capitalization, punctuation spacing, common contractions, word stutters, + * spoken self-corrections, and custom dictionary spellings locally. + */ +export function cleanTranscriptLocally( + rawTranscript: string, + options: { + readonly customWords: SpeechCustomWords; + readonly correctionWord?: string | undefined; + }, +): string { + let text = rawTranscript.replace(/\s+/g, " ").trim(); + if (!text) return ""; + + text = applySpokenCorrections(text, options.correctionWord); + + // Collapse accidental immediate word stutters ("the the" -> "the"). + text = text.replace(/\b([a-z]{1,12})\s+\1\b/gi, "$1"); + + // Fix contractions and standalone "i" -> "I". + for (const [pattern, replacement] of CONTRACTION_REPLACEMENTS) { + text = text.replace(pattern, (match) => preserveInitialCase(match, replacement)); + } + text = text.replace(/\bi\b/g, "I"); + + // Normalize spacing around punctuation. + text = text + .replace(/\s+([,.;:!?])/g, "$1") + .replace(/([,.;:!?])(?=[A-Za-z0-9])/g, "$1 ") + .replace(/\s+/g, " ") + .trim(); + + // Capitalize start of transcript and after sentence-ending punctuation. + text = text.replace(/(^|[.!?]\s+)([a-z])/g, (_, prefix: string, letter: string) => { + return `${prefix}${letter.toUpperCase()}`; + }); + + // Add terminal punctuation for multi-word utterances if none is present. + const wordCount = text.split(/\s+/).filter(Boolean).length; + if (wordCount >= 3 && !/[.!?…:]$/.test(text)) { + text += QUESTION_STARTER.test(text) ? "?" : "."; + } + + return applySpeechAliases(text, options.customWords).trim(); +} + +/** + * Calls a local OpenAI-compatible `/v1/chat/completions` endpoint for Phase 2 cleanup + * (e.g. Ollama, llama.cpp, LM Studio, or Spark local model server). + */ +export async function cleanTranscriptWithLocalEndpoint( + config: LocalCleanupEndpointConfig, + transcript: string, + instructions: string, + customWords: SpeechCustomWords, + signal?: AbortSignal, +): Promise { + const response = await fetch(config.url, { + method: "POST", + headers: { "content-type": "application/json" }, + redirect: "error", + body: JSON.stringify({ + model: config.model, + temperature: 0, + messages: [ + { role: "system", content: instructions }, + { role: "user", content: transcript }, + ], + }), + ...(signal ? { signal } : {}), + }); + if (!response.ok) { + throw new Error(`Local cleanup endpoint returned HTTP ${response.status}.`); + } + const body = (await response.json()) as { + choices?: ReadonlyArray<{ message?: { content?: unknown } }>; + }; + const content = body.choices?.[0]?.message?.content; + if (typeof content !== "string" || !content.trim()) { + throw new Error("Local cleanup endpoint returned empty content."); + } + return applySpeechAliases(content.trim(), customWords).trim(); +} diff --git a/apps/server/src/speech/localEndpoint.test.ts b/apps/server/src/speech/localEndpoint.test.ts new file mode 100644 index 0000000000000..bb7c7adafa248 --- /dev/null +++ b/apps/server/src/speech/localEndpoint.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { parseLocalSpeechEndpoint, transcribeWithLocalEndpoint } from "./localEndpoint.ts"; +import { encodePcm16Wav } from "./wav.ts"; + +describe("localEndpoint", () => { + it("parses valid http and https endpoints and defaults model to whisper-1", () => { + expect(parseLocalSpeechEndpoint("http://127.0.0.1:8178/inference", "")).toEqual({ + url: "http://127.0.0.1:8178/inference", + model: "whisper-1", + }); + expect( + parseLocalSpeechEndpoint(" https://spark.local/v1/audio/transcriptions ", "whisper-large-v3"), + ).toEqual({ + url: "https://spark.local/v1/audio/transcriptions", + model: "whisper-large-v3", + }); + expect(parseLocalSpeechEndpoint("", "")).toBeNull(); + expect(parseLocalSpeechEndpoint("file:///etc/passwd", "")).toBeNull(); + expect(parseLocalSpeechEndpoint("not-a-url", "")).toBeNull(); + }); + + it("encodes 16 kHz mono WAV header and samples", () => { + const wav = encodePcm16Wav(new Float32Array([0, 0.5, -1])); + expect(wav.byteLength).toBe(44 + 6); + const header = new TextDecoder().decode(new Uint8Array(wav, 0, 4)); + expect(header).toBe("RIFF"); + const view = new DataView(wav); + expect(view.getUint32(24, true)).toBe(16_000); + expect(view.getInt16(44, true)).toBe(0); + expect(view.getInt16(48, true)).toBe(-32768); + }); + + it("posts WAV multipart form data and reads JSON text", async () => { + let capturedForm: FormData | null = null; + using _fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + capturedForm = init?.body as FormData; + return new Response(JSON.stringify({ text: "hello from local whisper" }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }); + + const text = await transcribeWithLocalEndpoint( + { url: "http://127.0.0.1:8178/inference", model: "large-v3-turbo" }, + new Float32Array([0.1, -0.1]), + { + speechLanguage: "en", + speechTranslateToEnglish: false, + speechCustomWords: [{ term: "M3 Code", aliases: [] }], + speechRemoveFillerWords: true, + speechSilenceFiltering: true, + }, + ); + + expect(text).toBe("hello from local whisper"); + expect(capturedForm?.get("model")).toBe("large-v3-turbo"); + expect(capturedForm?.get("language")).toBe("en"); + expect(capturedForm?.get("prompt")).toBe("M3 Code"); + expect(capturedForm?.get("file")).toBeInstanceOf(Blob); + }); +}); diff --git a/apps/server/src/speech/localEndpoint.ts b/apps/server/src/speech/localEndpoint.ts new file mode 100644 index 0000000000000..f17d3233ed578 --- /dev/null +++ b/apps/server/src/speech/localEndpoint.ts @@ -0,0 +1,74 @@ +import type { SpeechTranscriptionOptions } from "@t3tools/contracts"; + +import { encodePcm16Wav } from "./wav.ts"; + +export interface LocalSpeechEndpointConfig { + readonly url: string; + readonly model: string; +} + +/** Parses and validates a local/LAN OpenAI-compatible or whisper.cpp STT endpoint URL. */ +export function parseLocalSpeechEndpoint( + rawUrl: string | undefined, + rawModel: string | undefined, +): LocalSpeechEndpointConfig | null { + const trimmed = rawUrl?.trim() ?? ""; + if (!trimmed) return null; + let parsed: URL; + try { + parsed = new URL(trimmed); + } catch { + return null; + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; + return { + url: parsed.toString(), + model: rawModel?.trim() || "whisper-1", + }; +} + +/** + * Sends 16 kHz mono Float32 PCM as a WAV upload to a local OpenAI-compatible + * (`/v1/audio/transcriptions`) or `whisper.cpp` (`/inference`) STT server. + */ +export async function transcribeWithLocalEndpoint( + config: LocalSpeechEndpointConfig, + pcm: Float32Array, + options: SpeechTranscriptionOptions, + signal?: AbortSignal, +): Promise { + const wav = encodePcm16Wav(pcm); + const form = new FormData(); + form.set("file", new Blob([wav], { type: "audio/wav" }), "dictation.wav"); + form.set("model", config.model); + form.set("response_format", "json"); + if (options.speechLanguage && options.speechLanguage !== "auto") { + form.set("language", options.speechLanguage); + } + if (options.speechCustomWords.length > 0) { + form.set("prompt", options.speechCustomWords.map(({ term }) => term).join(", ")); + } + const response = await fetch(config.url, { + method: "POST", + body: form, + redirect: "error", + ...(signal ? { signal } : {}), + }); + if (!response.ok) { + throw new Error(`Local speech endpoint returned HTTP ${response.status}.`); + } + const contentType = response.headers.get("content-type") ?? ""; + if (contentType.includes("application/json")) { + const body = (await response.json()) as { text?: unknown }; + if (typeof body.text === "string") return body.text; + throw new Error("Local speech endpoint JSON response did not include a text string."); + } + const raw = (await response.text()).trim(); + try { + const parsed = JSON.parse(raw) as { text?: unknown }; + if (typeof parsed.text === "string") return parsed.text; + } catch { + // Plain-text response (e.g. whisper.cpp text mode) + } + return raw; +} diff --git a/apps/server/src/speech/native.ts b/apps/server/src/speech/native.ts index 2bd2631c63fba..3c7a2fd31da79 100644 --- a/apps/server/src/speech/native.ts +++ b/apps/server/src/speech/native.ts @@ -267,7 +267,7 @@ export async function listNativeSpeechGpuDevices(moduleUrl?: string) { const timer = setTimeout(() => { child.kill(); reject(new Error("Speech device discovery timed out.")); - }, 10_000); + }, 30_000); child.on("message", (devices: unknown) => { if ( Array.isArray(devices) && diff --git a/apps/server/src/speech/postProcessing.ts b/apps/server/src/speech/postProcessing.ts index 92f4af17696c3..57a8883ba9075 100644 --- a/apps/server/src/speech/postProcessing.ts +++ b/apps/server/src/speech/postProcessing.ts @@ -13,6 +13,11 @@ import * as ServerSettings from "../serverSettings.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; import { buildTranscriptionPostProcessingPrompt } from "../textGeneration/TranscriptionPostProcessing.ts"; import { applySpeechAliases } from "./customWords.ts"; +import { + cleanTranscriptLocally, + cleanTranscriptWithLocalEndpoint, + parseLocalCleanupEndpoint, +} from "./localCleanup.ts"; import { SpeechOperationError } from "./SpeechService.ts"; export class SpeechPostProcessing extends Context.Service< @@ -39,18 +44,49 @@ const make = Effect.gen(function* () { const instructions = (mode === "custom" ? customInstructions.trim() : "") || DEFAULT_SPEECH_POST_PROCESSING_PROMPT; + const localFallback = () => + cleanTranscriptLocally(input.transcript, { + customWords: input.options.speechCustomWords, + correctionWord: input.options.speechCorrectionWord, + }); + const localEndpoint = parseLocalCleanupEndpoint( + settings.speechLocalCleanupEndpointUrl, + settings.speechLocalCleanupModel, + ); + if (localEndpoint) { + const text = yield* Effect.tryPromise({ + try: (signal) => + cleanTranscriptWithLocalEndpoint( + localEndpoint, + input.transcript, + instructions, + input.options.speechCustomWords, + signal, + ), + catch: () => null, + }).pipe(Effect.orElseSucceed(localFallback)); + return { text: text.length > 0 ? text : input.transcript }; + } + const hasConfiguredModel = + settings.speechPostProcessingModelSelection !== null || + settings.textGenerationModelSelection !== null; + if (!hasConfiguredModel) { + return { text: localFallback() }; + } // Providers run in a working directory; cleanup must not read a checkout. const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-voice-cleanup-" }); - const generated = yield* textGeneration.generateTranscriptionPostProcessing({ - cwd, - prompt: buildTranscriptionPostProcessingPrompt( - instructions, - input.transcript, - input.draft, - input.options.speechCorrectionWord, - ), - modelSelection: resolveSpeechPostProcessingModelSelection(settings, providers), - }); + const generated = yield* textGeneration + .generateTranscriptionPostProcessing({ + cwd, + prompt: buildTranscriptionPostProcessingPrompt( + instructions, + input.transcript, + input.draft, + input.options.speechCorrectionWord, + ), + modelSelection: resolveSpeechPostProcessingModelSelection(settings, providers), + }) + .pipe(Effect.orElseSucceed(() => ({ transcription: localFallback() }))); const text = generated.transcription.trim(); return { text: diff --git a/apps/server/src/speech/wav.ts b/apps/server/src/speech/wav.ts new file mode 100644 index 0000000000000..2589e5f3f1acf --- /dev/null +++ b/apps/server/src/speech/wav.ts @@ -0,0 +1,25 @@ +/** Encodes 16 kHz mono Float32 PCM samples into a 16-bit PCM RIFF/WAVE buffer. */ +export function encodePcm16Wav(samples: Float32Array): ArrayBuffer { + const buffer = new ArrayBuffer(44 + samples.length * 2); + const view = new DataView(buffer); + const tag = (at: number, value: string) => + new Uint8Array(buffer, at, 4).set(new TextEncoder().encode(value)); + tag(0, "RIFF"); + view.setUint32(4, buffer.byteLength - 8, true); + tag(8, "WAVE"); + tag(12, "fmt "); + 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); + tag(36, "data"); + view.setUint32(40, buffer.byteLength - 44, true); + for (let index = 0; index < samples.length; index++) { + const sample = samples[index]!; + view.setInt16(44 + index * 2, Math.round(sample * (sample < 0 ? 32768 : 32767)), true); + } + return buffer; +} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 65f78574256e6..4091a44088649 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -152,6 +152,7 @@ import { attachmentUploadBlockReason } from "../../lib/attachmentUploadState"; import { useDictationShortcut } from "../../speech/useDictationShortcut"; import { useDictationSubmissionShortcut } from "../../speech/useDictationSubmissionShortcut"; import { useEnvironmentSpeechInput } from "../../speech/useEnvironmentSpeechInput"; +import { parseVoiceCommand, type VoiceModelCandidate } from "../../speech/voiceCommands"; import { ComposerSpeechButton, ComposerSpeechRecordingPill } from "./ComposerSpeechButton"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; import { shortcutLabelForCommand, type ShortcutMatchContext } from "../../keybindings"; @@ -1962,6 +1963,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const readComposerSnapshotStable = useStableCallback(readComposerSnapshot); + const [voiceCommandSubmitSeq, setVoiceCommandSubmitSeq] = useState(0); const dictationDisabled = !canOperateThread || environmentUnavailable !== null || @@ -2010,14 +2012,84 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }, commitDraft: (text, selection) => { const snapshot = readComposerSnapshot(); - const applied = applyPromptReplacement(0, snapshot.value.length, text, { - expectedText: snapshot.value, - focusEditorAfterReplace: false, - }); - if (!applied) return; - const cursor = collapseExpandedComposerCursor(text, selection.start, isLiteralPendingAnswer); - setComposerCursor(cursor); - window.requestAnimationFrame(() => composerEditorRef.current?.focusAt(cursor)); + const applyCommittedText = (nextText: string, nextCursorOffset?: number) => { + const cursorOffset = nextCursorOffset ?? nextText.length; + const applied = applyPromptReplacement(0, snapshot.value.length, nextText, { + expectedText: snapshot.value, + focusEditorAfterReplace: false, + }); + if (!applied) return false; + const cursor = collapseExpandedComposerCursor( + nextText, + cursorOffset, + isLiteralPendingAnswer, + ); + setComposerCursor(cursor); + window.requestAnimationFrame(() => composerEditorRef.current?.focusAt(cursor)); + return true; + }; + + if (settings.voiceCommandsEnabled && !isLiteralPendingAnswer) { + const prefix = text.startsWith(snapshot.value) ? snapshot.value : ""; + const utterance = prefix ? text.slice(prefix.length) : text; + const voiceModelCandidates: VoiceModelCandidate[] = []; + for (const entry of providerInstanceEntries) { + const options = modelOptionsByInstance.get(entry.instanceId) ?? []; + for (const option of options) { + if (getModelDisabledReason(entry.instanceId, option.slug) !== null) continue; + voiceModelCandidates.push({ + instanceId: entry.instanceId, + model: option.slug, + label: option.name, + providerLabel: entry.displayName, + }); + } + } + const command = parseVoiceCommand(utterance, voiceModelCandidates); + if (command.kind === "stop") { + onInterrupt(); + toastManager.add({ type: "info", title: gt("Voice: Stopped turn") }); + return; + } + if (command.kind === "clear") { + applyCommittedText("", 0); + toastManager.add({ type: "info", title: gt("Voice: Cleared draft") }); + return; + } + if (command.kind === "switch-model") { + onProviderModelSelect( + command.candidate.instanceId as ProviderInstanceId, + command.candidate.model, + { focusComposer: false }, + ); + toastManager.add({ + type: "info", + title: gt("Voice: Switched to {model}", { model: command.candidate.label }), + }); + if (command.remainingText) { + const combined = prefix + ? `${prefix.trimEnd()} ${command.remainingText}` + : command.remainingText; + if (applyCommittedText(combined) && command.autoSend) { + setVoiceCommandSubmitSeq((seq) => seq + 1); + } + } + return; + } + if (command.kind === "send") { + const combined = command.text + ? prefix + ? `${prefix.trimEnd()} ${command.text}` + : command.text + : prefix.trimEnd(); + if (applyCommittedText(combined) && combined.trim().length > 0) { + setVoiceCommandSubmitSeq((seq) => seq + 1); + } + return; + } + } + + applyCommittedText(text, selection.start); }, }); const { blocksSubmission: voiceInputActive, submitAfterDictation } = speechInput; @@ -2442,6 +2514,62 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) submitComposerRef.current = (mode, intent, options) => submitComposerStable(undefined, mode, intent, options); }, [submitComposerStable]); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- submits a spoken "send it" command once its draft replacement commits + useEffect(() => { + if (voiceCommandSubmitSeq === 0) return; + submitComposerStable(); + }, [voiceCommandSubmitSeq, submitComposerStable]); + + // Hands-free auto-send: after speech is detected, a sustained pause finishes recording and submits. + const voiceAutoSendHeardSpeechRef = useRef(false); + const voiceAutoSendTimerRef = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears any pending hands-free timer on unmount + useEffect(() => { + return () => { + if (voiceAutoSendTimerRef.current !== null) { + window.clearTimeout(voiceAutoSendTimerRef.current); + voiceAutoSendTimerRef.current = null; + } + }; + }, []); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- manages the silence timer driven by live microphone levels during hands-free recording + useEffect(() => { + const clearSilenceTimer = () => { + if (voiceAutoSendTimerRef.current !== null) { + window.clearTimeout(voiceAutoSendTimerRef.current); + voiceAutoSendTimerRef.current = null; + } + }; + if (!settings.voiceAutoSend || speechInput.state.phase !== "recording") { + voiceAutoSendHeardSpeechRef.current = false; + clearSilenceTimer(); + return clearSilenceTimer; + } + if (speechInput.level >= 0.04) { + voiceAutoSendHeardSpeechRef.current = true; + clearSilenceTimer(); + return clearSilenceTimer; + } + if (speechInput.level >= 0.02) { + clearSilenceTimer(); + return clearSilenceTimer; + } + if (voiceAutoSendHeardSpeechRef.current && voiceAutoSendTimerRef.current === null) { + voiceAutoSendTimerRef.current = window.setTimeout(() => { + voiceAutoSendTimerRef.current = null; + voiceAutoSendHeardSpeechRef.current = false; + submitAfterDictation(() => submitComposerRef.current()); + }, settings.voiceSilenceTimeoutMs); + } + return undefined; + }, [ + settings.voiceAutoSend, + settings.voiceSilenceTimeoutMs, + speechInput.level, + speechInput.state.phase, + submitAfterDictation, + ]); useDictationSubmissionShortcut({ enabled: voiceInputActive && !speechInput.preparing, formRef: composerFormRef, diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index a6283977cf534..92a48682cc099 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx @@ -796,6 +796,104 @@ function useVoiceModels(prepared: PreparedConnection | null) { type VoiceModels = ReturnType; +function LocalSttEndpointRows({ disabled }: { disabled: boolean }) { + const gt = useGT(); + const scopedSettings = useScopedSettings(); + const updateScopedSettings = useUpdateScopedSettings(); + return ( + <> + { + const next = event.target.value.trim(); + if (next !== scopedSettings.speechLocalEndpointUrl) { + void updateScopedSettings({ speechLocalEndpointUrl: next }); + } + }} + /> + } + /> + {scopedSettings.speechLocalEndpointUrl.trim() ? ( + { + const next = event.target.value.trim(); + if (next !== scopedSettings.speechLocalEndpointModel) { + void updateScopedSettings({ speechLocalEndpointModel: next }); + } + }} + /> + } + /> + ) : null} + { + const next = event.target.value.trim(); + if (next !== scopedSettings.speechLocalCleanupEndpointUrl) { + void updateScopedSettings({ speechLocalCleanupEndpointUrl: next }); + } + }} + /> + } + /> + {scopedSettings.speechLocalCleanupEndpointUrl.trim() ? ( + { + const next = event.target.value.trim(); + if (next !== scopedSettings.speechLocalCleanupModel) { + void updateScopedSettings({ speechLocalCleanupModel: next }); + } + }} + /> + } + /> + ) : null} + + ); +} + function AdvancedSpeechSettings({ prepared, catalog, @@ -807,6 +905,7 @@ function AdvancedSpeechSettings({ const setting = useSearchableSetting(); const gt = useGT(); const settings = useClientSettings(); + const settingsScope = useOptionalSettingsScope(); const { run, controlsDisabled, status } = catalog; if (!status?.supported) return null; const supported = status; @@ -907,6 +1006,7 @@ function AdvancedSpeechSettings({ } /> + {settingsScope !== null ? : null} ); } @@ -1802,6 +1902,65 @@ export function VoiceSettingsPanel() { {prepared && } + + + void updateClientSettings({ voiceCommandsEnabled: checked }) + } + /> + } + /> + void updateClientSettings({ voiceAutoSend: checked })} + /> + } + /> + {settings.voiceAutoSend ? ( + { + const parsed = Number(value); + if (Number.isFinite(parsed) && parsed >= 800 && parsed <= 5_000) { + void updateClientSettings({ voiceSilenceTimeoutMs: parsed }); + } + }} + > + + {`${(settings.voiceSilenceTimeoutMs / 1000).toFixed(1)}s`} + + + {[1_000, 1_500, 1_800, 2_500, 3_500].map((ms) => ( + + {`${(ms / 1000).toFixed(1)}s`} + + ))} + + + } + /> + ) : null} + + + + void updateClientSettings({ speechLocalTwoPhaseCleanup: checked }) + } + /> + } + /> { + it("recognizes stop and clear commands", () => { + expect(parseVoiceCommand("Stop generating.", MODELS)).toEqual({ kind: "stop" }); + expect(parseVoiceCommand("cancel turn", MODELS)).toEqual({ kind: "stop" }); + expect(parseVoiceCommand("Clear draft!", MODELS)).toEqual({ kind: "clear" }); + }); + + it("recognizes standalone and trailing send commands", () => { + expect(parseVoiceCommand("send it.", MODELS)).toEqual({ kind: "send", text: "" }); + expect(parseVoiceCommand("Fix the failing unit test, send it.", MODELS)).toEqual({ + kind: "send", + text: "Fix the failing unit test", + }); + expect(parseVoiceCommand("Explain this diff, over", MODELS)).toEqual({ + kind: "send", + text: "Explain this diff", + }); + }); + + it("switches AI models by voice, with or without chained prompt", () => { + expect(parseVoiceCommand("Switch to Opus.", MODELS)).toEqual({ + kind: "switch-model", + candidate: MODELS[1], + remainingText: "", + autoSend: false, + }); + expect(parseVoiceCommand("Use model Gemini 3 Pro", MODELS)).toEqual({ + kind: "switch-model", + candidate: MODELS[3], + remainingText: "", + autoSend: false, + }); + expect(parseVoiceCommand("Switch to Sonnet and refactor the parser, send it.", MODELS)).toEqual( + { + kind: "switch-model", + candidate: MODELS[0], + remainingText: "refactor the parser", + autoSend: true, + }, + ); + }); + + it("leaves normal dictation untouched", () => { + expect(parseVoiceCommand("Refactor the sidebar to use flexbox", MODELS)).toEqual({ + kind: "none", + }); + expect(parseVoiceCommand("Switch to the settings tab when ready", MODELS)).toEqual({ + kind: "none", + }); + }); +}); diff --git a/apps/web/src/speech/voiceCommands.ts b/apps/web/src/speech/voiceCommands.ts new file mode 100644 index 0000000000000..f6e6b93261535 --- /dev/null +++ b/apps/web/src/speech/voiceCommands.ts @@ -0,0 +1,161 @@ +export interface VoiceModelCandidate { + readonly instanceId: string; + readonly model: string; + readonly label: string; + readonly providerLabel: string; +} + +export type ParsedVoiceCommand = + | { readonly kind: "none" } + | { readonly kind: "stop" } + | { readonly kind: "clear" } + | { readonly kind: "send"; readonly text: string } + | { + readonly kind: "switch-model"; + readonly candidate: VoiceModelCandidate; + readonly remainingText: string; + readonly autoSend: boolean; + }; + +function normalizePhrase(input: string): string { + return input + .toLowerCase() + .replace(/['’]/g, "") + .replace(/[^a-z0-9.\s-]+/g, " ") + .replace(/\.+(?=\s|$)/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +function stripTrailingSendPhrase(text: string): { readonly text: string; readonly send: boolean } { + const match = text.match( + /^(.*?)(?:[,.;:!?—–-\s]+)(send it|send message|send prompt|submit message|submit prompt|over)[.!?]*$/i, + ); + if (match) { + return { text: match[1]!.trim(), send: true }; + } + const standalone = normalizePhrase(text); + if ( + standalone === "send" || + standalone === "send it" || + standalone === "send message" || + standalone === "submit" || + standalone === "submit message" + ) { + return { text: "", send: true }; + } + return { text, send: false }; +} + +function scoreModelCandidate(query: string, candidate: VoiceModelCandidate): number { + const normalizedQuery = normalizePhrase(query); + if (!normalizedQuery) return 0; + const fields = [ + normalizePhrase(candidate.label), + normalizePhrase(candidate.model), + normalizePhrase(`${candidate.providerLabel} ${candidate.label}`), + normalizePhrase(candidate.providerLabel), + ]; + + for (const field of fields) { + if (field === normalizedQuery) return 100; + } + + const queryTokens = normalizedQuery.split(" ").filter((token) => token.length > 0); + if (queryTokens.length === 0) return 0; + + let best = 0; + for (const field of fields) { + if (field.includes(normalizedQuery)) { + best = Math.max(best, 80 + normalizedQuery.length); + continue; + } + const fieldTokens = field.split(/[\s.-]+/).filter(Boolean); + const matched = queryTokens.filter((token) => + fieldTokens.some( + (candidateToken) => candidateToken === token || candidateToken.startsWith(token), + ), + ); + if (matched.length === queryTokens.length) { + best = Math.max(best, 60 + matched.length * 5); + } + } + return best; +} + +export function matchVoiceModelCandidate( + query: string, + candidates: readonly VoiceModelCandidate[], +): VoiceModelCandidate | null { + let bestCandidate: VoiceModelCandidate | null = null; + let bestScore = 0; + for (const candidate of candidates) { + const score = scoreModelCandidate(query, candidate); + if (score > bestScore) { + bestScore = score; + bestCandidate = candidate; + } + } + return bestScore >= 60 ? bestCandidate : null; +} + +/** Parses a newly transcribed utterance for hands-free model-switching and turn-control commands. */ +export function parseVoiceCommand( + rawTranscript: string, + candidates: readonly VoiceModelCandidate[], +): ParsedVoiceCommand { + const trimmed = rawTranscript.trim(); + if (!trimmed) return { kind: "none" }; + const normalized = normalizePhrase(trimmed); + + if ( + normalized === "stop" || + normalized === "stop generating" || + normalized === "stop generation" || + normalized === "cancel turn" || + normalized === "interrupt" + ) { + return { kind: "stop" }; + } + + if (normalized === "clear" || normalized === "clear draft" || normalized === "clear prompt") { + return { kind: "clear" }; + } + + // Match "switch [model] to [ and ]" or "use model [ and ]" + const switchMatch = trimmed.match( + /^(?:switch(?:\s+the)?\s+model\s+to|switch\s+to|use\s+model|change\s+model\s+to)\s+(.+)$/i, + ); + if (switchMatch && candidates.length > 0) { + const rest = switchMatch[1]!.replace(/[.!?]+$/, "").trim(); + const chained = rest.match(/^(.+?)\s+(?:and|then)\s+(.+)$/i); + if (chained) { + const candidate = matchVoiceModelCandidate(chained[1]!, candidates); + if (candidate) { + const trailing = stripTrailingSendPhrase(chained[2]!.trim()); + return { + kind: "switch-model", + candidate, + remainingText: trailing.text, + autoSend: trailing.send, + }; + } + } + const candidate = matchVoiceModelCandidate(rest, candidates); + if (candidate) { + return { + kind: "switch-model", + candidate, + remainingText: "", + autoSend: false, + }; + } + } + + const trailingSend = stripTrailingSendPhrase(trimmed); + if (trailingSend.send) { + return { kind: "send", text: trailingSend.text }; + } + + return { kind: "none" }; +} diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index 577b26595efed..5adaf28212102 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -131,6 +131,7 @@ export class VoiceInputSession { | { readonly cleanup: SpeechPostProcessingOptions | null; readonly cleanupGrant: string | null; + readonly localTwoPhase: boolean; readonly cleanupPrepared: PreparedConnection | null; } | undefined; @@ -145,7 +146,9 @@ export class VoiceInputSession { if (!context) throw new Error(m(msg("Voice input has no draft to record into."))); const settings = context.clientSettings; const cleanupGrant = context.cleanup ? readCleanupGrant() : null; - const cleanupEnabled = cleanupGrant !== null; + const localTwoPhase = + context.cleanup && !key.cloudProvider && settings.speechLocalTwoPhaseCleanup; + const cleanupEnabled = cleanupGrant !== null || localTwoPhase; const cue = cleanupEnabled && context.cleanupPrepared ? settings.speechCorrectionWord : ""; const { speechCustomWords, speechHints } = resolveSpeechVocabulary({ personal: settings.speechCustomWords, @@ -154,6 +157,7 @@ export class VoiceInputSession { }); recordingPreferences = { cleanupGrant, + localTwoPhase, cleanupPrepared: context.cleanupPrepared, cleanup: cleanupEnabled ? { @@ -196,10 +200,12 @@ export class VoiceInputSession { options, ) => { const preferences = recordingPreferences; + const grantStillValid = + preferences?.localTwoPhase || preferences?.cleanupGrant === readCleanupGrant(); if ( !preferences?.cleanup || !hasAudioConsent() || - preferences.cleanupGrant !== readCleanupGrant() || + !grantStillValid || this.target?.ownerKey !== options.draft.ownerKey ) return null; @@ -213,7 +219,9 @@ export class VoiceInputSession { transcript, cleanupContext(options.draft), preferences.cleanup, - () => hasAudioConsent() && preferences.cleanupGrant === readCleanupGrant(), + () => + hasAudioConsent() && + (preferences.localTwoPhase || preferences.cleanupGrant === readCleanupGrant()), ), options, ).then((result) => result.text); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 20bc197a152d6..420ff2e743cad 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -606,6 +606,14 @@ export const ClientSettingsSchema = Schema.Struct({ ), ), speechCorrectionWord: SpeechCorrectionCue.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + voiceCommandsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + voiceAutoSend: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + voiceSilenceTimeoutMs: Schema.Finite.check( + Schema.isGreaterThanOrEqualTo(800), + Schema.isLessThanOrEqualTo(5_000), + ).pipe(Schema.withDecodingDefault(Effect.succeed(1_800))), + // Local 2nd-pass transcript polish (capitals, punctuation, typos) with zero external API calls. + speechLocalTwoPhaseCleanup: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), // A locale code or "system". Open string so new locales and downgrades need no migration. language: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed("en"))), snapShotEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), @@ -1474,6 +1482,12 @@ export const ServerSettings = Schema.Struct({ speechModelUnloadTimeout: SpeechModelUnloadTimeout.pipe( Schema.withDecodingDefault(Effect.succeed("min_15")), ), + // Optional local/LAN OpenAI-compatible or whisper.cpp HTTP STT endpoint (e.g. http://127.0.0.1:8178/inference). + speechLocalEndpointUrl: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + speechLocalEndpointModel: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + // Optional local/LAN OpenAI-compatible /v1/chat/completions endpoint for Phase 2 transcript cleanup. + speechLocalCleanupEndpointUrl: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + speechLocalCleanupModel: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))), // Vocabulary shared by everyone who dictates in a project; it lives with the project's environment. speechProjectCustomWords: SpeechCustomWords.pipe(Schema.withDecodingDefault(Effect.succeed([]))), // Null follows textGenerationModelSelection; a selection pins transcript cleanup to its own model. @@ -1954,6 +1968,10 @@ export const ServerSettingsPatch = Schema.Struct({ speechModelId: Schema.optionalKey(Schema.String), speechAcceleration: Schema.optionalKey(SpeechAcceleration), speechModelUnloadTimeout: Schema.optionalKey(SpeechModelUnloadTimeout), + speechLocalEndpointUrl: Schema.optionalKey(Schema.String), + speechLocalEndpointModel: Schema.optionalKey(Schema.String), + speechLocalCleanupEndpointUrl: Schema.optionalKey(Schema.String), + speechLocalCleanupModel: Schema.optionalKey(Schema.String), speechProjectCustomWords: Schema.optionalKey(SpeechCustomWords), speechPostProcessingModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)), projectAgentBrowserAccessOverrides: Schema.optionalKey( @@ -2235,6 +2253,12 @@ export const ClientSettingsPatch = Schema.Struct({ speechRemoveFillerWords: Schema.optionalKey(Schema.Boolean), speechPostProcessingPrompt: Schema.optionalKey(SpeechPostProcessingPromptSettings), speechCorrectionWord: Schema.optionalKey(SpeechCorrectionCue), + voiceCommandsEnabled: Schema.optionalKey(Schema.Boolean), + voiceAutoSend: Schema.optionalKey(Schema.Boolean), + voiceSilenceTimeoutMs: Schema.optionalKey( + Schema.Finite.check(Schema.isGreaterThanOrEqualTo(800), Schema.isLessThanOrEqualTo(5_000)), + ), + speechLocalTwoPhaseCleanup: Schema.optionalKey(Schema.Boolean), language: Schema.optionalKey(Schema.String), snapShotEnabled: Schema.optionalKey(Schema.Boolean), snapShotIncludeAccessibility: Schema.optionalKey(Schema.Boolean),