Open source CapCut alternative.
TypeScript
feat(site): triage mid-turn chat messages into fold, spawn, or queue [rebuild]
David Le791884109aaf
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.tsindex d9a3533d..e3d34bee 100644--- a/site/src/cut/components/AiPanel.tools.ts+++ b/site/src/cut/components/AiPanel.tools.ts@@ -109,6 +109,12 @@ export const AI_PANEL_TOOLS = ["Block until this project's in-flight video renders settle (up to ~100s), then report each one: landed (with its asset id, ready to place) or failed (with the error). Call it whenever the user's ask depends on a render that `renders` in the state shows as running — \"add it when it's done\", \"assemble the clips\" — and then finish the job in the same turn; never tell the user to come back and report when a card appears. If some renders are still running when it returns, say how long they've been going and call it again on the user's go-ahead.",inputSchema: obj({}),},+ {+ name: "queue_message",+ description:+ "Put a message on the composer queue to run as its own turn after this one finishes, with a fresh view of the project. For a further message the user sent while you were working that you cannot do yet: it needs this turn's finished result (an export, a share, a thumbnail of the final cut), or a fresh look at the timeline once your cuts have landed. Pass the user's words as they wrote them; the row goes out on its own when this turn settles, and your reply says what waits. The ask you were given is never queued — do it now.",+ inputSchema: obj({ text: str("The message, in the user's words") }, ["text"]),+ },{name: "import_url",description:diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex af79fce7..74b8e678 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -97,6 +97,7 @@ import {import { useCreditsRecheck, useOutOfCredits } from "@/cut/lib/hosted";import { cutChatLive, dropPiSession, foldIntoCutChat, hydratePiSession, readPiSession, streamCutChat, triageQueuedMessages } from "@/cut/lib/pi/cutAgent";import { toolProgress } from "@/cut/lib/queueTriage";+import { registerQueueSink } from "@/cut/lib/chatQueue";import { productionDeps } from "@/cut/lib/pi/prodDeps";import { withChatProject } from "@/cut/lib/projectChatTools";import { runAiTool } from "@/cut/lib/aiTools";@@ -1539,6 +1540,15 @@ function ChatSession({useEffect(() => {triageRef.current = triage;});+ // The running agent can park a message here itself (queue_message): the+ // row goes out as its own turn after the running one settles.+ useEffect(+ () =>+ registerQueueSink(threadId, (text) =>+ setQueue((q) => [...q, { id: crypto.randomUUID(), text, attachments: [], status: "queued" }]),+ ),+ [threadId],+ );// Height of the floating stack above the composer (warning tabs + queue// tray); the messages pad their bottom by it so the newest message can// scroll out from behind the stack.diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 5f7fc6f3..8e394140 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -89,6 +89,7 @@ import type { TransitionsToolName } from "@/cut/components/TransitionsPanel.toolimport { apiFetch, apiJson, getBackend } from "./backend";import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";import { chatOwner, tagChatAsset } from "./chatAssets";+import { queueMessageFromAgent } from "./chatQueue";import { applyOwnership, useGenerate, type VideoAttempt, type VideoGenOptions } from "./generate";import { useGenScene } from "./genScene";import { folderWithin } from "./folderTree";@@ -2707,6 +2708,13 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {return launchVideoJob(projectId, input, [{ prompt, opts: { ...baseOpts } }]);},+ queue_message: (_s, input) => {+ const text = String(input.text ?? "").trim();+ if (!text) throw new ToolError("queue_message needs the message text.");+ queueMessageFromAgent(text);+ return { queued: true, note: "It runs as its own turn after this one finishes." };+ },+wait_for_renders: async (s) => {const projectId = s.projectId;if (!projectId) throw new ToolError("No project open.");diff --git a/site/src/cut/lib/chatQueue.ts b/site/src/cut/lib/chatQueue.tsnew file mode 100644index 00000000..3b880b9d--- /dev/null+++ b/site/src/cut/lib/chatQueue.ts@@ -0,0 +1,30 @@+"use client";++import { chatOwner } from "./chatAssets";++// The composer queue as a tool target. The running agent can put a message+// on it — one it cannot do yet, because it needs this turn's finished result+// or a fresh look at the project after the cuts land — and the row goes out+// as its own turn once the running one settles, exactly like a message the+// user parked there. The queue is React state inside each thread's session,+// so a session registers a sink while mounted and the tool finds the sink+// through the streaming turn's thread.++const sinks = new Map<string, (text: string) => void>();++/** Register the mounted session's queue for its thread; returns the release. */+export function registerQueueSink(threadId: string, sink: (text: string) => void): () => void {+ sinks.set(threadId, sink);+ return () => {+ if (sinks.get(threadId) === sink) sinks.delete(threadId);+ };+}++/** Put a message on the streaming turn's queue. Throws where no session+ * holds a queue — a headless job has no composer and nobody to run the row+ * later, so the model does the work now or says what remains. */+export function queueMessageFromAgent(text: string): void {+ const sink = sinks.get(chatOwner() ?? "");+ if (!sink) throw new Error("No composer queue on this surface — do the work now, or say what remains.");+ sink(text);+}diff --git a/site/src/cut/lib/pi/cutAgent.ts b/site/src/cut/lib/pi/cutAgent.tsindex 0ca89909..88e1e6b3 100644--- a/site/src/cut/lib/pi/cutAgent.ts+++ b/site/src/cut/lib/pi/cutAgent.ts@@ -3,6 +3,15 @@ import { Agent, type AgentMessage } from "@earendil-works/pi-agent-core";import type { Message, UserMessage } from "@earendil-works/pi-ai";import { AI_TOOLS, attachedAssetsBlock, systemPrompt } from "@/cut/server/ai/catalog";import { isResumeMessage } from "../chatResume";+import {+ parseQueueTriage,+ QUEUE_TRIAGE_SCHEMA,+ queueTriageInput,+ queueTriagePrompt,+ type QueueVerdict,+ type TriageAnchor,+ type TriageRow,+} from "../queueTriage";import { parseTurnIntent, turnIntentInput, turnIntentPrompt, type TurnIntent } from "../turnIntent";import { enforceContextBudget } from "./contextBudget";import { donkeyModel, type ChatThinkingLevel } from "./donkeyModel";@@ -93,6 +102,137 @@ function isBudgetSteer(m: AgentMessage): boolean {);}+/** A composer message folded into a running turn. It is a real ask the+ * session keeps, and it belongs to the turn it joined: the media invariant+ * treats the turn's first ask as the newest, so the payloads that turn is+ * working from stay in context when the fold lands. */+interface FoldCarrier {+ fold?: true;+}++function isFold(m: AgentMessage): boolean {+ return (m as FoldCarrier).fold === true;+}++// ---------------------------------------------------------------------------+// Live turns: the thread's running agent, so a message the triage folds in+// can be steered into it. A fold is remembered on the turn until an agent+// injects it — the speculative run may be discarded and rerun routed, and+// the fold has to reach the run the turn keeps — and a fold no agent took by+// the time the turn ends is handed back, so the page can queue it instead.++interface Fold {+ message: UserMessage & WireCarrier & FoldCarrier;+ resolve: (injected: boolean) => void;+ /** The run that last injected it; a later run built for the same turn+ * takes it again. */+ takenBy: Agent | null;+}++interface LiveTurn {+ agent: Agent | null;+ folds: Fold[];+}++const liveTurns = new Map<string, LiveTurn>();++/** Whether a turn is running on this page for the thread, so a fold can land. */+export function cutChatLive(threadId: string): boolean {+ return liveTurns.has(threadId);+}++/** Hand every fold the turn holds to a freshly built agent: the ones no run+ * has injected yet, and the ones a discarded run took with it. */+function steerFolds(turn: LiveTurn, agent: Agent): void {+ turn.agent = agent;+ for (const f of turn.folds) if (f.takenBy !== agent) agent.steer(f.message);+}++/** Watch the run inject folds; each resolves once, the first time a run+ * takes it. */+function watchFolds(turn: LiveTurn, agent: Agent): () => void {+ return agent.subscribe((event) => {+ if (event.type !== "message_start") return;+ const f = turn.folds.find((x) => x.message === event.message);+ if (!f) return;+ if (!f.takenBy) f.resolve(true);+ f.takenBy = agent;+ });+}++/** Steer a composer message into the thread's running turn. Resolves true+ * once the turn has taken the message into its context, false when the turn+ * ended first — the message then goes out as its own turn. */+export async function foldIntoCutChat({+ threadId,+ text,+ attachments,+ deps,+}: {+ threadId: string;+ text: string;+ attachments: unknown[];+ deps: CutAgentDeps;+}): Promise<boolean> {+ if (!liveTurns.has(threadId)) return false;+ const ask: UIMessage = {+ id: "",+ role: "user",+ parts: [{ type: "text", text }],+ ...(attachments.length > 0 && { metadata: { attachments } }),+ };+ const message: Fold["message"] = { ...(await buildPrompt(ask, deps)), fold: true };+ const turn = liveTurns.get(threadId);+ if (!turn) return false;+ return new Promise<boolean>((resolve) => {+ turn.folds.push({ message, resolve, takenBy: null });+ turn.agent?.steer(message);+ });+}++const TRIAGE_PROMPT = queueTriagePrompt();++/** Where each mid-turn message goes: one light-model call over the running+ * ask and the rows. Fails closed — every row the call cannot place stays in+ * the queue. */+export async function triageQueuedMessages({+ anchor,+ waiting,+ rows,+ deps,+ abortSignal,+}: {+ anchor: TriageAnchor;+ waiting: TriageRow[];+ rows: TriageRow[];+ deps: CutAgentDeps;+ abortSignal?: AbortSignal;+}): Promise<Map<string, QueueVerdict>> {+ // Short ids on the wire; the verdict quotes them back.+ const wire = rows.map((r, i) => ({ id: `m${i + 1}`, text: r.text }));+ const byWire = new Map(wire.map((w, i) => [w.id, rows[i].id] as const));+ const closed = () => new Map<string, QueueVerdict>(rows.map((r) => [r.id, "queue"]));+ try {+ const res = await deps.post(+ {+ donkeyProvider: "gemini",+ model: deps.models.gate,+ instructions: TRIAGE_PROMPT,+ input: queueTriageInput(anchor, waiting, wire),+ text: { format: { type: "json_schema", schema: QUEUE_TRIAGE_SCHEMA } },+ },+ abortSignal+ );+ if (!res.ok) return closed();+ const body = (await res.json()) as { output_text?: string };+ const out = closed();+ for (const [w, v] of parseQueueTriage(body.output_text, wire)) out.set(byWire.get(w)!, v);+ return out;+ } catch {+ return closed();+ }+}+/** Every toolCall in the session answered. An aborted batch leaves calls with* no toolResult, and Gemini rejects a replay whose functionCalls outnumber* their responses — so unanswered calls get a synthetic interrupted result,@@ -133,7 +273,7 @@ function settleDanglingToolCalls(messages: AgentMessage[]): AgentMessage[] {function pruneStaleMedia(messages: AgentMessage[]): AgentMessage[] {let lastAsk = -1;messages.forEach((m, i) => {- if ((m as Message).role === "user" && !isBudgetSteer(m)) lastAsk = i;+ if ((m as Message).role === "user" && !isBudgetSteer(m) && !isFold(m)) lastAsk = i;});return messages.map((m, i) => {if (i >= lastAsk) return m;@@ -399,6 +539,8 @@ export function streamCutChat({const emit = (chunk: Record<string, unknown>) =>controller.enqueue(chunk as unknown as UIMessageChunk);emit({ type: "start" });+ const turn: LiveTurn = { agent: null, folds: [] };+ liveTurns.set(threadId, turn);try {const gateStart = performance.now();const lastUser = messages.findLast((m) => m.role === "user");@@ -498,6 +640,8 @@ export function streamCutChat({},});onAgent?.(agent);+ steerFolds(turn, agent);+ const unsubscribeFolds = watchFolds(turn, agent);const unsubscribeUi = subscribeUiChunks(agent, send);// Round timing for the eval: one assistant message = one LLM round.@@ -560,6 +704,7 @@ export function streamCutChat({unsubscribeUi();unsubscribeTiming();unsubscribeTurns();+ unsubscribeFolds();}return { agent, rounds, send };};@@ -659,6 +804,9 @@ export function streamCutChat({emit({ type: "error", errorText: err instanceof Error ? err.message : String(err) });}} finally {+ if (liveTurns.get(threadId) === turn) liveTurns.delete(threadId);+ // A fold no run took goes back to the page, which queues it.+ for (const f of turn.folds) if (!f.takenBy) f.resolve(false);emit({ type: "finish" });controller.close();}diff --git a/site/src/cut/lib/projectCommands.ts b/site/src/cut/lib/projectCommands.tsindex 3df74d3e..d9c3df2c 100644--- a/site/src/cut/lib/projectCommands.ts+++ b/site/src/cut/lib/projectCommands.ts@@ -1,7 +1,7 @@import type { ProjectOperation } from "@/cut/lib/projectOperation";export const UI_TOOLS: ReadonlySet<string> = new Set([- "set_side_panel", "set_view", "open_export", "set_playing",+ "set_side_panel", "set_view", "open_export", "set_playing", "queue_message",]);export function assertProjectCommand(operation: ProjectOperation, activeProjectId: string | null, name: string, activeVersion?: string | null): void {diff --git a/site/src/cut/lib/queueTriage.test.ts b/site/src/cut/lib/queueTriage.test.tsnew file mode 100644index 00000000..980453cb--- /dev/null+++ b/site/src/cut/lib/queueTriage.test.ts@@ -0,0 +1,72 @@+import { describe, expect, test } from "bun:test";+import { parseQueueTriage, queueTriageInput, toolProgress } from "./queueTriage";++const rows = [+ { id: "m1", text: "also make the title blue" },+ { id: "m2", text: "then export it" },+];++describe("parseQueueTriage", () => {+ test("reads one verdict per row", () => {+ const out = parseQueueTriage(+ JSON.stringify({ verdicts: [{ id: "m1", verdict: "fold" }, { id: "m2", verdict: "queue" }] }),+ rows+ );+ expect(out.get("m1")).toBe("fold");+ expect(out.get("m2")).toBe("queue");+ });++ test("a row the reply skips, misnames, or answers with another word stays queued", () => {+ const out = parseQueueTriage(+ JSON.stringify({ verdicts: [{ id: "m9", verdict: "spawn" }, { id: "m2", verdict: "later" }] }),+ rows+ );+ expect(out.get("m1")).toBe("queue");+ expect(out.get("m2")).toBe("queue");+ });++ test("a garbled or empty reply queues every row", () => {+ expect([...parseQueueTriage("fold", rows).values()]).toEqual(["queue", "queue"]);+ expect([...parseQueueTriage(undefined, rows).values()]).toEqual(["queue", "queue"]);+ expect([...parseQueueTriage("{}", rows).values()]).toEqual(["queue", "queue"]);+ });+});++describe("queueTriageInput", () => {+ test("lays out the running ask, its progress, other chats, the waiting rows and the rows to place", () => {+ const [turn] = queueTriageInput(+ { ask: "cut the silences", progress: ["detect_silence", "split_clip (running)"], elsewhere: ["add captions"] },+ [{ id: "w1", text: "what's the total length?" }],+ rows+ );+ const text = (turn.content as { text: string }[])[0].text;+ expect(text).toContain("Running ask:\ncut the silences");+ expect(text).toContain("Tools run so far: detect_silence, split_clip (running)");+ expect(text).toContain("Running in other chats:\n- add captions");+ expect(text).toContain("Already waiting in the queue:\n- what's the total length?");+ expect(text).toContain("[m1] also make the title blue\n[m2] then export it");+ });++ test("caps a pasted wall of text", () => {+ const [turn] = queueTriageInput(+ { ask: "x".repeat(5000), progress: [], elsewhere: [] },+ [],+ [{ id: "m1", text: "y".repeat(5000) }]+ );+ const text = (turn.content as { text: string }[])[0].text;+ expect(text.length).toBeLessThan(4400);+ });+});++describe("toolProgress", () => {+ test("names finished tools and marks open ones", () => {+ expect(+ toolProgress([+ { type: "text" },+ { type: "tool-detect_silence", state: "output-available" },+ { type: "dynamic-tool", toolName: "split_clip", state: "input-available" },+ { type: "tool-add_text", state: "output-error" },+ ])+ ).toEqual(["detect_silence", "split_clip (running)", "add_text"]);+ });+});diff --git a/site/src/cut/lib/queueTriage.ts b/site/src/cut/lib/queueTriage.tsnew file mode 100644index 00000000..c3ea9ab8--- /dev/null+++ b/site/src/cut/lib/queueTriage.ts@@ -0,0 +1,118 @@+// Where a message sent mid-turn goes. A fast structured model call reads the+// running ask, what it has done so far, and the message, and names one of+// three places: fold (the running turn takes it in stride), spawn (a second+// thread runs it in parallel because the work cannot collide), or queue (it+// waits in the tray for the finished result). The page acts deterministically+// on the verdict, and a garbled or failed call reads as queue — the tray is+// the safe place, and it is exactly what the queue did before triage existed.++export type QueueVerdict = "fold" | "queue" | "spawn";++export interface TriageAnchor {+ /** The ask the running turn is working on. */+ ask: string;+ /** Tools the turn has run so far, in order, "name" or "name (running)". */+ progress: string[];+ /** Asks running in other threads of the same project right now. */+ elsewhere: string[];+}++export interface TriageRow {+ id: string;+ text: string;+}++/** The gate's instructions. */+export function queueTriagePrompt(): string {+ return `You triage messages a user sends to the AI editor built into a video editor while it is already working on an earlier ask. The running ask, the tools it has run so far, asks running in other chats of the same project, and any messages already waiting in the queue are given as context. Judge each message listed under "triage" on its own and place it:++fold — the working agent takes it in the same pass. The message refines, extends, narrows, corrects, or adds to the running ask ("also…", "and make it…", "actually…", "not that one", "bigger"), asks about the work in progress, or is another question when the running ask is a question. A further edit to the same items, the same job, or the same stretch of the timeline folds too: the agent already holds that context and does the extra piece after what is in flight.++spawn — a second agent runs it in parallel right now, because it is a different job on things nothing running touches: a question about the footage, a source, or the project that changes nothing; or an edit to other items than the running work's — the look, color, or volume of a different clip, a caption style, the music level, a project setting — whose timing the running work cannot move and that does not need its result. Being in the same video is no collision; the same items or the same job is.++queue — it waits for the running ask to finish and for a fresh view of the project: it needs the finished result (export, render, share, publish, a thumbnail or summary of the final cut), or it is sequenced after the running work ("then…", "after that…", "once it's done…", "when you're finished…"). Anything unclear.++Collisions on the timeline: while any running work — in this chat or another — cuts, trims, moves, splits, deletes, or reorders clips, the times of everything after the cuts shift. A message that places or times something on the timeline (a sticker at 12 seconds, a title at the end, a sound effect on a moment) collides with it: fold it when it belongs with this chat's running job, and queue it in every other case — never spawn it.++When unsure between fold and queue, queue. When unsure between spawn and queue, queue.`;+}++/** The gate's input, as plain text turns. Rows carry short ids the verdict+ * quotes back, so a long message can never be mistaken for another. */+export function queueTriageInput(+ anchor: TriageAnchor,+ waiting: TriageRow[],+ rows: TriageRow[]+): Record<string, unknown>[] {+ const clip = (s: string) => s.slice(0, 2000);+ const lines: string[] = [`Running ask:\n${clip(anchor.ask) || "(none)"}`];+ lines.push(+ `Tools run so far: ${anchor.progress.length > 0 ? anchor.progress.join(", ") : "(none yet)"}`+ );+ if (anchor.elsewhere.length > 0)+ lines.push(`Running in other chats:\n${anchor.elsewhere.map((a) => `- ${clip(a)}`).join("\n")}`);+ if (waiting.length > 0)+ lines.push(`Already waiting in the queue:\n${waiting.map((r) => `- ${clip(r.text)}`).join("\n")}`);+ lines.push(`Triage:\n${rows.map((r) => `[${r.id}] ${clip(r.text)}`).join("\n")}`);+ return [{ role: "user", content: [{ text: lines.join("\n\n") }] }];+}++/** The verdict's shape: one entry per triaged row. */+export const QUEUE_TRIAGE_SCHEMA = {+ type: "object",+ properties: {+ verdicts: {+ type: "array",+ items: {+ type: "object",+ properties: {+ id: { type: "string" },+ verdict: { type: "string", enum: ["fold", "queue", "spawn"] },+ },+ required: ["id", "verdict"],+ },+ },+ },+ required: ["verdicts"],+} as const;++/** Deterministic read of the verdict. A row the reply skips, misnames, or+ * answers with anything but the three words stays in the queue. */+export function parseQueueTriage(+ outputText: string | undefined,+ rows: TriageRow[]+): Map<string, QueueVerdict> {+ const out = new Map<string, QueueVerdict>(rows.map((r) => [r.id, "queue"]));+ let parsed: unknown;+ try {+ parsed = JSON.parse(outputText ?? "");+ } catch {+ return out;+ }+ const verdicts = (parsed as { verdicts?: unknown } | null)?.verdicts;+ if (!Array.isArray(verdicts)) return out;+ for (const v of verdicts) {+ const id = (v as { id?: unknown })?.id;+ const verdict = (v as { verdict?: unknown })?.verdict;+ if (typeof id !== "string" || !out.has(id)) continue;+ if (verdict === "fold" || verdict === "spawn" || verdict === "queue") out.set(id, verdict);+ }+ return out;+}++/** The running turn's progress, read off the streaming assistant message's+ * parts: each tool it has called, finished ones by name and open ones marked. */+export function toolProgress(+ parts: readonly { type: string; state?: string; toolName?: string }[]+): string[] {+ return parts.flatMap((p) => {+ const name =+ p.type === "dynamic-tool"+ ? p.toolName+ : p.type.startsWith("tool-")+ ? p.type.slice(5)+ : undefined;+ if (!name) return [];+ return [p.state === "output-available" || p.state === "output-error" ? name : `${name} (running)`];+ });+}diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 0dc71291..6e0a2ad2 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -423,6 +423,7 @@ 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, name what you could do as a statement ("I can clear the unused overlays — say the word"), 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.- 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.+- A further message from the user can arrive while you work. It is part of the current job: take it in — a refinement changes what you are doing, an addition gets done alongside, a correction is followed — and when it depends on the work in flight, finish that first. One you cannot do in this turn — it needs this turn's finished result, or a fresh look at the timeline after your cuts land — goes to queue_message in the user's words and runs as its own turn after this one. Your reply covers both asks.- 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. Any other errored call produced nothing: report it as failed in plain words, and either retry it or hand it back — the failure and the recovery you propose are both statements ("The last clip has nothing after it to blend into; a fade-out on its tail would close the video instead."). Claim only what your tool results confirm.- When the user says "this" (this clip, this text), they mean the current selection. A "this" or "that" with nothing selected and several candidates is genuinely ambiguous — ask which one before touching anything.- Keep replies short and concrete — one or two sentences. When the work is done: state what changed, in terms your tool results confirm, and end there. You may close with at most one suggestion, phrased as a statement ("A 0.5s crossfade on the middle cut would smooth the jump."); a suggestion the user has already passed on stays retired. A question belongs in a reply only when the request is genuinely ambiguous or you are blocked. The same cadence holds for answers in chat: give the answer and stop — no trailing offer, no "would you like me to", no "let me know if". 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).