Skip to content

Open source CapCut alternative.

TypeScript

fix(cut): hand text models a listen as its words [rebuild]

David Le231fddcea348
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index 6f446d13..2bacc8cd 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -29,7 +29,7 @@ user message + @attachments + fresh <editor_state> snapshot
turn job runs the whole turn in the worker container
```
-The Mac engine serves native Bun Request/Response streams and drains each turn into a disk journal independently of its readers. Reopening an unfinished turn replays that journal under the same assistant message id; saved completed replies stay settled. Stop explicitly cancels the provider. The provider sees a single MCP server named `cut`: a small stdio proxy the provider harness spawns, which forwards every tool listing and call to the engine over HTTP. The engine writes each call into the open chat stream; the tab executes it on the editor store and posts the result back; the engine hands it to the waiting provider. A call the tab never answers times out after two minutes.
+The Mac engine drains each turn into a disk journal independently of its readers; reopening an unfinished turn replays it under the same message id, and Stop cancels the provider. The provider sees one MCP server, `cut`: a stdio proxy that forwards every tool call to the engine, which writes it into the chat stream for the tab to execute and answer within two minutes. Frames reach the provider as images and sound as its words, transcribed on the Mac.
A Claude or Codex turn can outlive its tab while the Mac engine remains running. The bridge retains the session's project after its last reader disconnects and executes subsequent document tools against that project on disk. Running threads keep their editor connection when the chat panel is hidden or another thread is selected. Tool claims let one attached tab execute each call; a disconnected call with an uncertain result returns that uncertainty to the model. Headless calls serialize access to the engine's editor store, and every call records its result in the journal. Tools that need the page's media primitives or hosted sign-in still return a typed error when detached.
diff --git a/site/src/cut/server/ai/bridge.ts b/site/src/cut/server/ai/bridge.ts
index cc681002..a616713a 100644
--- a/site/src/cut/server/ai/bridge.ts
+++ b/site/src/cut/server/ai/bridge.ts
@@ -79,18 +79,23 @@ export function unregisterSession(key: string) {
sessionProjects.delete(key);
}
-/** The chat stream carries a tool's output without its frames: the model
- * gets them through the returned result, the page never draws them, and one
- * watch_video's contact sheets would otherwise fill the turn journal. */
+/** The chat stream carries a tool's output without its frames or sound: the
+ * model gets them through the returned result, the page never draws or plays
+ * them, and one watch_video's contact sheets or a few listen_audio stretches
+ * would otherwise fill the turn journal. */
function streamedOutput(output: unknown): unknown {
if (!output || typeof output !== "object" || Array.isArray(output)) {
return output;
}
- const { image, images, ...rest } = output as Record<string, unknown>;
- if (image === undefined && images === undefined) {
+ const { image, images, audio, ...rest } = output as Record<string, unknown>;
+ if (image === undefined && images === undefined && audio === undefined) {
return output;
}
- return { ...rest, imagesOmitted: true };
+ return {
+ ...rest,
+ ...(image !== undefined || images !== undefined ? { imagesOmitted: true } : {}),
+ ...(audio !== undefined ? { audioOmitted: true } : {}),
+ };
}
const TOOL_TIMEOUT_MS = 120_000; // subtitles generation can take a while
diff --git a/site/src/cut/server/ai/heardWords.test.ts b/site/src/cut/server/ai/heardWords.test.ts
new file mode 100644
index 00000000..4c7481b5
--- /dev/null
+++ b/site/src/cut/server/ai/heardWords.test.ts
@@ -0,0 +1,39 @@
+import { expect, test } from "bun:test";
+import { audioAsWords } from "./heardWords";
+
+const sound = `data:audio/wav;base64,${Buffer.from("RIFF....WAVE").toString("base64")}`;
+// Bytes of an ADTS AAC frame, labelled the way a whole file served as
+// octet-stream comes back.
+const adts = `data:audio/aac;base64,${Buffer.from([0xff, 0xf1, 0x50, 0x80, 0, 0x1f, 0xfc]).toString("base64")}`;
+
+test("a listen reaches a text model as the words over the stretch, in source seconds", async () => {
+ const asked: { bytes: number; locale?: string; duration?: number; fileName?: string }[] = [];
+ const out = await audioAsWords(
+ { name: "take.mov", from: 10, coveredTo: 14, locale: "ko-KR", audio: sound },
+ async (audio, opts) => {
+ asked.push({ bytes: audio.byteLength, ...opts });
+ return [{ id: "c", start: 0.5, end: 1.25, text: "안녕하세요", words: [] }];
+ }
+ );
+ expect(asked).toEqual([{ bytes: 12, locale: "ko-KR", duration: 4, fileName: "span.wav" }]);
+ expect(out).toMatchObject({ name: "take.mov", from: 10, coveredTo: 14, words: [{ start: 10.5, end: 11.25, text: "안녕하세요" }] });
+ expect(JSON.stringify(out)).not.toContain(sound);
+});
+
+test("a result with no sound passes through untouched", async () => {
+ const output = { duration: 10, imagesOmitted: true };
+ expect(await audioAsWords(output, async () => [])).toBe(output);
+});
+
+test("the container is read off the bytes", async () => {
+ const names: (string | undefined)[] = [];
+ const transcribe = async (_audio: Uint8Array, opts: { fileName?: string }) => {
+ names.push(opts.fileName);
+ return [];
+ };
+ await audioAsWords({ from: 0, coveredTo: 1, audio: adts }, transcribe);
+ const ogg = `data:audio/aac;base64,${Buffer.from("OggS\0\0\0\0").toString("base64")}`;
+ const refused = await audioAsWords({ from: 0, coveredTo: 1, audio: ogg }, transcribe).then(() => "", (e: Error) => e.message);
+ expect(names).toEqual(["span.aac"]);
+ expect(refused).toContain("can't be transcribed");
+});
diff --git a/site/src/cut/server/ai/heardWords.ts b/site/src/cut/server/ai/heardWords.ts
new file mode 100644
index 00000000..9be8465c
--- /dev/null
+++ b/site/src/cut/server/ai/heardWords.ts
@@ -0,0 +1,81 @@
+import type { Cue } from "../transcribe";
+
+const DATA_URL = /^data:[^,]*;base64,([^]*)$/;
+
+/** The file name the speech tool reads a sound under, from the container its
+ * bytes open with: the labelled media type can be a guess (a whole file
+ * served as octet-stream comes back labelled AAC). Null for a container the
+ * Mac's audio reader does not open, e.g. Ogg. */
+function speechFileName(bytes: Uint8Array): string | null {
+ const ascii = (at: number, text: string) =>
+ text.split("").every((c, i) => bytes[at + i] === c.charCodeAt(0));
+ if (ascii(0, "RIFF") && ascii(8, "WAVE")) {
+ return "span.wav";
+ }
+ if (ascii(4, "ftyp")) {
+ return "span.m4a";
+ }
+ if (ascii(0, "fLaC")) {
+ return "span.flac";
+ }
+ if (ascii(0, "FORM")) {
+ return "span.aiff";
+ }
+ if (ascii(0, "caff")) {
+ return "span.caf";
+ }
+ if (ascii(0, "ID3")) {
+ return "span.mp3";
+ }
+ // A frame sync: ADTS AAC carries layer bits 00, an MPEG audio frame does not.
+ if (bytes[0] === 0xff && (bytes[1] & 0xf0) === 0xf0 && (bytes[1] & 0x06) === 0) {
+ return "span.aac";
+ }
+ if (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0) {
+ return "span.mp3";
+ }
+ return null;
+}
+
+const HEARD_AS_WORDS =
+ "You take sound as its words: this stretch was transcribed on this Mac, each line timed in source seconds. Tone, music and delivery do not come through, so judge those from the picture or say you cannot.";
+
+type Transcribe = (
+ audio: Uint8Array,
+ opts: { locale?: string; duration?: number; fileName?: string }
+) => Promise<Cue[]>;
+
+const round = (n: number) => Math.round(n * 1000) / 1000;
+
+/** A listen_audio result for a chat model that reads text and pictures only:
+ * the stretch's sound becomes the words over it. A result with no sound
+ * passes through. */
+export async function audioAsWords(output: unknown, transcribe: Transcribe): Promise<unknown> {
+ if (!output || typeof output !== "object" || Array.isArray(output)) {
+ return output;
+ }
+ const { audio, ...rest } = output as Record<string, unknown>;
+ const m = typeof audio === "string" ? DATA_URL.exec(audio) : null;
+ if (!m) {
+ return output;
+ }
+
+ // The stretch starts at `from` in source seconds and runs to `coveredTo`.
+ const from = typeof rest.from === "number" ? rest.from : 0;
+ const to = typeof rest.coveredTo === "number" ? rest.coveredTo : undefined;
+ const bytes = new Uint8Array(Buffer.from(m[1], "base64"));
+ const fileName = speechFileName(bytes);
+ if (!fileName) {
+ throw new Error("This sound's format can't be transcribed on this Mac.");
+ }
+ const cues = await transcribe(bytes, {
+ ...(typeof rest.locale === "string" ? { locale: rest.locale } : {}),
+ ...(to !== undefined ? { duration: round(to - from) } : {}),
+ fileName,
+ });
+ return {
+ ...rest,
+ heard: HEARD_AS_WORDS,
+ words: cues.map((c) => ({ start: round(from + c.start), end: round(from + c.end), text: c.text })),
+ };
+}
diff --git a/site/src/cut/server/ai/turnStreams.test.ts b/site/src/cut/server/ai/turnStreams.test.ts
index 6f049de5..a032cf47 100644
--- a/site/src/cut/server/ai/turnStreams.test.ts
+++ b/site/src/cut/server/ai/turnStreams.test.ts
@@ -126,3 +126,16 @@ test("frames reach the model and stay out of the turn journal", async () => {
expect(JSON.stringify(journaled).length).toBeLessThan(1000);
unregisterSession("frames");
});
+
+test("sound reaches the model and stays out of the turn journal", async () => {
+ const chunks: Record<string, unknown>[] = [];
+ registerSession("sound", { write: (chunk) => chunks.push(chunk) });
+ const pending = callBrowserTool("sound", "listen_audio", { asset_id: "a" });
+ const id = String(chunks[0].toolCallId);
+ const audio = `data:audio/wav;base64,${"A".repeat(2_000_000)}`;
+ resolveBrowserTool("sound", id, { output: { coveredTo: 30, audio } });
+ expect(((await pending).output as { audio?: string }).audio).toBe(audio);
+ const journaled = chunks.find((chunk) => chunk.type === "tool-output-available");
+ expect(journaled?.output).toEqual({ coveredTo: 30, audioOmitted: true });
+ unregisterSession("sound");
+});
diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.ts
index b9e1a4cc..94e978e1 100644
--- a/site/src/cut/server/http/ai.ts
+++ b/site/src/cut/server/http/ai.ts
@@ -23,6 +23,8 @@ import {
} from "../ai/bridge";
import { rewriteCaptions, translateCaptions } from "../ai/captions";
import { writeVisualCues, type VisualFrame } from "../ai/visualSubtitles";
+import { audioAsWords } from "../ai/heardWords";
+import { transcribeAudio } from "../transcribe";
import { AI_SKILL_INDEX, AI_TOOLS, attachedAssetsBlock, readSkill, skillRelevanceBlock, systemPrompt } from "../ai/catalog";
import {
declaresTool,
@@ -79,6 +81,10 @@ function mcpCommand(base: string, sessionKey: string): { command: string; args:
}
/** Claude models through the Agent SDK — the user's Claude Code login. */
+/** The longest one editor tool call may take under Codex: the speech
+ * engine's whole-run cap. */
+const CODEX_TOOL_TIMEOUT_S = 600;
+
async function runClaude(
emit: UIChunkWriter["write"],
prompt: string,
@@ -341,6 +347,10 @@ async function codexRun(
// The editor tools are the whole point of the run, so approve them all.
"-c",
`mcp_servers.cut.default_tools_approval_mode="approve"`,
+ // Codex cuts an MCP call off at 60s by default; the editor's waits run to
+ // 100s, and a listen's words can queue behind a caption run.
+ "-c",
+ `mcp_servers.cut.tool_timeout_sec=${CODEX_TOOL_TIMEOUT_S}`,
session ? prompt : `${systemPrompt()}\n\n${prompt}`
);
@@ -733,6 +743,15 @@ export const aiApi = {
if (result.errorText !== undefined) {
return Response.json({ ...mcpText(result.errorText), isError: true });
}
+ // The models behind this proxy read text and pictures, so a listen's sound
+ // reaches them as its words, transcribed here on the Mac.
+ if (name === "listen_audio") {
+ try {
+ return Response.json(mcpText(await audioAsWords(result.output, transcribeAudio)));
+ } catch (error) {
+ return Response.json({ ...mcpText(errorMessage(error, "Could not transcribe that stretch.")), isError: true });
+ }
+ }
// Frames come back as data URLs in `image`/`images`; hand them to the
// model as MCP image blocks. The data text rides first, so a provider
// that can't read images still gets the numbers.
diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.ts
index 109ab615..bff040dc 100644
--- a/site/src/cut/server/transcribe.ts
+++ b/site/src/cut/server/transcribe.ts
@@ -63,9 +63,51 @@ export interface TranscribeJob {
cues?: Cue[];
}
-const MAX_RUNNING = 1; // on-device transcription is heavy; one at a time
+// A speech run gets a fixed allowance plus twice the audio's length, so a run
+// that hangs gives the queue back in minutes, e.g. 2m20s for a 10s listen. The
+// whole-run cap holds for audio of unknown length.
+const STT_BASE_MS = 120_000;
+const STT_PER_AUDIO_SECOND_MS = 2_000;
+const STT_MAX_MS = 600_000;
+const sttTimeoutMs = (seconds: number) =>
+ Number.isFinite(seconds) ? Math.min(STT_MAX_MS, STT_BASE_MS + seconds * STT_PER_AUDIO_SECOND_MS) : STT_MAX_MS;
+
// Survives dev-server module reloads; caps the terminal backlog.
-const { jobs, runningCount, retire } = createJobRegistry<TranscribeJob>("__veditorSttJobs");
+const { jobs, retire } = createJobRegistry<TranscribeJob>("__veditorSttJobs");
+
+// On-device transcription is heavy, so jobs take the speech engine one at a
+// time. A job waiting its turn reports running: a caller waits it out the
+// same way it waits out the work itself. A chat waiting on the words goes
+// "next", ahead of captions and background sweep chunks already queued.
+type SpeechPlace = "next" | "last";
+const speechQueue: (() => void)[] = [];
+let speechBusy = false;
+function inSpeechTurn<T>(work: () => Promise<T>, place: SpeechPlace = "last"): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const start = () => {
+ work()
+ .then(resolve, reject)
+ .finally(() => {
+ const following = speechQueue.shift();
+ if (following) {
+ following();
+ } else {
+ speechBusy = false;
+ }
+ });
+ };
+ if (!speechBusy) {
+ speechBusy = true;
+ start();
+ return;
+ }
+ if (place === "next") {
+ speechQueue.unshift(start);
+ } else {
+ speechQueue.push(start);
+ }
+ });
+}
export function getTranscribeJob(id: string) {
return jobs.get(id);
@@ -236,18 +278,16 @@ function cuesFromStt(out: string, duration: number): Cue[] {
* 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.
+ * speech turn 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) return busyJob(id, "");
- const job: TranscribeJob = { id, projectId: "", status: "running", stage: "model" };
+ const job: TranscribeJob = { id: crypto.randomUUID().slice(0, 12), projectId: "", status: "running", stage: "model" };
jobs.set(job.id, job);
- void runAudioTranscribe(job, audio, opts)
+ void inSpeechTurn(() => runAudioTranscribe(job, audio, opts))
.catch((err: unknown) => {
job.status = "error";
job.error = errorMessage(err, String(err));
@@ -256,50 +296,52 @@ export async function createAudioTranscribeJob(
return job;
}
+/** Transcribe audio in hand and wait for its words, taking the speech
+ * engine's next turn. The chat bridge reads a listen this way for a model
+ * that takes text and pictures only. `fileName` carries the container the
+ * speech tool reads the bytes as, e.g. "span.aac" for the engine's own cut. */
+export function transcribeAudio(
+ audio: Uint8Array,
+ opts: { locale?: string; duration?: number; fileName?: string } = {}
+): Promise<Cue[]> {
+ assertLocalRuntime();
+ const job: TranscribeJob = { id: crypto.randomUUID().slice(0, 12), projectId: "", status: "running", stage: "model" };
+ return inSpeechTurn(async () => {
+ await runAudioTranscribe(job, audio, opts);
+ return job.cues ?? [];
+ }, "next");
+}
+
async function runAudioTranscribe(
job: TranscribeJob,
audio: Uint8Array,
- { locale, duration }: { locale?: string; duration?: number }
+ { locale, duration, fileName = "mix.wav" }: { locale?: string; duration?: number; fileName?: string }
) {
const tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-stt-"));
try {
- const wav = path.join(tmpDir, "mix.wav");
- await writeFile(wav, audio);
+ const file = path.join(tmpDir, fileName);
+ await writeFile(file, audio);
const bin = await ensureStt();
job.stage = "transcribe";
- const out = await run(bin, [wav, locale ?? "en-US"]);
- job.cues = await cuesFromRun(out, wav, duration && duration > 0 ? duration : Infinity);
+ const length = duration && duration > 0 ? duration : Infinity;
+ const out = await run(bin, [file, locale ?? "en-US"], undefined, sttTimeoutMs(length));
+ job.cues = await cuesFromRun(out, file, length);
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,
+ id: crypto.randomUUID().slice(0, 12),
projectId: spec.projectId,
status: "running",
stage: "audio",
};
jobs.set(job.id, job);
- void runTranscribe(job, spec)
+ void inSpeechTurn(() => runTranscribe(job, spec))
.catch((err: unknown) => {
job.status = "error";
job.error = errorMessage(err, String(err));
@@ -481,7 +523,7 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {
const bin = await ensureStt();
job.stage = "transcribe";
- const out = await run(bin, [wav, spec.locale ?? "en-US"]);
+ const out = await run(bin, [wav, spec.locale ?? "en-US"], undefined, sttTimeoutMs(spec.duration));
job.cues = await cuesFromRun(out, wav, spec.duration);
job.status = "done";
} finally {