Skip to content

Open source CapCut alternative.

TypeScript

fix(site): keep chat-placed overlays on line [rebuild]

David Leaaaac4f7718c
diff --git a/site/src/cut/components/Timeline.tools.ts b/site/src/cut/components/Timeline.tools.ts
index 2a183ee9..c9b4ac7b 100644
--- a/site/src/cut/components/Timeline.tools.ts
+++ b/site/src/cut/components/Timeline.tools.ts
@@ -17,7 +17,7 @@ import {
} from "@/cut/lib/textCompose";
import { TEXT_MOVE_IDS, TEXT_MOVE_NOTES } from "@/cut/lib/textMotion";
import { LETTER_SPACING_MAX, LETTER_SPACING_MIN, OVERLAY_ANIM_STYLE_IDS, TEXT_TEXTURES, TEXT_WEIGHTS } from "@donkeycut/effects-kit";
-import { REGION_MAX_SCALE, TIMELINE_IDS, TIMELINE_LABELS } from "@/cut/lib/types";
+import { IMAGE_CLIP_SECONDS, REGION_MAX_SCALE, TIMELINE_IDS, TIMELINE_LABELS } from "@/cut/lib/types";
import { BLOCKOUT_MAX } from "@/cut/lib/blockSource";
/** The title sizes the assistant and the inspector set, px at a 1080 short
@@ -259,10 +259,11 @@ export const TIMELINE_TOOLS = [
{
name: "add_overlay_video",
description:
- "Put a project video or image asset on an overlay video track, composited over track 0: tracks stack bottom-up, and the topmost full-frame clip covers everything below. Pick a layout to share the frame — halves for a split screen, pip for picture-in-picture. Asset ids come from `media` in the editor state.",
+ "Put a project video or image asset on an overlay video track, composited over track 0: tracks stack bottom-up, and the topmost full-frame clip covers everything below. Pick a layout to share the frame — halves for a split screen, pip for picture-in-picture. Asset ids come from `media` in the editor state. An image over a talking head belongs to the line that speaks of it: start it as that line starts and end it as the line ends.",
inputSchema: obj({
asset_id: str("Project asset id (video or image)"),
start: num("Timeline start s (default: the playhead)"),
+ end: num(`Timeline end s. An image runs from start to here; without it an image runs ${IMAGE_CLIP_SECONDS}s, stopping at the end of track 0. A video runs its source's length unless this ends it sooner`),
track: num("Video track, 1 or higher; 1 = first layer above track 0, higher = further in front (default 1)"),
layout: {
type: "string",
@@ -286,11 +287,11 @@ export const TIMELINE_TOOLS = [
layout: {
type: "string",
enum: ["full", "top", "bottom", "left", "right", "pip"],
- description: "Frame region preset",
+ description: "Frame region preset; leave out when passing region",
},
region: obj({
- x: num("Left edge in frame fractions; may sit past the frame (negative = off the left side), the frame crops the overhang"),
- y: num("Top edge in frame fractions; may sit past the frame (negative = above the top)"),
+ x: num("Centre of the box, frame fractions (0.5 = the middle), as add_title and add_shape take x; the box may run past the frame, and the frame crops the overhang"),
+ y: num("Centre of the box, frame fractions (0.5 = the middle)"),
w: num(`Width in frame fractions, 0.05..${REGION_MAX_SCALE}; past 1 the box runs off the frame`),
h: num(`Height in frame fractions, 0.05..${REGION_MAX_SCALE}`),
}, ["x", "y", "w", "h"]),
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index 674790ba..d184638e 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -49,6 +49,14 @@ export const roundT = (n: number) => Math.round(n * 1000) / 1000;
* two decimals blur by up to five pixels. */
const rF = (n: number) => Math.round(n * 10000) / 10000;
+/** A box as the chat reads and writes every box: x/y its centre and w/h its
+ * size, in frame fractions. The store keeps a top-left corner; the chat never
+ * sees one, so a measured box, a safe area and a layer's region all mean the
+ * same numbers. */
+export function centreBox(b: { x: number; y: number; w: number; h: number }) {
+ return { x: rF(b.x + b.w / 2), y: rF(b.y + b.h / 2), w: rF(b.w), h: rF(b.h) };
+}
+
/** The transition this clip applies into the next one, clamped to the live
* overlap the same way the preview and export are. Null when there's no
* transition or no next clip. */
@@ -529,19 +537,13 @@ function describeState(
magnet: s.magnet,
// Every guide preset's safe area for this frame, whether or not it
// shows, so placement can respect a platform's UI without a guide on:
- // safeArea and keepOut are frame fractions (x, y, w, h).
+ // safeArea and keepOut are boxes as the chat reads them (centreBox).
safeZones: Object.fromEntries(
GUIDE_PRESETS.filter((p) => p.id !== "custom" && guideFits(p.id, s.aspect)).flatMap((p) => {
const safeArea = safeAreaOf([p.id], s.aspect);
if (!safeArea) return [];
- const keepOut = guideGeometry([p.id], s.aspect).boxes.map((b) => ({
- label: b.label,
- x: rF(b.x),
- y: rF(b.y),
- w: rF(b.w),
- h: rF(b.h),
- }));
- return [[p.id, { safeArea, ...(keepOut.length ? { keepOut } : {}) }]];
+ const keepOut = guideGeometry([p.id], s.aspect).boxes.map((b) => ({ label: b.label, ...centreBox(b) }));
+ return [[p.id, { safeArea: centreBox(safeArea), ...(keepOut.length ? { keepOut } : {}) }]];
})
),
// The guides showing on the preview and the user's own lines.
@@ -892,7 +894,7 @@ function describeOverlayClip(c: VideoClip, assets: Map<string, { name: string }>
// The frame region this layer occupies: Full covers the frame; Top/Bottom/
// Left/Right split it; PiP floats inside it.
layout: regionLabel(rect),
- region: { x: rF(rect.x), y: rF(rect.y), w: rF(rect.w), h: rF(rect.h) },
+ region: centreBox(rect),
fit: c.fit ?? "fit",
...(clipZoom(c) > 1
? { zoom: r(clipZoom(c)), panX: r(c.panX ?? 0), panY: r(c.panY ?? 0) }
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index d054f936..d42a7675 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -264,7 +264,7 @@ import { zoomAnchor } from "./measure/camera";
import { DETECT_CHANGES_MAX, DETECT_CUTS_MAX, DETECT_CUTS_SPAN_MAX, SAMPLE_COLOR_MAX, SAMPLE_COLORS_K_MAX, TRACK_FRAMES_MAX, CAMERA_FRAMES_MAX, TRACK_MATCHES, TRACK_PATH_MAX, TRACK_TOLERANCE_DEFAULT } from "./measure/limits";
import { renderStageFrame, storeStageStill } from "./stageFrame";
import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";
-import { buildAiContext, describeCameraCard, describeDoc, describeParkedTimeline, hiddenFromChat, OTHER_CHATS_MEDIA_NOTE, roundT } from "./aiContext";
+import { buildAiContext, centreBox, describeCameraCard, describeDoc, describeParkedTimeline, hiddenFromChat, OTHER_CHATS_MEDIA_NOTE, roundT } from "./aiContext";
import { CARD_SIDES, newCard, normalizeCard, type CardSide } from "./cameraCard";
import { CAPTION_STYLES, captionEmphasis, cueSpot, EMPHASIS_SCALE_MAX, EMPHASIS_SCALE_MIN, laneCues, subtitleLaneCount, trackLocale } from "./subtitles";
import { cueEmphasis, emphasisIndicesOf, emphasizedWords } from "./captionEmphasis";
@@ -1696,9 +1696,32 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
throw new ToolError("Upper-track clips animate with fade or zoom only.");
const seconds = isNum(input.seconds) ? input.seconds : ANIM_DEFAULT_SECONDS;
s.setClipAnim(clip.id, which, { style, seconds });
- const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
+ const after = useEditor.getState();
+ const next = after.clips.find((c) => c.id === clip.id)!;
const anim = which === "in" ? next.animIn : next.animOut;
- return { id: next.id, which, style: anim?.style ?? "none", seconds: anim?.seconds ?? 0 };
+ if (anim) return { id: next.id, which, style: anim.style, seconds: anim.seconds };
+
+ // The bar did not take this edge. A clip butting against this one on
+ // its track turns the bar into the cut between the two, so the clip has
+ // no entrance or exit of its own there; say so, so the reply never
+ // claims an animation the clip lacks.
+ const edge = which === "in" ? next.start : next.start + clipLen(next);
+ const neighbour = after.clips.find(
+ (c) =>
+ c.track === next.track &&
+ c.id !== next.id &&
+ Math.abs((which === "in" ? c.start + clipLen(c) : c.start) - edge) <= ANIM_TOUCH_SECONDS
+ );
+ const name = (c: VideoClip) => after.assets.find((a) => a.id === c.assetId)?.name ?? c.id;
+ return {
+ id: next.id,
+ which,
+ style: "none",
+ seconds: 0,
+ note: neighbour
+ ? `Not set: "${name(neighbour)}" (${neighbour.id}) ${which === "in" ? "ends" : "starts"} at ${roundT(edge)}s on track ${next.track}, so the bar plays as the cut between the two and this clip has no ${which === "in" ? "entrance" : "exit"}. Leave a gap between them (update_overlay_video start or out) or move one to another track, then set it again.`
+ : `Not set: the bar did not land on this clip's ${which} edge at ${roundT(edge)}s.`,
+ };
},
get_state: (s, input) => {
@@ -2389,9 +2412,10 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
}
: {}),
...(timelineText ? { timeline: timelineText } : {}),
- // Frame fractions, quietest first: where a title or caption can go
- // over this stretch without covering the picture or the platform's UI.
- ...(spots.length > 0 ? { textFits: spots } : {}),
+ // Boxes (centre and size), quietest first: where a title or caption
+ // can go over this stretch without covering the picture or the
+ // platform's UI.
+ ...(spots.length > 0 ? { textFits: spots.map((sp) => ({ ...sp, ...centreBox(sp) })) } : {}),
// The picture box found or set on this source, so what the sheets
// show and what the measuring tools read are told apart.
...(asset.picture && !isFullFrame(asset.picture)
@@ -3139,7 +3163,20 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const track = isNum(input.track) ? Math.max(1, Math.round(input.track)) : 1;
if (isNum(input.track) && Math.round(input.track) === 0)
throw new ToolError("Track 0 holds the timeline clips — use place_clip for it.");
- s.addVideoFromAsset(asset.id, { kind: "track", track }, start);
+
+ // Its length goes in with the add, so the landing makes room for the
+ // clip it will be: `end` when given, else an image stops where track 0
+ // does, e.g. a still at 50.9 over a cut ending at 52.8 runs 1.9s, not
+ // 8s past the close over black.
+ if (isNum(input.end) && input.end < start + CLIP_MIN_SECONDS - 1e-9)
+ throw new ToolError(`end must come after the clip's start (${roundT(start)}s).`);
+ const cutEnd = totalDuration(s.clips);
+ const len = isNum(input.end)
+ ? input.end - start
+ : asset.type === "image" && cutEnd > start + CLIP_MIN_SECONDS
+ ? Math.min(IMAGE_CLIP_SECONDS, cutEnd - start)
+ : undefined;
+ s.addVideoFromAsset(asset.id, { kind: "track", track }, start, len);
const cur = useEditor.getState();
const sel = cur.selection;
const id = sel?.kind === "clip" ? sel.id : null;
@@ -3152,6 +3189,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
id: c.id,
track: c.track,
start: roundT(c.start),
+ end: roundT(c.start + clipLen(c)),
len: roundT(clipLen(c)),
layout: regionLabel(rectOf(c)),
};
@@ -3177,19 +3215,30 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
}
if (typeof input.muted === "boolean") patch.muted = input.muted;
if (typeof input.hidden === "boolean") patch.hidden = input.hidden || undefined;
+ // A preset and a box both name the region; taking one silently left
+ // the other unapplied and the model setting it again round after round.
+ if (typeof input.layout === "string" && input.region)
+ throw new ToolError("Pass layout or region, not both: layout is a preset box, region a box of your own.");
if (typeof input.layout === "string") {
Object.assign(patch, layoutPatch(input.layout));
} else if (input.region && typeof input.region === "object") {
const rg = input.region as Record<string, unknown>;
if (!isNum(rg.x) || !isNum(rg.y) || !isNum(rg.w) || !isNum(rg.h))
throw new ToolError("region needs numeric x, y, w, h (frame fractions).");
- // The box may hang past the frame's edges, as the preview's handles
- // let it (a screen in the shot that runs off the frame); the frame
- // crops it. A sliver always stays on the frame so it can't vanish.
+ // x/y name the box's centre, as every box the chat reads or writes
+ // does; the store keeps its top-left corner. The box may hang past
+ // the frame's edges, as the preview's handles let it (a screen in the
+ // shot that runs off the frame); the frame crops it. A sliver always
+ // stays on the frame so it can't vanish.
const w = clamp(rg.w, 0.05, REGION_MAX_SCALE);
const h = clamp(rg.h, 0.05, REGION_MAX_SCALE);
const keep = 0.05;
- patch.frame = { x: clamp(rg.x, keep - w, 1 - keep), y: clamp(rg.y, keep - h, 1 - keep), w, h };
+ patch.frame = {
+ x: clamp(rg.x - w / 2, keep - w, 1 - keep),
+ y: clamp(rg.y - h / 2, keep - h, 1 - keep),
+ w,
+ h,
+ };
}
refuseCardFraming(c, input, ["fit", "zoom"]);
if (input.fit === "fit" || input.fit === "fill") patch.fit = input.fit;
@@ -3211,11 +3260,14 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");
s.updateClip(c.id, patch);
const next = useEditor.getState().clips.find((x) => x.id === c.id)!;
+ const overhang = frameOverhang(rectOf(next));
return {
id: next.id,
track: next.track,
start: roundT(next.start),
layout: regionLabel(rectOf(next)),
+ region: centreBox(rectOf(next)),
+ ...(overhang ? { offFrame: overhang } : {}),
fit: next.fit ?? "fit",
...(clipZoom(next) > 1 ? { zoom: clipZoom(next) } : {}),
...(next.flipH ? { flipH: true } : {}),
@@ -8109,6 +8161,29 @@ function layoutPatch(layout: string): Partial<VideoClip> {
return { frame: key === "full" ? undefined : { ...L.rect }, fit: L.fit };
}
+/** How far a layer's box runs past each side of the frame, in frame
+ * fractions — the part the frame crops. Null when the box sits inside. A box
+ * set past the frame on purpose (a screen that spills off) reads the same;
+ * the chat checks the sides against what it meant.
+ * e.g. centre 0.875 at width 0.75 → { right: 0.25 } */
+function frameOverhang(r: { x: number; y: number; w: number; h: number }): Record<string, number> | null {
+ const sides = {
+ left: -r.x,
+ right: r.x + r.w - 1,
+ top: -r.y,
+ bottom: r.y + r.h - 1,
+ };
+ const past = Object.entries(sides).filter(([, v]) => v > OVERHANG_EPS);
+ return past.length > 0 ? Object.fromEntries(past.map(([k, v]) => [k, Math.round(v * 1000) / 1000])) : null;
+}
+
+// Under a pixel of a 1080 frame: a box flush with an edge is not past it.
+const OVERHANG_EPS = 0.001;
+
+// How close another clip's edge sits for set_animation to name it as the
+// clip that took the bar: a frame at 50 fps.
+const ANIM_TOUCH_SECONDS = 0.02;
+
/** The model asked for timeline placement — explicitly, or implicitly by
* giving a position. Otherwise generated media stays on its chat card. */
function wantsTimeline(input: Record<string, unknown>, positionKey: "index" | "start"): boolean {
diff --git a/site/src/cut/lib/overlayRegionTool.test.ts b/site/src/cut/lib/overlayRegionTool.test.ts
index 5ebf5c10..142b5fc6 100644
--- a/site/src/cut/lib/overlayRegionTool.test.ts
+++ b/site/src/cut/lib/overlayRegionTool.test.ts
@@ -6,9 +6,10 @@ import { useEditor } from "./store";
import { REGION_MAX_SCALE, emptySubtitles } from "./types";
/**
- * update_overlay_video's custom region: a box may run past the frame's
- * edges, as the preview's drag handles allow, so a screen in the shot that
- * spills off the frame can be covered by the region itself.
+ * update_overlay_video's custom region: x/y its centre and w/h its size. A
+ * box may run past the frame's edges, as the preview's drag handles allow, so
+ * a screen in the shot that spills off the frame can be covered by the region
+ * itself; the result names the sides it runs past.
*/
beforeEach(async () => {
@@ -29,8 +30,34 @@ beforeEach(async () => {
const overlay = () => useEditor.getState().clips.find((c) => c.track > 0)!;
test("a region can hang past the frame's sides", async () => {
- await runAiTool("update_overlay_video", { id: overlay().id, region: { x: -0.02, y: 0.29, w: 1.04, h: 0.37 } });
- expect(overlay().frame).toEqual({ x: -0.02, y: 0.29, w: 1.04, h: 0.37 });
+ await runAiTool("update_overlay_video", { id: overlay().id, region: { x: 0.5, y: 0.475, w: 1.04, h: 0.37 } });
+ const f = overlay().frame!;
+ expect(f.x).toBeCloseTo(-0.02, 6);
+ expect(f.y).toBeCloseTo(0.29, 6);
+ expect(f.w).toBe(1.04);
+ expect(f.h).toBe(0.37);
+});
+
+// x/y are the box's centre, as titles, shapes and the measuring tools take
+// them: a diagram boxed at the middle of the frame lands centred.
+test("a region's x/y name its centre", async () => {
+ const out = (await runAiTool("update_overlay_video", {
+ id: overlay().id,
+ region: { x: 0.5, y: 0.25, w: 0.75, h: 0.4 },
+ })) as { region: unknown; offFrame?: unknown };
+ const f = overlay().frame!;
+ expect(f.x).toBeCloseTo(0.125, 6);
+ expect(f.y).toBeCloseTo(0.05, 6);
+ expect(out.region).toEqual({ x: 0.5, y: 0.25, w: 0.75, h: 0.4 });
+ expect(out.offFrame).toBeUndefined();
+});
+
+test("the result names the sides a box runs past", async () => {
+ const out = (await runAiTool("update_overlay_video", {
+ id: overlay().id,
+ region: { x: 0.75, y: 0.5, w: 0.75, h: 0.4 },
+ })) as { offFrame?: Record<string, number> };
+ expect(out.offFrame).toEqual({ right: 0.125 });
});
test("a region stays within the oversize ceiling and keeps a sliver on the frame", async () => {
@@ -43,6 +70,12 @@ test("a region stays within the oversize ceiling and keeps a sliver on the frame
expect(f.y).toBeLessThan(1);
});
+test("layout and region together are refused", async () => {
+ expect(
+ runAiTool("update_overlay_video", { id: overlay().id, layout: "pip", region: { x: 0.5, y: 0.5, w: 0.8, h: 0.5 } })
+ ).rejects.toThrow("not both");
+});
+
test("the region schema says it may pass the frame edges", () => {
const tool = TIMELINE_TOOLS.find((t) => t.name === "update_overlay_video")!;
const region = (tool.inputSchema as { properties: Record<string, { properties: Record<string, { description: string }> }> })
diff --git a/site/src/cut/lib/overlayStillTool.test.ts b/site/src/cut/lib/overlayStillTool.test.ts
new file mode 100644
index 00000000..bc69a33e
--- /dev/null
+++ b/site/src/cut/lib/overlayStillTool.test.ts
@@ -0,0 +1,86 @@
+import { beforeEach, expect, test } from "bun:test";
+import { runAiTool } from "./aiTools";
+import { buildAiContext } from "./aiContext";
+import { useEditor } from "./store";
+import { emptySubtitles } from "./types";
+
+/**
+ * Stills over a talking head: add_overlay_video's length for an image, and
+ * set_animation's answer when a neighbour on the track takes the bar. A
+ * chart dropped near the close used to run its 8s default past the cut's
+ * end, and charts laid end to end lost their entrances without a word.
+ */
+
+beforeEach(async () => {
+ useEditor.setState({
+ projectId: "p1",
+ aspect: "9:16",
+ clips: [],
+ overlays: [],
+ transitions: [],
+ audioClips: [],
+ subtitles: emptySubtitles(),
+ assets: [
+ { id: "talk", fileName: "talk.mov", name: "Talk", type: "video", duration: 20, url: "" },
+ { id: "chart", fileName: "chart.jpg", name: "Chart", type: "image", duration: 0, width: 2000, height: 1125, url: "" },
+ { id: "chart2", fileName: "chart2.jpg", name: "Chart 2", type: "image", duration: 0, width: 2000, height: 1125, url: "" },
+ ],
+ });
+ await runAiTool("add_clip", { asset_id: "talk" });
+});
+
+const clip = (id: string) => useEditor.getState().clips.find((c) => c.id === id)!;
+const end = (id: string) => clip(id).start + (clip(id).out - clip(id).in);
+
+test("an image near the close stops where track 0 does", async () => {
+ const out = (await runAiTool("add_overlay_video", { asset_id: "chart", start: 17 })) as { id: string; end: number };
+ expect(end(out.id)).toBeCloseTo(20, 6);
+ expect(out.end).toBe(20);
+});
+
+test("end sets an image's length", async () => {
+ const out = (await runAiTool("add_overlay_video", { asset_id: "chart", start: 4, end: 7.5 })) as { id: string; len: number };
+ expect(end(out.id)).toBeCloseTo(7.5, 6);
+ expect(out.len).toBe(3.5);
+});
+
+// The landing measures the still at the length it asked for, so a clip
+// later on the track moves up past it and the two never overlap.
+test("an image lands at its asked length without overlapping", async () => {
+ const later = (await runAiTool("add_overlay_video", { asset_id: "chart2", start: 6, end: 8 })) as { id: string };
+ const out = (await runAiTool("add_overlay_video", { asset_id: "chart", start: 2, end: 9 })) as { id: string };
+ expect(end(out.id)).toBeCloseTo(9, 6);
+ expect(clip(later.id).start).toBeGreaterThanOrEqual(end(out.id) - 1e-6);
+});
+
+test("an end before the start is refused", async () => {
+ expect(runAiTool("add_overlay_video", { asset_id: "chart", start: 5, end: 4 })).rejects.toThrow("end must come after");
+});
+
+test("set_animation names the neighbour that took the bar", async () => {
+ const a = (await runAiTool("add_overlay_video", { asset_id: "chart", start: 2, end: 6 })) as { id: string };
+ const b = (await runAiTool("add_overlay_video", { asset_id: "chart2", start: 6, end: 9 })) as { id: string };
+ const res = (await runAiTool("set_animation", { clipId: b.id, which: "in", style: "zoom", seconds: 0.3 })) as {
+ style: string;
+ note?: string;
+ };
+ expect(res.style).toBe("none");
+ expect(res.note).toContain(a.id);
+ expect(res.note).toContain("Leave a gap");
+});
+
+test("set_animation on a free edge sets the entrance", async () => {
+ const a = (await runAiTool("add_overlay_video", { asset_id: "chart", start: 2, end: 6 })) as { id: string };
+ const res = (await runAiTool("set_animation", { clipId: a.id, which: "in", style: "zoom", seconds: 0.3 })) as {
+ style: string;
+ note?: string;
+ };
+ expect(res.style).toBe("zoom");
+ expect(res.note).toBeUndefined();
+});
+
+// Safe areas read as every other box does: x/y the centre.
+test("safeZones report centre boxes", () => {
+ const ctx = buildAiContext({ chatId: null }) as { project: { safeZones: Record<string, { safeArea: { x: number; y: number; w: number; h: number } }> } };
+ expect(ctx.project.safeZones.margins.safeArea).toEqual({ x: 0.5, y: 0.5, w: 0.9, h: 0.9 });
+});
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index af4922fa..eb7a0794 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -873,7 +873,9 @@ export interface EditorState {
moveClip: (id: string, toIndex: number) => void;
/** Add a video asset to the timeline at a placement: an existing track or a
* freshly inserted one. Used by media / library drops. */
- addVideoFromAsset: (assetId: string, place: VideoTrackPlacement, start: number) => void;
+ /** `len` sets the clip's timeline length (default: an image's
+ * IMAGE_CLIP_SECONDS, a video's whole source). */
+ addVideoFromAsset: (assetId: string, place: VideoTrackPlacement, start: number, len?: number) => void;
/** "Detach Audio": lift the selected clip's sound onto the
* soundtrack track (and mute the clip) so it can be cut independently. */
detachAudio: () => void;
@@ -4079,14 +4081,17 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
set({ ...next, clips: [...next.clips].sort((a, b) => a.start - b.start), subtitles: { ...s.subtitles, cues: next.subtitles.cues } });
},
- addVideoFromAsset: (assetId, aimed, start) => {
+ addVideoFromAsset: (assetId, aimed, start, len) => {
const asset = get().assets.find((a) => a.id === assetId);
if (!asset || (asset.type !== "video" && asset.type !== "image")) return;
// With the magnet on, nothing opens a row below track 0: a drop aimed
// under the stack inserts into track 0 at the pointer.
const place: VideoTrackPlacement =
get().magnet && aimed.kind === "insert" && aimed.level === 0 ? { kind: "track", track: 0 } : aimed;
- const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
+ // A given length lands as it is placed, so the collision-safe landing
+ // measures the clip it will be; a video never runs past its source.
+ const natural = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
+ const out = len === undefined ? natural : asset.type === "image" ? len : Math.min(natural, len);
push();
const { track, start: at, shifts } = landOnPlacement(
get().clips,
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 974c0c9d..113ed576 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -659,7 +659,7 @@ Rules:
- Edits are undoable (unlimited undo), so prefer doing over asking; only ask when the request is genuinely ambiguous. Ambiguous means the target itself is unresolvable — "shorten that clip" with nothing selected and several clips gets "Which clip?" and no edit; guessing a target and editing it is worse than the question. 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. Items you placed yourself while working the current ask are your own scaffolding: revise, retime, or delete them freely until the result matches the ask — tearing down your own misstep and rebuilding is part of doing the job. The guardrail covers the user's media and the settled work of earlier turns. 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.
- Keep the timeline as compact as its content allows. Every clip, sound and element goes on the lowest lane or row where it fits — sounds that never overlap share one soundtrack lane, elements that never overlap share one row — and a new lane opens only for something that plays over another or must stack in front of it (an effect still keeps rows of its own). When a build or an edit leaves lanes with room, pack_lanes closes them up in one call.
- Times are seconds. A \`@1:34\` in the user's message is a moment on the timeline — minutes and seconds — that they marked while writing it; it is kept pointing at the same picture as the cut changes, so read it as the timeline second it names right now. 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.
-- project.safeZones in editor_state gives, for this frame, the safe area of every guide preset (frame fractions, x/y/w/h) and the keepOut boxes where TikTok, Reels and Shorts draw their own UI or crop the frame's sides — known whether or not a guide shows. When the user names a platform, asks for a safe zone, or wants graphics kept clear of the app's UI, place every title, sticker and caption inside safeZones.shortform.safeArea and check with capture_frame; safeZones.margins is the general 5% inset. A safeArea is a rect — x/y its top-left corner, w/h its size — while an element's x/y is its center: centered in the safe area means x + w/2, y + h/2, and an element of width ew stays inside while its center is between x + ew/2 and x + w − ew/2. Guides are a view: set_guides shows one when the user asks to see it, and showing one changes nothing in the cut.
+- project.safeZones in editor_state gives, for this frame, the safe area of every guide preset (frame fractions, x/y/w/h) and the keepOut boxes where TikTok, Reels and Shorts draw their own UI or crop the frame's sides — known whether or not a guide shows. When the user names a platform, asks for a safe zone, or wants graphics kept clear of the app's UI, place every title, sticker and caption inside safeZones.shortform.safeArea and check with capture_frame; safeZones.margins is the general 5% inset. Every box here is x/y its centre and w/h its size, as an element, a layer's region and every measuring tool read: centred in the safe area means its x, y, and a box of width ew stays inside while its centre is within (w − ew)/2 of x. Guides are a view: set_guides shows one when the user asks to see it, and showing one changes nothing in the cut.
- Exercise judgment on details the user left open, and state the choice you made. Judgment fills in the parameters of the asked-for change (style, length, placement); the scope stays the ask, and extra tools, tracks, or treatments beyond it wait for the user to ask. Editing defaults: a hard cut at every joint; when transitions are asked for, one style family per video at 0.4–0.6s. The editing-taste skill carries the full doctrine. Editing a recording of someone speaking to camera is the talking-head-videos skill; the ask decides which of its steps run.
- Styling is part of the ask, never a bonus. Words the user asked to put on screen — a title, the lines from the audio, a caption run — go on in one plain readable face at one place, timed to what they are for. Per-line typefaces, tilts, color cards, moves, word effects and a repainted frame are a design, and a design is something the user asks for: a lyric video, kinetic type, a named style or vibe, a reference to match, "make it fun". Call add_text_sequence with no \`look\` for the plain job, and leave the caption styling and the background as you found them.
- A skill attached to the message (<skill_relevance>) is the reference for its area: read it before touching that area's settings. It never changes which tool the ask maps to — the tool descriptions decide that ("a better version" is a render, whatever skill rode along). list_skills / read_skill cover an area the attachment left out.