Open source CapCut alternative.
TypeScript
feat(site): run speech on this Mac for cloud projects [rebuild]
David Le2d2521d986ce
diff --git a/docs/README.md b/docs/README.mdindex a943ffc2..fc643c73 100644--- a/docs/README.md+++ b/docs/README.md@@ -15,6 +15,7 @@ Supported product and engineering guides live in `docs/guides/`. This list is th- [Cut](guides/cut/README.md) — the video editor: what runs in the browser, what runs on the Mac, and the local resources behind it.- [Cut's AI Assistant](guides/cut/ai-assistant.md) — how a chat turn runs: the providers, the tool bridge into the editor, what the model knows, and the context budgets.- [Brief to Video](guides/cut/brief-to-video.md) — the director pipeline's strategy: story planning, the identity ladder that keeps a cast consistent, and where audio goes next.+- [Local Compute for Cloud Projects](guides/cut/local-compute.md) — why a cloud project uses the Mac when there is one, and the rule that keeps its data in the cloud regardless.**Site and backend**diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 2a1574e4..d2c2b274 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -40,7 +40,7 @@ A dropped file does not wait for that upload. Because a presign claims the storeStorage a subscription paid for outlives the subscription for a while: when Pro ends and the account still holds more than the free tier, it keeps everything for thirty days, warned in the editor and on the projects home. After that the daily sweep brings it back under the cap — least-recently-updated projects first, then the oldest library assets, stopping the moment it fits — so what survives is the recent work, and an account already under the cap is never touched.-A cloud project can be shared read-only, Google-Docs style: the editor's Share dialog invites specific emails (viewers sign in) or opens the link to anyone (no sign-in), and switches opt extra surfaces in — chat, media, AI generations, subtitles, details — on top of the always-shared preview and timeline. The share row's id is the link token, so revoking deletes the link. Viewers ride a third backend driver against `/api/cut-shared/<token>/*`, a deliberately public API surface (the one exception to session auth on the cloud side): the server resolves access per request, filters the doc to the shared surfaces before it leaves, and refuses media outside that filter, so hiding is enforced by the backend rather than the client. A public share's reads are cached at the edge for a lifetime that tracks how long the owner has been idle — a doc saved seconds ago is served near-live, one untouched for an hour is served from cache for minutes — and the same number is handed back as the viewer's poll interval, so a link a crowd opens costs a handful of origin requests rather than one per viewer per tick. A restricted share's reads depend on the viewer's session, so they are never cached. A shared project's media is served from Cloudflare's edge rather than presigned against R2's S3 endpoint, which nothing caches: a Worker holding a private bucket binding checks a short token the hosted API mints, then answers from cache keyed on the object alone. Dropping the token from the cache key is what makes the token affordable to keep short — every viewer and every re-mint share one cached copy — and a short token is what makes unsharing mean something, since a presigned URL is a bearer credential nothing can withdraw before it expires. Owner-side editing still presigns R2 directly, where the URLs are minted on fixed windows so a browser can reuse bytes across reloads. A shared link unfurls with the project's own card: the render worker derives a first-frame still and a five-second animation from the opening of the cut, the page's metadata points at them through a URL carrying the doc version, and a project with no card yet gets a drawn one. Viewers poll the doc version on an interval the server picks — shared views trail live edits, they don't stream them — and a "Copy project" action duplicates everything the share exposes — the filtered doc, its media, and the chat threads when chat is shared — server-side into the viewer's own account and quota. Copies queue rather than run in the request: each request writes a job row and publishes it to a Cloudflare Queue whose serial consumer executes one copy at a time, so a burst of copy requests can't stampede storage; the client polls the job for the outcome. An owner duplicating their own cloud project from the dashboard rides the same queue. Exports, hover-preview proxies, share cards, and URL imports run on the render worker — a container (`site/src/cut/worker/`) that claims job rows from Postgres, reuses the engine's exact ffmpeg pipeline against R2, and reports progress back through the rows the client polls. Transcription and mic dictation call a hosted, credit-metered route that has Gemini produce cue-level timestamps from browser-rendered audio chunks; word timings are interpolated within each cue. The assistant offers its Gemini models (which already run entirely in the page); the Claude/Codex CLI providers stay app-only because they are the user's local logins.+A cloud project can be shared read-only, Google-Docs style: the editor's Share dialog invites specific emails (viewers sign in) or opens the link to anyone (no sign-in), and switches opt extra surfaces in — chat, media, AI generations, subtitles, details — on top of the always-shared preview and timeline. The share row's id is the link token, so revoking deletes the link. Viewers ride a third backend driver against `/api/cut-shared/<token>/*`, a deliberately public API surface (the one exception to session auth on the cloud side): the server resolves access per request, filters the doc to the shared surfaces before it leaves, and refuses media outside that filter, so hiding is enforced by the backend rather than the client. A public share's reads are cached at the edge for a lifetime that tracks how long the owner has been idle — a doc saved seconds ago is served near-live, one untouched for an hour is served from cache for minutes — and the same number is handed back as the viewer's poll interval, so a link a crowd opens costs a handful of origin requests rather than one per viewer per tick. A restricted share's reads depend on the viewer's session, so they are never cached. A shared project's media is served from Cloudflare's edge rather than presigned against R2's S3 endpoint, which nothing caches: a Worker holding a private bucket binding checks a short token the hosted API mints, then answers from cache keyed on the object alone. Dropping the token from the cache key is what makes the token affordable to keep short — every viewer and every re-mint share one cached copy — and a short token is what makes unsharing mean something, since a presigned URL is a bearer credential nothing can withdraw before it expires. Owner-side editing still presigns R2 directly, where the URLs are minted on fixed windows so a browser can reuse bytes across reloads. A shared link unfurls with the project's own card: the render worker derives a first-frame still and a five-second animation from the opening of the cut, the page's metadata points at them through a URL carrying the doc version, and a project with no card yet gets a drawn one. Viewers poll the doc version on an interval the server picks — shared views trail live edits, they don't stream them — and a "Copy project" action duplicates everything the share exposes — the filtered doc, its media, and the chat threads when chat is shared — server-side into the viewer's own account and quota. Copies queue rather than run in the request: each request writes a job row and publishes it to a Cloudflare Queue whose serial consumer executes one copy at a time, so a burst of copy requests can't stampede storage; the client polls the job for the outcome. An owner duplicating their own cloud project from the dashboard rides the same queue. Exports, hover-preview proxies, share cards, and URL imports run on the render worker — a container (`site/src/cut/worker/`) that claims job rows from Postgres, reuses the engine's exact ffmpeg pipeline against R2, and reports progress back through the rows the client polls. Transcription and mic dictation prefer this Mac: with the app running they use on-device speech even for a cloud project, and fall back to a hosted, credit-metered route — Gemini producing cue-level timestamps from browser-rendered audio, word timings interpolated inside each cue — when it isn't. That split between where a project's data lives and where its work runs is its own guide: [Local compute for cloud projects](local-compute.md). The assistant offers its Gemini models (which already run entirely in the page); the Claude/Codex CLI providers stay app-only because they are the user's local logins.## One API surface, one routerdiff --git a/docs/guides/cut/local-compute.md b/docs/guides/cut/local-compute.mdnew file mode 100644index 00000000..1f299e99--- /dev/null+++ b/docs/guides/cut/local-compute.md@@ -0,0 +1,59 @@+# Local Compute for Cloud Projects++A cloud project stores its document in Postgres and its media in R2, and it still uses the Mac when there is one. Speech is the case that matters today: transcription and dictation run on device whenever the Donkey app is running, even for a project whose media the engine has never seen. The user pays nothing for that work, gets it faster, and gets better timings out of it.++**The one rule:** compute never decides where data lands. Whoever does the work, the result goes back to the project's own backend — cues into the cloud document, a render into R2. A locally run job that finishes in a folder on the Mac and leaves the cloud project none the wiser breaks the rule.++## How it works++Where a project's data lives and who does its work are two separate decisions. Residency is a fact about the project, fixed when it is created. Compute is decided per job, at the moment the user asks for it, and the Mac wins whenever it is there.++```+cloud project, user asks for subtitles+ │+ browser renders the audible mix+ │+ ├─ the app answered ──▶ on-device speech on the Mac — free, real word timings+ │ │+ └─ no app ────────────▶ hosted speech — credits, timings interpolated per cue+ │+ ▼+ cues into the cloud document+```++The project's backend decides *where the result lives*; the app's presence decides *who does the work*.++## Availability++Availability is the probe the client already runs — the app's engine answered on this machine, or the page is served by it. Nothing new is asked of the browser, which matters: a hosted page's calls to the local machine are permission-gated, so the client probes only where that raises no prompt. No app, no probe, or a browser blocking the connection all read the same way, and the work goes hosted.++## Speech++The engine transcribes a rendered mix, not a timeline, and that is what makes this work for a project it doesn't store. For a cloud project the browser renders the mix itself — the same trims, speeds, volumes, and crossfades the engine's ffmpeg graph applies — and posts the audio to the Mac, which runs on-device speech over it and answers with cues. The engine reads nothing from R2 and learns nothing about the project.++Dictation is the same trade in the other direction: with the app running, mic audio streams to the engine live and the transcript evolves as the user speaks; without it, the take is recorded, sent up in one piece, and arrives when it arrives.++## Export++Export still runs hosted for cloud projects, on the render worker. Moving it to the Mac is the same shape as speech with two extra pieces: the engine has to pull each clip from a signed URL before it can render, and push the finished file back up to storage after.++## Rules++1. **Local is an optimization, never a requirement.** Every job routed to the Mac has a hosted path behind it. An engine that never answered, or one that fails the job, means the work goes hosted — the user hears about a failure only when both paths fail.+2. **The result lands where the project lives.** A job's output is addressed to the project's own backend, chosen from the project id, never from whatever the app happens to be bound to when the job finishes.+3. **Credits follow the work.** Metering belongs to the hosted route, not to the feature. Work done on the Mac spends nothing, and the user is never asked to choose.+4. **Silence about the machine.** The editor says what it is doing, not which computer is doing it. Closing the app mid-session makes the next job slower, not different.++## What runs where++| Work | Runs | Why |+| --- | --- | --- |+| Transcription, dictation | the Mac when it is there, hosted otherwise | the app ships the speech tool |+| Export, encoding, thumbnails | the Mac for its own projects, hosted for cloud ones | see Export above |+| Image, video, and voice generation | hosted, always | no local counterpart |+| The assistant's Gemini models | hosted, always | credits and the user's session |+| The assistant's Claude and Codex providers | the Mac, always | the user's own CLI logins |++## Where it lives++The client's backend seam picks the compute target beside the per-project driver, the browser-side mix render sits with the transcription client code, and the engine's speech handlers take work for a project they do not store.diff --git a/site/src/cut/lib/backend/index.ts b/site/src/cut/lib/backend/index.tsindex 824d1b11..ae76ab1f 100644--- a/site/src/cut/lib/backend/index.ts+++ b/site/src/cut/lib/backend/index.ts@@ -5,6 +5,7 @@//// This module stays React-free: the engine binary compiles lib/types.ts, which// imports apiUrl from here. React hooks live in ./hooks.+import { engineOrigin, servedFromEngine } from "../api";import { cloudBackend } from "./cloud";import { localBackend } from "./local";import { sharedBackend } from "./shared";@@ -70,6 +71,18 @@ export function getBackend(): CutBackend {return mode === "cloud" ? cloudBackend : mode === "shared" ? sharedBackend : localBackend;}+/**+ * Whether work can run on this Mac: the gate resolved the engine's origin, or+ * the page is served by it. Where a job *runs* is a separate question from+ * where the project's data lives — speech and encoding belong on the Mac+ * whenever the app is there, even for a cloud project, because it costs the+ * user nothing and answers faster. The result still lands through the+ * project's own backend, so where the work ran never decides where data goes.+ */+export function hasLocalCompute(): boolean {+ return servedFromEngine() || engineOrigin() !== "";+}+/** fetch() against the active backend. */export const apiFetch = (path: string, init?: RequestInit) => getBackend().fetch(path, init);diff --git a/site/src/cut/lib/cloudTranscribe.ts b/site/src/cut/lib/cloudTranscribe.tsindex 32590d78..810f3d19 100644--- a/site/src/cut/lib/cloudTranscribe.ts+++ b/site/src/cut/lib/cloudTranscribe.ts@@ -1,13 +1,14 @@"use client";-// Hosted transcription. The cloud backend has no on-device speech engine, so-// the browser does the audio work itself: render the timeline's audible mix-// with an OfflineAudioContext (the same trims/speeds/volumes/crossfades the-// engine's ffmpeg graph applies — see server/transcribe.ts), chunk it as-// 16 kHz mono WAV, POST each chunk to the metered /transcribe route, then-// stitch the returned cues back into timeline time and interpolate per-word-// timings. Mic dictation reuses the same chunk/post/stitch core on a-// MediaRecorder capture.+// Browser-side audio work for a project whose media the engine doesn't hold,+// and the hosted transcriber that goes with it. Rendering the mix is shared:+// an OfflineAudioContext applies the same trims, speeds, volumes, and+// crossfades the engine's ffmpeg graph does (see server/transcribe.ts), so the+// result is the cut's audible mix in timeline time — whether it then goes to+// this Mac (localStt.ts) or to the metered hosted route. The hosted path+// chunks it as 16 kHz mono WAV, POSTs each chunk, stitches the cues back into+// timeline time, and interpolates per-word timings. Mic dictation reuses the+// same chunk/post/stitch core on a MediaRecorder capture.import { apiFetch } from "./backend";import { mediaUrl, type SubtitleCue } from "./types";@@ -50,7 +51,10 @@ const clipDur = (c: CloudTranscribeSpec["clips"][number]) =>* at their absolute starts with their volumes, and speed rides playbackRate* (pitch shifts where atempo would preserve it — timing, which is what cue* placement needs, is identical). Returns null when nothing audible exists. */-async function renderMix(projectId: string, spec: CloudTranscribeSpec): Promise<AudioBuffer | null> {+export async function renderMix(+ projectId: string,+ spec: CloudTranscribeSpec+): Promise<AudioBuffer | null> {const ctx = new OfflineAudioContext(1, Math.max(1, Math.ceil(spec.duration * RATE)), RATE);const files = [...new Set([...spec.clips, ...spec.audio].map((c) => c.file).filter(Boolean))];const buffers = new Map<string, AudioBuffer>();@@ -213,7 +217,7 @@ function interpolateWords(* decides ownership — cues whose center falls in the earlier chunk's half are* dropped from the later one (and vice versa), so seams never duplicate.* Returns null when `isStale` trips mid-run. */-async function transcribeSamples(+export async function transcribeSamples(samples: Float32Array,locale: string | undefined,isStale?: () => boolean@@ -251,23 +255,6 @@ async function transcribeSamples(return cues.sort((a, b) => a.start - b.start);}-/** Cloud twin of the engine transcribe job: render the spec's audible mix in- * the browser, transcribe it chunk by chunk, and return timeline-timed cues.- * Returns null when `isStale` trips (caller switched projects mid-run). */-export async function cloudTranscribeSpec(- projectId: string,- spec: CloudTranscribeSpec,- isStale: () => boolean-): Promise<SubtitleCue[] | null> {- if (spec.clips.length === 0 && spec.audio.length === 0) {- throw new Error("Add audio or video to the timeline first.");- }- const mix = await renderMix(projectId, spec);- if (isStale()) return null;- if (!mix) return []; // nothing audible — no speech, like the engine's short-circuit- return transcribeSamples(mix.getChannelData(0), spec.locale, isStale);-}-/** Transcribe a finished mic recording: decode it, downmix/resample to the* wire format, run the chunk pipeline, and join the cue texts. */export async function cloudTranscribeRecording(blob: Blob, locale?: string): Promise<string> {diff --git a/site/src/cut/lib/genvideo/adapters/transcribe.ts b/site/src/cut/lib/genvideo/adapters/transcribe.tsindex 7140d4fc..5e8da31e 100644--- a/site/src/cut/lib/genvideo/adapters/transcribe.ts+++ b/site/src/cut/lib/genvideo/adapters/transcribe.ts@@ -1,9 +1,11 @@"use client";/**- * Transcription over the engine's on-device STT (Apple SpeechAnalyzer via- * cut-stt) — the same route (and poller) the subtitle tools use. Nothing- * leaves the machine.+ * Transcription through the same path the subtitle tools use, which prefers+ * this Mac's on-device speech (Apple SpeechAnalyzer via cut-stt) and falls+ * back to the hosted route when the app isn't running. Word timings are what+ * the shot cuts are built from, so the on-device path matters here: it reports+ * real ones where the hosted route interpolates them inside a cue.** The route transcribes a rendered mix, so we hand it a one-entry spec that* renders just the target audio asset: provided-mode ("animate this audio")diff --git a/site/src/cut/lib/localStt.ts b/site/src/cut/lib/localStt.tsnew file mode 100644index 00000000..851bfb43--- /dev/null+++ b/site/src/cut/lib/localStt.ts@@ -0,0 +1,46 @@+"use client";++// On-device speech for a project the engine does not store. A cloud project's+// media lives in R2, so the browser renders its audible mix (cloudTranscribe.ts)+// and hands the audio to this Mac's engine instead of the metered hosted route.+// The engine answers with the same cues the local-project path produces —+// carrying real word timings, which the hosted route can only interpolate.++import { localBackend } from "./backend/local";+import { encodeWav } from "./cloudTranscribe";+import type { SubtitleCue } from "./types";++const POLL_MS = 700;++/** Transcribe a rendered mix on this Mac. Returns null when `isStale` trips+ * (the caller moved on); throws when the engine can't do it, which is the+ * caller's cue to fall back to the hosted route. */+export async function engineTranscribeSamples(+ samples: Float32Array,+ duration: number,+ locale: string | undefined,+ isStale?: () => boolean+): Promise<SubtitleCue[] | null> {+ const form = new FormData();+ form.append("audio", new File([encodeWav(samples)], "mix.wav", { type: "audio/wav" }));+ form.append("duration", String(duration));+ if (locale) form.append("locale", locale);+ const res = await localBackend.fetch("/api/cut/stt", { method: "POST", body: form });+ const body = (await res.json().catch(() => null)) as { id?: string; error?: string } | null;+ if (!res.ok || !body?.id) {+ throw new Error(body?.error ?? "On-device transcription failed to start.");+ }+ for (;;) {+ await new Promise((r) => setTimeout(r, POLL_MS));+ if (isStale?.()) return null;+ const st = await localBackend.fetch(`/api/cut/stt/${body.id}`);+ if (!st.ok) throw new Error("The transcription job was lost.");+ const status = (await st.json()) as {+ status: string;+ error?: string;+ cues?: SubtitleCue[];+ };+ if (status.status === "error") throw new Error(status.error ?? "Transcription failed.");+ if (status.status === "done") return status.cues ?? [];+ }+}diff --git a/site/src/cut/lib/micTranscribe.ts b/site/src/cut/lib/micTranscribe.tsindex 498b6b9a..69d7df1e 100644--- a/site/src/cut/lib/micTranscribe.ts+++ b/site/src/cut/lib/micTranscribe.ts@@ -1,7 +1,8 @@"use client";import { useCallback, useEffect, useRef, useState } from "react";-import { apiFetch, getBackend } from "./backend";+import { hasLocalCompute } from "./backend";+import { localBackend } from "./backend/local";import { cloudTranscribeRecording } from "./cloudTranscribe";// Live dictation for the chat composer. The browser holds the mic permission,@@ -114,7 +115,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicControoff += c.length;}try {- await apiFetch(`/api/cut/mic/${job}/feed`, {+ await localBackend.fetch(`/api/cut/mic/${job}/feed`, {method: "POST",headers: { "Content-Type": "application/octet-stream" },body: merged.buffer,@@ -139,7 +140,10 @@ export function useMicTranscription(onResult: (text: string) => void): MicControsetError("Microphone access was blocked. Allow the microphone for this site, then try again.");return;}- if (getBackend().kind === "cloud") {+ // Dictation runs on the Mac whenever the app is there — on-device, free,+ // and live — whatever backend holds the project. Without it the take is+ // recorded and sent to the hosted route in one go.+ if (!hasLocalCompute()) {recChunksRef.current = [];const rec = new MediaRecorder(media);rec.ondataavailable = (e) => {@@ -153,7 +157,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicControreturn;}try {- const res = await apiFetch("/api/cut/mic/start", {+ const res = await localBackend.fetch("/api/cut/mic/start", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({}),@@ -192,7 +196,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicControconst job = jobRef.current;if (!job) return;try {- const res = await apiFetch(`/api/cut/mic/${job}`);+ const res = await localBackend.fetch(`/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);@@ -246,7 +250,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicControawait flush();let text = "";try {- const res = await apiFetch(`/api/cut/mic/${job}/stop`, { method: "POST" });+ const res = await localBackend.fetch(`/api/cut/mic/${job}/stop`, { method: "POST" });const data = (await res.json().catch(() => ({}))) as { text?: string };text = data.text ?? "";} catch {@@ -263,7 +267,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicControconst cancel = useCallback(() => {const job = jobRef.current;jobRef.current = null;- if (job) void apiFetch(`/api/cut/mic/${job}/cancel`, { method: "POST" }).catch(() => {});+ if (job) void localBackend.fetch(`/api/cut/mic/${job}/cancel`, { method: "POST" }).catch(() => {});discardRecorder();teardownAudio();setState("idle");@@ -275,7 +279,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicControuseEffect(() => {return () => {const job = jobRef.current;- if (job) void apiFetch(`/api/cut/mic/${job}/cancel`, { method: "POST" }).catch(() => {});+ if (job) void localBackend.fetch(`/api/cut/mic/${job}/cancel`, { method: "POST" }).catch(() => {});discardRecorder();teardownAudio();};diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 3a2e16ee..6ddefa34 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -27,7 +27,7 @@ import type {} from "./types";import type { VideoProject } from "./genvideo/types";import { fillSlot } from "./genvideo/fillSlot";-import { apiFetch, apiJson, getBackend } from "./backend";+import { apiFetch, apiJson, getBackend, hasLocalCompute } from "./backend";import { fetchSignedMediaUrls } from "./backend/cloud";import { markSignedBatch } from "./mediaLinks";import {@@ -37,7 +37,8 @@ import {writeCachedDoc,writeCachedMediaLinks,} from "./docCache";-import { cloudTranscribeSpec, type CloudTranscribeSpec } from "./cloudTranscribe";+import { renderMix, transcribeSamples, type CloudTranscribeSpec } from "./cloudTranscribe";+import { engineTranscribeSamples } from "./localStt";import { trackLocale } from "./subtitles";import { ANIM_STYLE_IDS, emptySubtitles, IMAGE_CLIP_SECONDS, LOOK_IDS, MAX_SUBTITLE_LANES, mediaUrl, migrateLegacyTransitions, normalizeAspect, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";import { readTextStyle } from "./textStyle";@@ -647,14 +648,30 @@ export function rippleInsert(* null when the user switches projects mid-run. Throws user-facing errors.* Shared with the brief-to-video transcribe adapter. */export async function runTranscription(projectId: string, spec: object): Promise<SubtitleCue[] | null> {- // The hosted backend has no transcription job runner: the browser renders- // the audible mix itself and calls the metered cloud route chunk by chunk.+ // A cloud project's media isn't on this Mac, so the engine can't render the+ // mix — the browser does, and then hands it to whoever can transcribe it:+ // this Mac when the app is running (on-device, free, real word timings), the+ // metered hosted route otherwise. A local project skips all of it; the+ // engine already holds the media and runs the whole job.if (getBackend().kind === "cloud") {- return cloudTranscribeSpec(- projectId,- spec as CloudTranscribeSpec,- () => useEditor.getState().projectId !== projectId- );+ const s = spec as CloudTranscribeSpec;+ if (s.clips.length === 0 && s.audio.length === 0) {+ throw new Error("Add audio or video to the timeline first.");+ }+ const stale = () => useEditor.getState().projectId !== projectId;+ const mix = await renderMix(projectId, s);+ if (stale()) return null;+ if (!mix) return []; // nothing audible — no speech, like the engine's short-circuit+ const samples = mix.getChannelData(0);+ if (hasLocalCompute()) {+ try {+ return await engineTranscribeSamples(samples, s.duration, s.locale, stale);+ } catch {+ // The app went away, or on-device speech is unavailable on this Mac.+ // The hosted route still works, so the user never sees the difference.+ }+ }+ return transcribeSamples(samples, s.locale, stale);}const res = await apiFetch(`/api/cut/projects/${projectId}/transcribe`, {method: "POST",diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 4154688b..2157877b 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -6,6 +6,7 @@ import { exportApi } from "./export";import { libraryApi } from "./library";import { micApi } from "./mic";import { projectsApi } from "./projects";+import { sttApi } from "./stt";type TableHandler = (req: Request, params: Record<string, string>) => Response | Promise<Response>;@@ -78,6 +79,9 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "DELETE", path: "/api/cut/export/:jobId", handler: (req, p) => exportApi.cancel(req, { jobId: p.jobId }) },{ method: "GET", path: "/api/cut/export/:jobId/file", handler: (req, p) => exportApi.file(req, { jobId: p.jobId }) },+ { method: "POST", path: "/api/cut/stt", handler: (req) => sttApi.create(req) },+ { method: "GET", path: "/api/cut/stt/:jobId", handler: (req, p) => sttApi.status(req, { jobId: p.jobId }) },+{ method: "POST", path: "/api/cut/mic/start", handler: (req) => micApi.start(req) },{ method: "POST", path: "/api/cut/mic/:id/feed", handler: (req, p) => micApi.feed(req, { id: p.id }) },{ method: "GET", path: "/api/cut/mic/:id", handler: (req, p) => micApi.poll(req, { id: p.id }) },diff --git a/site/src/cut/server/http/stt.ts b/site/src/cut/server/http/stt.tsnew file mode 100644index 00000000..a963e769--- /dev/null+++ b/site/src/cut/server/http/stt.ts@@ -0,0 +1,41 @@+import { createAudioTranscribeJob, getTranscribeJob } from "../transcribe";++/** On-device speech for audio the caller supplies, rather than for a project+ * this engine stores: a cloud project renders its audible mix in the browser+ * and sends it here so transcription still runs on the Mac. Start a job, poll+ * it — the same shape as the project transcribe routes. */+export const sttApi = {+ async create(req: Request) {+ try {+ const form = await req.formData();+ const audio = form.get("audio");+ if (!(audio instanceof File)) {+ return Response.json({ error: "audio is required." }, { status: 400 });+ }+ const duration = Number(form.get("duration"));+ const locale = form.get("locale");+ const job = await createAudioTranscribeJob(new Uint8Array(await audio.arrayBuffer()), {+ locale: typeof locale === "string" && locale ? locale : undefined,+ duration: Number.isFinite(duration) ? duration : undefined,+ });+ if (job.status === "error") return Response.json({ error: job.error }, { status: 400 });+ return Response.json({ id: job.id });+ } catch (e) {+ return Response.json(+ { error: e instanceof Error ? e.message : "Transcription failed to start." },+ { status: 500 }+ );+ }+ },++ status(_req: Request, { jobId }: { jobId: string }) {+ const job = getTranscribeJob(jobId);+ if (!job) return Response.json({ error: "Unknown transcription job." }, { status: 404 });+ return Response.json({+ status: job.status,+ stage: job.stage,+ error: job.error,+ cues: job.cues,+ });+ },+};diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.tsindex 46a680ae..4cabd267 100644--- a/site/src/cut/server/transcribe.ts+++ b/site/src/cut/server/transcribe.ts@@ -1,5 +1,5 @@import { spawn } from "node:child_process";-import { mkdir, mkdtemp, rm, stat } from "node:fs/promises";+import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import { assertLocalRuntime } from "./local-only";@@ -148,21 +148,83 @@ export function groupWords(words: Word[]): Cue[] {return cues;}-export async function createTranscribeJob(spec: TranscribeSpec): Promise<TranscribeJob> {+/** Cues from one cut-stt run: drop what the model emits degenerate, clamp to+ * the audio's own length, and group the words into caption-sized cues. */+function cuesFromStt(out: string, duration: number): Cue[] {+ const parsed = JSON.parse(out) as { words: Word[] };+ const words = parsed.words+ .filter((w) => w.w.trim().length > 0 && w.t1 > w.t0 - 0.001)+ .map((w) => ({+ t0: Math.max(0, Math.min(w.t0, duration)),+ t1: Math.max(0, Math.min(w.t1, duration)),+ w: w.w.trim(),+ }))+ .filter((w) => w.t1 > w.t0);+ return groupWords(words);+}++/**+ * Transcribe audio the caller hands over, for a project this engine does not+ * store. A cloud project's media lives in R2, so the browser renders its+ * audible mix (the same graph runTranscribe builds with ffmpeg) and posts the+ * wav here — on-device speech then works whatever holds the project, and its+ * real word timings beat the hosted route's interpolated ones. Shares the+ * registry with the project path, so heavy speech still runs one at a time.+ */+export async function createAudioTranscribeJob(+ audio: Uint8Array,+ opts: { locale?: string; duration?: number } = {}+): Promise<TranscribeJob> {assertLocalRuntime();const id = crypto.randomUUID().slice(0, 12);- if (runningCount() >= MAX_RUNNING) {- const job: TranscribeJob = {- id,- projectId: spec.projectId,- status: "error",- stage: "audio",- error: "A transcription is already running — wait for it to finish.",- };- jobs.set(id, job);- retire(job);- return job;+ if (runningCount() >= MAX_RUNNING) return busyJob(id, "");+ const job: TranscribeJob = { id, projectId: "", status: "running", stage: "model" };+ jobs.set(job.id, job);+ void runAudioTranscribe(job, audio, opts)+ .catch((err: unknown) => {+ job.status = "error";+ job.error = err instanceof Error ? err.message : String(err);+ })+ .finally(() => retire(job));+ return job;+}++async function runAudioTranscribe(+ job: TranscribeJob,+ audio: Uint8Array,+ { locale, duration }: { locale?: string; duration?: number }+) {+ const tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-stt-"));+ try {+ const wav = path.join(tmpDir, "mix.wav");+ await writeFile(wav, audio);+ const bin = await ensureStt();+ job.stage = "transcribe";+ const out = await run(bin, [wav, locale ?? "en-US"]);+ job.cues = cuesFromStt(out, duration && duration > 0 ? duration : Infinity);+ job.status = "done";+ } finally {+ void rm(tmpDir, { recursive: true, force: true });}+}++function busyJob(id: string, projectId: string): TranscribeJob {+ const job: TranscribeJob = {+ id,+ projectId,+ status: "error",+ stage: "audio",+ error: "A transcription is already running — wait for it to finish.",+ };+ jobs.set(id, job);+ retire(job);+ return job;+}++export async function createTranscribeJob(spec: TranscribeSpec): Promise<TranscribeJob> {+ assertLocalRuntime();+ const id = crypto.randomUUID().slice(0, 12);+ if (runningCount() >= MAX_RUNNING) return busyJob(id, spec.projectId);const job: TranscribeJob = {id,projectId: spec.projectId,@@ -323,18 +385,7 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {job.stage = "transcribe";const out = await run(bin, [wav, spec.locale ?? "en-US"]);- const parsed = JSON.parse(out) as { words: Word[] };- // Clamp to the cut and drop anything degenerate the model emits.- const words = parsed.words- .filter((w) => w.w.trim().length > 0 && w.t1 > w.t0 - 0.001)- .map((w) => ({- t0: Math.max(0, Math.min(w.t0, spec.duration)),- t1: Math.max(0, Math.min(w.t1, spec.duration)),- w: w.w.trim(),- }))- .filter((w) => w.t1 > w.t0);-- job.cues = groupWords(words);+ job.cues = cuesFromStt(out, spec.duration);job.status = "done";} finally {void rm(tmpDir, { recursive: true, force: true });