Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(agent): give the agent delete tools and camera-fullscreen, with honest removal
Etienne Lescotc445032a78d2
diff --git a/electron/ai-edition/agent-tools.test.ts b/electron/ai-edition/agent-tools.test.tsindex 0cc42ce7b..097248fb4 100644--- a/electron/ai-edition/agent-tools.test.ts+++ b/electron/ai-edition/agent-tools.test.ts@@ -87,11 +87,19 @@ describe("agent-tools specs", () => {"setSpeed","addAnnotation","setAnnotation",+ "addCameraFullscreen",+ "setCameraFullscreen",+ "removeTrim",+ "removeModifier",+ "removeClip",]);expect(isMutatingTool("getTranscript")).toBe(false);expect(isMutatingTool("replaceTimeline")).toBe(true);expect(isMutatingTool("addZoom")).toBe(true);expect(isMutatingTool("setAnnotation")).toBe(true);+ expect(isMutatingTool("removeTrim")).toBe(true);+ expect(isMutatingTool("removeModifier")).toBe(true);+ expect(isMutatingTool("removeClip")).toBe(true);expect(isMutatingTool("nope")).toBe(false);});});@@ -367,4 +375,120 @@ describe("executeAgentTool", () => {expect(snapshot.zoomRangeCount).toBeUndefined();expect(snapshot.annotationCount).toBeUndefined();});++ it("addCameraFullscreen / setCameraFullscreen write a region the snapshot exposes", () => {+ const added = executeAgentTool(+ fixtureDocument(),+ "addCameraFullscreen",+ JSON.stringify({ startSec: 9, endSec: 5 }),+ );+ expect(added.ok).toBe(true);+ const legacy = added.document?.legacyEditor as Record<string, unknown>;+ const region = (+ legacy.cameraFullscreenRegions as Array<{ id: string; startMs: number; endMs: number }>+ ).at(-1);+ // bounds normalised (start ≤ end).+ expect(region).toMatchObject({ startMs: 5000, endMs: 9000 });+ expect(() => documentSchema.parse(added.document)).not.toThrow();++ const snapshot = JSON.parse(+ executeAgentTool(added.document as AxcutDocument, "getCurrentDocument", "").resultJson,+ );+ expect(snapshot.cameraFullscreenRegions[0]).toMatchObject({ startSec: 5, endSec: 9 });+ expect(snapshot.timeBaseNote).toMatch(/cameraFullscreen/i);++ const moved = executeAgentTool(+ added.document as AxcutDocument,+ "setCameraFullscreen",+ JSON.stringify({ cameraFullscreenId: region?.id, startSec: 1, endSec: 2 }),+ );+ expect(moved.ok).toBe(true);+ const movedRegion = (+ (moved.document?.legacyEditor as Record<string, unknown>).cameraFullscreenRegions as Array<{+ startMs: number;+ endMs: number;+ }>+ )[0];+ expect(movedRegion).toMatchObject({ startMs: 1000, endMs: 2000 });+ expect(+ executeAgentTool(+ fixtureDocument(),+ "setCameraFullscreen",+ JSON.stringify({ cameraFullscreenId: "nope" }),+ ).ok,+ ).toBe(false);+ });++ it("removeTrim deletes a trim by id (and rejects an unknown one)", () => {+ const result = executeAgentTool(+ fixtureDocument(),+ "removeTrim",+ JSON.stringify({ trimRangeId: "trim_1" }),+ );+ expect(result.ok).toBe(true);+ expect(result.document?.timeline.trimRanges).toHaveLength(0);+ expect(() => documentSchema.parse(result.document)).not.toThrow();+ expect(+ executeAgentTool(fixtureDocument(), "removeTrim", JSON.stringify({ trimRangeId: "nope" })).ok,+ ).toBe(false);+ });++ it("removeModifier resolves the kind from the id across zoom / speed / annotation / full-camera", () => {+ const withZoom = executeAgentTool(+ fixtureDocument(),+ "addZoom",+ JSON.stringify({ startSec: 2, endSec: 4 }),+ ).document as AxcutDocument;+ const zoomId = withZoom.zoomRanges[0].id;+ const removed = executeAgentTool(withZoom, "removeModifier", JSON.stringify({ id: zoomId }));+ expect(removed.ok).toBe(true);+ expect(JSON.parse(removed.resultJson)).toMatchObject({ kind: "zoom" });+ expect(removed.document?.zoomRanges).toHaveLength(0);++ const withSpeed = executeAgentTool(+ fixtureDocument(),+ "addSpeed",+ JSON.stringify({ startSec: 2, endSec: 4, speed: 2 }),+ ).document as AxcutDocument;+ const speedId = (+ (withSpeed.legacyEditor as Record<string, unknown>).speedRegions as Array<{ id: string }>+ )[0].id;+ const removedSpeed = executeAgentTool(+ withSpeed,+ "removeModifier",+ JSON.stringify({ id: speedId }),+ );+ expect(JSON.parse(removedSpeed.resultJson)).toMatchObject({ kind: "speed" });+ expect(+ (removedSpeed.document?.legacyEditor as Record<string, unknown>).speedRegions,+ ).toHaveLength(0);++ // A trim id is NOT a modifier — the error steers to removeTrim.+ const wrong = executeAgentTool(+ fixtureDocument(),+ "removeModifier",+ JSON.stringify({ id: "trim_1" }),+ );+ expect(wrong.ok).toBe(false);+ expect(wrong.resultJson).toMatch(/removeTrim/);+ });++ it("removeClip deletes a clip and reflows the survivor (rejects an unknown id)", () => {+ const result = executeAgentTool(+ fixtureDocument(),+ "removeClip",+ JSON.stringify({ clipId: "clip_1" }),+ );+ expect(result.ok).toBe(true);+ expect(result.document?.timeline.clips.map((c) => c.id)).toEqual(["clip_2"]);+ // clip_2 slides to the front of the timeline.+ expect(result.document?.timeline.clips[0]).toMatchObject({+ timelineStartSec: 0,+ timelineEndSec: 30,+ });+ expect(() => documentSchema.parse(result.document)).not.toThrow();+ expect(+ executeAgentTool(fixtureDocument(), "removeClip", JSON.stringify({ clipId: "nope" })).ok,+ ).toBe(false);+ });});diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.tsindex a06f5a429..648ae946e 100644--- a/electron/ai-edition/agent-tools.ts+++ b/electron/ai-edition/agent-tools.ts@@ -10,7 +10,13 @@import { z } from "zod";import { createId } from "../../src/lib/ai-edition/document/ids";-import { replaceTimeline, setClipSourceRange } from "../../src/lib/ai-edition/document/timeline";+import {+ type RegionKind,+ removeClip,+ removeRegion,+ replaceTimeline,+ setClipSourceRange,+} from "../../src/lib/ai-edition/document/timeline";import type { AxcutDocument } from "../../src/lib/ai-edition/schema";import {anchorRegionsWithDerivedMs,@@ -88,33 +94,38 @@ function anchorForAgent<T extends { id: string; startMs: number; endMs: number }return anchorRegionsWithDerivedMs([region], document.timeline.clips, () => createId(prefix));}+// Zod arg schemas — the SINGLE source of truth for every tool's arguments. The executor+// below validates against them, and the deep-agent (LangChain) layer imports the same+// objects to build its `tool()`s, so the two can never advertise a different shape than the+// one we actually validate. (The primitives `secondsSchema`/`depthSchema`/`focusSchema` stay+// private — callers only ever need the composed `*Args`.)const secondsSchema = z.number().finite().nonnegative();-const addTrimArgs = z.object({+export const addTrimArgs = z.object({startSec: secondsSchema,endSec: secondsSchema,assetId: z.string().min(1).optional(),reason: z.string().default(""),});-const setTrimArgs = z.object({+export const setTrimArgs = z.object({trimRangeId: z.string().min(1),startSec: secondsSchema,endSec: secondsSchema,});-const setClipRangeArgs = z.object({+export const setClipRangeArgs = z.object({clipId: z.string().min(1),sourceStartSec: secondsSchema,sourceEndSec: secondsSchema,});-const replaceTimelineArgs = z.object({+export const replaceTimelineArgs = z.object({intervals: z.array(z.object({ startSec: secondsSchema, endSec: secondsSchema })).min(1),reason: z.string().default(""),});-const getTranscriptArgs = z.object({+export const getTranscriptArgs = z.object({assetId: z.string().min(1).optional(),});@@ -124,14 +135,14 @@ const getTranscriptArgs = z.object({const depthSchema = z.number().int().min(1).max(6);const focusSchema = z.object({ cx: z.number().min(0).max(1), cy: z.number().min(0).max(1) });-const addZoomArgs = z.object({+export const addZoomArgs = z.object({startSec: secondsSchema,endSec: secondsSchema,depth: depthSchema.default(3),focus: focusSchema.default({ cx: 0.5, cy: 0.5 }),});-const setZoomArgs = z.object({+export const setZoomArgs = z.object({zoomId: z.string().min(1),startSec: secondsSchema.optional(),endSec: secondsSchema.optional(),@@ -139,20 +150,20 @@ const setZoomArgs = z.object({focus: focusSchema.optional(),});-const addSpeedArgs = z.object({+export const addSpeedArgs = z.object({startSec: secondsSchema,endSec: secondsSchema,speed: z.number().positive().default(1.5),});-const setSpeedArgs = z.object({+export const setSpeedArgs = z.object({speedId: z.string().min(1),startSec: secondsSchema.optional(),endSec: secondsSchema.optional(),speed: z.number().positive().optional(),});-const addAnnotationArgs = z.object({+export const addAnnotationArgs = z.object({startSec: secondsSchema,endSec: secondsSchema,text: z.string().default(""),@@ -160,13 +171,36 @@ const addAnnotationArgs = z.object({y: z.number().min(0).max(100).default(50),});-const setAnnotationArgs = z.object({+export const setAnnotationArgs = z.object({annotationId: z.string().min(1),startSec: secondsSchema.optional(),endSec: secondsSchema.optional(),text: z.string().optional(),});+export const addCameraFullscreenArgs = z.object({+ startSec: secondsSchema,+ endSec: secondsSchema,+});++export const setCameraFullscreenArgs = z.object({+ cameraFullscreenId: z.string().min(1),+ startSec: secondsSchema.optional(),+ endSec: secondsSchema.optional(),+});++export const removeTrimArgs = z.object({+ trimRangeId: z.string().min(1),+});++export const removeModifierArgs = z.object({+ id: z.string().min(1),+});++export const removeClipArgs = z.object({+ clipId: z.string().min(1),+});+export const AGENT_TOOL_SPECS: AgentToolSpec[] = [{name: "getCurrentDocument",@@ -402,6 +436,73 @@ export const AGENT_TOOL_SPECS: AgentToolSpec[] = [},mutating: true,},+ {+ name: "addCameraFullscreen",+ description:+ "Add a camera-fullscreen region over a span of the *edited timeline* (virtual seconds): the webcam fills the frame for that span. Use for 'go fullscreen on the webcam here'.",+ parameters: {+ type: "object",+ properties: {+ startSec: { type: "number", minimum: 0, description: "Virtual-timeline start (seconds)." },+ endSec: { type: "number", minimum: 0, description: "Virtual-timeline end (seconds)." },+ },+ required: ["startSec", "endSec"],+ additionalProperties: false,+ },+ mutating: true,+ },+ {+ name: "setCameraFullscreen",+ description:+ "Move or resize an existing camera-fullscreen region by id. Times are virtual-timeline seconds. Only the fields you pass are changed.",+ parameters: {+ type: "object",+ properties: {+ cameraFullscreenId: { type: "string" },+ startSec: { type: "number", minimum: 0 },+ endSec: { type: "number", minimum: 0 },+ },+ required: ["cameraFullscreenId"],+ additionalProperties: false,+ },+ mutating: true,+ },+ {+ name: "removeTrim",+ description:+ "Delete a trim range by id (the cut is un-done — that source span plays and exports again). This is the correct way to 'remove a trim' / 'un-cut' — never re-add a trim to undo one.",+ parameters: {+ type: "object",+ properties: { trimRangeId: { type: "string" } },+ required: ["trimRangeId"],+ additionalProperties: false,+ },+ mutating: true,+ },+ {+ name: "removeModifier",+ description:+ "Delete a modifier (zoom / speed / annotation / camera-fullscreen) by id. Resolves the kind from the id. This is the correct way to 'remove'/'delete' one of these — never neutralise it (span 0, speed 1×): that leaves it in the document. For a trim use removeTrim; for a clip use removeClip.",+ parameters: {+ type: "object",+ properties: { id: { type: "string" } },+ required: ["id"],+ additionalProperties: false,+ },+ mutating: true,+ },+ {+ name: "removeClip",+ description:+ "Delete a placed clip by id. The remaining clips are re-laid back-to-back to close the gap, and any zoom/speed/annotation anchored to the removed clip is dropped. Use only when the user explicitly asks to remove a clip (not to shorten one — that is setClipRange).",+ parameters: {+ type: "object",+ properties: { clipId: { type: "string" } },+ required: ["clipId"],+ additionalProperties: false,+ },+ mutating: true,+ },];export function isMutatingTool(name: string): boolean {@@ -427,9 +528,13 @@ export function documentSnapshotForModel(document: AxcutDocument): Record<string(legacy?.speedRegions as| Array<{ id: string; startMs: number; endMs: number; speed: number }>| undefined) ?? [];+ const cameraFullscreenRegions =+ (legacy?.cameraFullscreenRegions as+ | Array<{ id: string; startMs: number; endMs: number }>+ | undefined) ?? [];return {timeBaseNote:- "clips and trims are in source-time seconds; zooms, speedRegions and annotations are in virtual (edited-timeline) seconds.",+ "clips and trims are in source-time seconds; zooms, speedRegions, annotations and cameraFullscreenRegions are in virtual (edited-timeline) seconds.",project: { id: document.project.id, title: document.project.title },primaryAssetId: document.project.primaryAssetId ?? document.assets[0]?.id ?? null,assets: document.assets.map((a) => ({@@ -472,6 +577,11 @@ export function documentSnapshotForModel(document: AxcutDocument): Record<stringtype: a.type,text: a.textContent ?? a.content ?? "",})),+ cameraFullscreenRegions: coalesceForAgent(cameraFullscreenRegions).map((c) => ({+ id: c.id,+ startSec: roundSec(c.startMs),+ endSec: roundSec(c.endMs),+ })),hasTranscript: document.transcripts.length > 0 || document.transcript !== null,};}@@ -869,6 +979,131 @@ export function executeAgentTool(};}+ case "addCameraFullscreen": {+ const parsed = addCameraFullscreenArgs.safeParse(args);+ if (!parsed.success) return failure(parsed.error.message);+ const startMs = toMs(Math.min(parsed.data.startSec, parsed.data.endSec));+ const endMs = toMs(Math.max(parsed.data.startSec, parsed.data.endSec));+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const prev = (legacy.cameraFullscreenRegions as unknown[] | undefined) ?? [];+ const region = { id: createId("camfull"), startMs, endMs };+ const next: AxcutDocument = {+ ...document,+ legacyEditor: {+ ...legacy,+ cameraFullscreenRegions: [...prev, ...anchorForAgent(region, document, "camfull")],+ },+ };+ return {+ ok: true,+ document: next,+ resultJson: JSON.stringify({+ cameraFullscreenId: region.id,+ startSec: startMs / 1000,+ endSec: endMs / 1000,+ }),+ summary: `full-camera ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,+ };+ }++ case "setCameraFullscreen": {+ const parsed = setCameraFullscreenArgs.safeParse(args);+ if (!parsed.success) return failure(parsed.error.message);+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const prev =+ (legacy.cameraFullscreenRegions as+ | Array<{ id: string; startMs: number; endMs: number }>+ | undefined) ?? [];+ const existing = prev.find((r) => r.id === parsed.data.cameraFullscreenId);+ if (!existing)+ return failure(`Unknown full-camera region: ${parsed.data.cameraFullscreenId}`);+ const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);+ const next: AxcutDocument = {+ ...document,+ legacyEditor: {+ ...legacy,+ cameraFullscreenRegions: replacePillSpan(+ prev,+ parsed.data.cameraFullscreenId,+ startMs,+ endMs,+ document.timeline.clips,+ () => createId("camfull"),+ ),+ },+ };+ return {+ ok: true,+ document: next,+ resultJson: JSON.stringify({+ cameraFullscreenId: parsed.data.cameraFullscreenId,+ startSec: startMs / 1000,+ endSec: endMs / 1000,+ }),+ summary: `moved full-camera to ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,+ };+ }++ case "removeTrim": {+ const parsed = removeTrimArgs.safeParse(args);+ if (!parsed.success) return failure(parsed.error.message);+ const { trimRangeId } = parsed.data;+ if (!document.timeline.trimRanges.some((s) => s.id === trimRangeId)) {+ return failure(`Unknown trim range: ${trimRangeId}`);+ }+ const next = removeRegion(document, "trim", trimRangeId);+ return {+ ok: true,+ document: next,+ resultJson: JSON.stringify({ removed: trimRangeId, kind: "trim" }),+ summary: `removed trim ${trimRangeId}`,+ };+ }++ case "removeModifier": {+ const parsed = removeModifierArgs.safeParse(args);+ if (!parsed.success) return failure(parsed.error.message);+ const { id } = parsed.data;+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const speedRegions = (legacy.speedRegions as Array<{ id: string }> | undefined) ?? [];+ const cameraFullscreenRegions =+ (legacy.cameraFullscreenRegions as Array<{ id: string }> | undefined) ?? [];+ let kind: RegionKind | null = null;+ if (document.zoomRanges.some((z) => z.id === id)) kind = "zoom";+ else if (document.annotations.some((a) => a.id === id)) kind = "annotation";+ else if (speedRegions.some((s) => s.id === id)) kind = "speed";+ else if (cameraFullscreenRegions.some((c) => c.id === id)) kind = "cameraFullscreen";+ if (!kind) {+ return failure(+ `No zoom / speed / annotation / full-camera modifier with id ${id}. ` ++ `For a trim use removeTrim; for a clip use removeClip.`,+ );+ }+ const next = removeRegion(document, kind, id);+ return {+ ok: true,+ document: next,+ resultJson: JSON.stringify({ removed: id, kind }),+ summary: `removed ${kind} ${id}`,+ };+ }++ case "removeClip": {+ const parsed = removeClipArgs.safeParse(args);+ if (!parsed.success) return failure(parsed.error.message);+ const { clipId } = parsed.data;+ if (!document.timeline.clips.some((c) => c.id === clipId)) {+ return failure(`Unknown clip: ${clipId}`);+ }+ const next = removeClip(document, clipId);+ return {+ ok: true,+ document: next,+ resultJson: JSON.stringify({ removed: clipId, clipCount: next.timeline.clips.length }),+ summary: `removed clip ${clipId}`,+ };+ }+default:return failure(`Unknown tool: ${name}`);}diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.tsindex 5a9b50416..b2af0a5b6 100644--- a/electron/ai-edition/deep-agent/service.ts+++ b/electron/ai-edition/deep-agent/service.ts@@ -7,7 +7,27 @@import { tool } from "langchain";import { z } from "zod";import type { AxcutDocument } from "../../../src/lib/ai-edition/schema";-import { documentSnapshotForModel, executeAgentTool, isMutatingTool } from "../agent-tools";+import {+ addAnnotationArgs,+ addCameraFullscreenArgs,+ addSpeedArgs,+ addTrimArgs,+ addZoomArgs,+ documentSnapshotForModel,+ executeAgentTool,+ getTranscriptArgs,+ isMutatingTool,+ removeClipArgs,+ removeModifierArgs,+ removeTrimArgs,+ replaceTimelineArgs,+ setAnnotationArgs,+ setCameraFullscreenArgs,+ setClipRangeArgs,+ setSpeedArgs,+ setTrimArgs,+ setZoomArgs,+} from "../agent-tools";import { createOpenScreenChatModel, type OpenScreenChatModelConfig } from "./chat-model";export interface OpenScreenAgentSink {@@ -17,91 +37,9 @@ export interface OpenScreenAgentSink {error: (message: string) => void;}-// ponytail: minimal-effort zod schemas for each of our agent tools. We had-// JSON-schema specs in agent-tools.ts; here we use Zod because LangChain's-// `tool()` factory wants Zod (one-line in axcut, one-line here). The-// executor below still re-validates via executeAgentTool, so the JSON schema-// stays the source of truth for the UI's "applied: ..." chip.-const secondsSchema = z.number().finite().nonnegative();--const addTrimArgs = z.object({- startSec: secondsSchema,- endSec: secondsSchema,- assetId: z.string().min(1).optional(),- reason: z.string().default(""),-});--const setTrimArgs = z.object({- trimRangeId: z.string().min(1),- startSec: secondsSchema,- endSec: secondsSchema,-});--const setClipRangeArgs = z.object({- clipId: z.string().min(1),- sourceStartSec: secondsSchema,- sourceEndSec: secondsSchema,-});--const replaceTimelineArgs = z.object({- intervals: z- .array(- z.object({- startSec: secondsSchema,- endSec: secondsSchema,- }),- )- .min(1),- reason: z.string().default(""),-});--// Effects (zoom / speed / annotation) — authored in virtual (edited-timeline)-// seconds, mirroring the JSON-schema specs in agent-tools.ts.-const depthSchema = z.number().int().min(1).max(6);-const focusSchema = z.object({ cx: z.number().min(0).max(1), cy: z.number().min(0).max(1) });--const addZoomArgs = z.object({- startSec: secondsSchema,- endSec: secondsSchema,- depth: depthSchema.default(3),- focus: focusSchema.default({ cx: 0.5, cy: 0.5 }),-});--const setZoomArgs = z.object({- zoomId: z.string().min(1),- startSec: secondsSchema.optional(),- endSec: secondsSchema.optional(),- depth: depthSchema.optional(),- focus: focusSchema.optional(),-});--const addSpeedArgs = z.object({- startSec: secondsSchema,- endSec: secondsSchema,- speed: z.number().positive().default(1.5),-});--const setSpeedArgs = z.object({- speedId: z.string().min(1),- startSec: secondsSchema.optional(),- endSec: secondsSchema.optional(),- speed: z.number().positive().optional(),-});--const addAnnotationArgs = z.object({- startSec: secondsSchema,- endSec: secondsSchema,- text: z.string().default(""),- x: z.number().min(0).max(100).default(50),- y: z.number().min(0).max(100).default(50),-});--const setAnnotationArgs = z.object({- annotationId: z.string().min(1),- startSec: secondsSchema.optional(),- endSec: secondsSchema.optional(),- text: z.string().optional(),-});+// The tool arg schemas live in agent-tools.ts (imported above) — one source of truth for+// both the executor's validation and the LangChain `tool()`s built here. Only the empty /+// inline read-tool schemas below stay local.const SYSTEM_PROMPT = ["You are an AI video editor working inside OpenScreen. The user is editing a recording.",@@ -110,14 +48,17 @@ const SYSTEM_PROMPT = ["You can call the tools below against the live document snapshot; the runtime executes each edit and feeds the result back into the loop.","The AxcutDocument is the single source of truth. The timeline, the transcript editor, and the chat panel are all direct editors of the same document — when the user places a clip on the timeline, the document updates immediately, and when the timeline is empty, the document has no clips. Your edits operate on the live document, so preserve the user's placed clips.","",- "Time-bases (do not mix them up): clips and trims are in SOURCE-time seconds of an asset; zooms, speed regions and annotations are in VIRTUAL (edited-timeline) seconds — the position on the ruler after clips + trims are applied. getCurrentDocument returns both, clearly labelled.",+ "Time-bases (do not mix them up): clips and trims are in SOURCE-time seconds of an asset; zooms, speed regions, annotations and camera-fullscreen regions are in VIRTUAL (edited-timeline) seconds — the position on the ruler after clips + trims are applied. getCurrentDocument returns all of them, clearly labelled.","","Tool-selection rules (these are non-negotiable):","- 'remove silences' / 'cut pauses' / 'cut the silence' / 'kill the silence' / 'tighten pacing': call addTrim ONCE PER SILENT RANGE. Do NOT call setClipRange, do NOT call replaceTimeline. The placed clip is the canonical cut, the silence becomes a trim inside it.","- 'trim this clip to 0-30' / 'cut the end of this clip' / 'shorten this clip': call setClipRange with the new sourceStartSec/sourceEndSec (this is the clip's in/out, distinct from a trim).",- "- 'zoom in on …' / smart zooms: call addZoom over the virtual-timeline span (depth 1–6, focus in 0–1 frame fractions). 'speed through …': addSpeed. 'add a caption/label': addAnnotation.",+ "- 'zoom in on …' / smart zooms: call addZoom over the virtual-timeline span (depth 1–6, focus in 0–1 frame fractions). 'speed through …': addSpeed. 'add a caption/label': addAnnotation. 'make the webcam fullscreen here': addCameraFullscreen.","- 'replace the timeline' / 'rebuild the timeline' / 'start over with these intervals': call replaceTimeline. Only when the user explicitly asks for a full rebuild.",+ "- DELETING is a first-class action, not a workaround. 'remove/delete this trim' → removeTrim; 'remove/delete this zoom/speed/annotation/full-camera' → removeModifier; 'remove/delete this clip' → removeClip. NEVER fake a deletion by re-adding an element or zeroing it out (span 0, speed 1×) — that leaves it in the document and misreports what you did.","Anything else (move a clip, resize a trim, restyle a zoom, change a clip's order, etc.) — pick the most specific tool. If the request is ambiguous, prefer the smallest edit that satisfies it.",+ "",+ "Honesty rules: if a request has NO matching tool (e.g. deleting an asset/recording, exporting), say so plainly — do not substitute a different edit and report it as the requested one. After your edits, if you are at all unsure the document ended up as intended, call getCurrentDocument and reconcile what you claim with the real state; each tool result already tells you exactly what it did, so never report a change the results don't support.",].join("\n");const TOOL_DESCRIPTIONS: Record<string, string> = {@@ -144,6 +85,16 @@ const TOOL_DESCRIPTIONS: Record<string, string> = {"Add a text annotation over a span of the edited timeline (virtual seconds). x/y are frame percentages (0–100, default centre). Use for callouts and labels.",setAnnotation:"Move, resize, or edit the text of an existing annotation by id (virtual-timeline seconds). Only the fields you pass are changed.",+ addCameraFullscreen:+ "Add a camera-fullscreen region over a span of the edited timeline (virtual seconds): the webcam fills the frame for that span.",+ setCameraFullscreen:+ "Move or resize an existing camera-fullscreen region by id (virtual-timeline seconds). Only the fields you pass are changed.",+ removeTrim:+ "Delete a trim range by id — the cut is undone and that span plays/exports again. This is how you 'remove a trim'; never re-add a trim to undo one.",+ removeModifier:+ "Delete a modifier (zoom / speed / annotation / camera-fullscreen) by id; the kind is resolved from the id. This is how you 'remove'/'delete' one — never neutralise it (span 0, speed 1×), which leaves it in the document. For a trim use removeTrim; for a clip use removeClip.",+ removeClip:+ "Delete a placed clip by id; remaining clips close the gap and effects anchored to it are dropped. Use only when the user asks to remove a clip — to shorten one, use setClipRange.",};// ponytail: mutable document holder so a write-tool that updates the snapshot@@ -189,7 +140,7 @@ function buildTools(holder: DocumentHolder, sink: OpenScreenAgentSink) {{name: "getTranscript",description: TOOL_DESCRIPTIONS.getTranscript,- schema: z.object({ assetId: z.string().min(1).optional() }),+ schema: getTranscriptArgs,},),mutatingTool(holder, sink, "addTrim", addTrimArgs),@@ -202,6 +153,11 @@ function buildTools(holder: DocumentHolder, sink: OpenScreenAgentSink) {mutatingTool(holder, sink, "setSpeed", setSpeedArgs),mutatingTool(holder, sink, "addAnnotation", addAnnotationArgs),mutatingTool(holder, sink, "setAnnotation", setAnnotationArgs),+ mutatingTool(holder, sink, "addCameraFullscreen", addCameraFullscreenArgs),+ mutatingTool(holder, sink, "setCameraFullscreen", setCameraFullscreenArgs),+ mutatingTool(holder, sink, "removeTrim", removeTrimArgs),+ mutatingTool(holder, sink, "removeModifier", removeModifierArgs),+ mutatingTool(holder, sink, "removeClip", removeClipArgs),];}diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.tsindex c5c402673..8fb9b9dfd 100644--- a/src/lib/ai-edition/document/timeline.test.ts+++ b/src/lib/ai-edition/document/timeline.test.ts@@ -8,6 +8,8 @@ import {normalizeIntervals,primaryAssetDuration,rederiveRegionMs,+ removeClip,+ removeRegion,replaceTimeline,resequenceClips,resolvePlaybackSegments,@@ -694,3 +696,110 @@ describe("setClipSourceRange — the one shared clip-trim mutator", () => {expect(next.preview.revision).toBe(before.preview.revision);});});++describe("removeRegion — the one shared region-delete mutator", () => {+ it("drops the whole pill a zoom id belongs to, and keeps a different-identity pill", () => {+ // z1 + z2 are the same identity (depth/focus) and touch → one pill; z3 differs.+ const doc = makeDoc({+ zoomRanges: [+ makeZoom({ id: "z1", startMs: 0, endMs: 2000 }),+ makeZoom({ id: "z2", startMs: 2000, endMs: 4000 }),+ makeZoom({ id: "z3", startMs: 5000, endMs: 6000, depth: 5 as const }),+ ] as unknown as AxcutDocument["zoomRanges"],+ });+ const next = removeRegion(doc, "zoom", "z1");+ expect(next.zoomRanges.map((z) => z.id)).toEqual(["z3"]);+ });++ it("filters a trim by id without touching other trims", () => {+ const doc = makeDoc({+ timeline: {+ ...makeDoc().timeline,+ trimRanges: [makeTrim({ id: "trim_1" }), makeTrim({ id: "trim_2" })],+ },+ });+ const next = removeRegion(doc, "trim", "trim_1");+ expect(next.timeline.trimRanges.map((t) => t.id)).toEqual(["trim_2"]);+ });++ it("removes speed and camera-fullscreen regions under legacyEditor", () => {+ const doc = makeDoc({+ legacyEditor: {+ speedRegions: [{ id: "sp1", startMs: 0, endMs: 1000, speed: 2 }],+ cameraFullscreenRegions: [{ id: "cf1", startMs: 0, endMs: 1000 }],+ },+ });+ const afterSpeed = removeRegion(doc, "speed", "sp1");+ expect((afterSpeed.legacyEditor as { speedRegions: unknown[] }).speedRegions).toHaveLength(0);+ const afterCam = removeRegion(doc, "cameraFullscreen", "cf1");+ expect(+ (afterCam.legacyEditor as { cameraFullscreenRegions: unknown[] }).cameraFullscreenRegions,+ ).toHaveLength(0);+ });++ it("is a no-op for an unknown id and never bumps preview.revision", () => {+ const doc = makeDoc({+ zoomRanges: [+ makeZoom({ id: "z1", startMs: 0, endMs: 2000 }),+ ] as unknown as AxcutDocument["zoomRanges"],+ });+ const next = removeRegion(doc, "zoom", "nope");+ expect(next.zoomRanges.map((z) => z.id)).toEqual(["z1"]);+ expect(next.preview.revision).toBe(doc.preview.revision);+ });+});++describe("removeClip — delete a clip, close the gap, drop its pills", () => {+ const doc = () =>+ makeDoc({+ timeline: {+ ...makeDoc().timeline,+ clips: [+ makeClip({ id: "clip_a", sourceStartSec: 0, sourceEndSec: 10, timelineEndSec: 10 }),+ makeClip({+ id: "clip_b",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 10,+ timelineEndSec: 20,+ }),+ ],+ },+ zoomRanges: [+ makeZoom({+ id: "z_a",+ clipId: "clip_a",+ sourceStartSec: 2,+ sourceEndSec: 4,+ startMs: 2000,+ endMs: 4000,+ }),+ makeZoom({+ id: "z_b",+ clipId: "clip_b",+ sourceStartSec: 2,+ sourceEndSec: 4,+ startMs: 12000,+ endMs: 14000,+ }),+ ] as unknown as AxcutDocument["zoomRanges"],+ });++ it("reflows survivors to close the gap and drops pills anchored to the removed clip", () => {+ const next = removeClip(doc(), "clip_a");+ expect(next.timeline.clips.map((c) => c.id)).toEqual(["clip_b"]);+ // clip_b slides to the front.+ expect(next.timeline.clips[0]).toMatchObject({ timelineStartSec: 0, timelineEndSec: 10 });+ // z_a's clip is gone → dropped; z_b's derived ms drops by the 10s clip_b moved.+ expect(next.zoomRanges.map((z) => z.id)).toEqual(["z_b"]);+ expect(next.zoomRanges[0]).toMatchObject({ startMs: 2000, endMs: 4000 });+ });++ it("is a no-op for an unknown clip and never bumps preview.revision", () => {+ const before = doc();+ const next = removeClip(before, "clip_missing");+ expect(next.timeline.clips.map((c) => c.id)).toEqual(["clip_a", "clip_b"]);+ expect(next).toBe(before);+ expect(next.preview.revision).toBe(before.preview.revision);+ });+});diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.tsindex 18eb05d41..3bce9ac49 100644--- a/src/lib/ai-edition/document/timeline.ts+++ b/src/lib/ai-edition/document/timeline.ts@@ -4,9 +4,19 @@// or a new document with updated clips.import type { AxcutClip, AxcutDocument, AxcutTranscript, AxcutTrimRange } from "../schema";-import { anchoredToRawSpanSec, anchorRegionsWithDerivedMs } from "../timeline/timelineMap";+import {+ anchoredToRawSpanSec,+ anchorRegionsWithDerivedMs,+ dropPillById,+} from "../timeline/timelineMap";import { createId } from "./ids";+/** The region families a delete can target by id. Shared with the store so "which kinds+ * exist" has exactly one definition. `trim` is a source-time cut; the rest are pill-merged+ * effects (zoom / speed / annotation / camera-fullscreen). Clips are removed via+ * {@link removeClip}, not here — deleting a clip reflows the whole timeline. */+export type RegionKind = "zoom" | "trim" | "annotation" | "speed" | "cameraFullscreen";+/** Length a clip is given before its media has been probed. Lives here, in the pure* document layer, because that layer decides which clips are still waiting for a real* duration (`applyProbedDuration`); the store re-exports it for its own callers. */@@ -570,6 +580,76 @@ export function setClipSourceRange(return rederiveRegionMs(next, newClips);}+/**+ * The single mutator for "delete a region by id" — the edit the UI's delete key and the+ * LLM's `removeTrim` / `removeModifier` tools all perform. Extracted here (like+ * `setClipSourceRange`) so the recipe lives in one place: a `trim` is a plain filter on the+ * source-time cut list; every other kind is a pill (`dropPillById` removes every region that+ * renders as the same pill as `id`, per the merge rule). Speed / camera-fullscreen live under+ * `legacyEditor`. An id that matches nothing is a no-op. Pure; does NOT touch `preview.revision`.+ */+export function removeRegion(document: AxcutDocument, kind: RegionKind, id: string): AxcutDocument {+ switch (kind) {+ case "zoom":+ return {+ ...document,+ zoomRanges: dropPillById(document.zoomRanges, id) as AxcutDocument["zoomRanges"],+ };+ case "annotation":+ return { ...document, annotations: dropPillById(document.annotations, id) };+ case "trim":+ return {+ ...document,+ timeline: {+ ...document.timeline,+ trimRanges: document.timeline.trimRanges.filter((s) => s.id !== id),+ },+ };+ case "speed": {+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const prev = dropPillById(+ (legacy.speedRegions as Array<{ id: string; startMs: number; endMs: number }>) ?? [],+ id,+ );+ return { ...document, legacyEditor: { ...legacy, speedRegions: prev } };+ }+ case "cameraFullscreen": {+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const prev = dropPillById(+ (legacy.cameraFullscreenRegions as Array<{ id: string; startMs: number; endMs: number }>) ??+ [],+ id,+ );+ return { ...document, legacyEditor: { ...legacy, cameraFullscreenRegions: prev } };+ }+ default: {+ // ponytail: exhaustive — TS errors here if a new RegionKind is added.+ const exhaustive: never = kind;+ void exhaustive;+ return document;+ }+ }+}++/**+ * The single mutator for "delete a clip". Removing a clip closes the gap: the survivors are+ * re-laid back-to-back (`resequenceClips`) and every anchored pill's derived ms is refreshed+ * against the new layout (`rederiveRegionMs`) — pills anchored to the removed clip drop out,+ * exactly like `setClipSourceRange`. Shared by the store's delete-clip action and the LLM's+ * `removeClip` tool. An unknown `clipId` is a no-op. Pure; does NOT touch `preview.revision`.+ */+export function removeClip(document: AxcutDocument, clipId: string): AxcutDocument {+ const oldClips = document.timeline.clips;+ const arr = oldClips.filter((c) => c.id !== clipId);+ if (arr.length === oldClips.length) return document;+ const newClips = resequenceClips(arr);+ const next: AxcutDocument = {+ ...document,+ timeline: { ...document.timeline, clips: newClips },+ };+ return oldClips.length > 0 && newClips.length > 0 ? rederiveRegionMs(next, newClips) : next;+}+export function restoreFullTimeline(document: AxcutDocument): AxcutDocument {const duration = primaryAssetDuration(document);if (duration <= 0) return document;diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex b80d636f1..27eb593ec 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -11,7 +11,10 @@ import {duplicateClip as duplicateClipInDocument,moveClip as moveClipInDocument,PLACEHOLDER_DURATION_SEC,+ type RegionKind,rederiveRegionMs,+ removeClip as removeClipInDocument,+ removeRegion as removeRegionInDocument,resequenceClips,setClipSourceRange,} from "../document/timeline";@@ -19,6 +22,7 @@ import type { AxcutClipCropRegion, AxcutDocument } from "../schema";import { probeVideoDimensions, probeVideoDuration } from "../timeline/duration";import {anchorRegionsWithDerivedMs,+ dropPillsByIds,replacePillSpan,resolvePillIds,} from "../timeline/timelineMap";@@ -26,8 +30,6 @@ import { resolveTimelineSpanToTrim } from "../timeline/trim-mapping";import type { AutoZoomSuggestion } from "../timeline/zoom-suggestions";import { useProjectStore } from "./projectStore";-type RegionKind = "zoom" | "trim" | "annotation" | "speed" | "cameraFullscreen";-// Placeholder duration applied to a freshly-inserted clip whose source asset hasn't// reported its real duration yet (media drag → drop before the preview video fires// `loadedmetadata`). `applyProbedDuration` (document layer) swaps it — and the@@ -44,20 +46,7 @@ interface RegionHandle {type Clip = AxcutDocument["timeline"]["clips"][number];/**- * Deleting a pill deletes every region under it. Which regions those are is RESOLVED- * from the universal merge rule (same properties + touching = one pill), never from- * stored provenance — so it stays correct however they came to be adjacent.- */-function dropPillById<T extends { id: string; startMs: number; endMs: number }>(- regions: T[],- id: string,-): T[] {- const under = new Set(resolvePillIds(regions, id));- return regions.filter((r) => !under.has(r.id));-}--/**- * Patch every region under the pill uid=197609(camil) gid=197609 groups=197609 belongs to. A payload edit must hit them all,+ * Patch every region under the pill `id` belongs to. A payload edit must hit them all,* or the pieces of one pill would disagree — and then, by the merge rule, visibly split.*/function patchPillById<T extends { id: string; startMs: number; endMs: number }>(@@ -69,16 +58,6 @@ function patchPillById<T extends { id: string; startMs: number; endMs: number }>return regions.map((r) => (under.has(r.id) ? { ...r, ...patch } : r));}-/** Batch variant of {@link dropPillById} — expands every selected id to its whole pill. */-function dropPillsByIds<T extends { id: string; startMs: number; endMs: number }>(- regions: T[],- ids: Iterable<string>,-): T[] {- let out = regions;- for (const id of ids) out = dropPillById(out, id);- return out;-}-export function useTimeline() {const document = useProjectStore((s) => s.document);const projectId = useProjectStore((s) => s.projectId);@@ -640,51 +619,8 @@ export function useTimeline() {const removeRegion = useCallback(async (kind: RegionKind, id: string) => {if (!document) return;- let next: AxcutDocument;- if (kind === "zoom") {- next = {- ...document,- zoomRanges: dropPillById(document.zoomRanges, id) as AxcutDocument["zoomRanges"],- };- } else if (kind === "trim") {- next = {- ...document,- timeline: {- ...document.timeline,- trimRanges: document.timeline.trimRanges.filter((s) => s.id !== id),- },- };- } else if (kind === "annotation") {- next = {- ...document,- annotations: dropPillById(document.annotations, id),- };- } else if (kind === "speed") {- const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};- const prev = dropPillById(- (legacy.speedRegions as Array<{ id: string; startMs: number; endMs: number }>) ?? [],- id,- );- next = {- ...document,- legacyEditor: { ...legacy, speedRegions: prev },- };- } else {- const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};- const prev = dropPillById(- (legacy.cameraFullscreenRegions as Array<{- id: string;- startMs: number;- endMs: number;- }>) ?? [],- id,- );- next = {- ...document,- legacyEditor: { ...legacy, cameraFullscreenRegions: prev },- };- }- await saveDocument(next);+ // One shared mutator with the agent's removeTrim / removeModifier tools.+ await saveDocument(removeRegionInDocument(document, kind, id));if (selection?.id === id) setSelection(null);setMultiSelection((prev) => prev.filter((h) => h.id !== id));},@@ -1125,16 +1061,8 @@ export function useTimeline() {const removeClip = useCallback(async (clipId: string) => {if (!document) return;- const oldClips = document.timeline.clips;- const arr = oldClips.filter((c) => c.id !== clipId);- const newClips = resequenceClips(arr);- const next: AxcutDocument = {- ...document,- timeline: { ...document.timeline, clips: newClips },- };- const finalDoc =- oldClips.length > 0 && newClips.length > 0 ? rederiveRegionMs(next, newClips) : next;- await saveDocument(finalDoc);+ // One shared mutator with the agent's removeClip tool: reflow survivors + rederive pills.+ await saveDocument(removeClipInDocument(document, clipId));if (clipSelection === clipId) setClipSelection(null);},[document, clipSelection, saveDocument],diff --git a/src/lib/ai-edition/timeline/timelineMap.ts b/src/lib/ai-edition/timeline/timelineMap.tsindex 15a9b433a..49e2fb1eb 100644--- a/src/lib/ai-edition/timeline/timelineMap.ts+++ b/src/lib/ai-edition/timeline/timelineMap.ts@@ -280,6 +280,31 @@ export function resolvePillIds<T extends { id: string; startMs: number; endMs: nreturn coalesceRegionsForRuler(regions, epsilonSec).find((p) => p.ids.includes(id))?.ids ?? [id];}+/**+ * Deleting a pill deletes every region under it. Which regions those are is RESOLVED from+ * the universal merge rule (same properties + touching = one pill), never from stored+ * provenance — so it stays correct however they came to be adjacent. Lives here, in the+ * pure layer, so the store (UI delete) and the document layer (agent delete) drop a pill+ * exactly the same way.+ */+export function dropPillById<T extends { id: string; startMs: number; endMs: number }>(+ regions: T[],+ id: string,+): T[] {+ const under = new Set(resolvePillIds(regions, id));+ return regions.filter((r) => !under.has(r.id));+}++/** Batch variant of {@link dropPillById} — expands every selected id to its whole pill. */+export function dropPillsByIds<T extends { id: string; startMs: number; endMs: number }>(+ regions: T[],+ ids: Iterable<string>,+): T[] {+ let out = regions;+ for (const id of ids) out = dropPillById(out, id);+ return out;+}+/*** Move/resize the pill containing `id`, obeying both rules: the requested span is first* CLAMPED against pills of a different identity (rule 2 — they act as walls and never