Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@dnd-kit/utilities": "^3.2.2",
"@effect/atom-react": "catalog:",
"@fontsource-variable/inter": "^5.3.0",
"@huggingface/transformers": "4.3.2",
"@legendapp/list": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
Expand Down
33 changes: 32 additions & 1 deletion apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,11 @@ import {
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen";
import { useStableCallback } from "../../hooks/useStableCallback";
import {
isComposerVoiceInputAvailable,
useComposerVoiceInput,
} from "../../voiceInput/useComposerVoiceInput";
import { ComposerVoiceInputButton } from "./ComposerVoiceInputButton";
import { usePanelAnimationSettings } from "../../panelAnimations";
import { readEnvironmentScope } from "../../state/session";
import type { ReviewCommentContext } from "../../reviewCommentContext";
Expand Down Expand Up @@ -1817,6 +1822,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
};
};
const readComposerSnapshotStable = useStableCallback(readComposerSnapshot);
const voiceInput = useComposerVoiceInput({
ownerKey: composerDraftTargetKey,
readDraft: () => ({
text: promptRef.current,
cursor: readComposerSnapshotStable().expandedCursor,
}),
commitDraft: (text, cursor) => {
// The controller only commits an insertion at the cursor it captured.
const start = cursor - (text.length - promptRef.current.length);
applyPromptReplacementStable(start, start, text.slice(start, cursor));
},
});

const resolveActiveComposerTrigger = (): {
snapshot: { value: string; cursor: number; expandedCursor: number };
Expand Down Expand Up @@ -2045,6 +2062,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
dispatchMode?: ComposerDispatchMode,
submissionIntent?: ComposerSubmissionIntent,
) => {
if (voiceInput.state.phase !== "idle") {
event?.preventDefault();
// Enter while dictating finishes the recording instead of sending.
if (voiceInput.state.phase === "recording") voiceInput.stop();
return;
}
if (
noProviderAvailable ||
isSendDisabled ||
Expand Down Expand Up @@ -3085,6 +3108,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
focusComposer={focusComposer}
/>
) : null;
const composerVoiceInputButton = isComposerVoiceInputAvailable ? (
<ComposerVoiceInputButton voiceInput={voiceInput} />
) : null;
return (
<form
ref={composerFormRef}
Expand Down Expand Up @@ -3429,7 +3455,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showMobilePendingAnswerActions && "hidden sm:flex",
)}
>
{composerAttachButton ? <div className="me-2">{composerAttachButton}</div> : null}
{composerAttachButton || composerVoiceInputButton ? (
<div className="me-2 flex min-w-0 items-center gap-0.5">
{composerAttachButton}
{composerVoiceInputButton}
</div>
) : null}
<div
data-chat-composer-actions="right"
data-chat-composer-transition-actions="true"
Expand Down
102 changes: 102 additions & 0 deletions apps/web/src/components/chat/ComposerVoiceInputButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { MicIcon, SquareIcon } from "lucide-react";
import { useEffect, useState } from "react";

import type { ComposerVoiceInput } from "~/voiceInput/useComposerVoiceInput";
import { Button } from "../ui/button";
import { Spinner } from "../ui/spinner";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";

function voiceInputLabel(voiceInput: ComposerVoiceInput): string {
switch (voiceInput.state.phase) {
case "preparing":
return voiceInput.downloadProgress === null
? "Starting voice input"
: "Downloading speech model";
case "recording":
return "Stop and transcribe";
case "transcribing":
return "Transcribing";
default:
return "Voice input";
}
}

function formatElapsed(seconds: number): string {
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
}

/** Counts whole seconds since mount; mounted only while recording. */
function RecordingElapsed() {
const [seconds, setSeconds] = useState(0);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- ticks a timer while the recording is on screen
useEffect(() => {
const timer = setInterval(() => setSeconds((value) => value + 1), 1000);
return () => clearInterval(timer);
}, []);
return <span className="tabular-nums">{formatElapsed(seconds)}</span>;
}

function VoiceInputStatus({ voiceInput }: { voiceInput: ComposerVoiceInput }) {
const { phase } = voiceInput.state;
if (phase === "idle" || phase === "error") return null;
return (
<span
role="status"
className="ms-1 truncate text-muted-foreground text-xs"
data-voice-input-status={phase}
>
{phase === "preparing" ? (
voiceInput.downloadProgress === null ? (
"Starting…"
) : (
<>
Downloading speech model, one time only ·{" "}
<span className="tabular-nums">{Math.round(voiceInput.downloadProgress * 100)}%</span>
</>
)
) : phase === "recording" ? (
<>
Listening <RecordingElapsed /> · Enter to finish
</>
) : (
"Transcribing…"
)}
</span>
);
}

