diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 8d76ea83a3..baa5499d99 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -33,6 +33,11 @@ const clientSettings: ClientSettings = { sidebarV2Enabled: false, sidebarV2ConfiguredByUser: false, timestampFormat: "24-hour", + voiceTranscriptionEnabled: true, + voiceTranscriptionProvider: "local", + voiceTranscriptionBaseUrl: "http://127.0.0.1:8080/v1", + voiceTranscriptionModel: "whisper-1", + voiceTranscriptionApiKey: "", wordWrap: true, }; diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 5a380be8fe..0272f6d701 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -40,8 +40,10 @@ import { } from "./auth/http.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts"; +import { forwardWhisperTranscription, MAX_TRANSCRIPTION_AUDIO_BYTES } from "./transcription.ts"; const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces"; +const TRANSCRIPTION_PATH = "/api/transcription"; const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]); const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"]; const GZIP_MIN_BYTES = 1024; @@ -247,6 +249,50 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add( ), ); +export const transcriptionRouteLayer = HttpRouter.add( + "POST", + TRANSCRIPTION_PATH, + Effect.gen(function* () { + yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope); + const request = yield* HttpServerRequest.HttpServerRequest; + const declaredLength = Number(request.headers["content-length"] ?? "0"); + if (Number.isFinite(declaredLength) && declaredLength > MAX_TRANSCRIPTION_AUDIO_BYTES) { + return HttpServerResponse.jsonUnsafe( + { error: "The recording exceeds the 25 MB limit." }, + { status: 413 }, + ); + } + + const body = yield* request.arrayBuffer; + const audio = new Uint8Array(body); + const result = yield* Effect.tryPromise(() => + forwardWhisperTranscription({ + audio, + audioMimeType: request.headers["content-type"] ?? "audio/webm", + baseUrl: request.headers["x-t3-transcription-base-url"] ?? "", + model: request.headers["x-t3-transcription-model"] ?? "", + apiKey: request.headers["x-t3-transcription-api-key"] ?? "", + }), + ).pipe( + Effect.orElseSucceed(() => ({ + ok: false as const, + status: 502, + message: "Transcription failed unexpectedly.", + })), + ); + + return result.ok + ? HttpServerResponse.jsonUnsafe({ text: result.text }) + : HttpServerResponse.jsonUnsafe({ error: result.message }, { status: result.status }); + }).pipe( + Effect.catchTags({ + EnvironmentAuthInvalidError: HttpServerRespondable.toResponse, + EnvironmentInternalError: HttpServerRespondable.toResponse, + EnvironmentScopeRequiredError: HttpServerRespondable.toResponse, + }), + ), +); + export const assetRouteLayer = HttpRouter.add( "GET", `${ASSET_ROUTE_PREFIX}/*`, diff --git a/apps/server/src/httpCors.ts b/apps/server/src/httpCors.ts index aeb8dbce5a..b41f65e1fb 100644 --- a/apps/server/src/httpCors.ts +++ b/apps/server/src/httpCors.ts @@ -5,6 +5,9 @@ export const browserApiCorsAllowedHeaders = [ "traceparent", "content-type", "dpop", + "x-t3-transcription-api-key", + "x-t3-transcription-base-url", + "x-t3-transcription-model", ] as const; export const browserApiCorsHeaders = { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 05657af6d4..62ad7c9bd3 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -13,6 +13,7 @@ import * as ServerConfig from "./config.ts"; import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts"; import { otlpTracesProxyRouteLayer, + transcriptionRouteLayer, assetRouteLayer, serverEnvironmentHttpApiLayer, staticAndDevRouteLayer, @@ -417,6 +418,7 @@ export const makeRoutesLayer = Layer.mergeAll( Layer.provide(environmentAuthenticatedAuthLayer), ), otlpTracesProxyRouteLayer, + transcriptionRouteLayer, assetRouteLayer, staticAndDevRouteLayer, websocketRpcRouteLayer, diff --git a/apps/server/src/transcription.test.ts b/apps/server/src/transcription.test.ts new file mode 100644 index 0000000000..44dd0a135e --- /dev/null +++ b/apps/server/src/transcription.test.ts @@ -0,0 +1,66 @@ +import { expect, it } from "@effect/vitest"; +import { describe, vi } from "vite-plus/test"; + +import { forwardWhisperTranscription, resolveWhisperTranscriptionUrl } from "./transcription.ts"; + +describe("resolveWhisperTranscriptionUrl", () => { + it("adds the OpenAI-compatible transcription path", () => { + expect(resolveWhisperTranscriptionUrl("http://127.0.0.1:8080/v1/")?.toString()).toBe( + "http://127.0.0.1:8080/v1/audio/transcriptions", + ); + expect( + resolveWhisperTranscriptionUrl( + "https://api.groq.com/openai/v1/audio/transcriptions", + )?.toString(), + ).toBe("https://api.groq.com/openai/v1/audio/transcriptions"); + }); + + it("rejects non-http and credential-bearing URLs", () => { + expect(resolveWhisperTranscriptionUrl("file:///tmp/whisper")).toBeNull(); + expect(resolveWhisperTranscriptionUrl("https://user:pass@example.com/v1")).toBeNull(); + }); +}); + +describe("forwardWhisperTranscription", () => { + it("sends OpenAI-compatible multipart audio with BYOK authorization", async () => { + const fetchImpl = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => { + expect(init?.headers).toEqual({ authorization: "Bearer groq-key" }); + expect(init?.body).toBeInstanceOf(FormData); + const form = init?.body as FormData; + expect(form.get("model")).toBe("whisper-large-v3-turbo"); + expect(form.get("file")).toBeInstanceOf(Blob); + return Response.json({ text: "hello from the microphone" }); + }); + + await expect( + forwardWhisperTranscription( + { + audio: new Uint8Array([1, 2, 3]), + audioMimeType: "audio/webm;codecs=opus", + baseUrl: "https://api.groq.com/openai/v1", + model: "whisper-large-v3-turbo", + apiKey: "groq-key", + }, + fetchImpl, + ), + ).resolves.toEqual({ ok: true, text: "hello from the microphone" }); + }); + + it("returns a safe provider error", async () => { + const fetchImpl = vi.fn(async () => + Response.json({ error: { message: "bad key" } }, { status: 401 }), + ); + await expect( + forwardWhisperTranscription( + { + audio: new Uint8Array([1]), + audioMimeType: "audio/webm", + baseUrl: "https://example.com/v1", + model: "whisper-1", + apiKey: "bad", + }, + fetchImpl, + ), + ).resolves.toEqual({ ok: false, status: 502, message: "bad key" }); + }); +}); diff --git a/apps/server/src/transcription.ts b/apps/server/src/transcription.ts new file mode 100644 index 0000000000..5d380bafa8 --- /dev/null +++ b/apps/server/src/transcription.ts @@ -0,0 +1,113 @@ +const TRANSCRIPTION_PATH = "/audio/transcriptions"; + +export const MAX_TRANSCRIPTION_AUDIO_BYTES = 25 * 1024 * 1024; + +export interface WhisperTranscriptionInput { + readonly audio: Uint8Array; + readonly audioMimeType: string; + readonly baseUrl: string; + readonly model: string; + readonly apiKey: string; +} + +type TranscriptionFetch = (input: string | URL | Request, init?: RequestInit) => Promise; + +export type WhisperTranscriptionResult = + | { readonly ok: true; readonly text: string } + | { readonly ok: false; readonly status: number; readonly message: string }; + +export function resolveWhisperTranscriptionUrl(baseUrl: string): URL | null { + try { + const url = new URL(baseUrl.trim()); + if (url.protocol !== "http:" && url.protocol !== "https:") return null; + if (url.username || url.password) return null; + url.search = ""; + url.hash = ""; + url.pathname = url.pathname.replace(/\/$/, ""); + if (!url.pathname.endsWith(TRANSCRIPTION_PATH)) { + url.pathname += TRANSCRIPTION_PATH; + } + return url; + } catch { + return null; + } +} + +function audioFileExtension(mimeType: string): string { + if (mimeType.includes("ogg")) return "ogg"; + if (mimeType.includes("mp4") || mimeType.includes("m4a")) return "m4a"; + if (mimeType.includes("wav")) return "wav"; + return "webm"; +} + +export async function forwardWhisperTranscription( + input: WhisperTranscriptionInput, + fetchImpl: TranscriptionFetch = globalThis.fetch, +): Promise { + const endpoint = resolveWhisperTranscriptionUrl(input.baseUrl); + if (!endpoint) { + return { ok: false, status: 400, message: "Enter a valid HTTP transcription endpoint." }; + } + if (!input.model.trim()) { + return { ok: false, status: 400, message: "Enter a transcription model." }; + } + if (input.audio.byteLength === 0) { + return { ok: false, status: 400, message: "The recording was empty." }; + } + if (input.audio.byteLength > MAX_TRANSCRIPTION_AUDIO_BYTES) { + return { ok: false, status: 413, message: "The recording exceeds the 25 MB limit." }; + } + + const mimeType = input.audioMimeType.split(";", 1)[0]?.trim() || "audio/webm"; + const form = new FormData(); + form.set("model", input.model.trim()); + form.set( + "file", + new Blob([input.audio], { type: mimeType }), + `recording.${audioFileExtension(mimeType)}`, + ); + + let response: Response; + try { + response = await fetchImpl(endpoint, { + method: "POST", + headers: input.apiKey ? { authorization: `Bearer ${input.apiKey}` } : undefined, + body: form, + signal: AbortSignal.timeout(120_000), + }); + } catch { + return { ok: false, status: 502, message: "Could not reach the transcription provider." }; + } + + let payload: unknown; + try { + payload = await response.json(); + } catch { + return { ok: false, status: 502, message: "The transcription provider returned invalid JSON." }; + } + + if (!response.ok) { + const providerMessage = + typeof payload === "object" && + payload !== null && + "error" in payload && + typeof payload.error === "object" && + payload.error !== null && + "message" in payload.error && + typeof payload.error.message === "string" + ? payload.error.message + : null; + return { + ok: false, + status: 502, + message: providerMessage?.slice(0, 300) || "The transcription provider rejected the request.", + }; + } + + const text = + typeof payload === "object" && payload !== null && "text" in payload ? payload.text : undefined; + if (typeof text !== "string") { + return { ok: false, status: 502, message: "The transcription response did not contain text." }; + } + return { ok: true, text: text.trim() }; +} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index e92ecd497e..dfcdbeeb40 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -107,6 +107,8 @@ import { buildExpandedImagePreview, type ExpandedImagePreview } from "./Expanded import { basenameOfPath } from "../../pierre-icons"; import { cn, randomUUID } from "~/lib/utils"; import { Separator } from "../ui/separator"; +import { useVoiceTranscription } from "../../hooks/useVoiceTranscription"; +import { VoiceTranscriptionPanel } from "./VoiceTranscriptionPanel"; function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children: ReactNode }) { const [position, setPosition] = useState<{ @@ -179,6 +181,7 @@ import { LockOpenIcon, PenLineIcon, SparklesIcon, + MicIcon, XIcon, } from "lucide-react"; import { proposedPlanTitle } from "../../proposedPlan"; @@ -1269,6 +1272,30 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) [composerDraftTarget, setComposerDraftPrompt], ); + const appendVoiceTranscript = useCallback( + (transcript: string) => { + const currentPrompt = promptRef.current; + const boundary = currentPrompt.length > 0 && !/\s$/.test(currentPrompt) ? " " : ""; + const nextPrompt = `${currentPrompt}${boundary}${transcript}`; + promptRef.current = nextPrompt; + setPrompt(nextPrompt); + const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length); + setComposerCursor(nextCursor); + setComposerTrigger(null); + scheduleComposerFocus(); + }, + [promptRef, scheduleComposerFocus, setPrompt], + ); + const voiceTranscription = useVoiceTranscription({ + config: { + provider: settings.voiceTranscriptionProvider, + baseUrl: settings.voiceTranscriptionBaseUrl, + model: settings.voiceTranscriptionModel, + apiKey: settings.voiceTranscriptionApiKey, + }, + onTranscript: appendVoiceTranscript, + }); + const addComposerImage = useCallback( (image: ComposerImageAttachment) => { addComposerDraftImage(composerDraftTarget, image); @@ -3102,6 +3129,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) + {settings.voiceTranscriptionEnabled && voiceTranscription.status !== "idle" ? ( + + ) : settings.voiceTranscriptionEnabled && voiceTranscription.error ? ( +

+ {voiceTranscription.error} +

+ ) : null} + {/* Bottom toolbar */} {isComposerCollapsedMobile ? null : activePendingApproval ? (
@@ -3205,6 +3245,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } className="flex shrink-0 flex-nowrap items-center justify-end gap-2" > + {settings.voiceTranscriptionEnabled && + voiceTranscription.status === "idle" && + !isComposerApprovalState && + pendingUserInputs.length === 0 ? ( + + void voiceTranscription.start()} + aria-label="Start dictation" + > + + + } + /> + Start dictation + + ) : null} `voice-waveform-${index}`); + +function formatElapsed(elapsedMs: number): string { + const seconds = Math.floor(elapsedMs / 1_000); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; +} + +export function VoiceTranscriptionPanel({ + status, + elapsedMs, + levels, + onStop, +}: { + readonly status: Exclude; + readonly elapsedMs: number; + readonly levels: readonly number[]; + readonly onStop: () => void; +}) { + return ( +
+ {status === "recording" ? ( + + ) : ( +
+ + transcribing with your configured provider... +
+ )} + + {formatElapsed(elapsedMs)} + + {status === "recording" ? ( + + ) : null} +
+ ); +} diff --git a/apps/web/src/components/settings/BetaSettingsPanel.tsx b/apps/web/src/components/settings/BetaSettingsPanel.tsx index 740d3048f0..c1f2b60d62 100644 --- a/apps/web/src/components/settings/BetaSettingsPanel.tsx +++ b/apps/web/src/components/settings/BetaSettingsPanel.tsx @@ -1,3 +1,8 @@ +import { + DEFAULT_VOICE_TRANSCRIPTION_BASE_URL, + DEFAULT_VOICE_TRANSCRIPTION_MODEL, + type VoiceTranscriptionProvider, +} from "@t3tools/contracts"; import { useEffect, useState } from "react"; import { @@ -5,7 +10,12 @@ import { useSidebarV2Enabled, useUpdateClientSettings, } from "../../hooks/useSettings"; +import { + GROQ_TRANSCRIPTION_BASE_URL, + GROQ_TRANSCRIPTION_MODEL, +} from "../../lib/voiceTranscription"; import { Input } from "../ui/input"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Switch } from "../ui/switch"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; import { searchableSetting } from "./settingsSearch"; @@ -60,8 +70,41 @@ export function BetaSettingsPanel() { const sidebarAutoSettleAfterDays = useClientSettings( (settings) => settings.sidebarAutoSettleAfterDays, ); + const voiceTranscriptionEnabled = useClientSettings( + (settings) => settings.voiceTranscriptionEnabled, + ); + const voiceTranscriptionProvider = useClientSettings( + (settings) => settings.voiceTranscriptionProvider, + ); + const voiceTranscriptionBaseUrl = useClientSettings( + (settings) => settings.voiceTranscriptionBaseUrl, + ); + const voiceTranscriptionModel = useClientSettings((settings) => settings.voiceTranscriptionModel); + const voiceTranscriptionApiKey = useClientSettings( + (settings) => settings.voiceTranscriptionApiKey, + ); const updateSettings = useUpdateClientSettings(); + const selectVoiceProvider = (provider: VoiceTranscriptionProvider) => { + if (provider === "local") { + updateSettings({ + voiceTranscriptionProvider: provider, + voiceTranscriptionBaseUrl: DEFAULT_VOICE_TRANSCRIPTION_BASE_URL, + voiceTranscriptionModel: DEFAULT_VOICE_TRANSCRIPTION_MODEL, + }); + return; + } + if (provider === "groq") { + updateSettings({ + voiceTranscriptionProvider: provider, + voiceTranscriptionBaseUrl: GROQ_TRANSCRIPTION_BASE_URL, + voiceTranscriptionModel: GROQ_TRANSCRIPTION_MODEL, + }); + return; + } + updateSettings({ voiceTranscriptionProvider: provider }); + }; + return ( @@ -114,6 +157,105 @@ export function BetaSettingsPanel() { ) : null} ) : null} + + updateSettings({ voiceTranscriptionEnabled: Boolean(checked) }) + } + aria-label="Enable voice dictation beta" + /> + } + /> + {voiceTranscriptionEnabled ? ( + <> + + selectVoiceProvider(value as VoiceTranscriptionProvider) + } + > + + + {voiceTranscriptionProvider === "local" + ? "Local" + : voiceTranscriptionProvider === "groq" + ? "Groq" + : "Custom"} + + + + + Local + + + Groq + + + Custom + + + + } + /> + + updateSettings({ voiceTranscriptionBaseUrl: event.target.value }) + } + placeholder="http://127.0.0.1:8080/v1" + aria-label="Transcription endpoint" + spellCheck={false} + /> + } + /> + + updateSettings({ voiceTranscriptionModel: event.target.value }) + } + placeholder="whisper-1" + aria-label="Transcription model" + spellCheck={false} + /> + } + /> + + updateSettings({ voiceTranscriptionApiKey: event.target.value }) + } + placeholder={voiceTranscriptionProvider === "local" ? "Optional" : "Required"} + aria-label="Transcription API key" + /> + } + /> + + ) : null} ); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 4ead6eff4d..e80b41a4e0 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -157,6 +157,11 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/beta", targetId: "sidebar-v2", }, + { + id: "voice-dictation", + title: "Voice dictation", + to: "/settings/beta", + }, { id: "archive", title: "Archived threads", diff --git a/apps/web/src/hooks/useVoiceTranscription.ts b/apps/web/src/hooks/useVoiceTranscription.ts new file mode 100644 index 0000000000..061739cef3 --- /dev/null +++ b/apps/web/src/hooks/useVoiceTranscription.ts @@ -0,0 +1,149 @@ +import { useCallback, useEffect, useRef, useState } from "react"; + +import { transcribeVoiceRecording, type VoiceTranscriptionConfig } from "../lib/voiceTranscription"; + +const LEVEL_COUNT = 36; +const MAX_RECORDING_MS = 5 * 60 * 1_000; +const MIME_TYPES = ["audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/mp4"]; + +export type VoiceTranscriptionStatus = "idle" | "recording" | "transcribing"; + +function supportedMimeType(): string | undefined { + if (typeof MediaRecorder === "undefined") return undefined; + return MIME_TYPES.find((mimeType) => MediaRecorder.isTypeSupported(mimeType)); +} + +export function useVoiceTranscription({ + config, + onTranscript, +}: { + readonly config: VoiceTranscriptionConfig; + readonly onTranscript: (text: string) => void; +}) { + const [status, setStatus] = useState("idle"); + const [elapsedMs, setElapsedMs] = useState(0); + const [levels, setLevels] = useState(() => Array(LEVEL_COUNT).fill(0.12)); + const [error, setError] = useState(null); + const recorderRef = useRef(null); + const streamRef = useRef(null); + const audioContextRef = useRef(null); + const intervalsRef = useRef([]); + const timeoutRef = useRef(null); + const startedAtRef = useRef(0); + const mountedRef = useRef(true); + const configRef = useRef(config); + const onTranscriptRef = useRef(onTranscript); + configRef.current = config; + onTranscriptRef.current = onTranscript; + + const cleanupCapture = useCallback(() => { + for (const interval of intervalsRef.current) window.clearInterval(interval); + intervalsRef.current = []; + if (timeoutRef.current !== null) window.clearTimeout(timeoutRef.current); + timeoutRef.current = null; + streamRef.current?.getTracks().forEach((track) => track.stop()); + streamRef.current = null; + void audioContextRef.current?.close(); + audioContextRef.current = null; + recorderRef.current = null; + }, []); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + const recorder = recorderRef.current; + if (recorder?.state === "recording") recorder.stop(); + cleanupCapture(); + }; + }, [cleanupCapture]); + + const stop = useCallback(() => { + const recorder = recorderRef.current; + if (recorder?.state === "recording") recorder.stop(); + }, []); + + const start = useCallback(async () => { + if (status !== "idle") return; + setError(null); + if (!navigator.mediaDevices?.getUserMedia || typeof MediaRecorder === "undefined") { + setError("Microphone recording is not supported on this device."); + return; + } + + try { + const stream = await navigator.mediaDevices.getUserMedia({ + audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }, + }); + if (!mountedRef.current) { + stream.getTracks().forEach((track) => track.stop()); + return; + } + + const mimeType = supportedMimeType(); + const recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined); + const chunks: Blob[] = []; + streamRef.current = stream; + recorderRef.current = recorder; + recorder.addEventListener("dataavailable", (event) => { + if (event.data.size > 0) chunks.push(event.data); + }); + recorder.addEventListener("error", () => { + if (mountedRef.current) setError("The microphone stopped unexpectedly."); + }); + recorder.addEventListener("stop", () => { + const blob = new Blob(chunks, { type: recorder.mimeType || mimeType || "audio/webm" }); + cleanupCapture(); + if (!mountedRef.current) return; + setStatus("transcribing"); + void transcribeVoiceRecording(blob, configRef.current) + .then((text) => { + if (!mountedRef.current) return; + if (text) onTranscriptRef.current(text); + setStatus("idle"); + setElapsedMs(0); + }) + .catch((cause: unknown) => { + if (!mountedRef.current) return; + setError(cause instanceof Error ? cause.message : "Voice transcription failed."); + setStatus("idle"); + }); + }); + + const audioContext = new AudioContext(); + audioContextRef.current = audioContext; + const analyser = audioContext.createAnalyser(); + analyser.fftSize = 128; + audioContext.createMediaStreamSource(stream).connect(analyser); + const samples = new Uint8Array(analyser.frequencyBinCount); + intervalsRef.current.push( + window.setInterval(() => { + analyser.getByteFrequencyData(samples); + setLevels( + Array.from({ length: LEVEL_COUNT }, (_, index) => { + const sampleIndex = Math.floor((index / LEVEL_COUNT) * samples.length); + return Math.max(0.1, (samples[sampleIndex] ?? 0) / 255); + }), + ); + }, 80), + ); + startedAtRef.current = Date.now(); + intervalsRef.current.push( + window.setInterval(() => setElapsedMs(Date.now() - startedAtRef.current), 250), + ); + timeoutRef.current = window.setTimeout(() => recorder.stop(), MAX_RECORDING_MS); + recorder.start(250); + setStatus("recording"); + } catch (cause) { + cleanupCapture(); + setStatus("idle"); + setError( + cause instanceof DOMException && cause.name === "NotAllowedError" + ? "Microphone permission was denied. Allow access and try again." + : "Could not start the microphone.", + ); + } + }, [cleanupCapture, status]); + + return { status, elapsedMs, levels, error, start, stop } as const; +} diff --git a/apps/web/src/lib/voiceTranscription.ts b/apps/web/src/lib/voiceTranscription.ts new file mode 100644 index 0000000000..05499b4c4f --- /dev/null +++ b/apps/web/src/lib/voiceTranscription.ts @@ -0,0 +1,47 @@ +import type { VoiceTranscriptionProvider } from "@t3tools/contracts"; + +import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth"; +import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary/target"; + +export const GROQ_TRANSCRIPTION_BASE_URL = "https://api.groq.com/openai/v1"; +export const GROQ_TRANSCRIPTION_MODEL = "whisper-large-v3-turbo"; + +export interface VoiceTranscriptionConfig { + readonly provider: VoiceTranscriptionProvider; + readonly baseUrl: string; + readonly model: string; + readonly apiKey: string; +} + +export async function transcribeVoiceRecording( + audio: Blob, + config: VoiceTranscriptionConfig, +): Promise { + const bearerToken = await readDesktopPrimaryBearerToken(); + const response = await globalThis.fetch(resolvePrimaryEnvironmentHttpUrl("/api/transcription"), { + method: "POST", + credentials: bearerToken ? "omit" : "include", + headers: { + ...(bearerToken ? { authorization: `Bearer ${bearerToken}` } : {}), + "content-type": audio.type || "audio/webm", + "x-t3-transcription-base-url": config.baseUrl, + "x-t3-transcription-model": config.model, + ...(config.apiKey ? { "x-t3-transcription-api-key": config.apiKey } : {}), + }, + body: audio, + }); + + const payload = (await response.json().catch(() => null)) as { + readonly text?: unknown; + readonly error?: unknown; + } | null; + if (!response.ok) { + throw new Error( + typeof payload?.error === "string" ? payload.error : "Voice transcription failed.", + ); + } + if (typeof payload?.text !== "string") { + throw new Error("The transcription response did not contain text."); + } + return payload.text.trim(); +} diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7edda2e52e..13b21c21a8 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -62,6 +62,11 @@ export const EnvironmentIdentificationMode = Schema.Literals(["artwork", "pill", export type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type; export const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = "artwork"; +export const VoiceTranscriptionProvider = Schema.Literals(["local", "groq", "custom"]); +export type VoiceTranscriptionProvider = typeof VoiceTranscriptionProvider.Type; +export const DEFAULT_VOICE_TRANSCRIPTION_BASE_URL = "http://127.0.0.1:8080/v1"; +export const DEFAULT_VOICE_TRANSCRIPTION_MODEL = "whisper-1"; + export const ClientSettingsSchema = Schema.Struct({ autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), @@ -130,6 +135,17 @@ export const ClientSettingsSchema = Schema.Struct({ timestampFormat: TimestampFormat.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)), ), + voiceTranscriptionEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + voiceTranscriptionProvider: VoiceTranscriptionProvider.pipe( + Schema.withDecodingDefault(Effect.succeed("local" as const)), + ), + voiceTranscriptionBaseUrl: TrimmedString.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_VOICE_TRANSCRIPTION_BASE_URL)), + ), + voiceTranscriptionModel: TrimmedString.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_VOICE_TRANSCRIPTION_MODEL)), + ), + voiceTranscriptionApiKey: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))), wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), }); export type ClientSettings = typeof ClientSettingsSchema.Type; @@ -712,6 +728,11 @@ export const ClientSettingsPatch = Schema.Struct({ sidebarV2Enabled: Schema.optionalKey(Schema.Boolean), sidebarV2ConfiguredByUser: Schema.optionalKey(Schema.Boolean), timestampFormat: Schema.optionalKey(TimestampFormat), + voiceTranscriptionEnabled: Schema.optionalKey(Schema.Boolean), + voiceTranscriptionProvider: Schema.optionalKey(VoiceTranscriptionProvider), + voiceTranscriptionBaseUrl: Schema.optionalKey(TrimmedString), + voiceTranscriptionModel: Schema.optionalKey(TrimmedString), + voiceTranscriptionApiKey: Schema.optionalKey(Schema.String), wordWrap: Schema.optionalKey(Schema.Boolean), }); export type ClientSettingsPatch = typeof ClientSettingsPatch.Type; diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index 7d2b7410a9..d6c53c5be9 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -349,6 +349,9 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { assert.notProperty(mac, "asarUnpack"); assert.notProperty(linux, "asarUnpack"); assert.deepStrictEqual(win.asarUnpack, WINDOWS_ASAR_UNPACK); + assert.deepStrictEqual((mac.mac as Record).extendInfo, { + NSMicrophoneUsageDescription: "T3 Code uses the microphone for voice dictation.", + }); // Linux must register the renderer schemes so the generated .desktop // entry advertises MimeType=x-scheme-handler/t3code; for OAuth deep links. assert.deepStrictEqual((linux.linux as Record).protocols, [ diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index a3c9996925..970b523944 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -1568,6 +1568,9 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* ( target: target === "dmg" ? [target, "zip"] : [target], icon: "icon.icns", category: "public.app-category.developer-tools", + extendInfo: { + NSMicrophoneUsageDescription: "T3 Code uses the microphone for voice dictation.", + }, protocols: [ { name: "T3 Code",