Skip to content

Open source CapCut alternative.

TypeScript

feat(site): agent turns run as durable worker jobs [rebuild]

David Le8675c67b2391
diff --git a/site/scripts/eval-cut-turn-job.ts b/site/scripts/eval-cut-turn-job.ts
new file mode 100644
index 00000000..99c407cc
--- /dev/null
+++ b/site/scripts/eval-cut-turn-job.ts
@@ -0,0 +1,114 @@
+#!/usr/bin/env bun
+/**
+ * Turn-as-job smoke: the close-the-tab test. Seeds a cloud project, POSTs a
+ * chat turn to the turns route, and then only polls — the worker claims the
+ * job, runs the headless turn, pushes the doc, and records the thread. The
+ * script asserts the stored document and thread both carry the result.
+ *
+ * Run with the site dev server up and a local worker running:
+ * bun run scripts/eval-cut-turn-job.ts [--base http://localhost:3000]
+ * (worker: `bun src/cut/worker/main.ts` from site/, .env supplies DATABASE_URL)
+ */
+
+const arg = (name: string): string | undefined => {
+ const i = process.argv.indexOf(`--${name}`);
+ return i >= 0 ? process.argv[i + 1] : undefined;
+};
+const base = arg("base") ?? "http://localhost:3000";
+// --voiceover runs the media-generation variant: the turn synthesizes speech
+// through the hosted TTS route and lands the audio in the project — the
+// whole generation chain (hosted call, upload, probe, placement) headless.
+const voiceover = process.argv.includes("--voiceover");
+const headers = {
+ "Content-Type": "application/json",
+ "x-donkey-client-id": "donkey-cut-eval",
+ "x-donkey-dev-auth-bypass": "1",
+};
+const api = (path: string, init?: RequestInit) => fetch(base + path, { headers, ...init && { ...init, headers: { ...headers, ...init.headers } } });
+const fail = (msg: string): never => {
+ // Throw so the seeded project's finally-block DELETE still runs; the
+ // exit code carries the failure.
+ process.exitCode = 1;
+ throw new Error(`FAIL ${msg}`);
+};
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+const created = await api("/api/cut-cloud/projects", {
+ method: "POST",
+ body: JSON.stringify({ name: `turn-job-eval-${Date.now()}` }),
+});
+if (!created.ok) fail(`could not create project (${created.status}) — is the dev server up?`);
+const projectId = ((await created.json()) as { id: string }).id;
+console.log(`seeded project ${projectId}`);
+
+try {
+ const threadId = `thread-${Date.now()}`;
+ const ask = voiceover
+ ? 'Generate a voiceover that says "Donkey headless test" and place it at the very start.'
+ : 'Add a title that says "TURNJOB" at the very start of the video.';
+ const queued = await api(`/api/cut-cloud/projects/${projectId}/turns`, {
+ method: "POST",
+ body: JSON.stringify({
+ threadId,
+ messages: [{ id: "m1", role: "user", parts: [{ type: "text", text: ask }] }],
+ }),
+ });
+ if (!queued.ok) fail(`could not queue turn (${queued.status}): ${await queued.text()}`);
+ const jobId = ((await queued.json()) as { jobId: string }).jobId;
+ console.log(`queued turn job ${jobId} — waiting on the worker`);
+
+ const deadline = Date.now() + 180_000;
+ let last = "";
+ for (;;) {
+ if (Date.now() > deadline) fail("turn job did not settle in 180s — is the worker running?");
+ const res = await api(`/api/cut-cloud/jobs/${jobId}`);
+ if (!res.ok) fail(`job poll failed (${res.status})`);
+ const job = (await res.json()) as { state: string; progress: number; error?: string; result?: { reply?: string; toolCalls?: string[] } };
+ const line = `${job.state} ${Math.round(job.progress * 100)}%`;
+ if (line !== last) console.log(` ${line}`);
+ last = line;
+ if (job.state === "error") fail(`turn job failed: ${job.error}`);
+ if (job.state === "canceled") fail("turn job was canceled");
+ if (job.state === "done") {
+ console.log(`reply: ${(job.result?.reply ?? "").slice(0, 200)}`);
+ console.log(`tools: [${(job.result?.toolCalls ?? []).join(", ")}]`);
+ break;
+ }
+ await sleep(1500);
+ }
+
+ const readBack = await api(`/api/cut-cloud/projects/${projectId}`);
+ if (!readBack.ok) fail(`could not re-read project (${readBack.status})`);
+ const stored = (await readBack.json()) as {
+ overlays?: { text?: unknown; start?: number }[];
+ audioClips?: { assetId: string; start: number }[];
+ assets?: { id: string; type: string; duration: number }[];
+ };
+ if (voiceover) {
+ const clip = (stored.audioClips ?? [])[0];
+ if (!clip) fail("no soundtrack clip in the stored doc");
+ const asset = (stored.assets ?? []).find((a) => a.id === clip!.assetId);
+ if (!asset || asset.type !== "audio" || !(asset.duration > 0))
+ fail(`the clip's asset is missing or empty: ${JSON.stringify(asset)}`);
+ console.log(`stored doc carries a ${asset!.duration.toFixed(1)}s voiceover at ${clip!.start}s`);
+ } else {
+ const title = (stored.overlays ?? []).find(
+ (o) => typeof o.text === "string" && o.text.toUpperCase().includes("TURNJOB")
+ );
+ if (!title) fail(`no TURNJOB title in the stored doc — overlays: ${JSON.stringify(stored.overlays)}`);
+ console.log(`stored doc carries the title at ${title!.start}s`);
+ }
+
+ const chats = await api(`/api/cut-cloud/projects/${projectId}/chats`);
+ if (!chats.ok) fail(`could not read chats (${chats.status})`);
+ const thread = ((await chats.json()) as { id: string; messages?: { role: string }[] }[]).find(
+ (t) => t.id === threadId
+ );
+ if (!thread) fail("the turn's thread was not recorded");
+ const roles = (thread.messages ?? []).map((m) => m.role);
+ if (!roles.includes("user") || !roles.includes("assistant"))
+ fail(`thread misses a side of the exchange: [${roles.join(", ")}]`);
+ console.log(`PASS thread recorded with [${roles.join(", ")}]`);
+} finally {
+ await api(`/api/cut-cloud/projects/${projectId}`, { method: "DELETE" });
+}
diff --git a/site/src/cut/lib/hosts.ts b/site/src/cut/lib/hosts.ts
index eddc7200..50dcd83f 100644
--- a/site/src/cut/lib/hosts.ts
+++ b/site/src/cut/lib/hosts.ts
@@ -24,6 +24,12 @@ export const CUT_MEDIA_ORIGIN = `https://${CUT_MEDIA_HOST}`;
export const CUT_WORKER_HOST = "worker.donkeycut.com";
export const CUT_WORKER_WAKE_URL = `https://${CUT_WORKER_HOST}/wake`;
+// Where the worker's runner calls the hosted API back: production containers
+// (NODE_ENV=production in the image) talk to the canonical host, a dev worker
+// run by hand talks to the local dev server.
+export const CUT_HOSTED_ORIGIN =
+ process.env.NODE_ENV === "production" ? DONKEYCUT_CANONICAL : "http://localhost:3000";
+
function hostname(host: string | null | undefined): string {
return host ? host.split(":")[0] : "";
}
diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.ts
index 4c69a825..163fc4c9 100644
--- a/site/src/cut/server/cloud/routes.ts
+++ b/site/src/cut/server/cloud/routes.ts
@@ -14,6 +14,7 @@ import { jobsCloud } from "./jobs";
import { libraryCloud } from "./library";
import { mediaCloud } from "./media";
import { projectsCloud } from "./projects";
+import { turnsCloud } from "./turns";
import { shareCloud } from "./share";
import { transcribeCloud } from "./transcribe";
import { usageApi } from "./usage";
@@ -89,6 +90,8 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "DELETE", path: "/api/cut-cloud/export/:jobId", handler: (_r, u, p) => jobsCloud.exportCancel(u, p.jobId) },
{ method: "GET", path: "/api/cut-cloud/export/:jobId/file", handler: (_r, u, p) => jobsCloud.exportFile(u, p.jobId) },
{ method: "GET", path: "/api/cut-cloud/jobs/:jobId", handler: (_r, u, p) => jobsCloud.status(u, p.jobId) },
+ { method: "POST", path: "/api/cut-cloud/projects/:id/turns", handler: (r, u, p) => turnsCloud.queue(u, p.id, r) },
+ { method: "POST", path: "/api/cut-cloud/turns/:jobId/cancel", handler: (_r, u, p) => turnsCloud.cancel(u, p.jobId) },
{ method: "POST", path: "/api/cut-cloud/transcribe", handler: (r, u) => transcribeCloud.transcribe(u, r) },
{ method: "POST", path: "/api/cut-cloud/ai/captions", handler: (r, u) => captionsCloud.captions(u, r) },
diff --git a/site/src/cut/server/cloud/turns.ts b/site/src/cut/server/cloud/turns.ts
new file mode 100644
index 00000000..8e680229
--- /dev/null
+++ b/site/src/cut/server/cloud/turns.ts
@@ -0,0 +1,88 @@
+// One chat turn as a durable job. The page (or an API caller) posts the
+// thread's messages; the worker container claims the row, runs the headless
+// turn against the project doc, and settles the row with the reply. The
+// queued/running row doubles as the project's agent write lease — one turn at
+// a time per project — and the generic /jobs/:jobId route serves the poll.
+import type { Prisma } from "@/generated/prisma/client";
+import { prisma } from "@/lib/prisma";
+import { getProject } from "./projects";
+import { caught, err } from "./util";
+import { wakeRenderWorker } from "./wake";
+
+// Well above a slimmed thread, well below anything that could hurt the row.
+const MAX_TURN_BYTES = 1_000_000;
+
+export interface AgentTurnSpec {
+ threadId: string;
+ messages: unknown[];
+ model?: string;
+}
+
+export const turnsCloud = {
+ async queue(userId: string, projectId: string, req: Request) {
+ try {
+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ const text = await req.text();
+ if (text.length > MAX_TURN_BYTES) return err("Turn too large.", 413);
+ const body = JSON.parse(text) as Partial<AgentTurnSpec>;
+ const threadId = typeof body.threadId === "string" ? body.threadId.trim() : "";
+ if (!threadId || !Array.isArray(body.messages) || body.messages.length === 0)
+ return err("threadId and messages are required.", 400);
+ // The runner reads messages as UIMessages; a malformed shape must be
+ // refused here, ahead of the model spend it would otherwise ride along
+ // to before crashing the record step.
+ const wellFormed = body.messages.every(
+ (m) =>
+ !!m &&
+ typeof m === "object" &&
+ typeof (m as { id?: unknown }).id === "string" &&
+ typeof (m as { role?: unknown }).role === "string" &&
+ Array.isArray((m as { parts?: unknown }).parts)
+ );
+ if (!wellFormed) return err("Every message needs id, role, and a parts array.", 400);
+ const spec: AgentTurnSpec = {
+ threadId,
+ messages: body.messages,
+ ...(typeof body.model === "string" && body.model ? { model: body.model } : {}),
+ };
+ // The write lease, race-safely: create first, then keep the row only if
+ // it is the oldest live turn for the project. Two concurrent queues both
+ // create, both re-check, and exactly one — the older row — survives.
+ const row = await prisma.cutRenderJob.create({
+ data: {
+ userId,
+ projectId,
+ kind: "agent_turn",
+ spec: spec as unknown as Prisma.InputJsonValue,
+ },
+ });
+ const oldest = await prisma.cutRenderJob.findFirst({
+ where: { userId, projectId, kind: "agent_turn", state: { in: ["queued", "running"] } },
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ select: { id: true },
+ });
+ if (oldest && oldest.id !== row.id) {
+ await prisma.cutRenderJob.delete({ where: { id: row.id } }).catch(() => {});
+ return err("A turn is already running for this project.", 409);
+ }
+ wakeRenderWorker();
+ return Response.json({ jobId: row.id });
+ } catch (e) {
+ return caught(e, "Could not start the turn.");
+ }
+ },
+
+ async cancel(userId: string, jobId: string) {
+ try {
+ // The worker honors "canceled" between stream reads; a queued row is
+ // simply never claimed.
+ await prisma.cutRenderJob.updateMany({
+ where: { id: jobId, userId, kind: "agent_turn", state: { in: ["queued", "running"] } },
+ data: { state: "canceled" },
+ });
+ return Response.json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not cancel the turn.");
+ }
+ },
+};
diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.ts
index 103516bc..de8ba127 100644
--- a/site/src/cut/worker/main.ts
+++ b/site/src/cut/worker/main.ts
@@ -4,6 +4,8 @@ import { prisma, type ClaimedJob } from "./db";
import { overlayKeysOf, runExportJob } from "./exportJob";
import { runHlsJob } from "./hlsJob";
import { runImportUrlJob } from "./importUrlJob";
+import { runTurnJob } from "./turnJob";
+import { installSkiaRaster } from "../lib/headless/skiaRaster";
import { deleteObjects } from "./r2";
// The cloud render worker: a headless loop that claims CutRenderJob rows the
@@ -52,10 +54,10 @@ let stopping = false;
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
-/** The kinds someone is watching happen: an export or a URL import has a
- * progress bar on screen, while a hover proxy and a share card are background
- * polish nobody is waiting on. */
-const WATCHED_KINDS = ["export", "import_url"];
+/** The kinds someone is watching happen: an export, a URL import, or a chat
+ * turn has a progress surface on screen, while a hover proxy and a share card
+ * are background polish nobody is waiting on. */
+const WATCHED_KINDS = ["export", "import_url", "agent_turn"];
/** Atomically claim the next queued job: the updateMany's state guard makes
* exactly one worker win each row, so replicas never double-run a job.
@@ -159,6 +161,12 @@ async function runJob(job: ClaimedJob): Promise<void> {
where: { id: job.id, state: "running" },
data: { state: "done", progress: 1, result: result as unknown as Prisma.InputJsonValue },
});
+ } else if (job.kind === "agent_turn") {
+ const result = await runTurnJob(job, handle, () => entry.canceled);
+ await prisma.cutRenderJob.updateMany({
+ where: { id: job.id, state: "running" },
+ data: { state: "done", progress: 1, result: result as unknown as Prisma.InputJsonValue },
+ });
} else {
throw new Error(`Unknown job kind: ${job.kind}`);
}
@@ -176,6 +184,12 @@ async function runJob(job: ClaimedJob): Promise<void> {
.catch(() => {});
}
console.error(`[cut-worker] ${job.kind} ${job.id} ${entry.canceled ? "canceled" : "failed"}: ${message}`);
+ // A canceled turn retires this process once its cleanup settles: the
+ // abort tears the agent loop down, and a fresh process guarantees the
+ // next claim starts with clean per-user transport bindings even if some
+ // in-flight tool call outlived the abort. The wake on the next queued
+ // job restarts the container in seconds.
+ if (job.kind === "agent_turn" && entry.canceled) stopping = true;
} finally {
clearInterval(watcher);
// The overlay PNGs are single-use render inputs: delete them once the job
@@ -221,7 +235,11 @@ async function stop(): Promise<void> {
async function main(): Promise<void> {
process.on("SIGTERM", () => void stop());
process.on("SIGINT", () => void stop());
- console.log(`[cut-worker] polling for jobs (max ${MAX_RUNNING} concurrent)`);
+ // The server canvas backs any turn that rasterizes overlays (an export
+ // kicked off headless). A worker without the module still runs every
+ // ffmpeg-only job.
+ const skia = await installSkiaRaster();
+ console.log(`[cut-worker] polling for jobs (max ${MAX_RUNNING} concurrent), raster: ${skia ? "skia" : "unavailable"}`);
const inFlight = new Set<Promise<void>>();
let idleSince: number | null = null;
let failingSince: number | null = null;
diff --git a/site/src/cut/worker/turnJob.ts b/site/src/cut/worker/turnJob.ts
new file mode 100644
index 00000000..4654560b
--- /dev/null
+++ b/site/src/cut/worker/turnJob.ts
@@ -0,0 +1,186 @@
+import type { UIMessage } from "ai";
+import { geminiModelRoles } from "@/lib/inference/gemini-models";
+import { openCloudProject, pushCloudProject } from "../lib/headless/docSession";
+import { CUT_HOSTED_ORIGIN } from "../lib/hosts";
+import { dropPiSession, streamCutChat } from "../lib/pi/cutAgent";
+import { headlessDeps, type HeadlessSession } from "../lib/pi/serverDeps";
+import type { RenderHandle } from "../server/exportPipeline";
+import type { AgentTurnSpec } from "../server/cloud/turns";
+import type { ClaimedJob } from "./db";
+
+// An agent turn, executed where the tab used to be: open the project doc into
+// the editor store, run the production chat loop with the headless deps, push
+// the doc back through the versioned PUT, and record the finished exchange on
+// the project's stored thread. Every hosted call rides the runner grant — the
+// shared secret plus the job's user — so the turn spends that user's credits
+// and writes that user's project, exactly as the page would.
+
+const CLIENT_ID = "donkey-cut-runner";
+
+/** A stored thread as the AI panel keeps it; the runner appends whole
+ * messages and touches nothing else in the payload. */
+interface StoredThreadPayload {
+ id: string;
+ title?: string;
+ updatedAt?: number;
+ messages?: unknown[];
+ [key: string]: unknown;
+}
+
+function runnerSession(job: ClaimedJob): HeadlessSession {
+ const secret = process.env.CUT_RUNNER_SECRET;
+ if (secret)
+ return {
+ base: CUT_HOSTED_ORIGIN,
+ headers: {
+ "x-donkey-client-id": CLIENT_ID,
+ "x-donkey-runner-secret": secret,
+ "x-donkey-runner-user": job.userId,
+ },
+ };
+ if (process.env.NODE_ENV === "production")
+ throw new Error("CUT_RUNNER_SECRET is not set — the runner cannot call the hosted API.");
+ // A dev worker run by hand against the dev server: the bypass grant, the
+ // same one the eval scripts use.
+ return {
+ base: CUT_HOSTED_ORIGIN,
+ headers: { "x-donkey-client-id": CLIENT_ID, "x-donkey-dev-auth-bypass": "1" },
+ };
+}
+
+/** Record the finished exchange on the project's stored thread: the turn's
+ * own messages plus the assistant reply, merged over whatever the thread
+ * already holds so a re-run never duplicates history. */
+async function recordThread(
+ s: HeadlessSession,
+ projectId: string,
+ spec: AgentTurnSpec,
+ jobId: string,
+ reply: string
+): Promise<void> {
+ const url = `${s.base}/api/cut-cloud/projects/${encodeURIComponent(projectId)}/chats/${encodeURIComponent(spec.threadId)}`;
+ const listRes = await fetch(
+ `${s.base}/api/cut-cloud/projects/${encodeURIComponent(projectId)}/chats`,
+ { headers: s.headers }
+ );
+ // The PUT below replaces the thread wholesale, so writing on a failed read
+ // would erase the stored history. Fail the record step; the job surfaces
+ // the error rather than losing a conversation.
+ if (!listRes.ok) throw new Error(`Could not read the project's chats (${listRes.status}).`);
+ const stored: StoredThreadPayload | undefined = ((await listRes.json()) as StoredThreadPayload[]).find(
+ (t) => t?.id === spec.threadId
+ );
+ const known = new Set(
+ (stored?.messages ?? [])
+ .map((m) => (m && typeof m === "object" ? String((m as { id?: unknown }).id ?? "") : ""))
+ .filter(Boolean)
+ );
+ const fresh = (spec.messages as { id?: string }[]).filter((m) => !known.has(String(m?.id ?? "")));
+ const firstText = (spec.messages as UIMessage[])
+ .filter((m) => m.role === "user")
+ .flatMap((m) => m.parts ?? [])
+ .find((p) => p.type === "text" && p.text.trim());
+ const payload: StoredThreadPayload = {
+ ...(stored ?? {}),
+ id: spec.threadId,
+ title: stored?.title ?? (firstText?.type === "text" ? firstText.text.slice(0, 60) : "Chat"),
+ updatedAt: Date.now(),
+ messages: [
+ ...(stored?.messages ?? []),
+ ...fresh,
+ {
+ id: `turn-${jobId}`,
+ role: "assistant",
+ parts: [{ type: "text", text: reply }],
+ },
+ ],
+ };
+ const put = await fetch(url, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json", ...s.headers },
+ body: JSON.stringify(payload),
+ });
+ if (!put.ok) throw new Error(`Could not record the thread (${put.status}).`);
+}
+
+export interface TurnResult {
+ reply: string;
+ toolCalls: string[];
+ docVersion: string | null;
+}
+
+export async function runTurnJob(
+ job: ClaimedJob,
+ handle: RenderHandle,
+ isCanceled: () => boolean
+): Promise<TurnResult> {
+ const spec = job.spec as AgentTurnSpec;
+ if (!job.projectId) throw new Error("Turn job carries no project.");
+ if (!spec?.threadId || !Array.isArray(spec.messages))
+ throw new Error("Turn job carries no thread payload.");
+
+ const session = runnerSession(job);
+ const doc = await openCloudProject(session, job.projectId);
+
+ const deps = headlessDeps(session);
+ const toolCalls: string[] = [];
+ const exec = deps.execTool;
+ deps.execTool = async (name, args) => {
+ toolCalls.push(name);
+ return exec(name, args);
+ };
+ let rounds = 0;
+ deps.hooks = {
+ onRound: () => {
+ rounds += 1;
+ // The row's progress bar: rounds settle asymptotically toward done.
+ handle.progress = Math.min(0.9, rounds / 8);
+ },
+ };
+
+ const piKey = `turn-${job.id}`;
+ let reply = "";
+ let streamError: string | null = null;
+ // The abort tears the agent loop down for real on cancel — model call,
+ // pending tool batch, and all. Without it a canceled reader leaves the loop
+ // running detached while this process moves on to another user's job. The
+ // poller fires it even while the loop is parked inside reader.read() on a
+ // stalled stream, so a cancel always lands.
+ const abort = new AbortController();
+ const cancelPoll = setInterval(() => {
+ if (isCanceled()) abort.abort();
+ }, 1000);
+ const reader = streamCutChat({
+ threadId: piKey,
+ model: spec.model ?? geminiModelRoles.chat,
+ messages: spec.messages as UIMessage[],
+ abortSignal: abort.signal,
+ deps,
+ }).getReader();
+ try {
+ for (;;) {
+ if (isCanceled()) {
+ abort.abort();
+ await reader.cancel();
+ break;
+ }
+ const { done, value } = await reader.read();
+ if (done) break;
+ const chunk = value as unknown as { type: string; delta?: string; errorText?: string };
+ if (chunk.type === "text-delta" && chunk.delta) reply += chunk.delta;
+ else if (chunk.type === "text-start" && reply) reply += "\n";
+ else if (chunk.type === "error" && chunk.errorText) streamError = chunk.errorText;
+ }
+ } finally {
+ clearInterval(cancelPoll);
+ dropPiSession(piKey);
+ }
+ if (streamError) throw new Error(streamError);
+ if (isCanceled()) throw new Error("Canceled.");
+
+ reply = reply.trim();
+ await pushCloudProject(session, doc);
+ await recordThread(session, job.projectId, spec, job.id, reply);
+ handle.progress = 1;
+ return { reply, toolCalls, docVersion: doc.version };
+}