Skip to content

Open source CapCut alternative.

TypeScript

feat(chatgpt): edits run in the editor open in the card

David Leafd2f0b3d93e
diff --git a/docs/guides/chatgpt-app.md b/docs/guides/chatgpt-app.md
index 1453295f..ecfd8936 100644
--- a/docs/guides/chatgpt-app.md
+++ b/docs/guides/chatgpt-app.md
@@ -14,28 +14,15 @@ ChatGPT tools and embedded card
↓
Scoped OAuth connection
↓
-Cloud project, command, history and render services
+Cloud project, command and render services
↓
-Command batch → worker runs the editor's own tools → versioned save + checkpoint
+Command batch → the editor in the card runs it → versioned save
Captured document → worker renderer → signed media
```
## Editing from ChatGPT
-ChatGPT reads the editor's tool catalog through `list_commands` and
-`describe_commands`, then sends a batch through `edit_project`. The batch runs as
-a job in the worker container: the project document opens into the editor store,
-each command runs through the same executor the chat assistant uses, the
-document saves through the versioned PUT, and the whole batch becomes one
-checkpoint in the project's undo history. `inspect_project` runs the same way
-without saving, so contact sheets and captured frames come back as images.
-Imports are the existing URL-import job with adoption turned on, so footage the
-user attaches in ChatGPT or links to lands as project assets; exports are the
-document export the phone uses, with the download offered on the card.
-
-Undo and redo walk the checkpoint line, which is anchored to the project's
-version: a save from the editor moves the version off the line, so ChatGPT
-never reverts an edit the user made in the app. Editing, previews and exports
+ChatGPT reads the editor's tool catalog and sends a batch through `edit_project`; the editor open in the card claims it, runs it on the document the user is looking at as one undo step, saves, and reports the result. Nothing else runs a batch: with no card open the tool answers that the project has to be opened first, and undo and redo step the card's own history, which the user's edits share. Editing, previews and exports
spend no credits; commands that generate media spend the account's credits, and
imports and exports use its storage allowance. The server's instructions and
tool descriptions say so, with the repository linked, so ChatGPT explains the
@@ -163,8 +150,7 @@ exercise ChatGPT's account-linking UI or the production database.
- `site/src/clients/chatgpt/server/` — OAuth, MCP tools, the command catalog, and the cloud-project adapter.
- `site/src/clients/chatgpt/ui/` — standalone MCP Apps widget and host bridge.
- `site/packages/artifact-player/` — shared website and widget playback.
-- `site/src/cut/server/cloud/commands.ts` and `history.ts` — the command job and the checkpoint history.
-- `site/src/cut/worker/commandJob.ts` — the batch runner and import adoption in the container.
+- `site/src/cut/server/cloud/commands.ts` and `site/src/cut/lib/hostCommands.ts` — the command job, and the editor in the card running it.
- `site/src/cut/server/cloud/previewJobs.ts` — revision reuse and document-backed rendering.
The protocol follows OpenAI's [authentication guidance](https://developers.openai.com/apps-sdk/build/auth)
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prisma
index 8b1b8973..80c19a95 100644
--- a/site/prisma/Cut.prisma
+++ b/site/prisma/Cut.prisma
@@ -18,24 +18,6 @@ model CutProject {
@@index([userId, updatedAt])
}
-// One saved state of a cloud project, kept so an edit made from outside the
-// editor (the ChatGPT app) can be undone and redone from another request.
-// Rows form a linear history per project ordered by seq; `version` is the
-// CutProject.version whose doc this row holds, re-aliased when a restore
-// writes the same doc under a new version.
-model CutProjectCheckpoint {
- id String @id @default(cuid())
- projectId String
- userId String
- seq Int
- version Int
- doc Json
- label String
- createdAt DateTime @default(now())
-
- @@index([projectId, seq])
-}
-
// A read-only share of one cloud project. The row id doubles as the link
// token: deleting the row kills the link, and re-sharing mints a fresh URL
// without moving the project. For a public share the token is the only gate,
diff --git a/site/scripts/eval-chatgpt-widget.ts b/site/scripts/eval-chatgpt-widget.ts
index f8d68be5..37775abf 100644
--- a/site/scripts/eval-chatgpt-widget.ts
+++ b/site/scripts/eval-chatgpt-widget.ts
@@ -23,7 +23,7 @@ const frame = document.querySelector('iframe');
const project = {id:'project',name:'Launch film',revision:'cloud:2',url:'https://donkeycut.com/app/p/project'};
let count = 0, renewals = 0;
window.calls = []; window.links = []; window.modes = []; window.editable = false;
-const view = (selected, preview = null) => ({view:selected?'project':'projects',projects:selected?[]:[project],nextCursor:null,project:selected?project:null,preview,canRender:true,canEdit:window.editable,export:null,job:null,results:[],changed:false,history:null,account:null});
+const view = (selected, preview = null) => ({view:selected?'project':'projects',projects:selected?[]:[project],nextCursor:null,project:selected?project:null,preview,canRender:true,canEdit:window.editable,export:null,job:null,results:[],changed:false,account:null});
// ChatGPT's sandbox drops null-valued keys before the widget sees a result.
const dropNulls = (value) => Array.isArray(value) ? value.map(dropNulls) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).filter(([, v]) => v !== null).map(([k, v]) => [k, dropNulls(v)])) : value;
const result = (data, playback = null, editor = null) => dropNulls({content:[{type:'text',text:'Preview'}],structuredContent:data,_meta:{playback,editor,pollMs:1000}});
diff --git a/site/scripts/eval-chatgpt-workflow.ts b/site/scripts/eval-chatgpt-workflow.ts
index de392cc8..7bd5def4 100644
--- a/site/scripts/eval-chatgpt-workflow.ts
+++ b/site/scripts/eval-chatgpt-workflow.ts
@@ -5,6 +5,11 @@
* footage, inspect it, make a vertical cut, preview, undo, redo, export — and
* assert every step landed in the stored document and the export downloads.
*
+ * Every batch runs in the editor open in the ChatGPT card, so this script
+ * stands that card in: it opens the project in the same editor store the page
+ * uses, claims batches through the card's routes, runs them through the
+ * headless executors, saves through the versioned PUT and reports back.
+ *
* Run with the site dev server up and a local worker running:
* bun run scripts/eval-chatgpt-workflow.ts [--base http://localhost:3000] [--keep]
* (worker: `npm run worker:build && node dist/cut-worker/main.js` from site/;
@@ -15,6 +20,11 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { SETTINGS } from "../src/lib/config/registry";
import { createChatgptServer, SERVER_INSTRUCTIONS } from "../src/clients/chatgpt/server/mcp";
import type { ProjectView } from "../src/clients/chatgpt/contracts";
+import { runCommandBatch, type CommandJobSpec } from "../src/cut/lib/commandBatch";
+import { bindHeadlessSession, type HeadlessSession } from "../src/cut/lib/headless/bind";
+import { openCloudProject, pushCloudProject } from "../src/cut/lib/headless/docSession";
+import { headlessDeps } from "../src/cut/lib/pi/serverDeps";
+import { serializeDoc, useEditor } from "../src/cut/lib/store";
import { deleteProjectCascade } from "../src/cut/server/cloud/projects";
import { prisma } from "../src/lib/prisma";
@@ -67,6 +77,40 @@ async function settle(first: Called, tool: "get_job_status" | "get_export_status
}
}
+/** The card, stood in for: claim the project's batches and run them on the
+ * open document until the signal ends it. */
+async function hostCard(projectId: string, signal: AbortSignal): Promise<void> {
+ const session: HeadlessSession = { base, headers: { "x-donkey-client-id": "eval-card", "x-donkey-dev-auth-bypass": "1" } };
+ bindHeadlessSession(session);
+ const deps = headlessDeps(session);
+ const open = await openCloudProject(session, projectId);
+ const api = (path: string, body?: unknown) =>
+ fetch(`${base}${path}`, { method: "POST", headers: { ...session.headers, "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ const snapshot = () => JSON.stringify(serializeDoc(useEditor.getState()));
+ while (!signal.aborted) {
+ const res = await api(`/api/cut-cloud/projects/${projectId}/commands/claim`);
+ if (res.status !== 200) { await sleep(300); continue; }
+ const { id, spec } = (await res.json()) as { id: string; spec: CommandJobSpec };
+ let report: unknown;
+ try {
+ const before = snapshot();
+ if (!spec.readOnly) useEditor.getState().beginHistoryBatch();
+ let results;
+ try {
+ results = await runCommandBatch(projectId, spec.commands, (name, input) => deps.execTool(name, input));
+ } finally {
+ if (!spec.readOnly) useEditor.getState().endHistoryBatch();
+ }
+ const changed = !spec.readOnly && snapshot() !== before;
+ if (changed) await pushCloudProject(session, open);
+ report = { ok: true, results, changed, docVersion: changed ? open.version : null };
+ } catch (error) {
+ report = { ok: false, error: error instanceof Error ? error.message : String(error) };
+ }
+ await api(`/api/cut-cloud/jobs/${id}/result`, report);
+ }
+}
+
const doc = async (projectId: string) => {
const row = await prisma.cutProject.findFirst({ where: { id: projectId, userId: USER_ID }, select: { doc: true, version: true } });
if (!row) fail("project row is gone");
@@ -74,6 +118,8 @@ const doc = async (projectId: string) => {
};
let projectId: string | null = null;
+const card = new AbortController();
+let hosting: Promise<void> | undefined;
try {
// Instructions and catalog: what ChatGPT reads first.
if (!SERVER_INSTRUCTIONS.includes("github.com/DonkeyCut/Donkey")) fail("server instructions do not link the repository");
@@ -87,12 +133,17 @@ try {
projectId = created.view.project?.id ?? fail("create_project returned no project");
console.log(`created ${projectId}`);
+ // An edit before the card is open is refused, and says so.
+ const closed = await client.callTool({ name: "edit_project", arguments: { projectId, commands: [{ name: "set_aspect", input: { aspect: "9:16" } }] } });
+ if (!closed.isError || !JSON.stringify(closed.content).includes("open_project")) fail(`an edit with no card open should ask for open_project: ${JSON.stringify(closed.content)}`);
+ console.log("no card open: the edit asks for open_project");
+ hosting = hostCard(projectId, card.signal).catch((e) => { if (!card.signal.aborted) console.error("card failed:", e); });
+
const imported = await settle(await call("import_media", { projectId, urls: [FOOTAGE] }), "get_job_status", "import");
const importAssets = imported.view.results.flatMap((r) => ((r.output as { assets?: { assetId: string; name: string; duration: number }[] })?.assets ?? []));
if (!importAssets.length) fail(`import landed no asset: ${imported.text}`);
const asset = importAssets[0];
console.log(`imported asset ${asset.assetId} "${asset.name}" (${asset.duration}s)`);
- if (imported.view.history?.undo !== `Imported ${asset.name}`) fail(`import is not on the undo history: ${JSON.stringify(imported.view.history)}`);
const inspected = await call("inspect_project", { projectId });
const state = inspected.view.results[0]?.output as { media?: unknown[] } | undefined;
@@ -118,7 +169,6 @@ try {
if (after.aspect !== "9:16") fail(`aspect did not save: ${after.aspect}`);
if (!(after.clips?.length === 1)) fail(`clip did not save: ${JSON.stringify(after.clips)}`);
if (after.version <= before.version) fail("the edit did not bump the version");
- if (placed.view.history?.undo !== "Vertical frame with the footage") fail(`history missing the step: ${JSON.stringify(placed.view.history)}`);
// A batch stops at its first failure and reports how far it got.
const broken = await settle(
@@ -152,14 +202,14 @@ try {
console.log("edited: aspect, clip, trim, title and a captured frame");
const undone = await call("undo", { projectId });
+ if (!undone.view.changed) fail(`undo changed nothing: ${undone.text}`);
const reverted = await doc(projectId);
if ((reverted.overlays ?? []).some((o) => o.text === "MADE IN CHATGPT")) fail("undo left the title in place");
- if (undone.view.history?.redo !== "Trim and title") fail(`redo not offered: ${JSON.stringify(undone.view.history)}`);
const redone = await call("redo", { projectId });
+ if (!redone.view.changed) fail(`redo changed nothing: ${redone.text}`);
const restored = await doc(projectId);
if (!(restored.overlays ?? []).some((o) => o.text === "MADE IN CHATGPT")) fail("redo did not bring the title back");
- if (redone.view.history?.undo !== "Trim and title") fail(`undo not offered after redo: ${JSON.stringify(redone.view.history)}`);
- console.log("undo and redo walk the history");
+ console.log("undo and redo step the card's history");
const previewed = await call("render_preview", { projectId });
if (!previewed.view.preview) fail("render_preview queued nothing");
@@ -173,6 +223,8 @@ try {
if (!head.ok) fail(`the export download answered ${head.status}`);
console.log(`PASS exported ${meta.download.name} (${head.headers.get("content-length")} bytes)`);
} finally {
+ card.abort();
+ await hosting?.catch(() => {});
await client.close().catch(() => {});
await server.close().catch(() => {});
if (projectId && !keep) await deleteProjectCascade(USER_ID, projectId).catch((e) => console.error("cleanup failed:", e));
diff --git a/site/src/clients/chatgpt/contracts.ts b/site/src/clients/chatgpt/contracts.ts
index 378ff24e..48da494f 100644
--- a/site/src/clients/chatgpt/contracts.ts
+++ b/site/src/clients/chatgpt/contracts.ts
@@ -13,14 +13,12 @@ export const exportSchema = z.object({ id: z.string(), status: jobStatusSchema,
export const jobSchema = z.object({ id: z.string(), kind: z.string(), status: jobStatusSchema, progress: z.number(), error: z.string().optional() });
/** One command's outcome inside a batch. */
export const outcomeSchema = z.object({ name: z.string(), ok: z.boolean(), output: z.unknown().optional(), error: z.string().optional() });
-/** What undo and redo would each revert, by the step's label. */
-export const historySchema = z.object({ undo: z.string().nullish(), redo: z.string().nullish() });
export const accountSchema = z.object({ credits: z.string(), storageBytes: z.number(), storageQuotaBytes: z.number().nullish(), plan: z.string() });
export const viewSchema = z.object({
view: z.enum(["projects", "project"]), projects: z.array(projectSchema), nextCursor: z.string().nullish(),
project: projectSchema.nullish(), preview: previewSchema.nullish(), canRender: z.boolean(), canEdit: z.boolean(),
export: exportSchema.nullish(), job: jobSchema.nullish(), results: z.array(outcomeSchema), changed: z.boolean(),
- history: historySchema.nullish(), account: accountSchema.nullish(),
+ account: accountSchema.nullish(),
});
export const playbackSchema = z.object({ url: z.url(), expiresAt: z.number() });
export const downloadSchema = z.object({ url: z.url(), expiresAt: z.number(), name: z.string() });
diff --git a/site/src/clients/chatgpt/server/catalog.ts b/site/src/clients/chatgpt/server/catalog.ts
index 26e68972..09dc4c39 100644
--- a/site/src/clients/chatgpt/server/catalog.ts
+++ b/site/src/clients/chatgpt/server/catalog.ts
@@ -1,4 +1,5 @@
import type { AiToolDef } from "@/cut/lib/aiToolDef";
+import { ADOPT_COMMAND } from "@/cut/lib/commandBatch";
import { AI_SKILL_INDEX, AI_SKILLS, PROJECT_TOOLS } from "@/cut/server/ai/catalog";
// The editing commands ChatGPT can run, drawn from the editor's own tool
@@ -31,9 +32,9 @@ const HIDDEN = new Set([
export const COMMANDS: AiToolDef[] = PROJECT_TOOLS.filter((tool) => !HIDDEN.has(tool.name));
export const COMMAND_NAMES = COMMANDS.map((tool) => tool.name);
-/** What a batch may name: the catalog, plus the state read inspect_project
- * runs by default. */
-const KNOWN_COMMANDS = new Set([...COMMAND_NAMES, "get_state"]);
+/** What a batch may name: the catalog, the state read inspect_project runs
+ * by default, and the adoption an import queues after its download. */
+const KNOWN_COMMANDS = new Set([...COMMAND_NAMES, "get_state", ADOPT_COMMAND]);
export const unknownCommandNames = (names: string[]): string[] => names.filter((name) => !KNOWN_COMMANDS.has(name));
/** Commands whose output matters and whose effect is on the caller's eyes:
diff --git a/site/src/clients/chatgpt/server/mcp.test.ts b/site/src/clients/chatgpt/server/mcp.test.ts
index ec2ef0dd..00198760 100644
--- a/site/src/clients/chatgpt/server/mcp.test.ts
+++ b/site/src/clients/chatgpt/server/mcp.test.ts
@@ -37,7 +37,6 @@ const data: ProjectResult = {
job: null,
results: [],
changed: false,
- history: null,
account: null,
},
playback: {
@@ -334,7 +333,6 @@ test("edit results reach the model as text and structure, and captured frames be
view: {
...data.view,
changed: true,
- history: { undo: "Vertical cut", redo: null },
results: [
{ name: "set_aspect", ok: true, output: { aspect: "9:16" } },
{ name: "capture_frame", ok: true, output: { image: frame, at: 1.5 } },
@@ -375,7 +373,6 @@ test("edit results reach the model as text and structure, and captured frames be
});
const content = result.content as { type: string; text?: string; data?: string; mimeType?: string }[];
expect(content[0].text).toContain("2 commands ran; the project was saved");
- expect(content[0].text).toContain("Undo would revert: Vertical cut");
expect(content[0].text).not.toContain("base64");
expect(content[1]).toMatchObject({ type: "image", mimeType: "image/jpeg", data: "/9j/4AAQ" });
expect(JSON.stringify(result.structuredContent)).not.toContain("base64");
diff --git a/site/src/clients/chatgpt/server/mcp.ts b/site/src/clients/chatgpt/server/mcp.ts
index c0ff5fa1..621d9b09 100644
--- a/site/src/clients/chatgpt/server/mcp.ts
+++ b/site/src/clients/chatgpt/server/mcp.ts
@@ -52,8 +52,8 @@ export const REPOSITORY_URL = "https://github.com/DonkeyCut/Donkey";
export const SERVER_INSTRUCTIONS = [
`Donkey Cut is an open-source video editor (Apache 2.0, ${REPOSITORY_URL}). Edit the connected account's cloud projects: import footage, inspect it, cut it, caption it, preview, undo, export.`,
"Editing, previews and exports are free. Hosted AI (voiceover, music, images, caption rewriting, transcription past the monthly allowance) spends the account's credits. Imports and exports use the account's cloud storage.",
- "Workflow: list_projects or create_project → import_media → inspect_project → list_commands once, describe_commands for the ones you need → edit_project (batches, one undo step each) → render_preview → undo/redo → export_video.",
- "open_project puts the full Donkey Cut editor in the card, timeline and panels included, when the connection can edit; a read-only connection sees the current preview playing. Call render_preview only after an edit or when the card reports no current preview.",
+ "Workflow: list_projects or create_project → open_project → import_media → inspect_project → list_commands once, describe_commands for the ones you need → edit_project (batches, one undo step each) → render_preview → undo/redo → export_video.",
+ "Every edit runs inside the Donkey Cut editor in the card, on the document the user is looking at: open_project puts that editor in the card, timeline and panels included, when the connection can edit, and edit_project, inspect_project, import_media, undo and redo answer that no card is open until it is. A read-only connection sees the current preview playing. Call render_preview only after an edit or when the card reports no current preview.",
"Times are seconds; ids come from inspect_project. A batch stops at its first failed command. A tool that answers with a job still running is finished by get_job_status.",
].join("\n");
@@ -250,7 +250,7 @@ export function createChatgptServer(
audio_only: z.boolean().optional(),
}),
outputSchema: viewSchema,
- annotations: { ...editAnnotations, openWorldHint: true },
+ annotations: editAnnotations,
_meta: { ...editMetadata, "openai/fileParams": ["files"], ...status("Importing footage", "Footage imported") },
},
({ projectId, files, urls, audio_only }) =>
@@ -364,7 +364,7 @@ export function createChatgptServer(
{
title: "Edit a project",
description:
- "Run editing commands on a cloud project, in order, as one undo step. Commands come from list_commands with inputs per describe_commands; ids and times come from inspect_project. The batch stops at the first command that fails and reports every outcome. label names the step for undo. Editing is free; commands that generate media (voiceover_generate, generate_music, generate_image, captions_generate) spend the account's credits. The result's history says what undo would revert.",
+ "Run editing commands on a cloud project, in order, as one undo step in the editor open in the card. Commands come from list_commands with inputs per describe_commands; ids and times come from inspect_project. The batch stops at the first command that fails and reports every outcome. label names the step for undo. Editing is free; commands that generate media (voiceover_generate, generate_music, generate_image, captions_generate) spend the account's credits.",
inputSchema: z.object({
projectId: idSchema,
commands: z.array(commandSchema).min(1).max(MAX_COMMANDS_PER_BATCH),
@@ -382,7 +382,7 @@ export function createChatgptServer(
"undo",
{
title: "Undo the last edit",
- description: "Revert the last edit_project or import_media step on a project. Steps saved from the Donkey Cut editor itself are not on this history.",
+ description: "Undo the last step in the editor open in the card, the same as ⌘Z there: edit_project batches, imports and the user's own edits share one history.",
inputSchema: z.object({ projectId: idSchema }),
outputSchema: viewSchema,
annotations: editAnnotations,
@@ -395,7 +395,7 @@ export function createChatgptServer(
"redo",
{
title: "Redo an undone edit",
- description: "Re-apply the step the last undo reverted.",
+ description: "Re-apply the step the last undo reverted, in the editor open in the card.",
inputSchema: z.object({ projectId: idSchema }),
outputSchema: viewSchema,
annotations: editAnnotations,
@@ -539,8 +539,6 @@ function describeProjectView(view: ProjectView): string {
}.`,
);
}
- if (view.history?.undo) lines.push(`Undo would revert: ${view.history.undo}.`);
- if (view.history?.redo) lines.push(`Redo would re-apply: ${view.history.redo}.`);
lines.push(`Open in Donkey Cut: ${project.url}`);
return lines.join("\n");
}
diff --git a/site/src/clients/chatgpt/server/projects.ts b/site/src/clients/chatgpt/server/projects.ts
index 2df08849..540b3f35 100644
--- a/site/src/clients/chatgpt/server/projects.ts
+++ b/site/src/clients/chatgpt/server/projects.ts
@@ -2,11 +2,11 @@ import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
import { getCreditBalance } from "@/lib/credits/inference";
import { getActiveProSubscription } from "@/lib/billing/pro-subscription";
-import { isDonkeySuperUser } from "@/lib/donkey-api-auth";
+import { isDonkeySuperUser } from "@/lib/super-user";
import { normalizeAspect, type ProjectDoc } from "@/cut/lib/types";
-import { queueCommands, waitForJob, type CommandCall, type CommandJobResult, type JobRow } from "@/cut/server/cloud/commands";
-import { historyState, HistoryError, restoreCheckpoint } from "@/cut/server/cloud/history";
-import { queueDocExport, queueImportUrl } from "@/cut/server/cloud/jobs";
+import { ADOPT_COMMAND, type AdoptedAsset } from "@/cut/lib/commandBatch";
+import { NO_CARD_OPEN, queueCommands, waitForJob, type CommandCall, type CommandJobResult, type JobRow } from "@/cut/server/cloud/commands";
+import { needsWorker, queueDocExport, queueImportUrl } from "@/cut/server/cloud/jobs";
import { cutLimitsFor } from "@/cut/server/cloud/limits";
import { previewFromDoc } from "@/cut/server/cloud/previewJobs";
import { mediaObjectUrl, mediaUrlLifetime } from "@/cut/server/cloud/mediaCdn";
@@ -23,13 +23,15 @@ export class ProjectToolError extends Error {}
export type ProjectResult = { view: ProjectView; playback: Playback | null; download?: Download | null; editor?: Editor | null };
/** A queue helper's refusal, read out of its Response as a message. */
-async function refusal(res: Response): Promise<never> {
+async function refusalText(res: Response): Promise<string> {
const body = (await res.json().catch(() => ({}))) as { error?: string; bytes?: number; quotaBytes?: number };
if (body.error === "storage_quota_exceeded")
- throw new ProjectToolError(
- `The account's cloud storage is full (${mb(body.bytes ?? 0)} of ${mb(body.quotaBytes ?? 0)} MB). Delete media or exports in Donkey Cut, or upgrade the plan.`
- );
- throw new ProjectToolError(body.error ?? "Donkey Cut refused the request.");
+ return `The account's cloud storage is full (${mb(body.bytes ?? 0)} of ${mb(body.quotaBytes ?? 0)} MB). Delete media or exports in Donkey Cut, or upgrade the plan.`;
+ return body.error ?? "Donkey Cut refused the request.";
+}
+
+async function refusal(res: Response): Promise<never> {
+ throw new ProjectToolError(await refusalText(res));
}
const mb = (bytes: number) => Math.round(bytes / 1024 ** 2);
@@ -69,7 +71,6 @@ export function projectTools(
job: null,
results: [],
changed: false,
- history: null,
account: null,
});
@@ -90,16 +91,9 @@ export function projectTools(
return projectSummary(await getOwnedRow(projectId));
}
- /** The project view with its undo state, as every edit tool answers. */
+ /** The project view every edit tool answers with. */
async function projectView(projectId: string): Promise<ProjectView> {
- const project = await getOwnedProject(projectId);
- const version = Number(project.revision.slice("cloud:".length));
- return {
- ...emptyProjectView(),
- view: "project",
- project,
- history: await historyState(db, identity.userId, projectId, version),
- };
+ return { ...emptyProjectView(), view: "project", project: await getOwnedProject(projectId) };
}
function requireEdit() {
@@ -224,30 +218,111 @@ export function projectTools(
if (row.kind === "export") return exportView(row);
if (row.kind === "preview" && row.projectId) return getPreviewStatus(row.projectId, row.id);
if (!row.projectId) throw new ProjectToolError("Job not found.");
+ if (row.kind === "import_url" && row.state === "done") return importView(row);
+ if (row.kind === "commands" && row.state === "dismissed") throw new ProjectToolError(NO_CARD_OPEN);
const view = await projectView(row.projectId);
const status = jobStatus(row);
view.job = { id: row.id, kind: row.kind, status, progress: Math.max(0, Math.min(1, row.progress)), ...(jobError(row) ? { error: jobError(row) } : {}) };
- if (status === "queued" || status === "running") wakeRenderWorker();
- if (status !== "done") return { view, playback: null };
- if (row.kind === "commands") {
+ if (row.kind !== "commands" && needsWorker(row)) wakeRenderWorker();
+ if (status === "done" && row.kind === "commands") {
const result = row.result as CommandJobResult | null;
view.results = result?.results ?? [];
view.changed = result?.changed ?? false;
- } else if (row.kind === "import_url") {
- const result = row.result as ImportUrlResult | null;
- view.results = [{ name: "import_media", ok: true, output: { assets: result?.assets ?? [], ...(result?.text ? { sourceText: result.text } : {}) } }];
- view.changed = (result?.assets?.length ?? 0) > 0;
}
return { view, playback: null };
}
+ /** A finished import as a result: its files become assets through a batch
+ * the editor in the card runs, and the import counts as done once they have. */
+ async function importView(row: JobRow): Promise<ProjectResult> {
+ const adoption = await adoptImport(row);
+ const view = await projectView(row.projectId!);
+ view.results = [importOutcome(row, adoption)];
+ view.changed = adoption.state === "adopted" && adoption.assets.length > 0;
+ if (adoption.state === "pending") view.job = { id: row.id, kind: row.kind, status: "running", progress: 1 };
+ if (adoption.state === "failed") view.job = { id: row.id, kind: row.kind, status: "error", progress: 1, error: adoption.error };
+ return { view, playback: null };
+ }
+
+ type Adoption =
+ | { state: "adopted"; assets: AdoptedAsset[] }
+ | { state: "pending" }
+ | { state: "failed"; error: string };
+
+ /** What the import row remembers past the download: the batch adopting its
+ * files, then the assets that batch landed. */
+ type ImportRecord = ImportUrlResult & { adoptJobId?: string; assets?: AdoptedAsset[] };
+
+ const importRecord = (row: JobRow) => (row.result ?? {}) as unknown as ImportRecord;
+
+ async function rememberOnImport(row: JobRow, patch: Partial<ImportRecord>): Promise<void> {
+ await db.cutRenderJob.updateMany({
+ where: { id: row.id, userId: identity.userId },
+ data: { result: { ...importRecord(row), ...patch } as unknown as Prisma.InputJsonValue },
+ });
+ }
+
+ /** Queue the batch that adopts a finished import's files, once. A batch
+ * dismissed because no card was open is queued again on the next poll. */
+ async function adoptionBatch(row: JobRow, record: ImportRecord): Promise<{ id: string } | Response> {
+ if (record.adoptJobId) {
+ const previous = await db.cutRenderJob.findFirst({ where: { id: record.adoptJobId, userId: identity.userId }, select: { id: true, state: true } });
+ if (previous && previous.state !== "dismissed") return { id: previous.id };
+ }
+ const files = record.files ?? [];
+ const name = (row.spec as { name?: string } | null)?.name;
+ const queued = await queueCommands(identity.userId, row.projectId!, {
+ commands: [{ name: ADOPT_COMMAND, input: { files, ...(name ? { name } : {}) } }],
+ label: `Imported ${files.map((f) => f.title || f.fileName).join(", ")}`,
+ });
+ if (!(queued instanceof Response)) await rememberOnImport(row, { adoptJobId: queued.id });
+ return queued;
+ }
+
+ /** Turn a finished import's files into project assets, through a batch the
+ * editor in the card runs. Once the batch lands, the assets are written
+ * back to the import row and every poll after reads them from there. */
+ async function adoptImport(row: JobRow): Promise<Adoption> {
+ const record = importRecord(row);
+ if (record.assets) return { state: "adopted", assets: record.assets };
+ if (!record.files?.length || !row.projectId) return { state: "adopted", assets: [] };
+ const queued = await adoptionBatch(row, record);
+ if (queued instanceof Response) return { state: "failed", error: await refusalText(queued) };
+ const batch = await waitForJob(identity.userId, queued.id, config.commandWaitMs, { editorClaimMs: config.editorClaimMs });
+ if (!batch) return { state: "failed", error: "The import could not be added to the project." };
+ if (batch.state === "queued" || batch.state === "running") return { state: "pending" };
+ if (batch.state === "dismissed") return { state: "failed", error: NO_CARD_OPEN };
+ const result = batch.result as CommandJobResult | null;
+ const outcome = result?.results?.[0];
+ if (batch.state !== "done" || !outcome?.ok)
+ return { state: "failed", error: outcome?.error ?? jobError(batch) ?? "The import could not be added to the project." };
+ const assets = (outcome.output as { assets?: AdoptedAsset[] } | null)?.assets ?? [];
+ await rememberOnImport(row, { assets, ...(result?.docVersion ? { docVersion: result.docVersion } : {}) });
+ return { state: "adopted", assets };
+ }
+
+ /** An import's line in the results, from where its adoption stands. */
+ function importOutcome(row: JobRow, adoption: Adoption): ProjectView["results"][number] {
+ const text = importRecord(row).text;
+ const sourceText = text ? { sourceText: text } : {};
+ switch (adoption.state) {
+ case "adopted":
+ return { name: "import_media", ok: true, output: { jobId: row.id, assets: adoption.assets, ...sourceText } };
+ case "pending":
+ return { name: "import_media", ok: true, output: { jobId: row.id, status: "running", detail: "The files are landing in the project. Poll get_job_status." } };
+ case "failed":
+ return { name: "import_media", ok: false, error: adoption.error };
+ }
+ }
+
async function ownedJob(jobId: string): Promise<JobRow> {
const row = await db.cutRenderJob.findFirst({ where: { id: jobId, userId: identity.userId } });
if (!row) throw new ProjectToolError("Job not found.");
return row;
}
- /** Queue a batch and wait on it within the call's budget. */
+ /** Queue a batch for the editor in the card and wait on it within the
+ * call's budget. */
async function runBatch(projectId: string, commands: CommandCall[], opts: { readOnly?: boolean; label?: string }): Promise<ProjectResult> {
await getOwnedProject(projectId);
const unknown = unknownCommandNames(commands.map((c) => c.name));
@@ -255,11 +330,18 @@ export function projectTools(
throw new ProjectToolError(`Unknown command${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")}. Call list_commands for the catalog.`);
const queued = await queueCommands(identity.userId, projectId, { commands, ...opts });
if (queued instanceof Response) return refusal(queued);
- const row = await waitForJob(identity.userId, queued.id, config.commandWaitMs);
+ const row = await waitForJob(identity.userId, queued.id, config.commandWaitMs, { editorClaimMs: config.editorClaimMs });
if (!row) throw new ProjectToolError("The job disappeared. Try again.");
return jobView(row);
}
+ /** Undo or redo in the editor in the card: its history holds ChatGPT's
+ * batches and the user's own edits as one line. */
+ async function step(projectId: string, direction: "undo" | "redo"): Promise<ProjectResult> {
+ requireEdit();
+ return runBatch(projectId, [{ name: direction, input: {} }], { label: direction });
+ }
+
return {
async list(cursor?: string): Promise<ProjectResult> {
// A cursor names an account-owned row, so a foreign id cannot influence pagination.
@@ -329,7 +411,7 @@ export function projectTools(
data: { userId: identity.userId, name: doc.name, doc: doc as unknown as Prisma.InputJsonValue },
select: { id: true, name: true, version: true },
});
- return { view: { ...emptyProjectView(), view: "project", project: projectSummary(row), history: { undo: null, redo: null } }, playback: null };
+ return { view: { ...emptyProjectView(), view: "project", project: projectSummary(row) }, playback: null };
},
async inspect(projectId: string, commands?: CommandCall[]): Promise<ProjectResult> {
@@ -353,7 +435,7 @@ export function projectTools(
const queued = await queueImportUrl(identity.userId, projectId, {
url: item.url,
audio: audioOnly,
- adopt: item.name ? { name: item.name } : {},
+ ...(item.name ? { name: item.name } : {}),
});
if (queued instanceof Response) {
if (ids.length === 0) return refusal(queued);
@@ -368,53 +450,34 @@ export function projectTools(
if (row) rows.push(row);
}
const view = await projectView(projectId);
- const pending = rows.filter((r) => r.state === "queued" || r.state === "running");
+ // Every import still downloading or still landing names its job, so
+ // none is lost once the call returns; the first is the job the view
+ // carries.
+ const pending: JobRow[] = [];
for (const row of rows) {
- const status = jobStatus(row);
- if (status === "done") {
- const result = row.result as ImportUrlResult | null;
- view.results.push({ name: "import_media", ok: true, output: { jobId: row.id, assets: result?.assets ?? [], ...(result?.text ? { sourceText: result.text } : {}) } });
- view.changed ||= (result?.assets?.length ?? 0) > 0;
- } else if (status === "error") {
+ if (row.state === "done") {
+ const adoption = await adoptImport(row);
+ view.results.push(importOutcome(row, adoption));
+ if (adoption.state === "adopted" && adoption.assets.length > 0) view.changed = true;
+ if (adoption.state === "pending") pending.push(row);
+ } else if (row.state === "queued" || row.state === "running") {
+ view.results.push({ name: "import_media", ok: true, output: { jobId: row.id, status: jobStatus(row) } });
+ pending.push(row);
+ } else {
view.results.push({ name: "import_media", ok: false, error: jobError(row) ?? "The import failed." });
}
}
- // Every unfinished import names its job, so none is lost once the call
- // returns; the first one is the job the view carries.
- for (const row of pending)
- view.results.push({ name: "import_media", ok: true, output: { jobId: row.id, status: jobStatus(row) } });
if (pending.length) {
const row = pending[0];
- view.job = { id: row.id, kind: row.kind, status: jobStatus(row), progress: row.progress };
+ view.job = { id: row.id, kind: row.kind, status: "running", progress: Math.max(0, Math.min(1, row.progress)) };
}
if (ids.length < items.length)
view.results.push({ name: "import_media", ok: false, error: `${items.length - ids.length} item(s) were not queued: the account's job cap was reached.` });
return { view, playback: null };
},
- async undo(projectId: string): Promise<ProjectResult> {
- requireEdit();
- await getOwnedProject(projectId);
- const step = await restoreCheckpoint(db, identity.userId, projectId, "undo").catch((e) => {
- throw e instanceof HistoryError ? new ProjectToolError(e.message) : e;
- });
- const view = await projectView(projectId);
- view.changed = true;
- view.results = [{ name: "undo", ok: true, output: { undone: step.label } }];
- return { view, playback: null };
- },
-
- async redo(projectId: string): Promise<ProjectResult> {
- requireEdit();
- await getOwnedProject(projectId);
- const step = await restoreCheckpoint(db, identity.userId, projectId, "redo").catch((e) => {
- throw e instanceof HistoryError ? new ProjectToolError(e.message) : e;
- });
- const view = await projectView(projectId);
- view.changed = true;
- view.results = [{ name: "redo", ok: true, output: { redone: step.label } }];
- return { view, playback: null };
- },
+ undo: (projectId: string) => step(projectId, "undo"),
+ redo: (projectId: string) => step(projectId, "redo"),
async exportVideo(projectId: string, preset: string): Promise<ProjectResult> {
requireEdit();
diff --git a/site/src/clients/chatgpt/ui/PreviewApp.tsx b/site/src/clients/chatgpt/ui/PreviewApp.tsx
index c67a9952..40651bba 100644
--- a/site/src/clients/chatgpt/ui/PreviewApp.tsx
+++ b/site/src/clients/chatgpt/ui/PreviewApp.tsx
@@ -41,13 +41,10 @@ export function PreviewApp() {
{exporting && <div role="status"><p>{exp.status === "queued" ? "Waiting to export…" : `Exporting ${exp.name ?? "video"}… ${Math.round(exp.progress * 100)}%`}</p><progress max={1} value={exp.progress} /></div>}
{exp?.status === "done" && !download && <p className="muted">Export {exp.name ?? ""} finished. Renewing the download link…</p>}
{(exp?.status === "error" || exp?.status === "expired") && <p role="alert">{exp.error ?? "The export did not finish."}</p>}
- {view.history?.undo && <p className="muted">Last step: {view.history.undo}</p>}
<nav>
{view.canRender && <button className="primary" disabled={busy || rendering || !ready} onClick={() => void run("render_preview", { projectId: project.id })}>Render preview</button>}
{download && <button className="primary" disabled={!ready} onClick={() => openDownload()}>Download {download.name}</button>}
{view.canEdit && <button disabled={busy || exporting || !ready} onClick={() => void run("export_video", { projectId: project.id })}>Export video</button>}
- {view.canEdit && view.history?.undo && <button disabled={busy || !ready} onClick={() => void run("undo", { projectId: project.id })}>Undo</button>}
- {view.canEdit && view.history?.redo && <button disabled={busy || !ready} onClick={() => void run("redo", { projectId: project.id })}>Redo</button>}
<button disabled={!ready} onClick={() => openDonkey()}>Open in Donkey Cut ↗</button>
<button disabled={busy || !ready} onClick={() => void run("list_projects", {})}>Projects</button>
{error && <button disabled={busy || !ready} onClick={() => void run("open_project", { projectId: project.id })}>Try again</button>}
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index cd29847b..8cb0a0e4 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -3936,12 +3936,12 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
},
undo: (s) => {
- s.undo();
+ if (!s.undo()) throw new ToolError("Nothing to undo.");
return { ok: true };
},
redo: (s) => {
- s.redo();
+ if (!s.redo()) throw new ToolError("Nothing to redo.");
return { ok: true };
},
diff --git a/site/src/cut/lib/commandBatch.test.ts b/site/src/cut/lib/commandBatch.test.ts
new file mode 100644
index 00000000..18663159
--- /dev/null
+++ b/site/src/cut/lib/commandBatch.test.ts
@@ -0,0 +1,47 @@
+import { expect, test } from "bun:test";
+import { boundMedia, runCommandBatch } from "./commandBatch";
+
+test("a batch runs in order and stops at the first failure", async () => {
+ const seen: string[] = [];
+ const results = await runCommandBatch(
+ "p",
+ [{ name: "a", input: { n: 1 } }, { name: "b", input: {} }, { name: "c", input: {} }],
+ async (name, input) => {
+ seen.push(name);
+ if (name === "b") throw new Error("b broke");
+ return { input };
+ }
+ );
+ expect(seen).toEqual(["a", "b"]);
+ expect(results).toEqual([
+ { name: "a", ok: true, output: { input: { n: 1 } } },
+ { name: "b", ok: false, error: "b broke" },
+ ]);
+});
+
+test("progress is reported per command and cancellation stops the batch", async () => {
+ const fractions: number[] = [];
+ let canceled = false;
+ await expect(
+ runCommandBatch(
+ "p",
+ [{ name: "a", input: {} }, { name: "b", input: {} }],
+ async () => { canceled = true; return null; },
+ { isCanceled: () => canceled, onProgress: (f) => fractions.push(f) }
+ )
+ ).rejects.toThrow("Canceled.");
+ expect(fractions).toEqual([0]);
+});
+
+test("inline media past the budget is dropped with a note", () => {
+ const big = `data:image/png;base64,${"x".repeat(2 * 1024 * 1024)}`;
+ const results = [
+ { name: "capture_frame", ok: true, output: { image: big } },
+ { name: "capture_frame", ok: true, output: { image: big } },
+ { name: "watch_video", ok: true, output: { images: [big, "https://cdn/x.png"] } },
+ ];
+ boundMedia(results);
+ expect(results[0].output.image).toBe(big);
+ expect(typeof results[1].output.image === "string" && results[1].output.image.startsWith("[dropped")).toBe(true);
+ expect(results[2].output.images?.[1]).toBe("https://cdn/x.png");
+});
diff --git a/site/src/cut/lib/commandBatch.ts b/site/src/cut/lib/commandBatch.ts
new file mode 100644
index 00000000..e401d151
--- /dev/null
+++ b/site/src/cut/lib/commandBatch.ts
@@ -0,0 +1,116 @@
+// A batch of typed editor commands, run by the editor inside the ChatGPT
+// card on the document the user is looking at.
+import { adoptImportedFiles } from "./media";
+
+export interface CommandCall {
+ name: string;
+ input: Record<string, unknown>;
+}
+
+export interface CommandJobSpec {
+ commands: CommandCall[];
+ /** A read: the document is inspected, never saved. */
+ readOnly?: boolean;
+ /** The undo history's name for this batch. */
+ label?: string;
+}
+
+export interface CommandOutcome {
+ name: string;
+ ok: boolean;
+ output?: unknown;
+ error?: string;
+}
+
+/** What a commands job records in CutRenderJob.result. */
+export interface CommandJobResult {
+ results: CommandOutcome[];
+ /** The document changed and was saved. */
+ changed: boolean;
+ /** The project version after the save, when one happened. */
+ docVersion: string | null;
+}
+
+/** Register files an import landed in the project's media as assets. An
+ * internal command: the import job downloads, the batch that follows adopts,
+ * so the adoption happens in the open editor. */
+export const ADOPT_COMMAND = "adopt_imported_files";
+
+export interface AdoptedAsset {
+ assetId: string;
+ name: string;
+ kind: string;
+ duration: number;
+}
+
+/** The undo history's name for a batch: its label, or the commands that ran. */
+export function batchLabel(spec: Pick<CommandJobSpec, "label">, results: CommandOutcome[]): string {
+ return spec.label?.trim() || results.filter((r) => r.ok).map((r) => r.name).join(", ") || "Edit";
+}
+
+/** Contact sheets, captured frames and listened audio ride in the result as
+ * data URLs. The result is one POST to the hosted API, whose request body
+ * caps at 4.5 MB, so past this much the later ones are dropped and say so. */
+const MAX_MEDIA_BYTES = 3.5 * 1024 * 1024;
+
+/** Keep the batch's inline media (frames, sheets, listened audio) inside one
+ * result budget. */
+export function boundMedia(results: CommandOutcome[]): void {
+ let budget = MAX_MEDIA_BYTES;
+ const take = (url: unknown): unknown => {
+ if (typeof url !== "string" || !url.startsWith("data:")) return url;
+ if (url.length <= budget) {
+ budget -= url.length;
+ return url;
+ }
+ return "[dropped: the batch's inline media exceeds the result budget — ask for this in its own call]";
+ };
+ for (const r of results) {
+ const out = r.output as { image?: unknown; images?: unknown[]; audio?: unknown } | null;
+ if (!out || typeof out !== "object") continue;
+ if ("image" in out) out.image = take(out.image);
+ if (Array.isArray(out.images)) out.images = out.images.map(take);
+ if ("audio" in out) out.audio = take(out.audio);
+ }
+}
+
+async function adoptFiles(projectId: string, input: Record<string, unknown>): Promise<{ assets: AdoptedAsset[] }> {
+ const files = Array.isArray(input.files) ? (input.files as { fileName?: unknown; title?: unknown }[]) : [];
+ const name = typeof input.name === "string" && input.name.trim() ? input.name.trim() : null;
+ const landed = files
+ .filter((f): f is { fileName: string; title?: unknown } => typeof f?.fileName === "string" && f.fileName.length > 0)
+ .map((f) => ({ fileName: f.fileName, title: typeof f.title === "string" && f.title ? f.title : f.fileName }));
+ // The name the user gave applies when it can only mean one file.
+ if (name && landed.length === 1) landed[0].title = name;
+ const { assets } = await adoptImportedFiles(projectId, { files: landed });
+ return {
+ assets: assets.map((a) => ({ assetId: a.id, name: a.name, kind: a.type, duration: Math.round(a.duration * 100) / 100 })),
+ };
+}
+
+/** Run the commands in order through `exec`. The batch stops at the first
+ * failure: later commands assumed this one landed, and the caller sees
+ * exactly how far it got. */
+export async function runCommandBatch(
+ projectId: string,
+ commands: CommandCall[],
+ exec: (name: string, input: Record<string, unknown>) => Promise<unknown>,
+ opts: { isCanceled?: () => boolean; onProgress?: (fraction: number) => void } = {}
+): Promise<CommandOutcome[]> {
+ const results: CommandOutcome[] = [];
+ for (const [i, call] of commands.entries()) {
+ if (opts.isCanceled?.()) throw new Error("Canceled.");
+ opts.onProgress?.(i / commands.length);
+ const input = call.input ?? {};
+ try {
+ const output = call.name === ADOPT_COMMAND ? await adoptFiles(projectId, input) : await exec(call.name, input);
+ results.push({ name: call.name, ok: true, output: output ?? null });
+ } catch (err) {
+ results.push({ name: call.name, ok: false, error: err instanceof Error ? err.message : String(err) });
+ break;
+ }
+ }
+ boundMedia(results);
+ opts.onProgress?.(1);
+ return results;
+}
diff --git a/site/src/cut/lib/hostCommands.ts b/site/src/cut/lib/hostCommands.ts
new file mode 100644
index 00000000..2e863e6b
--- /dev/null
+++ b/site/src/cut/lib/hostCommands.ts
@@ -0,0 +1,140 @@
+"use client";
+
+import { useEffect } from "react";
+import { runAiTool } from "./aiTools";
+import { apiFetch } from "./backend";
+import { runCommandBatch, type CommandJobSpec } from "./commandBatch";
+import { flushEditorSave } from "./editorWork";
+import { withChatProject } from "./projectChatTools";
+import { projectRevision } from "./projectRevision";
+import { serializeDoc, useEditor } from "./store";
+
+/**
+ * The editor inside the ChatGPT card runs the batches ChatGPT sends. A tool
+ * call queues a batch for the project; this editor claims it, runs each
+ * command on the open document through the same executors the chat uses,
+ * saves, and reports the outcome, which the tool call then returns to
+ * ChatGPT. Each batch is one undo step here, so the user's own ⌘Z and
+ * ChatGPT's undo agree on what a step is.
+ */
+const POLL_MS = 1000;
+const HIDDEN_POLL_MS = 3000;
+const HEARTBEAT_MS = 10_000;
+
+const snapshot = () => JSON.stringify(serializeDoc(useEditor.getState()));
+
+const postJson = (path: string, body: unknown, init: RequestInit = {}) =>
+ apiFetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), ...init });
+
+type Report = { ok: true; results: unknown[]; changed: boolean; docVersion: string | null } | { ok: false; error: string };
+
+/** The claimed batch's line to the server: heartbeats while it runs, and one
+ * report when it ends. A heartbeat the server refuses means the batch is no
+ * longer this editor's (expired, canceled), so the run is aborted. */
+function claimedJobReporter(id: string, abort: () => void) {
+ const beat = window.setInterval(() => {
+ void postJson(`/api/cut/jobs/${id}/heartbeat`, {})
+ .then((res) => { if (res.status === 409) abort(); })
+ .catch(() => {});
+ }, HEARTBEAT_MS);
+ return {
+ stop: () => window.clearInterval(beat),
+ /** One retry covers a dropped connection; past that the server's own
+ * heartbeat expiry closes the batch. */
+ async report(body: Report, init: RequestInit = {}): Promise<void> {
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ const res = await postJson(`/api/cut/jobs/${id}/result`, body, init);
+ if (res.ok || res.status === 409) return;
+ } catch {
+ // Retry below.
+ }
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+ },
+ };
+}
+
+/** Run the batch on the open document as one undo step and save. */
+async function runBatchInEditor(projectId: string, spec: CommandJobSpec, signal: AbortSignal): Promise<Report> {
+ return withChatProject(projectId, async () => {
+ const before = snapshot();
+ if (!spec.readOnly) useEditor.getState().beginHistoryBatch();
+ let results;
+ try {
+ results = await runCommandBatch(projectId, spec.commands, (name, input) => runAiTool(name, input), { isCanceled: () => signal.aborted });
+ } finally {
+ if (!spec.readOnly) useEditor.getState().endHistoryBatch();
+ }
+ const changed = !spec.readOnly && snapshot() !== before;
+ let docVersion: string | null = null;
+ if (changed) {
+ await flushEditorSave(projectId);
+ // A keystroke during the save leaves the state dirty again; only a
+ // failed PUT means the batch's edit did not land.
+ if (useEditor.getState().saveState === "error") throw new Error("The edit could not be saved.");
+ docVersion = projectRevision(projectId);
+ }
+ return { ok: true, results, changed, docVersion };
+ }, signal);
+}
+
+async function runClaimed(projectId: string, id: string, spec: CommandJobSpec, parent: AbortSignal): Promise<void> {
+ const controller = new AbortController();
+ const onParentAbort = () => controller.abort();
+ parent.addEventListener("abort", onParentAbort);
+ const line = claimedJobReporter(id, () => controller.abort());
+ try {
+ const report = await runBatchInEditor(projectId, spec, controller.signal);
+ await line.report(report);
+ } catch (err) {
+ if (parent.aborted) {
+ // The card is closing mid-batch: tell the server so the batch ends now
+ // rather than at the heartbeat expiry. keepalive lets the request
+ // outlive the page.
+ await line.report({ ok: false, error: "The editor closed before the batch finished." }, { keepalive: true });
+ return;
+ }
+ if (!controller.signal.aborted)
+ await line.report({ ok: false, error: err instanceof Error ? err.message : String(err) });
+ } finally {
+ line.stop();
+ parent.removeEventListener("abort", onParentAbort);
+ }
+}
+
+/** Poll for batches queued on this project and run them, while the editor
+ * is hosted by ChatGPT with a cloud project open. */
+export function useHostCommands(projectId: string, enabled: boolean): void {
+ useEffect(() => {
+ if (!enabled) return;
+ const controller = new AbortController();
+ const { signal } = controller;
+ let timer = 0;
+ const schedule = (ms: number) => {
+ if (!signal.aborted) timer = window.setTimeout(tick, ms);
+ };
+ const claim = async (): Promise<{ id: string; spec: CommandJobSpec } | null> => {
+ const res = await apiFetch(`/api/cut/projects/${projectId}/commands/claim`, { method: "POST", signal });
+ return res.status === 200 ? ((await res.json()) as { id: string; spec: CommandJobSpec }) : null;
+ };
+ const tick = async () => {
+ if (signal.aborted) return;
+ let claimed: { id: string; spec: CommandJobSpec } | null = null;
+ try {
+ claimed = await claim();
+ } catch {
+ // A failed poll is asked again on the next tick.
+ }
+ if (!claimed) return schedule(document.hidden ? HIDDEN_POLL_MS : POLL_MS);
+ await runClaimed(projectId, claimed.id, claimed.spec, signal);
+ // Another batch may be waiting behind this one.
+ schedule(0);
+ };
+ schedule(0);
+ return () => {
+ controller.abort();
+ window.clearTimeout(timer);
+ };
+ }, [projectId, enabled]);
+}
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index fdedc4b8..7bdd6781 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -1014,7 +1014,7 @@ export async function importUrlMedia(
// rides the cloud worker and the bytes come back down.
if (backend.kind === "browser") {
const staged = await importUrlThroughCloud(projectId, backend, url, opts);
- return adoptImportedFiles(projectId, backend, staged);
+ return adoptImportedFiles(projectId, staged, backend);
}
const res = await backend.fetch(`/api/cut/projects/${projectId}/import-url`, {
method: "POST",
@@ -1035,15 +1035,15 @@ export async function importUrlMedia(
if (!res.ok || (!body.files?.length && !body.text)) {
throw new Error(body.error ?? "Could not import that URL.");
}
- return adoptImportedFiles(projectId, backend, body);
+ return adoptImportedFiles(projectId, body, backend);
}
/** Register the files an import landed in the project, in order, and hand back
* what the caller places. */
-async function adoptImportedFiles(
+export async function adoptImportedFiles(
projectId: string,
- backend: CutBackend,
- imported: { files?: { fileName: string; title: string }[]; text?: string }
+ imported: { files?: { fileName: string; title: string }[]; text?: string },
+ backend: CutBackend = getBackend()
): Promise<{ assets: MediaAsset[]; text?: string }> {
const assets: MediaAsset[] = [];
for (const f of imported.files ?? []) {
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 5cb9c1a7..45fe032a 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -870,8 +870,9 @@ export interface EditorState {
setAiOpen: (v: boolean) => void;
setInspectorOpen: (v: boolean) => void;
setTimelineOpen: (v: boolean) => void;
- undo: () => void;
- redo: () => void;
+ /** Step the history; false when there is nothing to step to. */
+ undo: () => boolean;
+ redo: () => boolean;
upsertRender: (r: RenderRecord) => void;
removeRenders: (ids: string[]) => void;
pushHistory: () => void;
@@ -4696,18 +4697,20 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
undo: () => {
flush(); // commit any uncommitted edit before stepping back
const prev = history.pop();
- if (!prev) return;
+ if (!prev) return false;
future.push(snapshot());
restoreDoc(prev);
+ return true;
},
redo: () => {
flush();
const next = future.pop();
- if (!next) return;
+ if (!next) return false;
history.push(snapshot());
if (history.length > HISTORY_CAP) history.shift();
restoreDoc(next);
+ return true;
},
};
});
diff --git a/site/src/cut/server/cloud/commands.test.ts b/site/src/cut/server/cloud/commands.test.ts
new file mode 100644
index 00000000..95201692
--- /dev/null
+++ b/site/src/cut/server/cloud/commands.test.ts
@@ -0,0 +1,124 @@
+import { afterAll, beforeEach, expect, mock, test } from "bun:test";
+import { prisma as actualPrisma } from "@/lib/prisma";
+
+// The commands module reaches the database through the shared client; this
+// stand-in keeps job rows in memory and answers the handful of calls the
+// queue, claim, expiry and settle paths make.
+type Row = {
+ id: string; userId: string; projectId: string | null; kind: string; state: string;
+ spec: Record<string, unknown>; result: unknown; error: string | null; progress: number;
+ claimedAt: Date | null; createdAt: Date; updatedAt: Date;
+};
+const rows: Row[] = [];
+const project = { id: "p", userId: "u", version: 4, doc: { name: "Cut" } };
+const woken = { count: 0 };
+const matches = (row: Row, where: Record<string, unknown>) =>
+ Object.entries(where).every(([k, v]) => {
+ const got = (row as Record<string, unknown>)[k];
+ if (v && typeof v === "object" && !(v instanceof Date)) {
+ const op = v as { in?: unknown[]; not?: unknown; lt?: Date };
+ if (op.in) return op.in.includes(got);
+ if ("not" in op) return got !== op.not;
+ if (op.lt) return (got as Date).getTime() < op.lt.getTime();
+ }
+ return got === v;
+ });
+const prisma = {
+ cutRenderJob: {
+ findFirst: mock(async ({ where }: { where: Record<string, unknown> }) => rows.find((r) => matches(r, where)) ?? null),
+ findMany: mock(async ({ where }: { where: Record<string, unknown> }) => rows.filter((r) => matches(r, where))),
+ updateMany: mock(async ({ where, data }: { where: Record<string, unknown>; data: Partial<Row> }) => {
+ const hit = rows.filter((r) => matches(r, where));
+ for (const r of hit) Object.assign(r, data, { updatedAt: new Date() });
+ return { count: hit.length };
+ }),
+ create: mock(async ({ data }: { data: Partial<Row> }) => {
+ const row: Row = { id: `j${rows.length + 1}`, userId: "u", projectId: "p", kind: "commands", state: "queued", spec: {}, result: null, error: null, progress: 0, claimedAt: null, createdAt: new Date(), updatedAt: new Date(), ...data } as Row;
+ rows.push(row);
+ return row;
+ }),
+ delete: mock(async ({ where }: { where: { id: string } }) => {
+ const at = rows.findIndex((r) => r.id === where.id);
+ if (at >= 0) rows.splice(at, 1);
+ return {};
+ }),
+ count: mock(async () => 0),
+ },
+ cutProject: {
+ findFirst: mock(async ({ where }: { where: { id: string } }) => (where.id === project.id ? { ...project } : null)),
+ },
+ // The account is a super user, so the live-job cap never applies.
+ user: { findUnique: mock(async () => ({ superUser: true })) },
+ settingOverride: { findUnique: mock(async () => null) },
+};
+mock.module("@/lib/prisma", () => ({ prisma }));
+// The wake is a POST to the worker; count those instead of the network.
+process.env.CUT_RENDER_WAKE_SECRET = "test-wake";
+const realFetch = globalThis.fetch;
+globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
+ if (String(url).endsWith("/wake") && init?.method === "POST") { woken.count++; return new Response("ok"); }
+ return realFetch(url, init);
+}) as typeof fetch;
+const { claimEditorBatch, CLAIM_QUIET_MS, heartbeatEditorBatch, NO_CARD_OPEN, queueCommands, settleEditorBatch, waitForJob } = await import("./commands");
+afterAll(() => { mock.module("@/lib/prisma", () => ({ prisma: actualPrisma })); globalThis.fetch = realFetch; });
+beforeEach(() => { rows.splice(0); woken.count = 0; });
+
+test("batches queue behind each other for the card without waking the worker, and the card claims them oldest first", async () => {
+ expect(await queueCommands("u", "p", { commands: [{ name: "set_aspect", input: { aspect: "9:16" } }], label: "Frame" })).toEqual({ id: "j1" });
+ expect(await queueCommands("u", "p", { commands: [{ name: "add_title", input: {} }] })).toEqual({ id: "j2" });
+ expect(woken.count).toBe(0);
+ const claimed = await claimEditorBatch("u", "p");
+ expect(claimed).toEqual({ id: "j1", spec: { commands: [{ name: "set_aspect", input: { aspect: "9:16" } }], label: "Frame" } });
+ expect(rows[0].state).toBe("running");
+ expect((await claimEditorBatch("u", "p"))?.id).toBe("j2");
+ expect(await claimEditorBatch("u", "p")).toBeNull();
+});
+
+test("a batch contends with a chat turn on the same project", async () => {
+ rows.push({ id: "turn", userId: "u", projectId: "p", kind: "agent_turn", state: "running", spec: {}, result: null, error: null, progress: 0, claimedAt: new Date(), createdAt: new Date(Date.now() - 1000), updatedAt: new Date() });
+ const refused = await queueCommands("u", "p", { commands: [{ name: "set_aspect", input: {} }] });
+ expect(refused instanceof Response && refused.status).toBe(409);
+ expect(rows.map((r) => r.id)).toEqual(["turn"]);
+});
+
+test("a batch no card claims in time is dismissed with the answer the tool gives", async () => {
+ const queued = await queueCommands("u", "p", { commands: [{ name: "undo", input: {} }] });
+ const id = (queued as { id: string }).id;
+ rows[0].createdAt = new Date(Date.now() - 5000);
+ const row = await waitForJob("u", id, 50, { editorClaimMs: 1000 });
+ expect(row?.state).toBe("dismissed");
+ expect(row?.error).toBe(NO_CARD_OPEN);
+ expect(woken.count).toBe(0);
+ expect(await claimEditorBatch("u", "p")).toBeNull();
+});
+
+test("a claimed batch whose editor stops beating ends in error, and a late report changes nothing", async () => {
+ await queueCommands("u", "p", { commands: [{ name: "set_aspect", input: {} }] });
+ await claimEditorBatch("u", "p");
+ expect(await heartbeatEditorBatch("u", "j1", 0.5)).toBe(true);
+ expect(rows[0].progress).toBe(0.5);
+ rows[0].updatedAt = new Date(Date.now() - CLAIM_QUIET_MS - 1);
+ const row = await waitForJob("u", "j1", 50);
+ expect(row?.state).toBe("error");
+ expect(await heartbeatEditorBatch("u", "j1", null)).toBe(false);
+ expect(await settleEditorBatch("u", "j1", { ok: true, results: [], changed: true, docVersion: "5" })).toBe(false);
+ expect(rows[0].state).toBe("error");
+ // The next queue on the project clears any other quiet batch the same way.
+ rows.push({ ...rows[0], id: "j9", state: "running", updatedAt: new Date(Date.now() - CLAIM_QUIET_MS - 1) });
+ await queueCommands("u", "p", { commands: [{ name: "set_aspect", input: {} }] });
+ expect(rows.find((r) => r.id === "j9")?.state).toBe("error");
+});
+
+test("the editor's report settles the batch", async () => {
+ await queueCommands("u", "p", { commands: [{ name: "set_aspect", input: {} }], label: "Frame" });
+ await claimEditorBatch("u", "p");
+ expect(await settleEditorBatch("u", "j1", { ok: true, results: [{ name: "set_aspect", ok: true, output: {} }], changed: true, docVersion: "5" })).toBe(true);
+ expect(rows[0].state).toBe("done");
+ expect(rows[0].result).toEqual({ results: [{ name: "set_aspect", ok: true, output: {} }], changed: true, docVersion: "5" });
+ expect(await settleEditorBatch("u", "j1", { ok: false, error: "late" })).toBe(false);
+
+ await queueCommands("u", "p", { commands: [{ name: "get_state", input: {} }], readOnly: true });
+ await claimEditorBatch("u", "p");
+ expect(await settleEditorBatch("u", "j2", { ok: false, error: "The editor could not run the batch." })).toBe(true);
+ expect(rows[1]).toMatchObject({ state: "error", error: "The editor could not run the batch." });
+});
diff --git a/site/src/cut/server/cloud/commands.ts b/site/src/cut/server/cloud/commands.ts
index d753ed6a..69823b85 100644
--- a/site/src/cut/server/cloud/commands.ts
+++ b/site/src/cut/server/cloud/commands.ts
@@ -1,45 +1,44 @@
// A batch of editor commands as a durable job. A host with its own
// conversation — the ChatGPT app — sends typed tool calls with no model of
-// ours in the loop; the worker container opens the project document into the
-// editor store, runs each command through the same executor the chat uses,
-// pushes the document back, and records one undo checkpoint for the batch.
+// ours in the loop. The editor open in the ChatGPT card claims the batch,
+// runs it on the document in front of the user through the same executors
+// the chat uses, saves, and reports back. Nothing else runs a batch: one no
+// card claims in time is dismissed, and the tool call says the project has to
+// be open in the card.
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
+import type { CommandJobResult, CommandJobSpec, CommandOutcome } from "@/cut/lib/commandBatch";
+import { needsWorker } from "./jobs";
import { liveJobCheck } from "./limits";
import { queueLeasedJob } from "./lease";
import { getProject } from "./projects";
import { err } from "./util";
import { wakeRenderWorker } from "./wake";
+export type { CommandCall, CommandJobResult, CommandJobSpec, CommandOutcome } from "@/cut/lib/commandBatch";
+
export const MAX_COMMANDS_PER_BATCH = 40;
-export interface CommandCall {
- name: string;
- input: Record<string, unknown>;
-}
+/** How long a claimed batch may go without a heartbeat before the editor
+ * that claimed it counts as gone. The card beats every ten seconds. */
+export const CLAIM_QUIET_MS = 30_000;
-export interface CommandJobSpec {
- commands: CommandCall[];
- /** A read: the document is opened and inspected, never pushed. */
- readOnly?: boolean;
- /** The undo history's name for this batch. */
- label?: string;
-}
+/** The answer a tool call gets when nothing claimed its batch. */
+export const NO_CARD_OPEN = "No Donkey Cut card has this project open in the chat. Call open_project, then try again.";
-export interface CommandOutcome {
- name: string;
- ok: boolean;
- output?: unknown;
- error?: string;
-}
+export type JobRow = NonNullable<Awaited<ReturnType<typeof prisma.cutRenderJob.findFirst>>>;
+
+const specOf = (row: Pick<JobRow, "spec">) => (row.spec ?? {}) as unknown as CommandJobSpec;
+const specJson = (spec: CommandJobSpec) => spec as unknown as Prisma.InputJsonValue;
+const resultJson = (result: CommandJobResult) => result as unknown as Prisma.InputJsonValue;
-/** What a commands job records in CutRenderJob.result. */
-export interface CommandJobResult {
- results: CommandOutcome[];
- /** The document changed and was saved. */
- changed: boolean;
- /** The project version after the save, when one happened. */
- docVersion: string | null;
+/** Batches whose editor stopped beating end here, so they never hold the
+ * project's lease or a job slot. Runs on every queue and claim. */
+async function expireQuietBatches(userId: string, projectId: string): Promise<void> {
+ await prisma.cutRenderJob.updateMany({
+ where: { userId, projectId, kind: "commands", state: "running", updatedAt: { lt: new Date(Date.now() - CLAIM_QUIET_MS) } },
+ data: { state: "error", error: "The editor in the card stopped responding." },
+ });
}
export async function queueCommands(
@@ -50,41 +49,166 @@ export async function queueCommands(
if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
if (!Array.isArray(spec.commands) || spec.commands.length === 0) return err("At least one command is required.", 400);
if (spec.commands.length > MAX_COMMANDS_PER_BATCH) return err(`At most ${MAX_COMMANDS_PER_BATCH} commands per batch.`, 400);
+ await expireQuietBatches(userId, projectId);
const capped = await liveJobCheck(userId);
if (capped) return capped;
if (spec.readOnly) {
// A read never saves, so it runs beside whatever holds the write lease.
- const row = await prisma.cutRenderJob.create({
- data: { userId, projectId, kind: "commands", spec: spec as unknown as Prisma.InputJsonValue },
- });
- wakeRenderWorker();
+ const row = await prisma.cutRenderJob.create({ data: { userId, projectId, kind: "commands", spec: specJson(spec) } });
return { id: row.id };
}
- return queueLeasedJob(userId, projectId, "commands", spec as unknown as Prisma.InputJsonValue);
+ // The card runs batches one after another, so they queue behind each
+ // other and contend only with a chat turn editing the same document.
+ return queueLeasedJob(userId, projectId, "commands", specJson(spec), { wake: false, contendsWith: ["agent_turn"] });
}
-export type JobRow = NonNullable<Awaited<ReturnType<typeof prisma.cutRenderJob.findFirst>>>;
+const TERMINAL = new Set(["done", "error", "canceled", "dismissed"]);
-const HEARTBEAT_QUIET_MS = 30_000;
+/** A queued batch older than the claim window: no card picked it up. The
+ * window is measured from the row's age, the one clock the card's polling
+ * and this wait share. */
+const claimWindowClosed = (row: Pick<JobRow, "createdAt">, claimMs: number) =>
+ Date.now() - row.createdAt.getTime() > claimMs;
-/** The row is waiting to be claimed, or its worker's heartbeat went quiet. */
-export function needsWorker(row: Pick<JobRow, "state" | "claimedAt" | "updatedAt">): boolean {
- if (row.state === "queued") return true;
- return row.state === "running" && row.claimedAt !== null && Date.now() - row.updatedAt.getTime() > HEARTBEAT_QUIET_MS;
+async function dismissBatch(row: Pick<JobRow, "id">): Promise<void> {
+ await prisma.cutRenderJob.updateMany({
+ where: { id: row.id, state: "queued" },
+ data: { state: "dismissed", error: NO_CARD_OPEN },
+ });
}
-const TERMINAL = new Set(["done", "error", "canceled", "dismissed"]);
+async function expireBatch(row: Pick<JobRow, "id">): Promise<void> {
+ await prisma.cutRenderJob.updateMany({
+ where: { id: row.id, state: "running" },
+ data: { state: "error", error: "The editor in the card stopped responding." },
+ });
+}
/** Poll a job row until it settles or the budget runs out. The row comes back
- * either way; the caller reads its state. */
-export async function waitForJob(userId: string, jobId: string, budgetMs: number): Promise<JobRow | null> {
+ * either way; the caller reads its state. A command batch no card claims
+ * within `editorClaimMs` is dismissed; one whose editor stops beating ends
+ * in error. Any other kind of job is the worker's, which is woken as needed. */
+export async function waitForJob(
+ userId: string,
+ jobId: string,
+ budgetMs: number,
+ opts: { editorClaimMs?: number } = {}
+): Promise<JobRow | null> {
const deadline = Date.now() + budgetMs;
+ const claimMs = opts.editorClaimMs ?? 3000;
for (;;) {
const row = await prisma.cutRenderJob.findFirst({ where: { id: jobId, userId } });
if (!row) return null;
if (TERMINAL.has(row.state)) return row;
- if (needsWorker(row)) wakeRenderWorker();
+ if (row.kind === "commands") {
+ if (row.state === "queued" && claimWindowClosed(row, claimMs)) {
+ await dismissBatch(row);
+ continue;
+ }
+ if (row.state === "running" && Date.now() - row.updatedAt.getTime() > CLAIM_QUIET_MS) {
+ await expireBatch(row);
+ continue;
+ }
+ } else if (needsWorker(row)) {
+ wakeRenderWorker();
+ }
if (Date.now() >= deadline) return row;
await new Promise((r) => setTimeout(r, Math.min(1000, Math.max(50, deadline - Date.now()))));
}
}
+
+/** The editor in the card asks for the project's oldest waiting batch. */
+export async function claimEditorBatch(
+ userId: string,
+ projectId: string
+): Promise<{ id: string; spec: CommandJobSpec } | null> {
+ await expireQuietBatches(userId, projectId);
+ const candidates = await prisma.cutRenderJob.findMany({
+ where: { userId, projectId, kind: "commands", state: "queued" },
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ select: { id: true, spec: true },
+ take: 5,
+ });
+ for (const row of candidates) {
+ const { count } = await prisma.cutRenderJob.updateMany({
+ where: { id: row.id, state: "queued" },
+ data: { state: "running", claimedAt: new Date(), progress: 0, error: null },
+ });
+ if (count === 1) return { id: row.id, spec: specOf(row) };
+ }
+ return null;
+}
+
+/** The editor keeps a claimed batch alive while it runs. False once the batch
+ * is no longer running — expired, canceled — so the editor stops. */
+export async function heartbeatEditorBatch(userId: string, jobId: string, progress: number | null): Promise<boolean> {
+ const { count } = await prisma.cutRenderJob.updateMany({
+ where: { id: jobId, userId, kind: "commands", state: "running" },
+ data: { updatedAt: new Date(), ...(progress !== null ? { progress: Math.max(0, Math.min(1, progress)) } : {}) },
+ });
+ return count === 1;
+}
+
+export type EditorReport =
+ | { ok: true; results: CommandOutcome[]; changed: boolean; docVersion: string | null }
+ | { ok: false; error: string };
+
+/** The editor reports a batch it ran. False when the batch is no longer
+ * running, so a late report after an expiry changes nothing. */
+export async function settleEditorBatch(userId: string, jobId: string, report: EditorReport): Promise<boolean> {
+ const row = await prisma.cutRenderJob.findFirst({
+ where: { id: jobId, userId, kind: "commands", state: "running" },
+ select: { spec: true },
+ });
+ if (!row) return false;
+ const data = report.ok
+ ? {
+ state: "done",
+ progress: 1,
+ result: resultJson({
+ results: report.results,
+ changed: report.changed && !specOf(row).readOnly,
+ docVersion: report.changed ? report.docVersion : null,
+ }),
+ }
+ : { state: "error", error: report.error.slice(0, 2000) };
+ const { count } = await prisma.cutRenderJob.updateMany({ where: { id: jobId, state: "running" }, data });
+ return count === 1;
+}
+
+const isOutcome = (r: unknown): r is CommandOutcome =>
+ Boolean(r) && typeof r === "object" && typeof (r as CommandOutcome).name === "string" && typeof (r as CommandOutcome).ok === "boolean";
+
+/** The editor's report, read out of the request body. */
+function parseReport(body: unknown): EditorReport | null {
+ if (!body || typeof body !== "object") return null;
+ const b = body as { ok?: unknown; results?: unknown; changed?: unknown; docVersion?: unknown; error?: unknown };
+ if (b.ok === false) return { ok: false, error: typeof b.error === "string" ? b.error : "The editor could not run the batch." };
+ if (!Array.isArray(b.results)) return null;
+ return {
+ ok: true,
+ results: b.results.filter(isOutcome),
+ changed: b.changed === true,
+ docVersion: typeof b.docVersion === "string" ? b.docVersion : null,
+ };
+}
+
+/** The routes the editor in the card uses to run batches. */
+export const commandsCloud = {
+ async claim(userId: string, projectId: string) {
+ const claimed = await claimEditorBatch(userId, projectId);
+ if (!claimed) return new Response(null, { status: 204 });
+ return Response.json(claimed);
+ },
+ async heartbeat(userId: string, jobId: string, req: Request) {
+ const body = (await req.json().catch(() => ({}))) as { progress?: unknown };
+ const alive = await heartbeatEditorBatch(userId, jobId, typeof body.progress === "number" ? body.progress : null);
+ return alive ? Response.json({ ok: true }) : err("Not a running batch.", 409);
+ },
+ async result(userId: string, jobId: string, req: Request) {
+ const report = parseReport(await req.json().catch(() => null));
+ if (!report) return err("Bad result.", 400);
+ const settled = await settleEditorBatch(userId, jobId, report);
+ return settled ? Response.json({ ok: true }) : err("Not a running batch.", 409);
+ },
+};
diff --git a/site/src/cut/server/cloud/history.test.ts b/site/src/cut/server/cloud/history.test.ts
deleted file mode 100644
index 443bd013..00000000
--- a/site/src/cut/server/cloud/history.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { expect, test } from "bun:test";
-import type { ProjectDoc } from "@/cut/lib/types";
-import {
- CHECKPOINT_KEEP,
- historyState,
- recordCheckpoint,
- restoreCheckpoint,
- type HistoryDb,
-} from "./history";
-
-type Row = { id: string; projectId: string; userId: string; seq: number; version: number; doc: unknown; label: string };
-
-/** An in-memory stand-in for the two tables the history touches. */
-function fakeDb(project: { id: string; userId: string; version: number; doc: ProjectDoc }) {
- const rows: Row[] = [];
- let nextId = 1;
- const matches = (row: Row, where: Record<string, unknown>) =>
- Object.entries(where).every(([k, v]) => {
- if (k === "id" && v && typeof v === "object" && "in" in v) return (v.in as string[]).includes(row.id);
- return (row as Record<string, unknown>)[k] === v;
- });
- const db = {
- cutProjectCheckpoint: {
- findMany: async ({ where }: { where: Record<string, unknown> }) =>
- rows.filter((r) => matches(r, where)).sort((a, b) => a.seq - b.seq).map((r) => ({ ...r })),
- findUnique: async ({ where }: { where: { id: string } }) => rows.find((r) => r.id === where.id) ?? null,
- create: async ({ data }: { data: Omit<Row, "id"> }) => {
- const row = { ...data, id: `cp${nextId++}` };
- rows.push(row);
- return row;
- },
- deleteMany: async ({ where }: { where: Record<string, unknown> }) => {
- const keep = rows.filter((r) => !matches(r, where));
- const count = rows.length - keep.length;
- rows.splice(0, rows.length, ...keep);
- return { count };
- },
- update: async ({ where, data }: { where: { id: string }; data: Partial<Row> }) => {
- const row = rows.find((r) => r.id === where.id)!;
- Object.assign(row, data);
- return row;
- },
- },
- cutProject: {
- findFirst: async ({ where }: { where: { id: string; userId: string } }) =>
- where.id === project.id && where.userId === project.userId ? { version: project.version } : null,
- updateMany: async ({ where, data }: { where: { version: number }; data: { doc: ProjectDoc; version: number } }) => {
- if (where.version !== project.version) return { count: 0 };
- project.version = data.version;
- project.doc = data.doc;
- return { count: 1 };
- },
- },
- };
- return { db: db as unknown as HistoryDb, rows, project };
-}
-
-const docWith = (background: string): ProjectDoc =>
- ({ version: 1, name: "Cut", createdAt: 0, updatedAt: 0, assets: [], clips: [], audioClips: [], overlays: [], background }) as ProjectDoc;
-
-test("edits record a line, undo and redo walk it, and a new edit after undo drops the redo branch", async () => {
- const { db, project } = fakeDb({ id: "p", userId: "u", version: 3, doc: docWith("#000") });
- // Version 3 → 4: the first step also writes the baseline.
- await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#000"), version: 3 }, after: { doc: docWith("#111"), version: 4 }, label: "Black to grey" });
- project.version = 4;
- await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#111"), version: 4 }, after: { doc: docWith("#222"), version: 5 }, label: "Grey to lighter" });
- project.version = 5;
- expect(await historyState(db, "u", "p", 5)).toEqual({ undo: "Grey to lighter", redo: null });
-
- const undone = await restoreCheckpoint(db, "u", "p", "undo");
- expect(undone).toEqual({ label: "Grey to lighter", version: 6 });
- expect(project.doc.background).toBe("#111");
- expect(await historyState(db, "u", "p", 6)).toEqual({ undo: "Black to grey", redo: "Grey to lighter" });
-
- const twice = await restoreCheckpoint(db, "u", "p", "undo");
- expect(twice.label).toBe("Black to grey");
- expect(project.doc.background).toBe("#000");
- await expect(restoreCheckpoint(db, "u", "p", "undo")).rejects.toThrow("Nothing to undo.");
-
- const redone = await restoreCheckpoint(db, "u", "p", "redo");
- expect(redone.label).toBe("Black to grey");
- expect(project.doc.background).toBe("#111");
-
- // A fresh edit from here forgets the redo branch.
- await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#111"), version: project.version }, after: { doc: docWith("#333"), version: project.version + 1 }, label: "New direction" });
- project.version += 1;
- expect(await historyState(db, "u", "p", project.version)).toEqual({ undo: "New direction", redo: null });
-});
-
-test("a save from the editor breaks the line, and the next edit starts a new one", async () => {
- const { db, project, rows } = fakeDb({ id: "p", userId: "u", version: 1, doc: docWith("#000") });
- await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#000"), version: 1 }, after: { doc: docWith("#111"), version: 2 }, label: "First" });
- project.version = 9; // the editor saved
- await expect(restoreCheckpoint(db, "u", "p", "undo")).rejects.toThrow("last saved from the editor");
- await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#999"), version: 9 }, after: { doc: docWith("#aaa"), version: 10 }, label: "Second" });
- expect(rows.map((r) => [r.seq, r.version, r.label])).toEqual([[0, 9, "Before edits"], [1, 10, "Second"]]);
-});
-
-test("the line is capped", async () => {
- const { db, project, rows } = fakeDb({ id: "p", userId: "u", version: 0, doc: docWith("#000") });
- for (let i = 0; i < CHECKPOINT_KEEP + 5; i++) {
- await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#000"), version: i }, after: { doc: docWith("#111"), version: i + 1 }, label: `Step ${i}` });
- project.version = i + 1;
- }
- expect(rows.length).toBe(CHECKPOINT_KEEP);
- expect(rows[rows.length - 1].label).toBe(`Step ${CHECKPOINT_KEEP + 4}`);
-});
diff --git a/site/src/cut/server/cloud/history.ts b/site/src/cut/server/cloud/history.ts
deleted file mode 100644
index 989e9d8e..00000000
--- a/site/src/cut/server/cloud/history.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-// A cloud project's undo history for edits made from outside the editor.
-//
-// The editor keeps its history in the tab. An edit that arrives as a job — a
-// ChatGPT tool call, a headless command — has no tab, so its history lives
-// here: one checkpoint per applied step, holding the whole document. The
-// rows form one linear line per project, ordered by seq. Each row names the
-// project version whose document it holds; a restore writes that document
-// back under a fresh version and re-labels the row with it, so the line stays
-// walkable in both directions.
-//
-// The line is anchored to the project's live version. A save from the editor
-// moves the version off the line, and the next recorded step starts a new
-// line from that state — an outside edit is never silently undone.
-import type { Prisma } from "@/generated/prisma/client";
-import { prisma } from "@/lib/prisma";
-import type { ProjectDoc } from "@/cut/lib/types";
-
-/** Checkpoints kept per project; the oldest fall off. */
-export const CHECKPOINT_KEEP = 30;
-
-export type HistoryDb = Pick<typeof prisma, "cutProjectCheckpoint" | "cutProject">;
-
-type Snapshot = { doc: ProjectDoc; version: number };
-
-const asJson = (doc: ProjectDoc) => doc as unknown as Prisma.InputJsonValue;
-
-async function line(db: HistoryDb, userId: string, projectId: string) {
- return db.cutProjectCheckpoint.findMany({
- where: { projectId, userId },
- orderBy: { seq: "asc" },
- select: { id: true, seq: true, version: true, label: true },
- });
-}
-
-/** Record one applied step: the document before it and after it. */
-export async function recordCheckpoint(
- db: HistoryDb,
- input: { userId: string; projectId: string; before: Snapshot; after: Snapshot; label: string }
-): Promise<void> {
- const { userId, projectId } = input;
- const rows = await line(db, userId, projectId);
- const at = rows.findIndex((r) => r.version === input.before.version);
- let seq: number;
- if (at >= 0) {
- // Continuing the line: whatever was undone past this point is gone.
- const dropped = rows.slice(at + 1).map((r) => r.id);
- if (dropped.length) await db.cutProjectCheckpoint.deleteMany({ where: { id: { in: dropped } } });
- seq = rows[at].seq + 1;
- } else {
- // A new line from the current state.
- if (rows.length) await db.cutProjectCheckpoint.deleteMany({ where: { projectId, userId } });
- await db.cutProjectCheckpoint.create({
- data: { projectId, userId, seq: 0, version: input.before.version, doc: asJson(input.before.doc), label: "Before edits" },
- });
- seq = 1;
- }
- await db.cutProjectCheckpoint.create({
- data: { projectId, userId, seq, version: input.after.version, doc: asJson(input.after.doc), label: input.label },
- });
- const kept = await line(db, userId, projectId);
- const excess = kept.slice(0, Math.max(0, kept.length - CHECKPOINT_KEEP)).map((r) => r.id);
- if (excess.length) await db.cutProjectCheckpoint.deleteMany({ where: { id: { in: excess } } });
-}
-
-export class HistoryError extends Error {}
-
-/** What undo and redo would each restore from the given version, by label. */
-export async function historyState(
- db: HistoryDb,
- userId: string,
- projectId: string,
- version: number
-): Promise<{ undo: string | null; redo: string | null }> {
- const rows = await line(db, userId, projectId);
- const at = rows.findIndex((r) => r.version === version);
- if (at < 0) return { undo: null, redo: null };
- return {
- undo: at > 0 ? rows[at].label : null,
- redo: at + 1 < rows.length ? rows[at + 1].label : null,
- };
-}
-
-/** Walk one step along the line and write that document back as a new
- * version. Returns the label of the step undone or redone. */
-export async function restoreCheckpoint(
- db: HistoryDb,
- userId: string,
- projectId: string,
- direction: "undo" | "redo"
-): Promise<{ label: string; version: number }> {
- const project = await db.cutProject.findFirst({
- where: { id: projectId, userId },
- select: { version: true },
- });
- if (!project) throw new HistoryError("Project not found.");
- const rows = await line(db, userId, projectId);
- const at = rows.findIndex((r) => r.version === project.version);
- if (at < 0)
- throw new HistoryError(
- direction === "undo"
- ? "Nothing to undo: the project was last saved from the editor."
- : "Nothing to redo: the project was last saved from the editor."
- );
- const target = direction === "undo" ? rows[at - 1] : rows[at + 1];
- if (!target) throw new HistoryError(direction === "undo" ? "Nothing to undo." : "Nothing to redo.");
- const row = await db.cutProjectCheckpoint.findUnique({ where: { id: target.id }, select: { doc: true } });
- if (!row) throw new HistoryError("The checkpoint is gone.");
- const doc = { ...(row.doc as unknown as ProjectDoc), updatedAt: Date.now() };
- const version = project.version + 1;
- const updated = await db.cutProject.updateMany({
- where: { id: projectId, userId, version: project.version },
- data: { doc: asJson(doc), name: doc.name, version },
- });
- if (updated.count === 0) throw new HistoryError("The project changed while restoring. Try again.");
- await db.cutProjectCheckpoint.update({ where: { id: target.id }, data: { version } });
- return { label: direction === "undo" ? rows[at].label : target.label, version };
-}
diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.ts
index 32fc2558..4ac98120 100644
--- a/site/src/cut/server/cloud/jobs.ts
+++ b/site/src/cut/server/cloud/jobs.ts
@@ -4,7 +4,6 @@
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
import { cutLimitsFor, EXPORT_QUOTA_MARGIN, renderJobCheck } from "./limits";
-import { liveLeaseHolder } from "./lease";
import { wakeRenderWorker } from "./wake";
import { queuePreview } from "./previewJobs";
import { getProject } from "./projects";
@@ -85,7 +84,7 @@ function specRefusal(spec: Record<string, unknown>): string | null {
* that died mid-job, which the woken replacement sweeps back to queued. A
* healthy running job needs nothing, and a browser render (running with no
* claim) is never a worker's. */
-function needsWorker(row: JobRow): boolean {
+export function needsWorker(row: Pick<JobRow, "state" | "claimedAt" | "updatedAt">): boolean {
if (row.state === "queued") return true;
return (
row.state === "running" &&
@@ -222,15 +221,13 @@ export async function queueDocExport(
export async function queueImportUrl(
userId: string,
projectId: string,
- opts: { url: string; audio?: boolean; key?: string; adopt?: { name?: string } }
+ opts: { url: string; audio?: boolean; key?: string; name?: string }
): Promise<{ id: string } | Response> {
if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
const open = await importJobFor(userId, opts.key);
if (open) return { id: open.id };
const capped = await renderJobCheck(userId);
if (capped) return capped;
- if (opts.adopt && (await liveLeaseHolder(userId, projectId)))
- return err("An edit is still running for this project. Wait for it to finish, then import.", 409);
// What lands counts against storage, so an account with none left gets
// no download, and the worker downloads no more than what is left.
const over = await quotaCheck(userId, 0);
@@ -246,7 +243,8 @@ export async function queueImportUrl(
maxBytes,
...(opts.audio === true ? { audio: true } : {}),
...(opts.key ? { key: opts.key } : {}),
- ...(opts.adopt ? { adopt: opts.adopt } : {}),
+ // The name the caller gave the file, for whoever adopts it.
+ ...(opts.name ? { name: opts.name } : {}),
} as unknown as Prisma.InputJsonValue,
},
});
diff --git a/site/src/cut/server/cloud/lease.ts b/site/src/cut/server/cloud/lease.ts
index 1257e852..a87b108b 100644
--- a/site/src/cut/server/cloud/lease.ts
+++ b/site/src/cut/server/cloud/lease.ts
@@ -6,26 +6,15 @@ import { prisma } from "@/lib/prisma";
import { err } from "./util";
import { wakeRenderWorker } from "./wake";
-/** The job kinds that hold the lease. An import that adopts its files into
- * the document (spec.adopt) writes the document too, so it holds the lease
- * against turns and batches; adopting imports run alongside each other and
- * merge through a retry in the worker. */
+/** The job kinds that hold the lease. An import only lands files; the batch
+ * that adopts them into the document is a commands job of its own. */
export const LEASE_KINDS = ["agent_turn", "commands"];
-/** A live import that will write the document, if any. */
-export async function liveAdoptingImport(userId: string, projectId: string): Promise<{ id: string } | null> {
- const rows = await prisma.cutRenderJob.findMany({
- where: { userId, projectId, kind: "import_url", state: { in: ["queued", "running"] } },
- select: { id: true, spec: true },
- });
- return rows.find((r) => Boolean((r.spec as { adopt?: unknown } | null)?.adopt)) ?? null;
-}
-
/** The live lease holders on a project, oldest first. A read-only command
* batch never saves, so it holds nothing. */
-async function liveLeaseRows(userId: string, projectId: string): Promise<{ id: string }[]> {
+async function liveLeaseRows(userId: string, projectId: string, kinds: string[]): Promise<{ id: string }[]> {
const rows = await prisma.cutRenderJob.findMany({
- where: { userId, projectId, kind: { in: LEASE_KINDS }, state: { in: ["queued", "running"] } },
+ where: { userId, projectId, kind: { in: kinds }, state: { in: ["queued", "running"] } },
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
select: { id: true, spec: true },
});
@@ -33,29 +22,28 @@ async function liveLeaseRows(userId: string, projectId: string): Promise<{ id: s
}
/** A live turn or batch holding the lease, if any. */
-export async function liveLeaseHolder(userId: string, projectId: string): Promise<{ id: string } | null> {
- return (await liveLeaseRows(userId, projectId))[0] ?? null;
+export async function liveLeaseHolder(userId: string, projectId: string, kinds: string[] = LEASE_KINDS): Promise<{ id: string } | null> {
+ return (await liveLeaseRows(userId, projectId, kinds))[0] ?? null;
}
-/** Create the row, then keep it only if it is the oldest live lease holder for
- * the project. Two concurrent queues both create, both re-check, and exactly
- * one — the older row — survives. Returns the 409 for the loser. */
+/** Create the row, then keep it only if no older live row of the kinds it
+ * contends with holds the lease. Two concurrent queues both create, both
+ * re-check, and exactly one — the older row — survives. Returns the 409 for
+ * the loser. Command batches contend with chat turns only: the editor in the
+ * card runs its batches one after another, so they queue behind each other. */
export async function queueLeasedJob(
userId: string,
projectId: string,
kind: (typeof LEASE_KINDS)[number],
- spec: Prisma.InputJsonValue
+ spec: Prisma.InputJsonValue,
+ opts: { wake?: boolean; contendsWith?: string[] } = {}
): Promise<{ id: string } | Response> {
const row = await prisma.cutRenderJob.create({ data: { userId, projectId, kind, spec } });
- const oldest = await liveLeaseHolder(userId, projectId);
+ const oldest = await liveLeaseHolder(userId, projectId, opts.contendsWith ?? LEASE_KINDS);
if (oldest && oldest.id !== row.id) {
await prisma.cutRenderJob.delete({ where: { id: row.id } }).catch(() => {});
return err("Another edit is already running for this project. Wait for it to finish.", 409);
}
- if (await liveAdoptingImport(userId, projectId)) {
- await prisma.cutRenderJob.delete({ where: { id: row.id } }).catch(() => {});
- return err("An import is still landing in this project. Wait for it to finish, then edit.", 409);
- }
- wakeRenderWorker();
+ if (opts.wake !== false) wakeRenderWorker();
return { id: row.id };
}
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index e8315e3a..fab891fd 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -120,7 +120,6 @@ export async function deleteProjectCascade(userId: string, id: string): Promise<
await prisma.$transaction(async (tx) => {
await tx.cutMediaObject.deleteMany({ where: { userId, projectId: id } });
await tx.cutChatThread.deleteMany({ where: { userId, projectId: id } });
- await tx.cutProjectCheckpoint.deleteMany({ where: { userId, projectId: id } });
await tx.cutProjectShare.deleteMany({ where: { projectId: id } });
// deleteMany, so ownership is enforced here rather than trusted from the
// caller: a mismatched (userId, id) pair deletes nothing.
diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.ts
index 37bdae1a..0e23b09b 100644
--- a/site/src/cut/server/cloud/routes.ts
+++ b/site/src/cut/server/cloud/routes.ts
@@ -10,6 +10,7 @@ import { isDonkeySuperUser } from "@/lib/super-user";
import { matchRouteTable, type RouteEntry } from "../http/match";
import { captionsCloud } from "./captions";
import { chatsCloud } from "./chats";
+import { commandsCloud } from "./commands";
import { copyJobs } from "./copyQueue";
import { runGc } from "./gc";
import { jobsCloud } from "./jobs";
@@ -108,6 +109,12 @@ 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) },
+ // A command batch queued for a project runs in the editor that has it open:
+ // the editor claims the oldest waiting batch, keeps it alive while it runs,
+ // and reports the outcome.
+ { method: "POST", path: "/api/cut-cloud/projects/:id/commands/claim", handler: (_r, u, p) => commandsCloud.claim(u, p.id) },
+ { method: "POST", path: "/api/cut-cloud/jobs/:jobId/heartbeat", handler: (r, u, p) => commandsCloud.heartbeat(u, p.jobId, r) },
+ { method: "POST", path: "/api/cut-cloud/jobs/:jobId/result", handler: (r, u, p) => commandsCloud.result(u, p.jobId, r) },
{ 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/projects/:id/scene-lease", handler: (r, u, p) => cloudSceneLease(u, p.id, r) },
{ method: "POST", path: "/api/cut-cloud/turns/:jobId/cancel", handler: (_r, u, p) => turnsCloud.cancel(u, p.jobId) },
diff --git a/site/src/cut/server/cloud/wake.ts b/site/src/cut/server/cloud/wake.ts
index eed1d8c6..4ca74073 100644
--- a/site/src/cut/server/cloud/wake.ts
+++ b/site/src/cut/server/cloud/wake.ts
@@ -39,9 +39,10 @@ export function wakeRenderWorker(): void {
// an idle box. A burst that arrives inside the wake window is picked up by the
// next status poll's wake, which counts again.
async function wake(secret: string): Promise<void> {
+ // Command batches run in the editor inside the ChatGPT card, never here.
const [queued, running] = await Promise.all([
- prisma.cutRenderJob.count({ where: { state: "queued" } }),
- prisma.cutRenderJob.count({ where: { state: "running" } }),
+ prisma.cutRenderJob.count({ where: { state: "queued", kind: { not: "commands" } } }),
+ prisma.cutRenderJob.count({ where: { state: "running", kind: { not: "commands" } } }),
]);
const res = await fetch(CUT_WORKER_WAKE_URL, {
method: "POST",
diff --git a/site/src/cut/worker/commandJob.ts b/site/src/cut/worker/commandJob.ts
deleted file mode 100644
index b5ccc057..00000000
--- a/site/src/cut/worker/commandJob.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { assetFromProjectFile } from "../lib/media";
-import { bindHeadlessSession } from "../lib/headless/bind";
-import { openCloudProject, ProjectConflictError, pushCloudProject, type HeadlessDocSession } from "../lib/headless/docSession";
-import { headlessDeps, type HeadlessSession } from "../lib/pi/serverDeps";
-import { serializeDoc, useEditor } from "../lib/store";
-import type { CommandJobResult, CommandJobSpec, CommandOutcome } from "../server/cloud/commands";
-import { recordCheckpoint } from "../server/cloud/history";
-import type { RenderHandle } from "../server/exportPipeline";
-import { prisma, type ClaimedJob } from "./db";
-import { runnerSession } from "./session";
-
-// A command batch, executed where the tab used to be: open the project
-// document into the editor store, run each typed command through the chat's
-// own executor, push the document back through the versioned PUT, and record
-// the batch as one undo checkpoint. No model runs here — the caller decided
-// what to do; this process does it.
-
-/** Contact sheets, captured frames and listened audio ride in the result as
- * data URLs. Past this much, later ones are dropped and say so, so one batch
- * never writes a row the poll cannot read. */
-const MAX_MEDIA_BYTES = 8 * 1024 * 1024;
-
-/** How many times an adoption re-opens the document after losing the
- * versioned PUT to a parallel import. */
-const ADOPT_ATTEMPTS = 5;
-
-const snapshot = () => JSON.stringify(serializeDoc(useEditor.getState()));
-
-/** Save the store's edits under the session's version and record the step.
- * The checkpoint holds the document as the PUT stored it — the server
- * normalizes what it receives, so the checkpoint reads the row back. */
-async function saveStep(
- session: HeadlessSession,
- userId: string,
- doc: HeadlessDocSession,
- label: string
-): Promise<string> {
- const before = { doc: doc.doc, version: Number(doc.version) };
- await pushCloudProject(session, doc);
- const stored = await prisma.cutProject.findFirst({
- where: { id: doc.projectId, userId },
- select: { doc: true, version: true },
- });
- if (!stored) throw new Error("The project is gone after the save.");
- await recordCheckpoint(prisma, {
- userId,
- projectId: doc.projectId,
- before,
- after: { doc: stored.doc as unknown as HeadlessDocSession["doc"], version: stored.version },
- label,
- });
- return String(stored.version);
-}
-
-/** Keep the batch's inline media (frames, sheets, listened audio) inside one
- * result budget. */
-function boundMedia(results: CommandOutcome[]): void {
- let budget = MAX_MEDIA_BYTES;
- const take = (url: unknown): unknown => {
- if (typeof url !== "string" || !url.startsWith("data:")) return url;
- if (url.length <= budget) {
- budget -= url.length;
- return url;
- }
- return "[dropped: the batch's inline media exceeds the result budget — ask for this in its own call]";
- };
- for (const r of results) {
- const out = r.output as { image?: unknown; images?: unknown[]; audio?: unknown } | null;
- if (!out || typeof out !== "object") continue;
- if ("image" in out) out.image = take(out.image);
- if (Array.isArray(out.images)) out.images = out.images.map(take);
- if ("audio" in out) out.audio = take(out.audio);
- }
-}
-
-export async function runCommandJob(
- job: ClaimedJob,
- handle: RenderHandle,
- isCanceled: () => boolean
-): Promise<CommandJobResult> {
- const spec = job.spec as CommandJobSpec;
- if (!job.projectId) throw new Error("Command job carries no project.");
- if (!Array.isArray(spec?.commands) || spec.commands.length === 0)
- throw new Error("Command job carries no commands.");
-
- const session = runnerSession(job);
- bindHeadlessSession(session);
- const doc = await openCloudProject(session, job.projectId);
- const deps = headlessDeps(session);
- const before = snapshot();
- const results: CommandOutcome[] = [];
- for (const [i, call] of spec.commands.entries()) {
- if (isCanceled()) throw new Error("Canceled.");
- handle.progress = i / spec.commands.length;
- try {
- const output = await deps.execTool(call.name, call.input ?? {});
- results.push({ name: call.name, ok: true, output: output ?? null });
- } catch (err) {
- // The batch stops at the first failure: later commands assumed this
- // one landed. The caller sees exactly how far it got.
- results.push({ name: call.name, ok: false, error: err instanceof Error ? err.message : String(err) });
- break;
- }
- }
- boundMedia(results);
- const changed = snapshot() !== before;
- let docVersion: string | null = null;
- if (changed && !spec.readOnly) {
- const label = spec.label?.trim() || results.filter((r) => r.ok).map((r) => r.name).join(", ") || "Edit";
- docVersion = await saveStep(session, job.userId, doc, label);
- }
- handle.progress = 1;
- return { results, changed: changed && !spec.readOnly, docVersion };
-}
-
-/** Register files an import landed as project assets and save the document:
- * the adoption a tab does after its own import, done here for a caller with
- * no tab. Returns the assets as the catalog's import reports them. */
-export async function adoptImportedFiles(
- job: ClaimedJob,
- files: { fileName: string; title: string }[],
- name?: string
-): Promise<{ assets: { assetId: string; name: string; kind: string; duration: number }[]; docVersion: string }> {
- if (!job.projectId) throw new Error("Import job carries no project.");
- const session = runnerSession(job);
- bindHeadlessSession(session);
- // Parallel imports into one project each add their own assets; the loser
- // of the versioned PUT re-opens the newer document and adds them again.
- for (let attempt = 1; ; attempt++) {
- const doc = await openCloudProject(session, job.projectId);
- const assets: { assetId: string; name: string; kind: string; duration: number }[] = [];
- for (const f of files) {
- const asset = await assetFromProjectFile(job.projectId, f.fileName, (files.length === 1 && name) || f.title || f.fileName);
- useEditor.getState().addAsset(asset);
- assets.push({ assetId: asset.id, name: asset.name, kind: asset.type, duration: Math.round(asset.duration * 100) / 100 });
- }
- try {
- const docVersion = await saveStep(session, job.userId, doc, `Imported ${assets.map((a) => a.name).join(", ")}`);
- return { assets, docVersion };
- } catch (err) {
- if (!(err instanceof ProjectConflictError) || attempt >= ADOPT_ATTEMPTS) throw err;
- }
- }
-}
diff --git a/site/src/cut/worker/importUrlJob.ts b/site/src/cut/worker/importUrlJob.ts
index 7bae107f..c7a5701f 100644
--- a/site/src/cut/worker/importUrlJob.ts
+++ b/site/src/cut/worker/importUrlJob.ts
@@ -8,7 +8,6 @@ import type { LibraryAsset } from "../server/library";
import { probeDuration } from "../server/frames";
import { download } from "../server/urlDownload";
import { videoDimensions } from "../server/util";
-import { adoptImportedFiles } from "./commandJob";
import { prisma, registerObject, unregisterObjects, type ClaimedJob } from "./db";
import { deleteObjects, libraryKey, mediaKey, mimeFor, uploadFile } from "./r2";
@@ -17,7 +16,8 @@ import { deleteObjects, libraryKey, mediaKey, mimeFor, uploadFile } from "./r2";
export interface ImportUrlResult {
files: { fileName: string; title: string }[];
text?: string;
- /** Set when the job adopted the files into the project document itself. */
+ /** Set once the files were adopted into the project document — by the
+ * batch the ChatGPT server queues after the download. */
assets?: { assetId: string; name: string; kind: string; duration: number }[];
docVersion?: string;
}
@@ -40,14 +40,11 @@ export async function runImportUrlJob(
job: ClaimedJob,
isCanceled: () => boolean
): Promise<ImportUrlResult | LibraryImportResult> {
- const { url, target, origin, audio, maxBytes, adopt } = (job.spec ?? {}) as {
+ const { url, target, origin, audio, maxBytes } = (job.spec ?? {}) as {
url?: string;
target?: string;
origin?: string;
audio?: boolean;
- /** Register what lands as project assets here, for a caller with no
- * editor to do it (the ChatGPT app). */
- adopt?: { name?: string };
/** What is left of the account's storage when the job was queued; the
* route always sets it. Everything that came down is measured against it
* before any byte is uploaded — the one place every rung and every
@@ -163,11 +160,6 @@ export async function runImportUrlJob(
assets.push(asset);
}
if (toLibrary) return { assets, ...(dl.text ? { text: dl.text } : {}) };
- if (adopt && files.length > 0) {
- // Landed in the document as well; a failure here cleans up like any other.
- const adopted = await adoptImportedFiles(job, files, adopt.name);
- return { files, ...adopted, ...(dl.text ? { text: dl.text } : {}) };
- }
return { files, ...(dl.text ? { text: dl.text } : {}) };
} catch (err) {
if (libraryRows.length > 0)
diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.ts
index 060a94bc..49269363 100644
--- a/site/src/cut/worker/main.ts
+++ b/site/src/cut/worker/main.ts
@@ -6,14 +6,13 @@ import { runHlsJob } from "./hlsJob";
import { runConvertJob } from "./convertJob";
import { runImportUrlJob } from "./importUrlJob";
import { runTurnJob } from "./turnJob";
-import { runCommandJob } from "./commandJob";
import { describeRuntime, installHeadlessRuntime } from "../lib/headless/runtime";
import { deleteObjects } from "./r2";
// The cloud render worker: a headless loop that claims CutRenderJob rows the
-// hosted API queues (export, preview, import_url, convert, agent_turn,
-// commands), executes them with the
-// same pipeline code the local engine runs, and writes progress and results
+// hosted API queues (export, preview, import_url, convert, agent_turn),
+// executes them with the same pipeline code the local engine runs, and writes
+// progress and results
// back to the row the client polls. Scale is horizontal: one job per process,
// several processes — the atomic claim keeps them apart.
@@ -53,7 +52,6 @@ const MAX_RUNTIME_MS: Record<string, number> = {
import_url: 20 * 60_000,
convert: 60 * 60_000,
agent_turn: 20 * 60_000,
- commands: 20 * 60_000,
};
const DEFAULT_MAX_RUNTIME_MS = 60 * 60_000;
@@ -77,7 +75,7 @@ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
/** 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", "convert", "agent_turn", "commands"];
+const WATCHED_KINDS = ["export", "import_url", "convert", "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.
@@ -91,7 +89,7 @@ async function claimNext(): Promise<ClaimedJob | null> {
const candidates = await prisma.cutRenderJob.findMany({
where: { state: "queued", kind },
orderBy: { createdAt: "asc" },
- take: 5,
+ take: 10,
select: { id: true, userId: true, projectId: true, kind: true, spec: true, outName: true },
});
for (const c of candidates) {
@@ -128,6 +126,9 @@ async function sweepStaleRunning(): Promise<void> {
state: "running",
updatedAt: { lt: new Date(Date.now() - STALE_RUNNING_MS) },
id: { notIn: [...active.keys()] },
+ // A command batch belongs to the editor in the ChatGPT card; the hosted
+ // API expires one whose editor went quiet.
+ kind: { not: "commands" },
},
data: { state: "queued", claimedAt: null, progress: 0 },
});
@@ -223,12 +224,6 @@ 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 === "commands") {
- const result = await runCommandJob(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}`);
}
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 5936b9bd..636d59ec 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -41,15 +41,18 @@ export const SETTINGS = defineSettings({
requestsPerMinute: z.number().int().min(10).max(600),
oauthRequestsPerIpMinute: z.number().int().min(10).max(10000).default(600),
pollMs: z.number().int().min(1000).max(30000),
- // How long a tool call waits on the worker before handing back a job id.
+ // How long a tool call waits on the batch before handing back a job id.
commandWaitMs: z.number().int().min(5000).max(240000).default(50000),
+ // How long a batch waits for the editor in the card to claim it before
+ // the call answers that no card has the project open.
+ editorClaimMs: z.number().int().min(500).max(30000).default(3000),
// How long the editor stays signed in inside the ChatGPT card.
editorSessionHours: z.number().int().min(1).max(72).default(12),
}).strict(),
- default: { enabled: false, issuer: "https://donkeycut.com", redirectUris: ["https://chatgpt.com/connector_platform_oauth_redirect"], accessSeconds: 3600, refreshDays: 30, requestsPerMinute: 120, oauthRequestsPerIpMinute: 600, pollMs: 2000, commandWaitMs: 50000, editorSessionHours: 12 },
+ default: { enabled: false, issuer: "https://donkeycut.com", redirectUris: ["https://chatgpt.com/connector_platform_oauth_redirect"], accessSeconds: 3600, refreshDays: 30, requestsPerMinute: 120, oauthRequestsPerIpMinute: 600, pollMs: 2000, commandWaitMs: 50000, editorClaimMs: 3000, editorSessionHours: 12 },
public: false,
title: "ChatGPT app",
- description: "Account linking, allowed OAuth callbacks, token lifetimes, preview polling, how long an edit call waits on the worker, and how long the editor stays signed in inside the card. Enable after the OAuth tables are deployed.",
+ description: "Account linking, allowed OAuth callbacks, token lifetimes, preview polling, how long an edit call waits and how long the card's editor has to claim it, and how long the editor stays signed in inside the card. Enable after the OAuth tables are deployed.",
},
cutPreviewJobs: {
schema: z.object({ maxAttempts: z.number().int().min(1).max(10) }).strict(),