Skip to content

Open source CapCut alternative.

TypeScript

feat(site): voice dictation in Cut chat and generation prompts

David Le72e02337caa9
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index 003c330b..aa6971e3 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -14,6 +14,7 @@ import {
FolderPlus,
History,
Maximize2,
+ Mic,
Plus,
Sparkles,
Square,
@@ -62,8 +63,10 @@ import { useEditor } from "@/cut/lib/store";
import { cn } from "@/lib/utils";
import { cardIconButton } from "@/cut/components/iconButton";
import { MentionTextarea, RefChips, RefThumb, RefTokenChip } from "./AssetRefs";
+import { DictationBody } from "./MicDictation";
import { ToolOutputAssets } from "./ChatAssets";
import { HostedErrorText } from "./hostedError";
+import { useMicTranscription } from "@/cut/lib/micTranscribe";
// Chat attachments are asset refs — anything in the project, the library, or
// the stock catalog. They arrive by drag (media cards, library clips, stock
@@ -337,6 +340,11 @@ function ChatSession({
onModelChange: (id: string) => void;
}) {
const [input, setInput] = useState("");
+ // Live dictation → drops the finished transcript into the composer, appended
+ // after whatever the user had already typed.
+ const mic = useMicTranscription((text) =>
+ setInput((prev) => (prev.trim() ? `${prev.trim()} ${text}` : text))
+ );
const [attachments, setAttachments] = useState<AssetRef[]>([]);
const candidates = useRefCandidates();
// Any OS file drag over the window hints the composer as a drop target;
@@ -576,43 +584,63 @@ function ChatSession({
Drop to attach
</div>
)}
- <RefChips
- refs={attachments}
- onRemove={(ref) => setAttachments((p) => p.filter((x) => !sameRef(x, ref)))}
- className="px-2.5 pt-2.5"
- />
- <MentionTextarea
- className="ai-input max-h-40 min-h-[38px] w-full resize-none overflow-y-auto bg-transparent px-3 pt-2 text-[12.5px] leading-relaxed outline-none placeholder:text-muted-foreground/70"
- rows={2}
- autoGrow
- placeholder="Ask about your video, or tell me what to change… @ references media"
- value={input}
- onChange={setInput}
- candidates={candidates}
- submitKey="enter"
- menuSide="top"
- onSubmit={() => send(input)}
- />
- <div className="flex items-center gap-1 px-1.5 pb-1.5">
- <ModelSelector info={info} model={model} onSelect={onModelChange} />
- <div className="flex-1" />
- {busy ? (
- <Button variant="outline" size="sm" className="ai-stop" title="Stop" onClick={() => void stop()}>
- <Square className="size-3" />
- </Button>
- ) : (
- <Button
- size="sm"
- className="ai-send"
- title="Send (Enter)"
- disabled={(!input.trim() && attachments.length === 0) || !currentAvailable}
- onClick={() => send(input)}
- >
- <ArrowUp className="size-3.5" />
- </Button>
- )}
- </div>
+ {mic.state === "idle" ? (
+ <>
+ <RefChips
+ refs={attachments}
+ onRemove={(ref) => setAttachments((p) => p.filter((x) => !sameRef(x, ref)))}
+ className="px-2.5 pt-2.5"
+ />
+ <MentionTextarea
+ className="ai-input max-h-40 min-h-[38px] w-full resize-none overflow-y-auto bg-transparent px-3 pt-2 text-[12.5px] leading-relaxed outline-none placeholder:text-muted-foreground/70"
+ rows={2}
+ autoGrow
+ placeholder="Ask about your video, or tell me what to change… @ references media"
+ value={input}
+ onChange={setInput}
+ candidates={candidates}
+ submitKey="enter"
+ menuSide="top"
+ onSubmit={() => send(input)}
+ />
+ <div className="flex items-center gap-1 px-1.5 pb-1.5">
+ <ModelSelector info={info} model={model} onSelect={onModelChange} />
+ <div className="flex-1" />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="ai-mic text-muted-foreground"
+ title="Dictate"
+ disabled={busy}
+ onClick={() => void mic.start()}
+ >
+ <Mic className="size-3.5" />
+ </Button>
+ {busy ? (
+ <Button variant="outline" size="sm" className="ai-stop" title="Stop" onClick={() => void stop()}>
+ <Square className="size-3" />
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ className="ai-send"
+ title="Send (Enter)"
+ disabled={(!input.trim() && attachments.length === 0) || !currentAvailable}
+ onClick={() => send(input)}
+ >
+ <ArrowUp className="size-3.5" />
+ </Button>
+ )}
+ </div>
+ </>
+ ) : (
+ <DictationBody text={input} mic={mic} />
+ )}
</div>
+ {mic.error && (
+ <p className="mt-1.5 px-1 text-[10.5px] leading-relaxed text-amber-700">{mic.error}</p>
+ )}
{info && !currentAvailable && (
provider(model) === "gemini" ? (
<p className="ai-provider-note mt-1.5 px-1 text-[10.5px] leading-relaxed text-muted-foreground">
diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsx
index 25467740..ed852d57 100644
--- a/site/src/cut/components/AudioPanel.tsx
+++ b/site/src/cut/components/AudioPanel.tsx
@@ -20,6 +20,7 @@ import {
Trash2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
+import { DictationControl } from "@/cut/components/MicDictation";
import { SectionTitle } from "@/cut/components/SectionTitle";
import {
DropdownMenu,
@@ -240,12 +241,19 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
and why it's disabled until there's a script — is obvious. */}
<div className="flex flex-col gap-2">
<SectionTitle>Script</SectionTitle>
- <textarea
- className="voice-script min-h-[88px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"
- placeholder="What should the voice say?"
- value={script}
- onChange={(e) => setScript(e.target.value)}
- />
+ <div className="relative rounded-lg border border-input focus-within:border-ring">
+ <textarea
+ className="voice-script min-h-[88px] w-full resize-y rounded-lg bg-transparent px-2.5 py-2 pr-9 text-[12.5px] leading-relaxed outline-none"
+ placeholder="What should the voice say?"
+ value={script}
+ onChange={(e) => setScript(e.target.value)}
+ />
+ <DictationControl
+ text={script}
+ onResult={setScript}
+ buttonClassName="absolute right-1.5 bottom-2 bg-background/70 backdrop-blur-sm"
+ />
+ </div>
<Button
className="voice-generate w-full"
disabled={!script.trim() || signedOut}
@@ -450,7 +458,12 @@ export function AudioRow({
onDragEnd={onDragStart ? clearAssetDrag : undefined}
title={onDragStart ? "Drag onto the timeline, or click + to add" : undefined}
>
- <span className="pointer-events-none absolute top-[3px] right-14 left-8 truncate text-[9.5px] font-medium text-white/90 [text-shadow:0_1px_2px_rgba(0,0,0,0.35)]">
+ {/* Scrim so the name reads over the white waveform, not just the text-shadow. */}
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 top-0 h-5 rounded-t-[7px] bg-gradient-to-b from-black/45 via-black/25 to-transparent"
+ />
+ <span className="pointer-events-none absolute top-[3px] right-14 left-8 truncate text-[9.5px] font-medium text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.45)]">
{name}
</span>
<button
@@ -465,10 +478,12 @@ export function AudioRow({
>
{playing ? <Pause className="size-3" /> : <Play className="size-3" />}
</button>
- <span className="pointer-events-none absolute right-1.5 bottom-1 rounded-[5px] bg-black/40 px-1 py-px font-mono text-[9px] text-white tabular-nums">
+ {/* Steps aside when the hover controls take the right edge — the pill is
+ too short to stack both without them colliding. */}
+ <span className="pointer-events-none absolute right-1.5 bottom-1 rounded-[5px] bg-black/40 px-1 py-px font-mono text-[9px] text-white tabular-nums transition-opacity group-hover:opacity-0 has-data-popup-open:opacity-0">
{formatTime(duration)}
</span>
- <div className="absolute top-1 right-1 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100 has-data-popup-open:opacity-100">
+ <div className="absolute top-1/2 right-1.5 flex -translate-y-1/2 items-center gap-1.5 opacity-0 transition-opacity group-hover:opacity-100 has-data-popup-open:opacity-100">
{menu}
<button
type="button"
@@ -485,6 +500,10 @@ export function AudioRow({
);
}
+/** Voiceovers are minted as `AI voice — <lead>`; under the "Generated audio"
+ * heading the prefix is redundant, so show just the spoken lead here. */
+const voiceLabel = (name: string) => name.replace(/^AI voice\s*—\s*/, "");
+
function ProjectAudio({
projectId,
importing,
@@ -511,7 +530,7 @@ function ProjectAudio({
{audio.map((a) => (
<AudioRow
key={a.id}
- name={a.name}
+ name={voiceLabel(a.name)}
duration={a.duration}
url={a.url}
peaks={a.peaks}
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index 1325955b..fc317c43 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -28,6 +28,7 @@ import {
} from "@/cut/lib/videoGen";
import { cn } from "@/lib/utils";
import { MentionTextarea, RefChips, RefHandlePill } from "./AssetRefs";
+import { DictationControl } from "./MicDictation";
import { GeneratedAssetMenu } from "./GeneratedAssetMenu";
import { HostedErrorText } from "./hostedError";
import { cardIconButton } from "./iconButton";
@@ -135,7 +136,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
also highlights this box while a drag hovers the panel. */}
<div
className={cn(
- "flex shrink-0 flex-col rounded-lg border border-input focus-within:border-ring",
+ "relative flex shrink-0 flex-col rounded-lg border border-input focus-within:border-ring",
dropActive && "border-[#0a84ff] ring-2 ring-[#0a84ff]/30 ring-inset"
)}
>
@@ -166,7 +167,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
peekSide="bottom"
/>
<MentionTextarea
- className="gen-prompt min-h-[88px] w-full resize-y bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none"
+ className="gen-prompt min-h-[88px] w-full resize-y bg-transparent px-2.5 py-2 pr-9 text-[12.5px] leading-relaxed outline-none"
placeholder={
character
? "What should they say?"
@@ -179,6 +180,11 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
menuSide="bottom"
onSubmit={go}
/>
+ <DictationControl
+ text={prompt}
+ onResult={(v) => useVideoGen.getState().setPrompt(v)}
+ buttonClassName="absolute right-2 bottom-2 bg-background/70 backdrop-blur-sm"
+ />
</div>
{/* Which model renders the clip — a dropdown, since the catalog grows. */}
diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsx
index 70e1c37b..2fc4aa38 100644
--- a/site/src/cut/components/ImageGenPanel.tsx
+++ b/site/src/cut/components/ImageGenPanel.tsx
@@ -21,6 +21,7 @@ import { useEditor } from "@/cut/lib/store";
import type { MediaAsset } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { MentionTextarea, RefChips, RefHandlePill } from "./AssetRefs";
+import { DictationControl } from "./MicDictation";
import { cardIconButton } from "./iconButton";
import { PillSelect } from "./PillSelect";
import { GeneratedAssetMenu } from "./GeneratedAssetMenu";
@@ -103,7 +104,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
the input box, above the prompt (Claude-style). */}
<div
className={cn(
- "flex shrink-0 flex-col rounded-lg border border-input focus-within:border-ring",
+ "relative flex shrink-0 flex-col rounded-lg border border-input focus-within:border-ring",
dropActive && "border-[#0a84ff] ring-2 ring-[#0a84ff]/30 ring-inset"
)}
>
@@ -114,7 +115,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
peekSide="bottom"
/>
<MentionTextarea
- className="min-h-[100px] w-full resize-y bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none"
+ className="min-h-[100px] w-full resize-y bg-transparent px-2.5 py-2 pr-9 text-[12.5px] leading-relaxed outline-none"
placeholder="A neon-lit street market at night, cinematic… Drop an image in or type @ to reference one."
value={prompt}
onChange={(v) => useImageGen.getState().setPrompt(v)}
@@ -123,6 +124,11 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
menuSide="bottom"
onSubmit={go}
/>
+ <DictationControl
+ text={prompt}
+ onResult={(v) => useImageGen.getState().setPrompt(v)}
+ buttonClassName="absolute right-2 bottom-2 bg-background/70 backdrop-blur-sm"
+ />
</div>
{/* Aspect ratio and resolution pills on one row. Closed pills stay short
diff --git a/site/src/cut/components/MicDictation.tsx b/site/src/cut/components/MicDictation.tsx
new file mode 100644
index 00000000..0055bdcd
--- /dev/null
+++ b/site/src/cut/components/MicDictation.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { Check, Mic, X } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { useMicTranscription, type MicController } from "@/cut/lib/micTranscribe";
+import { LiveWaveform } from "./RecordDialog";
+
+// Shared voice-dictation UI, used by every prompt input (the AI chat composer
+// and the image / video / audio generation prompts). The capture + on-device
+// transcription live in lib/micTranscribe.ts; this is the presentation:
+// - DictationBody: the read-only live transcript over a level meter, with
+// cancel (✕) and use (✓). The chat renders it inline; embedded inputs render
+// it inside an overlay.
+// - DictationControl: a mic trigger plus that overlay, for dropping into any
+// input whose container is `relative`.
+
+/** Append a fresh transcript after whatever the user had already typed. */
+export function appendTranscript(existing: string, transcript: string): string {
+ const base = existing.trim();
+ return base ? `${base} ${transcript}` : transcript;
+}
+
+/** The live transcript + waveform + controls. `text` is the input's current
+ * value, shown muted alongside the evolving partial. */
+export function DictationBody({
+ text,
+ mic,
+ className,
+}: {
+ text: string;
+ mic: MicController;
+ className?: string;
+}) {
+ const shown = [text.trim(), mic.partial].filter(Boolean).join(" ");
+ const finishing = mic.state === "finishing";
+ return (
+ <div className={cn("flex min-h-[72px] flex-col", className)}>
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 pt-2.5">
+ <p className="text-[12.5px] leading-relaxed text-muted-foreground/80 italic">
+ {shown || "Listening…"}
+ </p>
+ </div>
+ <div className="flex items-center gap-2 px-2 pt-1 pb-2">
+ {mic.stream ? (
+ <LiveWaveform
+ stream={mic.stream}
+ sampleMs={130}
+ className="h-7 min-w-0 flex-1 text-muted-foreground/70"
+ />
+ ) : (
+ <div className="flex-1" />
+ )}
+ <button
+ type="button"
+ title="Cancel"
+ disabled={finishing}
+ onClick={mic.cancel}
+ className="grid size-7 place-items-center rounded-lg bg-muted text-muted-foreground transition-colors hover:bg-muted/70 disabled:opacity-50"
+ >
+ <X className="size-3.5" />
+ </button>
+ <button
+ type="button"
+ title="Use transcription"
+ disabled={finishing}
+ onClick={() => void mic.confirm()}
+ className="grid size-7 place-items-center rounded-lg bg-[#0a84ff] text-white transition-colors hover:bg-[#0a84ff]/90 disabled:opacity-50"
+ >
+ <Check className="size-3.5" />
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/** A mic trigger that, while recording, overlays its input with the live
+ * transcript. Drop it inside a `relative` container; on confirm the transcript
+ * is appended to `text` via `onResult`. */
+export function DictationControl({
+ text,
+ onResult,
+ buttonClassName,
+ disabled,
+}: {
+ text: string;
+ onResult: (transcript: string) => void;
+ buttonClassName?: string;
+ disabled?: boolean;
+}) {
+ const mic = useMicTranscription((t) => onResult(appendTranscript(text, t)));
+ return (
+ <>
+ {mic.state !== "idle" && (
+ <div className="absolute inset-0 z-20 overflow-hidden rounded-[inherit] bg-background/95 backdrop-blur-sm">
+ <DictationBody text={text} mic={mic} className="h-full" />
+ </div>
+ )}
+ {mic.state === "idle" && (
+ <button
+ type="button"
+ title="Dictate"
+ disabled={disabled}
+ onClick={() => void mic.start()}
+ className={cn(
+ "grid size-7 place-items-center rounded-md text-muted-foreground/70 transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40",
+ buttonClassName
+ )}
+ >
+ <Mic className="size-3.5" />
+ </button>
+ )}
+ {mic.error && mic.state === "idle" && (
+ <div className="absolute right-1 bottom-full z-30 mb-1 max-w-[240px] rounded-md bg-popover px-2 py-1 text-[10.5px] leading-snug text-amber-700 shadow-md">
+ {mic.error}
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/site/src/cut/components/RecordDialog.tsx b/site/src/cut/components/RecordDialog.tsx
index 22bdaac9..00152d7f 100644
--- a/site/src/cut/components/RecordDialog.tsx
+++ b/site/src/cut/components/RecordDialog.tsx
@@ -390,8 +390,19 @@ function DevicePill({
// RMS below this reads as silence and draws no bar.
const SILENCE = 0.015;
-/** Scrolling level meter fed by the stream's audio track; color follows CSS `color`. */
-function LiveWaveform({ stream, className }: { stream: MediaStream; className?: string }) {
+/** Scrolling level meter fed by the stream's audio track; color follows CSS `color`.
+ * `sampleMs` sets how much time each bar spans — larger values scroll slower and
+ * cover a longer window (the loudest moment in the window wins). Omitted, it
+ * advances one bar per animation frame (the record dialog's original feel). */
+export function LiveWaveform({
+ stream,
+ className,
+ sampleMs,
+}: {
+ stream: MediaStream;
+ className?: string;
+ sampleMs?: number;
+}) {
const canvasRef = useRef<HTMLCanvasElement>(null);
// Bar color follows CSS `color`. Resolve it only when the className changes
// (i.e. when `recording` toggles) instead of every animation frame.
@@ -412,8 +423,10 @@ function LiveWaveform({ stream, className }: { stream: MediaStream; className?:
const samples = new Uint8Array(analyser.fftSize);
const levels: number[] = [];
let raf = 0;
+ let lastPush = 0;
+ let peak = 0;
- const draw = () => {
+ const draw = (ts: number) => {
raf = requestAnimationFrame(draw);
analyser.getByteTimeDomainData(samples);
let sum = 0;
@@ -431,11 +444,6 @@ function LiveWaveform({ stream, className }: { stream: MediaStream; className?:
const barWidth = 3 * dpr;
const step = barWidth + 2 * dpr;
const maxBars = Math.max(1, Math.floor(width / step));
- levels.push(rms);
- // Pad the history so the meter spans the full frame from the first frame
- // instead of growing in from the right; padding reads as idle dots.
- while (levels.length < maxBars) levels.unshift(0);
- if (levels.length > maxBars) levels.splice(0, levels.length - maxBars);
const g = canvas.getContext("2d");
if (!g) return;
@@ -444,26 +452,50 @@ function LiveWaveform({ stream, className }: { stream: MediaStream; className?:
// Idle input draws a row of small centered dots so the meter reads as a
// ready track spanning the whole width; sound grows each into a bar.
const idle = barWidth;
- for (let i = 0; i < levels.length; i++) {
- const x = width - (levels.length - i) * step;
- const h =
- levels[i] >= SILENCE
- ? Math.max(idle, Math.min(1, levels[i] * 3) * height)
- : idle;
+ const bar = (x: number, level: number) => {
+ if (x + barWidth < 0 || x > width) return;
+ const h = level >= SILENCE ? Math.max(idle, Math.min(1, level * 3) * height) : idle;
const r = Math.min(barWidth / 2, h / 2);
g.beginPath();
g.roundRect(x, (height - h) / 2, barWidth, h, r);
g.fill();
+ };
+
+ if (!sampleMs) {
+ // Record dialog: one bar per frame, right-aligned (its original feel).
+ levels.push(rms);
+ while (levels.length < maxBars) levels.unshift(0);
+ if (levels.length > maxBars) levels.splice(0, levels.length - maxBars);
+ for (let i = 0; i < levels.length; i++) bar(width - (levels.length - i) * step, levels[i]);
+ return;
}
+
+ // Commit one bar per `sampleMs` (that's the time scale) but slide the whole
+ // strip left every frame by the fraction of the window elapsed, so motion
+ // is continuous instead of ticking a full bar at once. Committed bars hold
+ // the window's peak; a forming bar at the right edge tracks the live level.
+ if (lastPush === 0) lastPush = ts;
+ peak = Math.max(peak, rms);
+ if (ts - lastPush >= sampleMs) {
+ levels.push(peak);
+ peak = 0;
+ lastPush = ts;
+ }
+ while (levels.length < maxBars + 1) levels.unshift(0);
+ if (levels.length > maxBars + 2) levels.splice(0, levels.length - (maxBars + 2));
+ const offset = Math.min(1, (ts - lastPush) / sampleMs) * step;
+ const n = levels.length;
+ for (let i = 0; i < n; i++) bar(width - step - (n - i) * step - offset, levels[i]);
+ bar(width - step - offset, rms);
};
- draw();
+ raf = requestAnimationFrame(draw);
return () => {
cancelAnimationFrame(raf);
source.disconnect();
void audioCtx.close().catch(() => {});
};
- }, [stream]);
+ }, [stream, sampleMs]);
return <canvas ref={canvasRef} className={className} />;
}
diff --git a/site/src/cut/lib/micTranscribe.ts b/site/src/cut/lib/micTranscribe.ts
new file mode 100644
index 00000000..f6b9f81f
--- /dev/null
+++ b/site/src/cut/lib/micTranscribe.ts
@@ -0,0 +1,225 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { apiFetch } from "./api";
+
+// Live dictation for the chat composer. The browser holds the mic permission,
+// so it captures audio here and streams 16 kHz mono s16le PCM to the local
+// engine, which runs it through Apple's on-device SpeechAnalyzer (see
+// server/mic.ts + native/cut-stt.swift). The transcript never leaves the Mac.
+
+export type MicState = "idle" | "starting" | "recording" | "finishing";
+
+const TARGET_RATE = 16000; // must match cut-stt.swift's live input format
+const FEED_MS = 250; // how often queued PCM is flushed to the engine
+const POLL_MS = 150; // how often the evolving transcript is fetched
+
+/** Average-downsample Float32 PCM to 16 kHz signed-16-bit little-endian. */
+function toPcm16(input: Float32Array, srcRate: number): Int16Array {
+ const ratio = srcRate / TARGET_RATE;
+ const outLen = Math.floor(input.length / ratio);
+ const out = new Int16Array(outLen);
+ for (let i = 0; i < outLen; i++) {
+ const start = Math.floor(i * ratio);
+ const end = Math.min(input.length, Math.floor((i + 1) * ratio));
+ let sum = 0;
+ for (let j = start; j < end; j++) sum += input[j];
+ const v = Math.max(-1, Math.min(1, sum / Math.max(1, end - start)));
+ out[i] = v < 0 ? v * 0x8000 : v * 0x7fff;
+ }
+ return out;
+}
+
+export interface MicController {
+ state: MicState;
+ /** Live stream while recording (for the waveform); null otherwise. */
+ stream: MediaStream | null;
+ /** Evolving transcript while recording. */
+ partial: string;
+ error: string | null;
+ /** Begin capturing + transcribing. */
+ start: () => Promise<void>;
+ /** Finish, resolve the final transcript, and hand it to `onResult`. */
+ confirm: () => Promise<void>;
+ /** Discard the dictation. */
+ cancel: () => void;
+}
+
+export function useMicTranscription(onResult: (text: string) => void): MicController {
+ const [state, setState] = useState<MicState>("idle");
+ const [stream, setStream] = useState<MediaStream | null>(null);
+ const [partial, setPartial] = useState("");
+ const [error, setError] = useState<string | null>(null);
+
+ const jobRef = useRef<string | null>(null);
+ const streamRef = useRef<MediaStream | null>(null);
+ const ctxRef = useRef<AudioContext | null>(null);
+ const nodesRef = useRef<{ source: MediaStreamAudioSourceNode; processor: ScriptProcessorNode } | null>(null);
+ const queueRef = useRef<Int16Array[]>([]);
+ const feedingRef = useRef(false);
+ const feedTimer = useRef<ReturnType<typeof setInterval> | null>(null);
+ const pollTimer = useRef<ReturnType<typeof setInterval> | null>(null);
+ const onResultRef = useRef(onResult);
+ onResultRef.current = onResult;
+
+ const teardownAudio = useCallback(() => {
+ if (feedTimer.current) clearInterval(feedTimer.current);
+ if (pollTimer.current) clearInterval(pollTimer.current);
+ feedTimer.current = null;
+ pollTimer.current = null;
+ nodesRef.current?.processor.disconnect();
+ nodesRef.current?.source.disconnect();
+ nodesRef.current = null;
+ void ctxRef.current?.close().catch(() => {});
+ ctxRef.current = null;
+ streamRef.current?.getTracks().forEach((t) => t.stop());
+ streamRef.current = null;
+ queueRef.current = [];
+ feedingRef.current = false;
+ setStream(null);
+ }, []);
+
+ /** Concatenate and POST all queued PCM. Guarded so chunks stay ordered. */
+ const flush = useCallback(async () => {
+ const job = jobRef.current;
+ if (!job || feedingRef.current || queueRef.current.length === 0) return;
+ feedingRef.current = true;
+ const chunks = queueRef.current;
+ queueRef.current = [];
+ const total = chunks.reduce((n, c) => n + c.length, 0);
+ const merged = new Int16Array(total);
+ let off = 0;
+ for (const c of chunks) {
+ merged.set(c, off);
+ off += c.length;
+ }
+ try {
+ await apiFetch(`/api/cut/mic/${job}/feed`, {
+ method: "POST",
+ headers: { "Content-Type": "application/octet-stream" },
+ body: merged.buffer,
+ });
+ } catch {
+ // A dropped chunk just shortens the transcript; keep the dictation alive.
+ } finally {
+ feedingRef.current = false;
+ }
+ }, []);
+
+ const start = useCallback(async () => {
+ if (state !== "idle") return;
+ setError(null);
+ setPartial("");
+ setState("starting");
+ let media: MediaStream;
+ try {
+ media = await navigator.mediaDevices.getUserMedia({ audio: true });
+ } catch {
+ setState("idle");
+ setError("Microphone access was blocked. Allow the microphone for this site, then try again.");
+ return;
+ }
+ try {
+ const res = await apiFetch("/api/cut/mic/start", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ });
+ const data = (await res.json().catch(() => ({}))) as { id?: string; error?: string };
+ if (!res.ok || !data.id) throw new Error(data.error || "Dictation needs the Donkey app running on this Mac.");
+ jobRef.current = data.id;
+ } catch (e) {
+ media.getTracks().forEach((t) => t.stop());
+ setState("idle");
+ setError(e instanceof Error ? e.message : "Could not start dictation.");
+ return;
+ }
+
+ streamRef.current = media;
+ setStream(media);
+
+ const ctx = new AudioContext();
+ void ctx.resume().catch(() => {});
+ ctxRef.current = ctx;
+ const source = ctx.createMediaStreamSource(media);
+ const processor = ctx.createScriptProcessor(4096, 1, 1);
+ processor.onaudioprocess = (e) => {
+ queueRef.current.push(toPcm16(e.inputBuffer.getChannelData(0), ctx.sampleRate));
+ };
+ // Route through a muted gain so onaudioprocess fires without echoing the mic.
+ const mute = ctx.createGain();
+ mute.gain.value = 0;
+ source.connect(processor);
+ processor.connect(mute);
+ mute.connect(ctx.destination);
+ nodesRef.current = { source, processor };
+
+ feedTimer.current = setInterval(() => void flush(), FEED_MS);
+ pollTimer.current = setInterval(async () => {
+ const job = jobRef.current;
+ if (!job) return;
+ try {
+ const res = await apiFetch(`/api/cut/mic/${job}`);
+ if (!res.ok) return;
+ const data = (await res.json()) as { text?: string; status?: string; error?: string };
+ if (typeof data.text === "string") setPartial(data.text);
+ if (data.status === "error" && data.error) setError(data.error);
+ } catch {
+ // Transient poll failure; the next tick retries.
+ }
+ }, POLL_MS);
+
+ setState("recording");
+ }, [state, flush]);
+
+ const confirm = useCallback(async () => {
+ const job = jobRef.current;
+ if (!job || state !== "recording") return;
+ setState("finishing");
+ // Stop pulling new audio, flush what's queued, then close the input so the
+ // model emits its final text.
+ nodesRef.current?.processor.disconnect();
+ if (feedTimer.current) clearInterval(feedTimer.current);
+ if (pollTimer.current) clearInterval(pollTimer.current);
+ feedTimer.current = null;
+ pollTimer.current = null;
+ // Wait out any in-flight feed, then drain the tail.
+ while (feedingRef.current) await new Promise((r) => setTimeout(r, 20));
+ await flush();
+ let text = "";
+ try {
+ const res = await apiFetch(`/api/cut/mic/${job}/stop`, { method: "POST" });
+ const data = (await res.json().catch(() => ({}))) as { text?: string };
+ text = data.text ?? "";
+ } catch {
+ text = partial;
+ }
+ jobRef.current = null;
+ teardownAudio();
+ setState("idle");
+ setPartial("");
+ const trimmed = text.trim();
+ if (trimmed) onResultRef.current(trimmed);
+ }, [state, flush, partial, teardownAudio]);
+
+ const cancel = useCallback(() => {
+ const job = jobRef.current;
+ jobRef.current = null;
+ if (job) void apiFetch(`/api/cut/mic/${job}/cancel`, { method: "POST" }).catch(() => {});
+ teardownAudio();
+ setState("idle");
+ setPartial("");
+ setError(null);
+ }, [teardownAudio]);
+
+ // Abandon a dictation if the composer unmounts mid-recording.
+ useEffect(() => {
+ return () => {
+ const job = jobRef.current;
+ if (job) void apiFetch(`/api/cut/mic/${job}/cancel`, { method: "POST" }).catch(() => {});
+ teardownAudio();
+ };
+ }, [teardownAudio]);
+
+ return { state, stream, partial, error, start, confirm, cancel };
+}