Skip to content

Open source CapCut alternative.

TypeScript

fix(site): carry finished tool work into the next chat turn [rebuild]

David Le2597de1c5921
diff --git a/site/scripts/eval-cut-chat.ts b/site/scripts/eval-cut-chat.ts
index a0a0e558..c08b3943 100644
--- a/site/scripts/eval-cut-chat.ts
+++ b/site/scripts/eval-cut-chat.ts
@@ -21,7 +21,7 @@ import { mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { geminiModelRoles } from "../src/lib/inference/gemini-models";
-import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt } from "../src/cut/server/ai/catalog";
+import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt, toolsRanBlock } from "../src/cut/server/ai/catalog";
import {
parseTurnIntent,
TURN_INTENT_PROMPT,
@@ -252,8 +252,8 @@ const AUDIO_STATE = {
/** A tweet photo import_url landed in an earlier turn: chat-owned (aiTools
* tags chat imports origin "chat"), named by the post's text, not yet placed.
- * Past turns' tool traffic is stripped from the request, so the model must
- * find this asset through `media` in the snapshot. */
+ * A past turn replays as its text plus a ledger of the tool names it ran, so
+ * the model must find this asset through `media` in the snapshot. */
const TWEET_ASSET = {
id: "a-tw1",
name: "first snow of the year ❄️",
@@ -266,6 +266,41 @@ const TWEET_STATE = {
media: [...EDITOR_STATE.media, TWEET_ASSET],
};
+/** The project after a styling turn finished: the reference import landed in
+ * media, the three city clips are already joined by the crosszooms that turn
+ * set, and every clip is still unmuted. Everything the previous turn did is
+ * visible here, so redoing any of it is plainly redundant. */
+const cityClip = (n: number, name: string, start: number, styled: boolean) => ({
+ index: n - 1,
+ id: `c${n}`,
+ asset: name,
+ start,
+ len: 4.7,
+ in: 0,
+ out: 4.7,
+ sourceDuration: 4.7,
+ muted: false,
+ framing: "fit",
+ speed: 1,
+ ...(styled ? { transitionToNext: { style: "crosszoom", seconds: 1 } } : {}),
+});
+const STYLED_STATE = {
+ ...EDITOR_STATE,
+ media: [
+ ...EDITOR_STATE.media,
+ TWEET_ASSET,
+ { id: "a-c1", name: "seoul.mp4", type: "video", duration: 4.7, origin: "generated" },
+ { id: "a-c2", name: "san-francisco.mp4", type: "video", duration: 4.7, origin: "generated" },
+ { id: "a-c3", name: "toronto.mp4", type: "video", duration: 4.7, origin: "generated" },
+ ],
+ videoTrack: [
+ cityClip(1, "seoul.mp4", 0, true),
+ cityClip(2, "san-francisco.mp4", 3.7, true),
+ cityClip(3, "toronto.mp4", 7.4, false),
+ ],
+ soundtrack: [],
+};
+
/** A finished scene run's timeline: three generated takes, each clip carrying
* its plan shot number (sceneShot), the narration as the spine. */
const sceneClip = (n: number, start: number, len: number) => ({
@@ -348,6 +383,13 @@ function userTurn(
const plainUserTurn = (text: string): Item => ({ role: "user", content: [{ text }] });
const assistantTurn = (text: string): Item => ({ role: "assistant", content: [{ text }] });
+/** An earlier assistant turn that ran tools, carrying the same <tools_ran>
+ * ledger production replays it with (catalog's toolsRanBlock). */
+const assistantToolTurn = (text: string, tools: string[]): Item => ({
+ role: "assistant",
+ content: [{ text: `${text}${toolsRanBlock(tools)}` }],
+});
+
/** A tiny track-0 simulator for composed cut flows: splits, trims, deletes,
* and undo evolve real state, so get_state shows the model its own edits and
* later calls can use the new clip ids. A frozen snapshot can't support a
@@ -681,6 +723,36 @@ function cases(audio: { dataBase64: string; mimeType: string }): EvalCase[] {
},
},
},
+ {
+ // The screenshot regression: after a turn that imported a reference and
+ // styled the cut, "mute all clips" mutes and stops. A replayed
+ // conversation carries no tool traffic, so without the <tools_ran>
+ // ledger the model reads its own last reply as an unfinished plan and
+ // runs the whole thing again — re-importing, re-watching, re-styling —
+ // then narrates that as the answer. The snapshot names every clip and
+ // its muted flag, so the mute needs no reads either.
+ name: "mute-all-does-not-redo-prior-turn",
+ input: () => [
+ plainUserTurn(
+ "use the illustration style at https://x.com/example/status/1 and blend the three city clips together"
+ ),
+ assistantToolTurn(
+ "Imported the reference illustration and blended Seoul, San Francisco, and Toronto with 1-second crosszooms.",
+ ["import_url", "watch_video", "watch_video", "watch_video", "set_transition", "set_transition"]
+ ),
+ userTurn("mute all clips", { state: STYLED_STATE }),
+ ],
+ reply: /mut/i,
+ requiredTools: ["set_clip_muted"],
+ maxToolCalls: 3,
+ state: STYLED_STATE,
+ simulate: () => (name) => {
+ if (name === "import_url" || name === "watch_video" || name === "set_transition")
+ throw new Error(`${name} — the previous turn already ran it; "mute all clips" only mutes`);
+ return undefined;
+ },
+ stubs: { set_clip_muted: { muted: true } },
+ },
{
// The tweet-import flow: after import_url landed a photo in an earlier
// turn, "the exact same thing but…" must anchor generate_image on that
diff --git a/site/src/cut/lib/geminiChat.ts b/site/src/cut/lib/geminiChat.ts
index 8559bad8..a30dd5a4 100644
--- a/site/src/cut/lib/geminiChat.ts
+++ b/site/src/cut/lib/geminiChat.ts
@@ -2,7 +2,7 @@
import type { UIMessage, UIMessageChunk } from "ai";
import { geminiModelRoles } from "@/lib/inference/gemini-models";
-import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt } from "@/cut/server/ai/catalog";
+import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt, toolsRanBlock } from "@/cut/server/ai/catalog";
import { buildAiContext } from "./aiContext";
import { runAiTool } from "./aiTools";
import { normalizeRef } from "./assetRef";
@@ -219,11 +219,29 @@ const toolDeclarations = () =>
parameters: t.inputSchema,
}));
-/** The conversation replayed as hosted-Responses input items. Only text (and
- * attachment refs) from past turns — tool traffic stays within its own turn.
- * The fresh editor snapshot rides on the newest user message alone, and so do
- * the attachments' actual payloads (video frames, images, audio, text-file contents):
- * older turns keep just the metadata JSON so replays stay within budget. */
+/** The tools an assistant turn finished, read off its rendered parts. A call
+ * that errored did no work, so it stays out and a retry stays open. */
+function toolsRanIn(m: UIMessage): string[] {
+ const parts = m.parts as unknown as { type: string; state?: string; toolName?: string }[];
+ return parts.flatMap((p) => {
+ const name =
+ p.type === "dynamic-tool"
+ ? p.toolName
+ : p.type.startsWith("tool-")
+ ? p.type.slice(5)
+ : undefined;
+ return name && p.state === "output-available" ? [name] : [];
+ });
+}
+
+/** The conversation replayed as hosted-Responses input items. Past turns keep
+ * their text plus a <tools_ran> ledger of what each reply executed — the tool
+ * traffic itself (media payloads, thought signatures) stays within its own
+ * turn, but the record of it has to survive or the model re-runs finished
+ * work. The fresh editor snapshot rides on the newest user message alone, and
+ * so do the attachments' actual payloads (video frames, images, audio,
+ * text-file contents): older turns keep just the metadata JSON so replays stay
+ * within budget. */
async function inputFromMessages(messages: UIMessage[]): Promise<Item[]> {
const lastUser = messages.findLast((m) => m.role === "user");
const items: Item[] = [];
@@ -249,6 +267,8 @@ async function inputFromMessages(messages: UIMessage[]): Promise<Item[]> {
if (m === lastUser) {
text += `\n\n<editor_state>\n${JSON.stringify(buildAiContext())}\n</editor_state>`;
}
+ } else {
+ text += toolsRanBlock(toolsRanIn(m));
}
if (!text && extra.length === 0) continue;
items.push({
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index f9d2a274..006e6b8a 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -865,12 +865,13 @@ export function systemPrompt(): string {
Rules:
- First decide what the user wants handed back: an edit to the project, or words in chat. "Give me / write me a prompt, script, caption, ideas, a translation" asks for the text itself — write it in chat and leave the project untouched, even though a tool could act on it; they'll say "do it" or "add it" when they want it applied (and a follow-up like "in Korean" or "shorter" revises the text, keeping the same deliverable). A complaint or observation ("ugh, this is cluttered") is words too: sympathize, offer what you could do, and touch nothing until they say go. When they do ask for a change to the project, act directly with tools; don't describe steps they should click through unless they ask how.
-- Use ids exactly as given in the state, and act on what your tools return — each reports what it changed, so batch independent edits into one step and call get_state only when the snapshot is stale or a result surprised you. A tool that comes back "unreachable" or "no live editor session" is a dropped bridge, not a limit and not your request's fault — the editor never received the call, so quietly make the same call once more before doing anything else, and never tell the user to reconnect or restart the editor.
+- Do what the newest message asks, then stop. The turns above are finished work: what an earlier reply already ran is recorded with it, and the snapshot shows where the project landed — start from there and leave settled work alone. Ideas beyond the ask (a transition, a look, music, captions) belong in one closing sentence for the user to take up.
+- Use ids exactly as given in the state — <editor_state> lists every clip, title, cue, asset, and setting with its id, so an edit it already answers ("mute all clips", "delete the second title") goes straight to the tools. Act on what your tools return — each reports what it changed, so batch independent edits into one step and call get_state only when the snapshot is stale or a result surprised you. A tool that comes back "unreachable" or "no live editor session" is a dropped bridge, not a limit and not your request's fault — the editor never received the call, so quietly make the same call once more before doing anything else, and never tell the user to reconnect or restart the editor.
- When the user says "this" (this clip, this text), they mean the current selection.
- Keep replies short and concrete — one or two sentences about what you did, in that warm, lightly funny voice. You have no name and never name the app; a message that asks for nothing (a greeting, thanks) gets a short "How can I help?" / "What would you like to do?" back — words alone, no tool calls. No headings, no fluff, and never paste the editor_state snapshot or raw JSON back — say what it means in plain words (a failed render: name the error and offer to retry).
- Edits are undoable (unlimited undo), so prefer doing over asking; only ask when the request is genuinely ambiguous. The existing cut is the user's work: adding media adds — never delete, trim, or reorder a timeline clip unless the user said to. Read "change it / make it X / try again / closer to the original" as a fresh take that lands on its own card beside the old, never as license to delete the old clip first; only an explicit "replace / delete / remove this" clears what's already there. Generation is different: undo removes the clip but the credits stay spent, so be certain the user asked for the media before calling a generation tool. Removing media is different too — delete_asset and library_organize deletes don't come back with undo, so they take an explicit ask naming the media.
- Times are seconds. The frame follows project.aspect in editor_state — any "W:H" ratio, short side 1080px; project.frame has the exact pixels. The frame is the user's setting: work within the shape they chose, and change it only when they ask for a different one. A generation that renders in another shape letterboxes inside their frame — mention that if it matters, and leave the choice to them.
-- Read list_skills / read_skill before working in an area you're unsure about — they document every setting.
+- Read list_skills / read_skill before working in an area you're unsure about — they document every setting. A tool whose description already answers the ask goes straight through.
- Transcription tools write tracks the user sees — run subtitles_generate / captions_generate only when captions were asked for, never just to read the words: existing cues are in editor_state, and audio plays to you via listen_audio. Don't transcribe a video with no speech (subtitles_from_visuals narrates silent footage), and never invent a spoken transcript.
- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.
- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud / generate_music make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. generate_music makes a music track — a vocal-free background bed by default ("add music to this video"), or a full sung song (instrumental:false); it's sung music, so a spoken narration is voiceover_generate. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. Write a rich, specific prompt from their shorthand. Video renders take a minute or two. "Generate a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop at the storyboard — the user reviews the frames (regenerate_shot redraws any before approval, no credits), then call approve_scene, since it renders many paid shots (regenerate_shot / recut_scene / restyle_scene revise it after).
@@ -879,6 +880,21 @@ Rules:
export const AI_SKILL_INDEX = Object.keys(AI_SKILLS);
+/** The ledger an assistant turn carries when the conversation is replayed
+ * rather than resumed. A provider session keeps its own tool traffic; a
+ * replayed conversation carries text alone, so without this line a past reply
+ * reads as a plan nobody carried out — and the next message makes the model
+ * run the whole thing again on top of what it was actually asked for. Names
+ * and counts are the whole record: the editor snapshot carries the result.
+ * Empty when the turn ran nothing. */
+export function toolsRanBlock(names: string[]): string {
+ if (names.length === 0) return "";
+ const counts = new Map<string, number>();
+ for (const n of names) counts.set(n, (counts.get(n) ?? 0) + 1);
+ const list = [...counts].map(([n, c]) => (c > 1 ? `${n} ×${c}` : n)).join(", ");
+ return `\n\n<tools_ran>This reply already ran: ${list}. That work is done.</tools_ran>`;
+}
+
/** The <attached_assets> block a user turn carries when it has attachment
* refs. One builder serves hosted chat, the engine chat, and the eval mirror,
* so the doctrine — especially the clip-scope steering — can never drift