Open source CapCut alternative.
TypeScript
fix(site): a turn ends in words on every provider [rebuild]
David Le3b1a039a5678
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.mdindex c9d4b94c..9951947b 100644--- a/docs/guides/cut/ai-assistant.md+++ b/docs/guides/cut/ai-assistant.md@@ -45,7 +45,7 @@ The same loop code runs with no browser at all. A headless session opens a projeA job can do everything a tab can, because the same tool code runs over swapped primitives. The library draws, decodes and measures through narrow seams — a canvas factory, a frame sink, a font installer — which the page fills with the browser's own and the container fills at startup with a native canvas, native decoders, a Web Audio graph, and the editor's font files staged in the image. So watching footage, cutting on silence, freezing a frame, matting a sticker, writing captions and capturing the composited frame all behave in a job the way they behave in the tab, and parity holds by construction: there is one implementation. Two things stay page-only — on-device MediaPipe matting, which falls through to the hosted vision path, and Lottie stickers, which need a DOM.-Two mechanisms keep a turn honest. A mutation ledger, computed in code from the tool results, rides every model call as an ephemeral context note: what ran, what failed, and what debris the edits left (a parked transition bar, an item stranded past the video's end) — the model must fix or plainly report each entry before its reply lands, and the note is never stored or rendered. And the round budget extends itself: a build that outgrows its 24 rounds gets fresh budget automatically (up to three extensions, so 96 rounds in all), so the user never types "keep going". At the ceiling tool calls stop and the model gets one round to say where it landed; a turn still reaching for tools ends with a line offering "keep going".+Two mechanisms keep a turn honest. A mutation ledger, computed in code from the tool results, rides every model call as an ephemeral context note: what ran, what failed, and what debris the edits left (a parked transition bar, an item stranded past the video's end) — the model must fix or plainly report each entry before its reply lands, and the note is never stored or rendered. And the step budget extends itself, the same way on every provider: a build that outgrows its 24 steps gets fresh budget automatically (up to three extensions, so 96 in all), so the user never types "keep going". Gemini blocks tool calls at the ceiling and gets one round to say where it landed; a CLI run that spends the budget is resumed from its own session. However a turn ends — at the ceiling, on a provider's error, or saying nothing at all — it closes with a line the person can act on, never with the provider's word for it.The composer stays open while a turn runs. A message sent mid-turn waits in a small tray on the composer's top edge and goes out when the running turn settles — one turn at a time, each with a fresh editor snapshot, so a queued ask always sees the edits made before it. A typed triage places each mid-turn message first: a refinement of the running work is steered into the live turn, an independent ask that cannot collide starts a parallel thread, and everything else — including whatever the call cannot place — waits in the tray, where the running agent can also park a message itself when it needs the finished result first. A row is placed against the tools the turn had run at the time, so the tray is placed again as the turn advances: the work a row was waiting on lands, and it folds in rather than waiting out the turn. The tray is the review surface: waiting rows can be reordered, rewritten, or removed, and the queue pauses and resumes from its header. While a row is being rewritten the list holds still — the row under edit waits, the others keep draining and cross out in place as they finish. Stopping a turn or hitting an error pauses the queue automatically, so the remaining asks hold for review. Waiting rows are saved with the thread on the machine: a reload or a trip to another project brings them back paused, ready to resume.@@ -122,8 +122,7 @@ A thread saves one session slot per provider, so switching models mid-thread kee| Limit | Value || --- | --- |-| Provider turns per request (Claude) | 30 |-| Tool rounds per turn (Gemini) | 24, extending to a 96 ceiling |+| Tool steps per turn | 24, extending to a 96 ceiling || Inline media per model call | 16MB, trimmed oldest-first || Browser tool execution | 120s || One watch-video call | 600s of source, 4 sheets (36 frames), 150 decoded candidates, a 90s decode budget; the result says where coverage stopped |diff --git a/site/src/cut/lib/pi/cutAgent.ts b/site/src/cut/lib/pi/cutAgent.tsindex 3fcb5706..909bf44a 100644--- a/site/src/cut/lib/pi/cutAgent.ts+++ b/site/src/cut/lib/pi/cutAgent.ts@@ -12,6 +12,13 @@ import {TOOL_AREA_NAMES,} from "@/cut/server/ai/catalog";import { isResumeMessage } from "../chatResume";+import {+ BUDGET_STEER_PREFIX,+ budgetSteer,+ MAX_EXTENSIONS,+ STEP_BUDGET,+ turnClose,+} from "../turnBudget";import { cutJudge } from "../chatRuntime";import {instantAction,@@ -57,12 +64,10 @@ import { subscribeUiChunks } from "./uiChunks";// replay as structured toolCall/toolResult messages, so no bookkeeping rides// as prose the model could mimic.-// A round is one assistant message that requests tools. The budget-// auto-extends so the user never types "keep going". At the ceiling every+// A round is one assistant message that requests tools; the budget and its+// extensions are the shared ones in lib/turnBudget. At the ceiling every// call blocks with a reply-now instruction; a model that still requests// tools the round after gets its batch terminated, ending the turn.-const ROUND_BUDGET = 24;-const MAX_EXTENSIONS = 3;export interface CutAgentDeps {post: PostFn;@@ -130,10 +135,6 @@ function keepSession(threadId: string, messages: AgentMessage[]): void {while (sessions.size > SESSIONS_KEPT) sessions.delete(sessions.keys().next().value!);}-/** The budget-extension steer is turn-local scaffolding; this prefix marks it- * so the save path can keep it out of the stored session. */-const BUDGET_STEER_PREFIX = "[budget]";-function isBudgetSteer(m: AgentMessage): boolean {const msg = m as Message;return (@@ -723,7 +724,7 @@ export function streamCutChat({// its own awaits, inside the try that answers the user..catch(() => {});- const roundBudget = deps.limits?.roundBudget ?? ROUND_BUDGET;+ const roundBudget = deps.limits?.roundBudget ?? STEP_BUDGET;const maxExtensions = deps.limits?.maxExtensions ?? MAX_EXTENSIONS;const roundCeiling = roundBudget * (maxExtensions + 1);@@ -904,7 +905,7 @@ export function streamCutChat({deps.hooks?.onExtension?.(extensions);agent.steer({role: "user",- content: `[budget] Round budget auto-extended (${extensions} of ${maxExtensions}). Keep working; finish the job or report the concrete blocker.`,+ content: budgetSteer(extensions, maxExtensions),timestamp: Date.now(),});}@@ -939,31 +940,35 @@ export function streamCutChat({send: (chunk: Record<string, unknown>) => void;}) => {keepSession(threadId, sanitizeSession(run.agent.state.messages));- // The step-limit handoff guarantee: a turn that ends at the ceiling- // with the model still requesting tools closes with readable text —- // the terminated batch alone would leave the reply on blocked tool+ const errorMessage = run.agent.state.errorMessage;+ // The handoff guarantee, the same one every provider keeps: a turn+ // that ends at the ceiling with the model still requesting tools,+ // or ends saying nothing at all, closes with readable text — the+ // terminated batch alone would leave the reply on blocked tool// chips with no sign-off.- if (run.rounds > roundCeiling && !abortSignal?.aborted) {- const last = [...run.agent.state.messages]- .reverse()- .find((m) => (m as Message).role === "assistant") as Message | undefined;- const spoke =- !!last &&- Array.isArray(last.content) &&- last.content.some((c) => c.type === "text" && c.text.trim());- if (!spoke) {- const id = crypto.randomUUID();- run.send({ type: "text-start", id });- run.send({- type: "text-delta",- id,- delta:- 'Paused at this turn\'s step limit with work still open. Say "keep going" to continue.',+ const last = [...run.agent.state.messages]+ .reverse()+ .find((m) => (m as Message).role === "assistant") as Message | undefined;+ const spoke =+ !!last &&+ Array.isArray(last.content) &&+ last.content.some((c) => c.type === "text" && c.text.trim());+ const close = abortSignal?.aborted+ ? null+ : turnClose({+ end: errorMessage ? "failed" : run.rounds > roundCeiling ? "budget" : "done",+ spoke,+ // At the ceiling the extensions are all spent, so this is the+ // handoff rather than more budget.+ extensions: maxExtensions,+ maxExtensions,});- run.send({ type: "text-end", id });- }+ if (close && "signoff" in close) {+ const id = crypto.randomUUID();+ run.send({ type: "text-start", id });+ run.send({ type: "text-delta", id, delta: close.signoff });+ run.send({ type: "text-end", id });}- const errorMessage = run.agent.state.errorMessage;if (errorMessage && !abortSignal?.aborted) {run.send({ type: "error", errorText: errorMessage });}diff --git a/site/src/cut/lib/turnBudget.test.ts b/site/src/cut/lib/turnBudget.test.tsnew file mode 100644index 00000000..615455ef--- /dev/null+++ b/site/src/cut/lib/turnBudget.test.ts@@ -0,0 +1,39 @@+import { expect, test } from "bun:test";+import { budgetSteer, stopText, turnClose } from "./turnBudget";++// One policy for every provider: a spent budget carries on, a spent ceiling+// hands back in words, and a token never reaches the chat.++test("a model that signed off is left alone", () => {+ expect(turnClose({ end: "done", spoke: true, extensions: 0 })).toBeNull();+ expect(turnClose({ end: "blocked", spoke: false, extensions: 0 })).toBeNull();+ expect(turnClose({ end: "failed", spoke: false, extensions: 0 })).toBeNull();+});++test("a spent budget carries on, counted", () => {+ const first = turnClose({ end: "budget", spoke: true, extensions: 0, maxExtensions: 3 }) as { steer: string };+ expect(first.steer).toContain("1 of 3");+ const last = turnClose({ end: "budget", spoke: true, extensions: 2, maxExtensions: 3 }) as { steer: string };+ expect(last.steer).toContain("3 of 3");+});++test("the spent ceiling hands off in words", () => {+ const out = turnClose({ end: "budget", spoke: true, extensions: 3, maxExtensions: 3 }) as { signoff: string };+ expect(out.signoff).toContain("keep going");+ expect(out.signoff).not.toContain("max_turns");+});++test("a turn that said nothing still gets an ending", () => {+ const out = turnClose({ end: "done", spoke: false, extensions: 0 }) as { signoff: string };+ expect(out.signoff).toContain("keep going");+});++test("the steer is marked as turn-local scaffolding", () => {+ expect(budgetSteer(1).startsWith("[budget]")).toBe(true);+});++test("a stop with no account of itself still reads as a sentence", () => {+ expect(stopText("Usage limit reached. Try again at 4pm.")).toBe("Usage limit reached. Try again at 4pm.");+ expect(stopText(undefined)).toContain("keep going");+ expect(stopText(" ")).toContain("keep going");+});diff --git a/site/src/cut/lib/turnBudget.ts b/site/src/cut/lib/turnBudget.tsnew file mode 100644index 00000000..f2c0999c--- /dev/null+++ b/site/src/cut/lib/turnBudget.ts@@ -0,0 +1,56 @@+/** One turn's step budget, and how a turn ends. Shared by every provider.+ *+ * A step is one model round that asks for tools. Every provider stops+ * somewhere — this loop counts rounds, the Claude Agent SDK caps its own+ * turns — and a build that runs out mid-edit must not end on the provider's+ * word for it. The budget extends itself a few times so a long build+ * finishes on its own, and once it is spent the turn hands back in a+ * sentence the person can act on. A turn that ends saying nothing gets the+ * same treatment: tool chips with no words is not an ending.+ */++export const STEP_BUDGET = 24;+export const MAX_EXTENSIONS = 3;++/** Turn-local scaffolding: the prefix marks the steer so the save path can+ * keep it out of the stored session. */+export const BUDGET_STEER_PREFIX = "[budget]";++export const PAUSED_HANDOFF =+ 'Paused at this turn\'s step limit with work still open. Say "keep going" to continue.';+export const SILENT_HANDOFF = 'That turn ended without a reply. Say "keep going" to pick it up.';++/** How a run ended: the model signed off, it spent its steps, it failed, or+ * it never got its tools. */+export type TurnEnd = "done" | "budget" | "failed" | "blocked";++export function budgetSteer(extension: number, maxExtensions: number = MAX_EXTENSIONS): string {+ return `${BUDGET_STEER_PREFIX} Step budget auto-extended (${extension} of ${maxExtensions}). Keep working; finish the job or report the concrete blocker.`;+}++/** What a finished run owes the person: more budget to carry on with, a line+ * to close on, or nothing when the model signed off itself. */+export function turnClose(opts: {+ end: TurnEnd;+ /** The run put words on screen. */+ spoke: boolean;+ /** Extensions already granted this turn. */+ extensions: number;+ maxExtensions?: number;+}): { steer: string } | { signoff: string } | null {+ const max = opts.maxExtensions ?? MAX_EXTENSIONS;+ if (opts.end === "budget")+ return opts.extensions < max+ ? { steer: budgetSteer(opts.extensions + 1, max) }+ : { signoff: PAUSED_HANDOFF };+ if (opts.end === "done" && !opts.spoke) return { signoff: SILENT_HANDOFF };+ return null;+}++/** A provider's own account of a stop, or a plain line when all it handed+ * back was a token or nothing at all. */+export function stopText(detail?: unknown): string {+ return typeof detail === "string" && detail.trim()+ ? detail.trim()+ : 'The turn stopped before it finished. Say "keep going" to pick it up.';+}diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.tsindex 16a3fb61..dcf5fc9e 100644--- a/site/src/cut/server/http/ai.ts+++ b/site/src/cut/server/http/ai.ts@@ -20,6 +20,7 @@ import {import { rewriteCaptions, translateCaptions } from "../ai/captions";import { writeVisualCues, type VisualFrame } from "../ai/visualSubtitles";import { AI_SKILL_INDEX, AI_TOOLS, attachedAssetsBlock, readSkill, skillRelevanceBlock, systemPrompt } from "../ai/catalog";+import { STEP_BUDGET, stopText, turnClose, type TurnEnd } from "../../lib/turnBudget";interface ChatBody {threadId: string;@@ -79,89 +80,124 @@ async function runClaude(signal: AbortSignal) {signal.throwIfAborted();- const q = query({- prompt,- options: {- model: body.model,- ...(body.providerSession ? { resume: body.providerSession } : {}),- // Inside the compiled engine the SDK can't resolve its built-in CLI;- // the engine resolves the user's own Claude Code install at startup.- ...(process.env.DONKEY_CUT_CLAUDE- ? { pathToClaudeCodeExecutable: process.env.DONKEY_CUT_CLAUDE }- : {}),- systemPrompt: systemPrompt(),- tools: [], // no built-in tools — the editor MCP server is the whole surface- mcpServers: {- cut: {- type: "stdio",- ...mcpCommand(base, sessionKey),- alwaysLoad: true,+ let textCount = 0;+ let session = body.providerSession;+ const say = (text: string) => {+ const id = `t${++textCount}`;+ emit({ type: "text-start", id });+ emit({ type: "text-delta", id, delta: text });+ emit({ type: "text-end", id });+ };++ /** One run of the query. It ends when the model signs off, when the SDK+ * spends the step budget, or when the editor tools failed to bind. */+ const pass = async (ask: string): Promise<TurnEnd> => {+ signal.throwIfAborted();+ const q = query({+ prompt: ask,+ options: {+ model: body.model,+ ...(session ? { resume: session } : {}),+ // Inside the compiled engine the SDK can't resolve its built-in CLI;+ // the engine resolves the user's own Claude Code install at startup.+ ...(process.env.DONKEY_CUT_CLAUDE+ ? { pathToClaudeCodeExecutable: process.env.DONKEY_CUT_CLAUDE }+ : {}),+ systemPrompt: systemPrompt(),+ tools: [], // no built-in tools — the editor MCP server is the whole surface+ mcpServers: {+ cut: {+ type: "stdio",+ ...mcpCommand(base, sessionKey),+ alwaysLoad: true,+ },},+ allowedTools: ["mcp__cut"],+ permissionMode: "dontAsk",+ settingSources: [], // don't drag the user's CLAUDE.md/settings into app chats+ // The editor MCP is the whole tool surface. settingSources:[] only drops+ // filesystem config — the SDK still auto-fetches the account's claude.ai+ // cloud connectors (Gmail, Drive, …) and surfaces them to the model.+ // These two flags make the isolation total: no connectors, and no MCP+ // server except the one we pass here.+ strictMcpConfig: true,+ settings: { disableClaudeAiConnectors: true },+ includePartialMessages: true,+ maxTurns: STEP_BUDGET,+ cwd: os.tmpdir(),},- allowedTools: ["mcp__cut"],- permissionMode: "dontAsk",- settingSources: [], // don't drag the user's CLAUDE.md/settings into app chats- // The editor MCP is the whole tool surface. settingSources:[] only drops- // filesystem config — the SDK still auto-fetches the account's claude.ai- // cloud connectors (Gmail, Drive, …) and surfaces them to the model.- // These two flags make the isolation total: no connectors, and no MCP- // server except the one we pass here.- strictMcpConfig: true,- settings: { disableClaudeAiConnectors: true },- includePartialMessages: true,- maxTurns: 30,- cwd: os.tmpdir(),- },- });- const onAbort = () => void q.interrupt().catch(() => {});- signal.addEventListener("abort", onAbort);+ });+ const onAbort = () => void q.interrupt().catch(() => {});+ signal.addEventListener("abort", onAbort);- let textCount = 0;- let textId: string | null = null;- try {- for await (const msg of q) {- const m = msg as unknown as Record<string, unknown> & { type: string };- if (m.type === "system" && m.subtype === "init") {- // The editor MCP is the assistant's entire tool surface. If it didn't- // bind (an engine hiccup, an out-of-scope proxy call), the model would- // improvise by narrating tool calls as raw XML — surface a clear error- // instead of letting that reach the user.- const tools = Array.isArray(m.tools) ? (m.tools as unknown[]) : [];- if (!tools.some((t) => typeof t === "string" && t.startsWith("mcp__cut"))) {- emit({ type: "error", errorText: "The editor tools didn't load. Reload the tab and try again." });- await q.interrupt().catch(() => {});+ let end: TurnEnd = "done";+ let textId: string | null = null;+ try {+ for await (const msg of q) {+ const m = msg as unknown as Record<string, unknown> & { type: string };+ if (m.type === "system" && m.subtype === "init") {+ // The editor MCP is the assistant's entire tool surface. If it didn't+ // bind (an engine hiccup, an out-of-scope proxy call), the model would+ // improvise by narrating tool calls as raw XML — surface a clear error+ // instead of letting that reach the user.+ const tools = Array.isArray(m.tools) ? (m.tools as unknown[]) : [];+ if (!tools.some((t) => typeof t === "string" && t.startsWith("mcp__cut"))) {+ emit({ type: "error", errorText: "The editor tools didn't load. Reload the tab and try again." });+ await q.interrupt().catch(() => {});+ end = "blocked";+ break;+ }+ // Each run gets its own session id; the next one resumes from the+ // newest, so an extended turn keeps one continuous history.+ if (typeof m.session_id === "string") session = m.session_id;+ emit({ type: "data-session", data: { providerSession: m.session_id }, transient: true });+ } else if (m.type === "stream_event") {+ const ev = m.event as {+ type: string;+ content_block?: { type: string };+ delta?: { type: string; text?: string };+ };+ if (ev.type === "content_block_start" && ev.content_block?.type === "text") {+ textId = `t${++textCount}`;+ emit({ type: "text-start", id: textId });+ } else if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && textId) {+ emit({ type: "text-delta", id: textId, delta: ev.delta.text ?? "" });+ } else if (ev.type === "content_block_stop" && textId) {+ emit({ type: "text-end", id: textId });+ textId = null;+ }+ } else if (m.type === "result") {+ // The SDK names its stops with tokens ("error_max_turns"), which+ // say nothing to someone waiting on a half-built edit: a spent+ // budget carries on below, and anything else is said in words.+ if (m.subtype === "error_max_turns") end = "budget";+ else if (m.subtype !== "success") {+ end = "failed";+ emit({ type: "error", errorText: stopText(m.result) });+ }+ // The result message is the run's last word — after it the CLI only+ // tears down. Leaving the loop closes the chat stream now instead of+ // holding the working indicator open through process exit.break;}- emit({ type: "data-session", data: { providerSession: m.session_id }, transient: true });- } else if (m.type === "stream_event") {- const ev = m.event as {- type: string;- content_block?: { type: string };- delta?: { type: string; text?: string };- };- if (ev.type === "content_block_start" && ev.content_block?.type === "text") {- textId = `t${++textCount}`;- emit({ type: "text-start", id: textId });- } else if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && textId) {- emit({ type: "text-delta", id: textId, delta: ev.delta.text ?? "" });- } else if (ev.type === "content_block_stop" && textId) {- emit({ type: "text-end", id: textId });- textId = null;- }- } else if (m.type === "result") {- if (m.subtype !== "success") {- const detail = typeof m.result === "string" ? m.result : String(m.subtype);- emit({ type: "error", errorText: `Claude stopped: ${detail}` });- }- // The result message is the turn's last word — after it the CLI only- // tears down. Leaving the loop closes the chat stream now instead of- // holding the working indicator open through process exit.- break;}+ } finally {+ signal.removeEventListener("abort", onAbort);+ if (textId) emit({ type: "text-end", id: textId });}- } finally {- signal.removeEventListener("abort", onAbort);- if (textId) emit({ type: "text-end", id: textId });+ return end;+ };++ // A run that spent the budget resumes from its own session, so the next+ // one carries the whole tool history and the build finishes on its own.+ let ask = prompt;+ for (let extensions = 0; ; extensions++) {+ const end = await pass(ask);+ if (signal.aborted) return;+ const close = turnClose({ end, spoke: textCount > 0, extensions });+ if (!close) return;+ if ("signoff" in close) return say(close.signoff);+ ask = close.steer;}}@@ -213,6 +249,12 @@ async function runCodex(};let textCount = 0;+ const say = (text: string) => {+ const id = `t${++textCount}`;+ emit({ type: "text-start", id });+ emit({ type: "text-delta", id, delta: text });+ emit({ type: "text-end", id });+ };let stdoutBuf = "";let stderrTail = "";proc.stdout.setEncoding("utf8");@@ -232,15 +274,15 @@ async function runCodex(if (ev.type === "thread.started" && ev.thread_id) {emit({ type: "data-session", data: { providerSession: ev.thread_id }, transient: true });} else if (ev.type === "item.completed" && ev.item?.type === "agent_message" && ev.item.text) {- const id = `t${++textCount}`;- emit({ type: "text-start", id });- emit({ type: "text-delta", id, delta: ev.item.text });- emit({ type: "text-end", id });+ say(ev.item.text);} else if (ev.type === "error" || ev.type === "turn.failed") {- const message = ev.error?.message ?? ev.message ?? "Codex failed.";- emit({ type: "error", errorText: message });+ emit({ type: "error", errorText: stopText(ev.error?.message ?? ev.message) });if (ev.type === "turn.failed") settle();} else if (ev.type === "turn.completed") {+ // The CLI runs a turn to its own end — there is no step cap to+ // extend — so the only ending it can leave open is a silent one.+ const close = turnClose({ end: "done", spoke: textCount > 0, extensions: 0 });+ if (close && "signoff" in close && !signal.aborted) say(close.signoff);settle();}if (settled) return;