[WIP] feat(voice): add configurable local voice transcription #8928
ClosedUtkarshUsername(GitHub profile, opens in a new tab)wants to merge 191 commits into
main fromrefs/pull/8928/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/desktop/src/speech/DesktopSpeech.ts lines 207 to 211OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +191,21 @@191+ })),192+ setMicrophone: (deviceName) =>193+ Effect.gen(function* () {194+ if (deviceName && !DesktopMicrophoneCapture.getAvailableDevices().includes(deviceName)) {195+ return yield* new DesktopSpeechOperationError({196+ operation: "set microphone",197+ cause: new Error(`microphone is unavailable: ${deviceName}`),198+ });199+ }200+ const current = Option.getOrElse(yield* clientSettings.get, () => DEFAULT_CLIENT_SETTINGS);201+ yield* clientSettings.set({ ...current, voiceMicrophone: deviceName });202+ yield* Ref.set(selectedMicrophone, deviceName);203+ return {204+ devices: DesktopMicrophoneCapture.getAvailableDevices(),205+ selected: deviceName,206+ };207+ }).pipe(208+ Effect.mapError(209+ (cause) => new DesktopSpeechOperationError({ operation: "set microphone", cause }),210+ ),211+ ),apps/desktop/src/speech/DesktopSpeech.ts lines 188 to 191OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +171,21 @@171+ yield* Effect.addFinalizer(() =>172+ attempt("shutdown", () => runtime.shutdown()).pipe(Effect.orDie),173+ );174+175+ const subscribe = (listener: SpeechEventListener): Effect.Effect<void, never, Scope.Scope> =>176+ Effect.acquireRelease(177+ Ref.update(listeners, (current) => new Set([...current, listener])),178+ () =>179+ Ref.update(listeners, (current) => {180+ const next = new Set(current);181+ next.delete(listener);182+ return next;183+ }),184+ ).pipe(Effect.asVoid);185+186+ return DesktopSpeech.of({187+ getStatus: attempt("get status", () => runtime.getStatus()),188+ getMicrophones: attempt("get microphones", async () => ({189+ devices: DesktopMicrophoneCapture.getAvailableDevices(),190+ selected: await runPromise(Ref.get(selectedMicrophone)),191+ })),apps/desktop/src/speech/DesktopSpeech.ts lines 195 to 198OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +178,21 @@178+ () =>179+ Ref.update(listeners, (current) => {180+ const next = new Set(current);181+ next.delete(listener);182+ return next;183+ }),184+ ).pipe(Effect.asVoid);185+186+ return DesktopSpeech.of({187+ getStatus: attempt("get status", () => runtime.getStatus()),188+ getMicrophones: attempt("get microphones", async () => ({189+ devices: DesktopMicrophoneCapture.getAvailableDevices(),190+ selected: await runPromise(Ref.get(selectedMicrophone)),191+ })),192+ setMicrophone: (deviceName) =>193+ Effect.gen(function* () {194+ if (deviceName && !DesktopMicrophoneCapture.getAvailableDevices().includes(deviceName)) {195+ return yield* new DesktopSpeechOperationError({196+ operation: "set microphone",197+ cause: new Error(`microphone is unavailable: ${deviceName}`),198+ });
- apps/desktop/src/speech/DesktopTranscriptionBackend.ts lines 14 to 19OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,19 @@1+import type { TranscribeModel } from "transcribe-cpp";2+3+export class DesktopTranscriptionBackend {4+ private readonly modelPath: string;5+ private model: TranscribeModel | undefined;6+ private loading: Promise<TranscribeModel> | undefined;7+8+ constructor(modelPath: string) {9+ this.modelPath = modelPath;10+ }11+12+ async prepare(): Promise<void> {13+ if (this.model) return;14+ this.loading ??= import("transcribe-cpp")15+ .then(({ TranscribeModel }) => TranscribeModel.load(this.modelPath, { backend: "cpu" }))16+ .then((model) => {17+ this.model = model;18+ return model;19+ });apps/web/src/components/settings/VoiceSettingsPanel.tsx line 70OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +50,21 @@50+ const selectedIsUnavailable = Boolean(selected && !microphones?.devices.includes(selected));51+52+ return (53+ <SettingsPageContainer>54+ <SettingsSection title="Voice">55+ <SettingsRow56+ {...searchableSetting("microphone")}57+ description={58+ selectedIsUnavailable59+ ? "The selected microphone is disconnected. Voice input will use the system default until it returns."60+ : "Choose the microphone used for local voice input."61+ }62+ control={63+ <div className="flex w-full max-w-80 items-center gap-1.5">64+ <Select65+ value={selected || SYSTEM_DEFAULT}66+ disabled={!microphones || loadingMicrophones}67+ onValueChange={(value) => {68+ if (!value) return;69+ void speech70+ .setMicrophone(value === SYSTEM_DEFAULT ? "" : value)apps/web/src/components/settings/VoiceSettingsPanel.tsx lines 691 to 697Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +52,21 @@52+ return (53+ <SettingsPageContainer>54+ <SettingsSection title="Voice">55+ <SettingsRow56+ {...searchableSetting("microphone")}57+ description={58+ selectedIsUnavailable59+ ? "The selected microphone is disconnected. Voice input will use the system default until it returns."60+ : "Choose the microphone used for local voice input."61+ }62+ control={63+ <div className="flex w-full max-w-80 items-center gap-1.5">64+ <Select65+ value={selected || SYSTEM_DEFAULT}66+ disabled={!microphones || loadingMicrophones}67+ onValueChange={(value) => {68+ if (!value) return;69+ void speech70+ .setMicrophone(value === SYSTEM_DEFAULT ? "" : value)71+ .then(setMicrophones);72+ }}packages/contracts/src/ipc.ts line 1185OutdatedResolvedby UtkarshUsername(GitHub profile, opens in a new tab)@@ -1166,3 +1172,14 @@11661172 downloadUpdate: () => Promise<DesktopUpdateActionResult>;11671173 installUpdate: () => Promise<DesktopUpdateActionResult>;11681174 onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;1175+ /** Desktop-local speech input. Absent in older desktop shells and regular browsers. */1176+ speech?: {1177+ getStatus: () => Promise<DesktopSpeechStatus>;1178+ getMicrophones: () => Promise<DesktopMicrophoneSettings>;1179+ setMicrophone: (deviceName: string) => Promise<DesktopMicrophoneSettings>;1180+ prepare: () => Promise<DesktopSpeechPreparation>;1181+ cancelPreparation: () => Promise<void>;1182+ startRecording: () => Promise<void>;1183+ stopRecording: () => Promise<string>;1184+ cancelRecording: () => Promise<void>;1185+ transcribe: (uri: string) => Promise<string>;apps/desktop/src/speech/DesktopTranscriptionBackend.ts line 26OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +6,21 @@6+ private loading: Promise<TranscribeModel> | undefined;7+8+ constructor(modelPath: string) {9+ this.modelPath = modelPath;10+ }11+12+ async prepare(): Promise<void> {13+ if (this.model) return;14+ this.loading ??= import("transcribe-cpp")15+ .then(({ TranscribeModel }) => TranscribeModel.load(this.modelPath, { backend: "cpu" }))16+ .then((model) => {17+ this.model = model;18+ return model;19+ });20+ await this.loading;21+ }22+23+ async transcribe(pcm: Float32Array): Promise<string> {24+ if (pcm.length === 0) throw new Error("no audio samples were provided");25+ await this.prepare();26+ const result = await this.model!.transcribe(pcm, {apps/web/src/speech/desktopVoiceInput.ts line 54OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +34,21 @@34+ prepareToRecordAsync: async () => {35+ recordingUri = null;36+ await bridge.startRecording();37+ recordingStarted = true;38+ },39+ record: ({ forDuration }) => {40+ durationTimer = setTimeout(stopAtDurationLimit, forDuration * 1_000);41+ },42+ stop: async () => {43+ if (durationTimer !== undefined) clearTimeout(durationTimer);44+ durationTimer = undefined;45+ if (!recordingStarted) return;46+ recordingStarted = false;47+ recordingUri = await bridge.stopRecording();48+ },49+ };50+51+ const transcriber: VoiceTranscriber = {52+ prepare: async ({ signal }) => {53+ throwIfVoiceTranscriptionAborted(signal);54+ const cancel = () => void bridge.cancelPreparation();apps/web/src/components/settings/VoiceSettingsPanel.tsx line 69OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +49,21 @@49+ const selected = microphones?.selected ?? "";50+ const selectedIsUnavailable = Boolean(selected && !microphones?.devices.includes(selected));51+52+ return (53+ <SettingsPageContainer>54+ <SettingsSection title="Voice">55+ <SettingsRow56+ {...searchableSetting("microphone")}57+ description={58+ selectedIsUnavailable59+ ? "The selected microphone is disconnected. Voice input will use the system default until it returns."60+ : "Choose the microphone used for local voice input."61+ }62+ control={63+ <div className="flex w-full max-w-80 items-center gap-1.5">64+ <Select65+ value={selected || SYSTEM_DEFAULT}66+ disabled={!microphones || loadingMicrophones}67+ onValueChange={(value) => {68+ if (!value) return;69+ void speechapps/desktop/src/speech/DesktopSpeechRuntime.ts line 63OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +43,21 @@43+ private capture: Capture | undefined;44+ private backend: Backend | undefined;45+ private preparationAbortController: AbortController | undefined;46+ private state: "missing-model" | "downloading" | "ready" | "recording" | "transcribing" =47+ "missing-model";48+49+ constructor(options: RuntimeOptions) {50+ this.options = options;51+ }52+53+ async getStatus(): Promise<DesktopSpeechStatus> {54+ if (!this.options.supported) {55+ return { supported: false, reason: this.options.unsupportedReason ?? "unsupported platform" };56+ }57+ if (this.state === "missing-model" && (await this.options.modelReady())) this.state = "ready";58+ return { supported: true, state: this.state };59+ }60+61+ async prepare(): Promise<{ locale: string }> {62+ this.assertSupported();63+ if (!(await this.options.modelReady())) {apps/web/src/components/chat/ChatComposer.tsx line 1981OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1976,3 +1978,4 @@19761978 };19771979 }, [composerCursor, composerTerminalContexts, promptRef]);197819801981+ const speechInput = useDesktopSpeechInput({packages/contracts/src/settings.ts line 499Resolvedby UtkarshUsername(GitHub profile, opens in a new tab)@@ -276,3 +276,6 @@276276 timestampFormat: TimestampFormat.pipe(277277 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),278278 ),279+ // Desktop-local input device name. An empty string follows the operating280+ // system default, which remains stable when devices are added or removed.281+ voiceMicrophone: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
- apps/web/src/speech/useDesktopSpeechInput.ts lines 145 to 153OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +133,21 @@133+ if (!controller) return;134+ if (!modelStatus || (modelStatus.supported && modelStatus.state === "missing-model")) {135+ const confirmed = await ensureLocalApi().dialogs.confirm(136+ "Download a 48 MiB English speech model? Voice input is processed locally and microphone audio is not saved.",137+ );138+ if (!confirmed) return;139+ }140+ setProgress(null);141+ setLevel(0);142+ await controller.start();143+ }, [controller, modelStatus]);144+145+ return {146+ available,147+ state,148+ progress,149+ level,150+ start,151+ stop: useCallback(() => controller?.stop() ?? Promise.resolve(), [controller]),152+ cancel: useCallback(() => controller?.cancel(), [controller]),153+ };
- apps/desktop/src/speech/DesktopTranscriptionBackend.ts line 20OutdatedResolvedby UtkarshUsername(GitHub profile, opens in a new tab)@@ -0,0 +1,20 @@1+import type { TranscribeModel } from "transcribe-cpp";2+3+export class DesktopTranscriptionBackend {4+ private readonly modelPath: string;5+ private model: TranscribeModel | undefined;6+ private loading: Promise<TranscribeModel> | undefined;7+8+ constructor(modelPath: string) {9+ this.modelPath = modelPath;10+ }11+12+ async prepare(): Promise<void> {13+ if (this.model) return;14+ this.loading ??= import("transcribe-cpp")15+ .then(({ TranscribeModel }) => TranscribeModel.load(this.modelPath, { backend: "cpu" }))16+ .then((model) => {17+ this.model = model;18+ return model;19+ });20+ await this.loading;apps/web/src/components/chat/ChatComposer.tsx line 3617Resolvedby UtkarshUsername(GitHub profile, opens in a new tab)@@ -1978,0 +1982,21 @@1982+ ownerKey: JSON.stringify(composerDraftTarget),1983+ draftText: prompt,1984+ readDraft: () => {1985+ const snapshot = readComposerSnapshot();1986+ return {1987+ text: snapshot.value,1988+ selection: { start: snapshot.expandedCursor, end: snapshot.expandedCursor },1989+ };1990+ },1991+ commitDraft: (text, selection) => {1992+ const snapshot = readComposerSnapshot();1993+ const applied = applyPromptReplacement(0, snapshot.value.length, text, {1994+ expectedText: snapshot.value,1995+ focusEditorAfterReplace: false,1996+ });1997+ if (!applied) return;1998+ const cursor = collapseExpandedComposerCursor(text, selection.start);1999+ setComposerCursor(cursor);2000+ window.requestAnimationFrame(() => composerEditorRef.current?.focusAt(cursor));2001+ },2002+ });
UtkarshUsername(GitHub profile, opens in a new tab) changed the title
- apps/web/src/components/settings/VoiceSettingsPanel.tsx line 53OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +33,21 @@33+ const refreshMicrophones = useCallback(async () => {34+ if (!navigator.mediaDevices?.enumerateDevices) return;35+ setLoadingMicrophones(true);36+ try {37+ const devices = await navigator.mediaDevices.enumerateDevices();38+ setMicrophones(devices.filter((device) => device.kind === "audioinput"));39+ } catch (error) {40+ toastManager.add({41+ type: "error",42+ title: "Could not list microphones",43+ description: error instanceof Error ? error.message : String(error),44+ });45+ } finally {46+ setLoadingMicrophones(false);47+ }48+ }, []);49+50+ const refreshStatus = useCallback(async () => {51+ if (!prepared) return;52+ try {53+ setStatus(await runtime.runPromise(getEnvironmentSpeechStatus(prepared)));apps/web/src/speech/useEnvironmentSpeechInput.ts lines 134 to 145OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +125,21 @@125+ }, [prepared]);126+127+ const previousOwnerRef = useRef(input.ownerKey);128+ useEffect(() => {129+ if (previousOwnerRef.current === input.ownerKey) return;130+ previousOwnerRef.current = input.ownerKey;131+ controllerRef.current?.ownerChanged();132+ }, [input.ownerKey]);133+134+ const start = useCallback(async () => {135+ const controller = controllerRef.current;136+ if (!controller || !status?.supported) return;137+ if (status.state === "missing-model") {138+ const confirmed = await ensureLocalApi().dialogs.confirm(139+ "Download a 48 MiB English speech model to this T3 environment? Recordings will be sent to this environment for transcription and deleted after use.",140+ );141+ if (!confirmed) return;142+ }143+ setLevel(0);144+ await controller.start();145+ }, [status]);apps/web/src/speech/useEnvironmentSpeechInput.ts lines 135 to 144OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +124,21 @@124+ };125+ }, [prepared]);126+127+ const previousOwnerRef = useRef(input.ownerKey);128+ useEffect(() => {129+ if (previousOwnerRef.current === input.ownerKey) return;130+ previousOwnerRef.current = input.ownerKey;131+ controllerRef.current?.ownerChanged();132+ }, [input.ownerKey]);133+134+ const start = useCallback(async () => {135+ const controller = controllerRef.current;136+ if (!controller || !status?.supported) return;137+ if (status.state === "missing-model") {138+ const confirmed = await ensureLocalApi().dialogs.confirm(139+ "Download a 48 MiB English speech model to this T3 environment? Recordings will be sent to this environment for transcription and deleted after use.",140+ );141+ if (!confirmed) return;142+ }143+ setLevel(0);144+ await controller.start();apps/web/src/speech/useEnvironmentSpeechInput.ts lines 138 to 142OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +122,21 @@122+ return () => {123+ disposed = true;124+ };125+ }, [prepared]);126+127+ const previousOwnerRef = useRef(input.ownerKey);128+ useEffect(() => {129+ if (previousOwnerRef.current === input.ownerKey) return;130+ previousOwnerRef.current = input.ownerKey;131+ controllerRef.current?.ownerChanged();132+ }, [input.ownerKey]);133+134+ const start = useCallback(async () => {135+ const controller = controllerRef.current;136+ if (!controller || !status?.supported) return;137+ if (status.state === "missing-model") {138+ const confirmed = await ensureLocalApi().dialogs.confirm(139+ "Download a 48 MiB English speech model to this T3 environment? Recordings will be sent to this environment for transcription and deleted after use.",140+ );141+ if (!confirmed) return;142+ }apps/server/src/speech/model.ts lines 52 to 53OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +33,21 @@33+export function isSpeechModelReady(directory: string): Promise<boolean> {34+ return hasExpectedModel(speechModelPath(directory));35+}36+37+export async function downloadSpeechModel(38+ directory: string,39+ signal?: AbortSignal,40+): Promise<string> {41+ const finalPath = speechModelPath(directory);42+ signal?.throwIfAborted();43+ await NodeFSP.mkdir(directory, { recursive: true });44+ if (await hasExpectedModel(finalPath)) return finalPath;45+46+ const partialPath = `${finalPath}.${NodeCrypto.randomUUID()}.part`;47+ try {48+ const response = await fetch(SPEECH_MODEL.url, { signal });49+ if (!response.ok || !response.body) {50+ throw new Error(`speech model download failed with status ${response.status}`);51+ }52+ const contentLength = Number(response.headers.get("content-length"));53+ if (Number.isFinite(contentLength) && contentLength !== SPEECH_MODEL.size) {
- apps/web/src/speech/useEnvironmentSpeechInput.ts lines 167 to 170OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +150,21 @@150+ }151+ setStatus({ prepared, value: freshStatus });152+ if (!freshStatus.supported) return;153+ if (freshStatus.state === "missing-model") {154+ const confirmed = await ensureLocalApi().dialogs.confirm(155+ "Download a 48 MiB English speech model to this T3 environment? Recordings will be sent to this environment for transcription and deleted after use.",156+ );157+ if (!confirmed) return;158+ }159+ const controller = controllerRef.current;160+ if (controller !== expectedController || latestInputRef.current.ownerKey !== expectedOwner)161+ return;162+ setLevel(0);163+ await controller.start();164+ }, [prepared]);165+166+ return {167+ available:168+ currentStatus?.supported === true &&169+ typeof navigator !== "undefined" &&170+ Boolean(navigator.mediaDevices?.getUserMedia),
- packages/client-runtime/src/voice-input/environment.ts line 7OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,7 @@1+import type {2+ EnvironmentSpeechStatus,3+ EnvironmentSpeechTranscriptionResult,4+} from "@t3tools/contracts";5+import * as Effect from "effect/Effect";6+7+import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";apps/server/src/speech/SpeechService.ts lines 127 to 131OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +111,21 @@111+ const currentStatus = async (): Promise<EnvironmentSpeechStatus> => {112+ if (unsupportedReason) return { supported: false, reason: unsupportedReason };113+ return {114+ supported: true,115+ state:116+ activeTranscriptions > 0117+ ? "transcribing"118+ : (await isSpeechModelReady(modelDirectory))119+ ? "ready"120+ : "missing-model",121+ model: SPEECH_MODEL.name,122+ };123+ };124+125+ return SpeechService.of({126+ status: attempt("status", currentStatus),127+ transcribe: (pcmBytes) =>128+ attempt("transcription", async () => {129+ if (unsupportedReason) throw new Error(unsupportedReason);130+ const pcm = decodeSpeechPcm(pcmBytes);131+ if (pcm.length === 0) return "";apps/server/src/speech/SpeechService.ts line 78OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +58,21 @@58+ ) => Promise<{ readonly text: string }>;59+ readonly dispose: () => void;60+};61+62+export class SpeechService extends Context.Service<63+ SpeechService,64+ {65+ readonly status: Effect.Effect<EnvironmentSpeechStatus, SpeechOperationError>;66+ readonly transcribe: (pcmBytes: Uint8Array) => Effect.Effect<string, SpeechOperationError>;67+ readonly removeModel: Effect.Effect<EnvironmentSpeechStatus, SpeechOperationError>;68+ }69+>()("t3/speech/SpeechService") {}70+71+function supported(platform: string, architecture: string): string | null {72+ const tuple = `${platform}-${architecture}`;73+ return new Set(["darwin-arm64", "darwin-x64", "win32-x64", "linux-x64", "linux-arm64"]).has(tuple)74+ ? null75+ : `voice transcription is not available on ${tuple}`;76+}77+78+const make = Effect.gen(function* () {
- apps/server/src/speech/SpeechService.ts line 78OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +58,21 @@58+ ) => Promise<{ readonly text: string }>;59+ readonly dispose: () => void;60+};61+62+export class SpeechService extends Context.Service<63+ SpeechService,64+ {65+ readonly status: Effect.Effect<EnvironmentSpeechStatus, SpeechOperationError>;66+ readonly transcribe: (pcmBytes: Uint8Array) => Effect.Effect<string, SpeechOperationError>;67+ readonly removeModel: Effect.Effect<EnvironmentSpeechStatus, SpeechOperationError>;68+ }69+>()("t3/speech/SpeechService") {}70+71+function supported(platform: string, architecture: string): string | null {72+ const tuple = `${platform}-${architecture}`;73+ return new Set(["darwin-arm64", "darwin-x64", "win32-x64", "linux-x64", "linux-arm64"]).has(tuple)74+ ? null75+ : `voice transcription is not available on ${tuple}`;76+}77+78+const make = Effect.gen(function* () {apps/server/src/speech/SpeechService.ts lines 128 to 140OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +120,21 @@120+ : "missing-model",121+ model: SPEECH_MODEL.name,122+ };123+ };124+125+ return SpeechService.of({126+ status: attempt("status", currentStatus),127+ transcribe: (pcmBytes) =>128+ attempt("transcription", async () => {129+ if (unsupportedReason) throw new Error(unsupportedReason);130+ const pcm = decodeSpeechPcm(pcmBytes);131+ if (pcm.length === 0) return "";132+ const loaded = await loadModel();133+ activeTranscriptions += 1;134+ try {135+ const result = await loaded.transcribe(pcm, { timestamps: "none", language: "en" });136+ return result.text.trim();137+ } finally {138+ activeTranscriptions -= 1;139+ }140+ }),apps/server/src/speech/model.ts line 1OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1 @@1+// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalFetch:off - low-level streaming file boundary.apps/server/src/speech/SpeechService.ts line 1125Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +133,21 @@133+ activeTranscriptions += 1;134+ try {135+ const result = await loaded.transcribe(pcm, { timestamps: "none", language: "en" });136+ return result.text.trim();137+ } finally {138+ activeTranscriptions -= 1;139+ }140+ }),141+ removeModel: attempt("model removal", async () => {142+ if (activeTranscriptions > 0) throw new Error("wait for transcription to finish");143+ await loading?.catch(() => undefined);144+ model?.dispose();145+ model = undefined;146+ loading = undefined;147+ await removeSpeechModel(modelDirectory);148+ return currentStatus();149+ }),150+ });151+});152+153+export const layer = Layer.effect(SpeechService, make);
- apps/web/src/components/settings/settingsSearch.ts line 295OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -150,3 +152,8 @@150152 to: "/settings/general",151153 searchTerms: ["combine matching repositories environments sidebar"],152154 },155+ {156+ id: "local-voice-input",157+ title: "Local voice input",158+ to: "/settings/voice",159+ desktopOnly: true,apps/server/src/environment/ServerEnvironment.ts line 245OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -229,3 +229,4 @@229229 threadTitleRegeneration: true,230230 threadPullRequestLinking: true,231231 environmentIcon: true,232+ voiceTranscription: true,
- apps/server/src/speech/model.ts lines 17 to 27OutdatedResolvedby t3-code-bot[bot](GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+import * as NodeStreamPromises from "node:stream/promises";8+9+export const SPEECH_MODEL = {10+ name: "Moonshine Streaming Tiny",11+ filename: "moonshine-streaming-tiny-Q8_0.gguf",12+ size: 50_462_816,13+ sha256: "930e4622ad3a24158b91406c30c977fa6a26b34cb32d6ac3e57cfb23383a869e",14+ url: "https://huggingface.co/handy-computer/moonshine-streaming-tiny-gguf/resolve/85ddff612fa3a2cf40b2f745abcfa90ef82f293b/moonshine-streaming-tiny-Q8_0.gguf",15+} as const;16+17+async function hasExpectedModel(path: string): Promise<boolean> {18+ const stat = await NodeFSP.stat(path).catch(() => null);19+ if (stat?.size !== SPEECH_MODEL.size) return false;20+ const digest = NodeCrypto.createHash("sha256");21+ try {22+ for await (const chunk of NodeFS.createReadStream(path)) digest.update(chunk);23+ return digest.digest("hex") === SPEECH_MODEL.sha256;24+ } catch {25+ return false;26+ }27+}apps/server/src/speech/SpeechService.ts lines 276 to 287Resolvedby t3-code-bot[bot](GitHub profile, opens in a new tab)@@ -0,0 +115,21 @@115+ const platform = yield* HostProcessPlatform;116+ const architecture = yield* HostProcessArchitecture;117+ const config = yield* ServerConfig.ServerConfig;118+ const path = yield* Path.Path;119+ const unsupportedReason = unsupportedPlatformReason(platform, architecture);120+ const modelDirectory = path.join(config.stateDir, "speech", "models");121+ let model: LoadedModel | undefined;122+ let loading: Promise<LoadedModel> | undefined;123+ let activeTranscriptions = 0;124+ let activeOperation: Promise<unknown> | undefined;125+ let closing = false;126+127+ yield* Effect.addFinalizer(() =>128+ Effect.promise(async () => {129+ closing = true;130+ await activeOperation?.catch(() => undefined);131+ model?.dispose();132+ model = undefined;133+ loading = undefined;134+ }),135+ );apps/web/src/components/chat/ChatComposer.tsx lines 5944 to 5950OutdatedResolvedby t3-code-bot[bot](GitHub profile, opens in a new tab)@@ -5881,0 +5930,21 @@5930+ progress={speechInput.progress}5931+ disabled={5932+ isConnecting || projectSelectionRequired || pendingUserInputs.length > 05933+ }5934+ onStart={() => void speechInput.start()}5935+ onStop={() => void speechInput.stop()}5936+ onCancel={() => void speechInput.cancel()}5937+ />5938+ <ComposerSpeechCancelButton5939+ state={speechInput.state}5940+ onCancel={() => void speechInput.cancel()}5941+ />5942+ </>5943+ ) : null}5944+ {speechPresentation.showsSend ? (5945+ <ComposerFooterPrimaryActions5946+ compact={isComposerResting || isComposerPrimaryActionsCompact}5947+ activeContextWindow={5948+ settings.contextWindowMeterEnabled ? activeContextWindow : null5949+ }5950+ reserveContextWindowMeter={reserveContextWindowMeter}docs/user/voice-input.md lines 4 to 6Resolvedby t3-code-bot[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+# Voice input2+3+Voice input is available in supported browsers, in the desktop app, and on iOS4+26 or newer. Select the microphone button beside Send to record, then select the5+stop button to transcribe. Select discard to cancel. The transcript is inserted6+into the composer for editing and is never sent automatically.packages/client-runtime/src/voice-input/environment.ts lines 50 to 51OutdatedResolvedby t3-code-bot[bot](GitHub profile, opens in a new tab)@@ -0,0 +31,21 @@31+ method: input.method,32+ url: input.path,33+ timeoutMs: VOICE_REQUEST_TIMEOUT_MS,34+ request: input.run,35+ });36+});37+38+export const getEnvironmentSpeechStatus = (prepared: PreparedConnection) =>39+ request<EnvironmentSpeechStatus>({40+ prepared,41+ method: "GET",42+ path: (baseUrl) => makeEnvironmentHttpApiUrlBuilder(baseUrl).voice.status(),43+ run: ({ client, headers }) => client.voice.status({ headers }),44+ });45+46+export const transcribeEnvironmentPcm = (prepared: PreparedConnection, pcm: Uint8Array) =>47+ request<EnvironmentSpeechTranscriptionResult>({48+ prepared,49+ method: "POST",50+ path: (baseUrl) => makeEnvironmentHttpApiUrlBuilder(baseUrl).voice.transcribe(),51+ run: ({ client, headers }) => client.voice.transcribe({ headers, payload: pcm }),packages/contracts/src/environmentHttp.ts line 695Resolvedby t3-code-bot[bot](GitHub profile, opens in a new tab)@@ -553,3 +558,15 @@553558 }).middleware(EnvironmentAuthenticatedAuth),554559 ) {}555560561+export class EnvironmentVoiceHttpApi extends HttpApiGroup.make("voice")562+ .add(563+ HttpApiEndpoint.get("status", "/api/voice/status", {564+ headers: OptionalBearerHeaders,565+ success: EnvironmentSpeechStatus,566+ error: EnvironmentScopedOperationErrors,567+ }).middleware(EnvironmentAuthenticatedAuth),568+ )569+ .add(570+ HttpApiEndpoint.post("transcribe", "/api/voice/transcribe", {571+ headers: OptionalBearerHeaders,572+ payload: Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()),
- packages/client-runtime/src/state/environmentHttpAuth.ts line 152Resolvedby t3-code-bot[bot](GitHub profile, opens in a new tab)@@ -131,3 +132,4 @@131132 authorization = current.httpAuthorization;132133 }133134135+ if (input.validateUrl) yield* input.validateUrl(httpBaseUrl);
- packages/client-runtime/src/voice-input/environment.ts lines 52 to 54OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +34,21 @@34+ try: () => {35+ const url = new URL(baseUrl);36+ const loopback =37+ url.hostname === "localhost" ||38+ url.hostname === "[::1]" ||39+ /^127\.\d+\.\d+\.\d+$/.test(url.hostname);40+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {41+ throw new Error("Voice input requires HTTPS for remote environments.");42+ }43+ },44+ catch: (cause) =>45+ new RemoteEnvironmentAuthFetchError({46+ message: "Voice input requires HTTPS for remote environments.",47+ cause,48+ }),49+ }),50+ request: (args) =>51+ input.run(args).pipe(52+ Effect.provideService(FetchHttpClient.RequestInit, {53+ redirect: "error",54+ credentials: "include",
- apps/server/src/speech/SpeechService.ts line 24OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +4,21 @@4+import * as Effect from "effect/Effect";5+import * as Layer from "effect/Layer";6+import * as Path from "effect/Path";7+import * as Schema from "effect/Schema";8+9+import * as ServerConfig from "../config.ts";10+import { loadNativeSpeechModel } from "./native.ts";11+import {12+ downloadSpeechModel,13+ isSpeechModelReady,14+ removeSpeechModel,15+ SPEECH_MODEL,16+} from "./model.ts";17+18+const SAMPLE_RATE = 16_000;19+const MAX_SPEECH_DURATION_SECONDS = 5 * 60;20+export const MAX_SPEECH_BYTES =21+ SAMPLE_RATE * Float32Array.BYTES_PER_ELEMENT * MAX_SPEECH_DURATION_SECONDS;22+const MIN_CAPTURE_RMS = 0.0005;23+24+export class SpeechInvalidAudioError extends Schema.TaggedErrorClass<SpeechInvalidAudioError>()(
Sign in to join this conversation.


Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
14f12148-5f41-4c5a-a3b1-e97657012e55📥 Commits
Reviewing files that changed from the base of the PR and between 46d6b8f937c4d7b7fef4c7693cc77ac67b915b4c and 027bfdb8210880952272beff0b45dcc8a03ba3e3.
📒 Files selected for processing (1)
apps/server/src/speech/SpeechService.ts🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
📝 Walkthrough
Walkthrough#
This change adds environment-backed voice transcription, browser recording, composer integration, voice settings, authenticated voice APIs, native model management, packaging support, tests, and documentation.
Changes#
Speech contracts and client runtime
packages/contracts/src/speech.ts,packages/contracts/src/environmentHttp.ts,packages/client-runtime/src/voice-input/*packages/contracts/src/settings.ts,packages/contracts/src/settings.test.tsvoiceMicrophonesetting and patch validation.Server transcription
apps/server/src/speech/native.ts,apps/server/src/speech/SpeechService.ts,apps/server/src/speech/model.ts,apps/server/src/speech/*test.tsapps/server/src/speech/http.ts,apps/server/src/server.ts,apps/server/src/environment/ServerEnvironment.ts,apps/server/src/speech/http.test.tsvoiceTranscription.apps/server/package.json,pnpm-workspace.yaml,scripts/lib/cli-external-packages.ts,scripts/lib/cli-external-packages.test.tsBrowser voice input and composer
apps/web/src/speech/browserVoiceInput.ts,apps/web/src/speech/useEnvironmentSpeechInput.ts,apps/web/src/speech/*test*apps/web/src/components/chat/ComposerSpeechButton.tsx,apps/web/src/components/chat/ChatComposer.tsx,apps/web/src/components/chat/ComposerSpeechButton.test.tsVoice settings and documentation
apps/web/src/routes/settings.voice.tsx,apps/web/src/routeTree.gen.ts,apps/web/src/components/settings/*scripts/build-desktop-artifact.ts,docs/README.md,docs/internals/voice-input.md,docs/user/voice-input.mdEstimated code review effort: 4 (Complex) | ~75 minutes
Merge Risk: 🟡 Moderate · up to
027bfThe PR moves transcription into environment APIs and adds browser voice controls. Loopback requests may expose credential-bearing traffic, and voice input can hide the stop-generation action; merge readiness is moderate until these issues are addressed.
🚥 Pre-merge checks | ✅ 3 | ❌ 2
❌ Failed checks (2 warnings)#
✅ Passed checks (3 passed)
Full details: Description check
Explanation
The description provides substantial change and verification details, but it does not follow the required template. It omits the Problem and Scope and approval sections, leaves required UI evidence unchecked, and lists features not supported by the provided change summary.
Resolution
Rewrite the description using the required Problem, Change, Scope and approval, and Verification headings. Describe the underlying problem and expected behavior. Add the triaged issue or explicit maintainer approval, or explain the valid exemption. Reconcile the feature list with the actual changes in this pull request. Add before/after screenshots and a recording of the voice interaction, then report focused test results and any checks not run.
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.