export function ComposerVoiceInputButton({ voiceInput }: { voiceInput: ComposerVoiceInput }) {
const { phase } = voiceInput.state;
const label = voiceInputLabel(voiceInput);
return (
<>
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
variant={phase === "recording" ? "destructive-outline" : "ghost"}
size="icon-sm"
// Keep focus in the editor so Enter stops the recording.
onPointerDown={(event) => event.preventDefault()}
onClick={voiceInput.toggle}
disabled={phase === "transcribing"}
aria-label={label}
aria-pressed={phase === "recording"}
/>
}
>
{phase === "preparing" || phase === "transcribing" ? (
<Spinner aria-hidden />
) : phase === "recording" ? (
<SquareIcon />
) : (
<MicIcon />
)}
</TooltipTrigger>
<TooltipPopup>{label}</TooltipPopup>
</Tooltip>
<VoiceInputStatus voiceInput={voiceInput} />
</>
);
}
4 changes: 4 additions & 0 deletions apps/web/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ export const isElectron = typeof window !== "undefined" && window.desktopBridge
export const isSecretsFeatureEnabled = ["1", "true"].includes(
import.meta.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "",
);

export const isVoiceInputFeatureEnabled = ["1", "true"].includes(
import.meta.env.T3CODE_FEATURE_VOICE_INPUT?.trim().toLowerCase() ?? "",
);
1 change: 1 addition & 0 deletions apps/web/src/vite-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ interface ImportMetaEnv {
readonly VITE_RELAY_OTLP_TRACES_TOKEN: string;
readonly T3CODE_DESKTOP_UPDATE_REPOSITORY: string;
readonly T3CODE_FEATURE_SECRETS: string;
readonly T3CODE_FEATURE_VOICE_INPUT: string;
readonly APP_VERSION: string;
}

Expand Down
105 changes: 105 additions & 0 deletions apps/web/src/voiceInput/browserVoiceRecorder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import type { VoiceRecorder, VoiceRecorderStatus } from "@t3tools/client-runtime/voice-input";

export function supportsBrowserVoiceRecording(): boolean {
return (
typeof navigator !== "undefined" &&
navigator.mediaDevices?.getUserMedia !== undefined &&
typeof MediaRecorder !== "undefined"
);
}

/** Asks for the microphone without holding it open while the speech model loads. */
export async function requestBrowserMicrophonePermission(): Promise<{
readonly granted: boolean;
readonly canAskAgain: boolean;
}> {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
for (const track of stream.getTracks()) track.stop();
return { granted: true, canAskAgain: true };
} catch {
const status = await navigator.permissions
?.query({ name: "microphone" as PermissionName })
.catch(() => null);
return { granted: false, canAskAgain: status?.state !== "denied" };
}
}

/** Records into a blob URL; the controller revokes it through `deleteRecording`. */
export class BrowserVoiceRecorder implements VoiceRecorder {
uri: string | null = null;
private readonly onStatus: (status: VoiceRecorderStatus) => void;
private stream: MediaStream | null = null;
private recorder: MediaRecorder | null = null;
private chunks: Blob[] = [];
private limitTimer: ReturnType<typeof setTimeout> | null = null;
private stopped: Promise<string | null> | null = null;

constructor(onStatus: (status: VoiceRecorderStatus) => void) {
this.onStatus = onStatus;
}

async prepareToRecordAsync(): Promise<void> {
this.uri = null;
this.chunks = [];
this.stopped = null;
this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const recorder = new MediaRecorder(this.stream);
recorder.addEventListener("dataavailable", (event) => this.chunks.push(event.data));
recorder.addEventListener("error", () =>
this.reportFailure("The microphone stopped recording."),
);
for (const track of this.stream.getAudioTracks()) {
track.addEventListener("ended", () => this.reportFailure("The microphone was disconnected."));
}
this.recorder = recorder;
}

record(options: { readonly forDuration: number }): void {
this.recorder?.start();
this.limitTimer = setTimeout(() => {
void this.stop().then(() =>
this.onStatus({ isFinished: true, hasError: false, error: null, url: this.uri }),
);
}, options.forDuration * 1000);
}

stop(): Promise<void> {
this.stopped ??= this.finish();
return this.stopped.then(() => undefined);
}

/** Stops the microphone without waiting for a recording; safe to call repeatedly. */
release(): void {
if (this.limitTimer) clearTimeout(this.limitTimer);
this.limitTimer = null;
for (const track of this.stream?.getTracks() ?? []) track.stop();
this.stream = null;
}

private finish(): Promise<string | null> {
const recorder = this.recorder;
if (!recorder || recorder.state === "inactive") {
this.release();
return Promise.resolve(this.uri);
}
return new Promise((resolve) => {
recorder.addEventListener(
"stop",
() => {
this.release();
this.uri = URL.createObjectURL(new Blob(this.chunks, { type: recorder.mimeType }));
this.chunks = [];
resolve(this.uri);
},
{ once: true },
);
recorder.stop();
});
}

private reportFailure(error: string): void {
if (this.recorder?.state !== "recording") return;
this.onStatus({ isFinished: false, hasError: true, error, url: null });
}
}
Loading