feat: add voice dictation beta

This commit is contained in:
t3-code[bot] committed 2026-08-02 04:33:13 +00:00
1 parent 5192f777fe
commit 1dbfe76c62
15 files changed
+736

No files matched your search

@@ -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,
};
+46
View File
@@ -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}/*`,
+3
View File
@@ -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 = {
+2
View File
@@ -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,
+66
View File
@@ -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:[email protected]/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" });
});
});
+113
View File
@@ -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<Response>;
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<WhisperTranscriptionResult> {
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() };
}
@@ -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)
</div>
</div>
{settings.voiceTranscriptionEnabled && voiceTranscription.status !== "idle" ? (
<VoiceTranscriptionPanel
status={voiceTranscription.status}
elapsedMs={voiceTranscription.elapsedMs}
levels={voiceTranscription.levels}
onStop={voiceTranscription.stop}
/>
) : settings.voiceTranscriptionEnabled && voiceTranscription.error ? (
<p className="mx-4 mb-2 text-xs text-destructive" role="alert">
{voiceTranscription.error}
</p>
) : null}
{/* Bottom toolbar */}
{isComposerCollapsedMobile ? null : activePendingApproval ? (
<div className="flex items-center justify-end gap-2 px-2.5 pb-2.5 sm:px-3 sm:pb-3">
@@ -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 ? (
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-sm"
variant="ghost"
disabled={isConnecting || projectSelectionRequired}
className="rounded-full text-muted-foreground"
onClick={() => void voiceTranscription.start()}
aria-label="Start dictation"
>
<MicIcon className="size-4" />
</Button>
}
/>
<TooltipPopup side="top">Start dictation</TooltipPopup>
</Tooltip>
) : null}
<ComposerFooterPrimaryActions
compact={isComposerPrimaryActionsCompact}
activeContextWindow={activeContextWindow}
@@ -0,0 +1,68 @@
import { LoaderCircleIcon, SquareIcon } from "lucide-react";
import type { VoiceTranscriptionStatus } from "../../hooks/useVoiceTranscription";
import { Button } from "../ui/button";
const WAVEFORM_BAR_IDS = Array.from({ length: 36 }, (_, index) => `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<VoiceTranscriptionStatus, "idle">;
readonly elapsedMs: number;
readonly levels: readonly number[];
readonly onStop: () => void;
}) {
return (
<div
className="mx-3 mb-2 flex min-h-12 items-center gap-3 rounded-xl border border-border/55 bg-background/35 px-3"
role="status"
aria-label={status === "recording" ? "Voice recording in progress" : "Transcribing voice"}
>
{status === "recording" ? (
<div
className="flex min-w-0 flex-1 items-center gap-[3px] overflow-hidden"
aria-hidden="true"
>
{WAVEFORM_BAR_IDS.map((id, index) => (
<span
key={id}
className="w-0.5 shrink-0 rounded-full bg-foreground/80 transition-[height] duration-75"
style={{ height: `${Math.max(4, Math.round((levels[index] ?? 0.1) * 30))}px` }}
/>
))}
<span className="ml-1 h-px min-w-4 flex-1 border-t border-dashed border-muted-foreground/45" />
</div>
) : (
<div className="flex min-w-0 flex-1 items-center gap-2 text-sm text-muted-foreground">
<LoaderCircleIcon className="size-4 animate-spin" />
transcribing with your configured provider...
</div>
)}
<span className="shrink-0 text-sm tabular-nums text-muted-foreground">
{formatElapsed(elapsedMs)}
</span>
{status === "recording" ? (
<Button
type="button"
size="icon-sm"
variant="secondary"
className="shrink-0 rounded-full"
onClick={onStop}
aria-label="Stop dictation"
title="Stop dictation"
>
<SquareIcon className="size-3 fill-current" />
</Button>
) : null}
</div>
);
}
@@ -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 (
<SettingsPageContainer>
<SettingsSection title="Beta features">
@@ -114,6 +157,105 @@ export function BetaSettingsPanel() {
) : null}
</>
) : null}
<SettingsRow
{...searchableSetting("voice-dictation")}
description="Record from the composer and turn speech into text. Uses portable browser media APIs on Linux, macOS, and Windows."
control={
<Switch
checked={voiceTranscriptionEnabled}
onCheckedChange={(checked) =>
updateSettings({ voiceTranscriptionEnabled: Boolean(checked) })
}
aria-label="Enable voice dictation beta"
/>
}
/>
{voiceTranscriptionEnabled ? (
<>
<SettingsRow
title="Transcription provider"
description="Local is the default and works with an OpenAI-compatible whisper.cpp or faster-whisper server."
control={
<Select
value={voiceTranscriptionProvider}
onValueChange={(value) =>
selectVoiceProvider(value as VoiceTranscriptionProvider)
}
>
<SelectTrigger className="w-full sm:w-44" aria-label="Transcription provider">
<SelectValue>
{voiceTranscriptionProvider === "local"
? "Local"
: voiceTranscriptionProvider === "groq"
? "Groq"
: "Custom"}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="local">
Local
</SelectItem>
<SelectItem hideIndicator value="groq">
Groq
</SelectItem>
<SelectItem hideIndicator value="custom">
Custom
</SelectItem>
</SelectPopup>
</Select>
}
/>
<SettingsRow
title="Endpoint"
description="Base URL for any OpenAI Whisper-compatible API."
control={
<Input
className="w-full sm:w-80"
value={voiceTranscriptionBaseUrl}
onChange={(event) =>
updateSettings({ voiceTranscriptionBaseUrl: event.target.value })
}
placeholder="http://127.0.0.1:8080/v1"
aria-label="Transcription endpoint"
spellCheck={false}
/>
}
/>
<SettingsRow
title="Model"
description="The model name sent to the provider."
control={
<Input
className="w-full sm:w-64"
value={voiceTranscriptionModel}
onChange={(event) =>
updateSettings({ voiceTranscriptionModel: event.target.value })
}
placeholder="whisper-1"
aria-label="Transcription model"
spellCheck={false}
/>
}
/>
<SettingsRow
title="API key"
description="Optional for local servers and required by most hosted providers. The key stays in this client's local settings."
control={
<Input
type="password"
autoComplete="off"
className="w-full sm:w-64"
value={voiceTranscriptionApiKey}
onChange={(event) =>
updateSettings({ voiceTranscriptionApiKey: event.target.value })
}
placeholder={voiceTranscriptionProvider === "local" ? "Optional" : "Required"}
aria-label="Transcription API key"
/>
}
/>
</>
) : null}
</SettingsSection>
</SettingsPageContainer>
);
@@ -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",
+149
View File
@@ -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<VoiceTranscriptionStatus>("idle");
const [elapsedMs, setElapsedMs] = useState(0);
const [levels, setLevels] = useState<readonly number[]>(() => Array(LEVEL_COUNT).fill(0.12));
const [error, setError] = useState<string | null>(null);
const recorderRef = useRef<MediaRecorder | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const audioContextRef = useRef<AudioContext | null>(null);
const intervalsRef = useRef<number[]>([]);
const timeoutRef = useRef<number | null>(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;
}
+47
View File
@@ -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<string> {
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();
}
+21
View File
@@ -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;
+3
View File
@@ -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<string, unknown>).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<string, unknown>).protocols, [
+3
View File
@@ -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",