Open source CapCut alternative.
TypeScript
feat(site): the Cutout tab runs on one segmented Remove control [rebuild]
David Le5807711429b0
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 95de16bb..eb8bf819 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -32,7 +32,7 @@ The client probes the engine's health endpoint (dedicated port first, dev server**Framing is per clip.** Every video clip meets its box — the whole frame, or the region it was given — through one geometry: fitted with margins or covering with a crop, zoomed in further, panned to choose what the crop keeps, turned, faded, cornered, masked, and shadowed. One function computes where the picture lands, the preview draws that rectangle, and the export graph scales and crops to the same numbers, so a reframed clip looks the same on every surface, freeze frames and headless renders included. On the stage the selected clip wears two outlines: a blue box for its layout — a drag anywhere on it moves the clip, its grips resize it, the button above turns it — and a grey dashed one standing where the source really lands, so the part a crop discards stays visible: its corners zoom the picture and dragging the discarded part slides the crop. The shadow is cast by the shape the clip actually shows, mask included, which is what makes a circle-masked camera bubble throw a circular shadow.-**A cutout keys the clip to a matte.** Every video clip can carry a cutout — the Inspector's Cutout tab: an alpha matte decides which of its pixels stay, ink can trace the kept silhouette, and a color or image can fill in behind it, with lower tracks showing through wherever nothing fills. Every mode resolves to that one matte in the clip's own pixels. A chroma key computes it live, from reference math in the effects kit that the GPU shader, the CPU pass, and the export all share. The AI modes bake it into a small grayscale video stored as a project asset: auto mattes the person with the on-device segmenter in seconds and for free, then a hosted tracker (credits, like all AI work) re-bakes it at quality and swaps the asset in; a custom selection goes straight to the tracker, seeded by a few words naming the subject or by the strokes painted on the stage — the instant feedback while painting comes from a small on-device tap-to-select model, and the stored words and seeds make every bake reproducible. A long clip tracks in parts: the span splits into pieces of a few minutes, each submitted to the tracker as its own billable job with the selection handed across the seam, and a persisted ticket pins the submitted parts and the exact span they were cut from — a reload resumes the run on the paid pieces, and a part whose track dies is re-bought alone on retry. A fingerprint on the matte records what it was baked from — the source and the selection, trims left out — so a retrim inside the baked range keeps the matte and its bill, while a changed selection re-bakes; a background sweep settles bakes against the doc through undo, redo, and deletion, and holds them while a brush session is still painting. For the ffmpeg export each cutout clip ships as a client-rendered pair of videos — the keyed picture's color and its alpha — baked by the same compositor that draws the preview, so the engine and the worker composite exactly what the tab showed. Headless surfaces consume stored mattes; a turn that runs with no browser writes the cutout onto the clip and the next editor session's sweep starts the bake it owes.+**A cutout keys the clip to a matte.** Every video clip can carry a cutout — the Inspector's Cutout tab: an alpha matte decides which of its pixels stay, ink can trace the selection's silhouette, and a color or image can fill in behind it, with lower tracks showing through wherever nothing fills. The cutout runs in either direction — keep the selection and remove the background around it, or remove the selection and keep the rest — and the matte is the same in both, so flipping the direction re-bakes nothing. Every mode resolves to that one matte in the clip's own pixels, baked into a small grayscale video stored as a project asset: auto mattes the person with the on-device segmenter in seconds and for free, and a hosted tracker (credits, like all AI work) re-bakes it at quality and swaps the asset in when the user asks for the upgrade; a custom selection goes straight to the tracker, seeded by a few words naming the subject or by the strokes painted on the stage, and the stored words and seeds make every bake reproducible. Every bake starts from an explicit Apply — picking a mode or painting only describes the selection, and the chat tool's call counts as the ask. A long clip tracks in parts: the span splits into pieces of a few minutes, each submitted to the tracker as its own billable job with the selection handed across the seam, and a persisted ticket pins the submitted parts and the exact span they were cut from — a reload resumes the run on the paid pieces, and a part whose track dies is re-bought alone on retry. A fingerprint on the matte records what it was baked from — the source and the selection, trims left out — so a retrim inside the baked range keeps the matte and its bill, while a changed selection re-bakes; a background sweep settles bakes against the doc through undo, redo, and deletion, and holds them while a brush session is still painting. Switching the cutout off keeps the removal and its baked matte on the clip — nothing renders and nothing bakes until it is switched back on, and the switch back is free. For the ffmpeg export each cutout clip ships as a client-rendered pair of videos — the keyed picture's color and its alpha — baked by the same compositor that draws the preview, so the engine and the worker composite exactly what the tab showed. Headless surfaces consume stored mattes; a turn that runs with no browser writes the cutout onto the clip and the next editor session's sweep starts the bake it owes.**Words as the picture.** A lyric video, a kinetic-typography passage, a quote sequence: the assistant places a whole run of lines in one call, carrying a named look. A look is the design of the whole run rather than of one line — the frame color, the cards it cycles, and the ensemble the run walks across its length: the faces it rotates through, the entrances, where successive lines land in the frame, and what each line does while it holds. That is what stops a hundred lines coming out identical and dead center, which is the failure a text video actually has. The looks live in one registry the tools and the skills both read, so adding a look teaches the assistant a new style with no other change. Words ride one of two carriers — a caption track, which holds per-word timings, or elements, which give each line its own card, color and motion. Both carriers play a line word by word, and what a word does is data like everything else: three poses — before its moment, at it, and after — and the seconds between them. An emphasis travels along a line that is fully up, because the pose after a word's moment is the pose before it; a build assembles the line as it is spoken, because the pose after is the pose it arrived at. That one shape covers a karaoke highlight, a word swelling on the beat, a sentence appearing a word at a time, and a faint line going solid word by word, and it is what makes adding another an entry in the catalog. One evaluator resolves each word to a color, an opacity and a pose, and the preview, the burn-in and the frame samplers all read that, so a word effect looks the same wherever it plays. Text the user already has (lyrics, a script) is timed by aligning it to a transcript of the audio: the recognizer supplies the clock and the user's wording is kept exactly, which is what makes it survive singing.diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex a826696c..0e6e79f5 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -115,9 +115,10 @@ import {import { getPreviewCanvas } from "@/cut/lib/previewCanvas";import { cn } from "@/lib/utils";import { ScrollArea } from "@/components/ui/scroll-area";-import { InfoTip, ResetButton, Row, useSliderCheckpoint, Value } from "@/cut/components/panelBits";+import { InfoTip, ResetButton, Row, Section, useSliderCheckpoint, Value } from "@/cut/components/panelBits";import { ColorPanel } from "@/cut/components/ColorPanel";import { RemovalPanel } from "@/cut/components/RemovalPanel";+import { useMatteBakes } from "@/cut/lib/removal/bakeJobs";/** Where the animation panel is, for the panel that offers the way in. It is* held by the Inspector rather than by each panel because the animation panel@@ -288,46 +289,6 @@ function SegToggle({);}-/** Hoverable (i) explaining the control it follows. */-/**- * A named group of rows under a hairline. A section that owns a feature carries- * the switch that turns it on and holds its rows back until it is, so the panel- * reads as a short list of what the element actually has and grows only where- * it was asked to. Pass no `onEnabledChange` for a group that is always open.- */-function Section({- title,- info,- enabled,- onEnabledChange,- aside,- children,-}: {- title: string;- info?: React.ReactNode;- enabled?: boolean;- onEnabledChange?: (enabled: boolean) => void;- /** Controls that belong to the group as a whole, sat at the end of its title. */- aside?: React.ReactNode;- children?: React.ReactNode;-}) {- const gated = !!onEnabledChange;- return (- <section className="mt-1.5 border-t border-border pt-1.5 first:mt-0 first:border-t-0">- <div className="flex min-h-9 items-center justify-between gap-2">- <span className="flex min-w-0 items-center gap-1 text-[13px] font-medium">- <span className="truncate">{title}</span>- {info && <InfoTip label={title}>{info}</InfoTip>}- </span>- {aside}- {gated && (- <Switch checked={!!enabled} onCheckedChange={onEnabledChange} aria-label={title} />- )}- </div>- {(!gated || enabled) && children}- </section>- );-}/** Matches the store's MIN_LEN: the shortest a trim can leave a clip. */const MIN_TRIM = 0.1;@@ -446,18 +407,23 @@ function ClipColumn({ clip }: { clip: VideoClip }) {)}</ScrollArea>)}- <ClipToolbar tab={tab} onPick={(t) => setTab(tab === t ? "main" : t)} />+ <ClipToolbar clipId={clip.id} tab={tab} onPick={(t) => setTab(tab === t ? "main" : t)} /></div>);}function ClipToolbar({+ clipId,tab,onPick,}: {+ clipId: string;tab: ClipTab;onPick: (tab: Exclude<ClipTab, "main">) => void;}) {+ // A running matte bake shows on the Cutout tab itself, so the work stays+ // visible from any view.+ const baking = useMatteBakes((s) => s.jobs[clipId]?.status === "running");return (<div className="flex shrink-0 border-t border-border bg-card">{CLIP_TABS.map(({ id, label, Icon }) => (@@ -466,7 +432,7 @@ function ClipToolbar({type="button"aria-pressed={tab === id}className={cn(- `clip-tab-${id} flex flex-1 flex-col items-center justify-center gap-0.5 py-1 text-[10px] leading-none font-medium transition-colors`,+ `clip-tab-${id} relative flex flex-1 flex-col items-center justify-center gap-0.5 py-1 text-[10px] leading-none font-medium transition-colors`,tab === id? "bg-neutral-900 text-white": "text-muted-foreground hover:bg-foreground/5 hover:text-foreground"@@ -475,6 +441,9 @@ function ClipToolbar({><Icon className="size-3.5" strokeWidth={tab === id ? 2.25 : 2} />{label}+ {id === "cutout" && baking && (+ <Loader2 className="absolute top-1 right-1.5 size-2.5 animate-spin" />+ )}</button>))}</div>@@ -529,7 +498,6 @@ function ClipAudioPanel({ clip, onBack }: { clip: VideoClip; onBack: () => void<ValueSliderlabel="Volume"sliderClassName="clip-volume data-horizontal:w-24"- const panCk = useSliderCheckpoint();valueClassName="w-9 text-muted-foreground"value={volume}min={0}@@ -547,25 +515,6 @@ function ClipAudioPanel({ clip, onBack }: { clip: VideoClip; onBack: () => void</Row><Row label="Mute audio"><Switch- // Which axes the crop window can travel on: the picture hangs past the box- // there, so pan has somewhere to go. Measured in frame pixels, the same- // geometry the preview's grey outline draws.- const frPx = frameOf(aspect);- const boxPx = { x: rect.x * frPx.w, y: rect.y * frPx.h, w: rect.w * frPx.w, h: rect.h * frPx.h };- const picPx =- asset?.width && asset?.height- ? contentRect(- boxPx,- asset.width,- asset.height,- clipCovers(clip),- clipZoom(clip),- clip.panX ?? 0,- clip.panY ?? 0- )- : boxPx;- const panXFree = picPx.w - boxPx.w > 1;- const panYFree = picPx.h - boxPx.h > 1;checked={clip.muted}onCheckedChange={(v) => updateClip(clip.id, { muted: v })}/>@@ -589,6 +538,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {const aspect = useEditor((s) => s.aspect);const updateClip = useEditor((s) => s.updateClip);const zoomCk = useSliderCheckpoint();+ const panCk = useSliderCheckpoint();const turnCk = useSliderCheckpoint();const fadeCk = useSliderCheckpoint();const [speedDraft, setSpeedDraft] = useState<number | null>(null);@@ -606,6 +556,25 @@ function ClipPanel({ clip }: { clip: VideoClip }) {: null;const snugMoves =!!snug && (["x", "y", "w", "h"] as const).some((k) => Math.abs(snug[k] - rect[k]) > 1e-3);+ // Which axes the crop window can travel on: the picture hangs past the box+ // there, so pan has somewhere to go. Measured in frame pixels, the same+ // geometry the preview's grey outline draws.+ const frPx = frameOf(aspect);+ const boxPx = { x: rect.x * frPx.w, y: rect.y * frPx.h, w: rect.w * frPx.w, h: rect.h * frPx.h };+ const picPx =+ asset?.width && asset?.height+ ? contentRect(+ boxPx,+ asset.width,+ asset.height,+ clipCovers(clip),+ clipZoom(clip),+ clip.panX ?? 0,+ clip.panY ?? 0+ )+ : boxPx;+ const panXFree = picPx.w - boxPx.w > 1;+ const panYFree = picPx.h - boxPx.h > 1;return (<><div className="flex flex-col gap-1 px-3.5 pb-4">diff --git a/site/src/cut/components/RemovalBrush.tsx b/site/src/cut/components/RemovalBrush.tsxindex 4fac7cf3..9082a47a 100644--- a/site/src/cut/components/RemovalBrush.tsx+++ b/site/src/cut/components/RemovalBrush.tsx@@ -3,8 +3,8 @@import { useEffect, useRef, useState } from "react";import { createPortal } from "react-dom";import { useBrushUi } from "@/cut/lib/removal/brushUi";-import { QuickSelectSession } from "@/cut/lib/removal/interactive";-import { usePreviewSelector, useSkim } from "@/cut/lib/playhead";+import { BrushSession } from "@/cut/lib/removal/brushSession";+import { usePreviewSelector } from "@/cut/lib/playhead";import { decodeRasterImageUrl } from "@/cut/lib/raster";import { useEditor } from "@/cut/lib/store";import {@@ -21,12 +21,11 @@ import {/*** The custom-removal brush on the stage: a pointer surface laid over the- * selected clip's picture while its brush session is open. Smart-select strokes- * run the on-device tap-to-select segmenter and preview the pick live under- * the pointer; plain strokes paint the mask directly. The selection shows as a- * red overlay, a loupe magnifies the pixels being worked, and every finished- * stroke lands in the doc as a seed record — the prompts and paint the hosted- * tracker replays across the whole clip. A size ring rides the pointer over+ * selected clip's picture while its brush session is open. Strokes paint the+ * mask directly. The selection shows as a red overlay, a loupe magnifies the+ * pixels being worked, and every finished stroke lands in the doc as a seed+ * record — the paint the hosted tracker replays across the whole clip. A+ * size ring rides the pointer over* the picture, and over the panel's Size row so the slider shows the* diameter it is setting.*/@@ -35,8 +34,6 @@ const LOUPE_PX = 128;const LOUPE_ZOOM = 3;/** Pointer samples closer than this (frame fractions) fold into one point. */const MIN_STEP = 0.008;-/** The most points one stroke stores as a tracker prompt. */-const PROMPT_POINTS_MAX = 24;type Frac = { x: number; y: number };@@ -50,14 +47,15 @@ export function RemovalBrush({ stage }: { stage: { w: number; h: number } }) {const selection = useEditor((s) => s.selection);const clips = useEditor((s) => s.clips);const assets = useEditor((s) => s.assets);- const skimTime = useSkim();const clip =brushClipId && selection?.kind === "clip" && selection.id === brushClipId? clips.find((c) => c.id === brushClipId) ?? null: null;const armed = !!clip && clip.removal?.mode === "custom" && !clip.hidden;+ // Preview time follows the skimmer, so the surface stays up while the+ // pointer rides the timeline and the overlay tracks the frame on screen.const tLocal = usePreviewSelector((t) => (armed && clip ? t - clip.start : -1));- if (!armed || !clip || skimTime !== null) return null;+ if (!armed || !clip) return null;const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;const len = Math.max(0.1, (clip.out - clip.in) / speed);if (tLocal < 0 || tLocal >= len) return null;@@ -79,7 +77,7 @@ function BrushSurface({}) {const tool = useBrushUi((s) => s.tool);const size = useBrushUi((s) => s.size);- const sessionRef = useRef<QuickSelectSession | null>(null);+ const sessionRef = useRef<BrushSession | null>(null);const [sessionEpoch, setSessionEpoch] = useState(0);const overlayRef = useRef<HTMLCanvasElement | null>(null);const loupeRef = useRef<HTMLCanvasElement | null>(null);@@ -106,16 +104,11 @@ function BrushSurface({/** The seeds object this surface last wrote, so the replay effect only* rebuilds the mask for outside writes — undo, redo, the panel's Reset. */const lastWritten = useRef<RemovalSeeds | undefined | null>(null);- const gesture = useRef<{- points: Frac[];- erase: boolean;- quick: boolean;- lastSeg: number;- } | null>(null);+ const gesture = useRef<{ points: Frac[]; erase: boolean } | null>(null);useEffect(() => {let alive = true;- void QuickSelectSession.open().then((s) => {+ void BrushSession.open().then((s) => {if (!alive) return;sessionRef.current = s;setSessionEpoch((e) => e + 1);@@ -141,17 +134,32 @@ function BrushSurface({const srcT = () => clip.in + Math.max(0, tLocal) * (clip.speed && clip.speed > 0 ? clip.speed : 1);- // Outside writes to the seeds rebuild the working mask from them.+ // The overlay shows the strokes recorded on the frame the preview shows:+ // the mask rebuilds when the seeds change from outside (undo, redo, the+ // panel's Reset) and when the displayed frame moves onto or off a stroke+ // frame — parking on a painted frame brings its strokes back, any other+ // frame clears them. Playback keeps the overlay down; replay decodes the+ // stored paint, which has no place inside a frame tick.const seeds = clip.removal?.seeds;+ const playing = useEditor((s) => s.playing);+ const speedNow = clip.speed && clip.speed > 0 ? clip.speed : 1;+ const srcNow = clip.in + Math.max(0, tLocal) * speedNow;+ const activeT = playing+ ? null+ : ((seeds?.paint ?? []).find((p) => Math.abs(p.t - srcNow) < 0.05)?.t ?? null);+ const lastActiveT = useRef<number | null | undefined>(undefined);useEffect(() => {const s = sessionRef.current;- if (!s || lastWritten.current === seeds) return;- lastWritten.current = seeds;+ if (!s || gesture.current) return;+ if (lastWritten.current === seeds && lastActiveT.current === activeT) return;if (!s.refreshFrame(clip.id)) return;- void s.replaySeeds(seeds, decodeSeed, srcT()).then(paintOverlay);- // srcT reads the frame the rebuild runs against; a playhead move alone- // must not re-replay, and the lastWritten guard above holds that line.- }, [seeds, sessionEpoch, clip.id]); // eslint-disable-line react-hooks/exhaustive-deps+ lastWritten.current = seeds;+ lastActiveT.current = activeT;+ void s.replaySeeds(seeds, decodeSeed, srcNow).then(paintOverlay);+ // srcNow reads the frame the rebuild runs against; within one stroke+ // bucket a playhead move alone must not re-replay, and the activeT dep+ // holds that line.+ }, [seeds, activeT, sessionEpoch, clip.id]); // eslint-disable-line react-hooks/exhaustive-depsconst paintLoupe = (p: Frac) => {const s = sessionRef.current;@@ -201,27 +209,26 @@ function BrushSurface({const s = sessionRef.current;if (!s) return;const t = srcT();- if (g.quick) {- s.commitTentative();- paintOverlay();- if (!s.quickAvailable) return;- const label: 0 | 1 = g.erase ? 0 : 1;- const kept =- g.points.length <= PROMPT_POINTS_MAX- ? g.points- : g.points.filter(- (_, i) => i % Math.ceil(g.points.length / PROMPT_POINTS_MAX) === 0- );- writeSeeds((next) => {- const at = next.prompts.findIndex((p) => Math.abs(p.t - t) < 0.02);- const points = kept.map((p) => ({ x: p.x, y: p.y, label }));- if (at >= 0)- next.prompts[at] = { ...next.prompts[at], points: [...next.prompts[at].points, ...points] };- else next.prompts.push({ t, points });- });+ paintOverlay();+ // An erase that leaves the frame blank drops the frame's stored records+ // whole — the timeline's stroke tabs leave with the paint, and no erase+ // bitmap piles up over strokes that no longer exist.+ if (g.erase && !s.hasSelection()) {+ const cur = useEditor.getState().clips.find((c) => c.id === clip.id)?.removal;+ const at = (ts: number) => Math.abs(ts - t) < 0.02;+ const had =+ !!cur?.seeds &&+ (cur.seeds.prompts.some((p) => at(p.t)) || (cur.seeds.paint ?? []).some((p) => at(p.t)));+ if (had) {+ writeSeeds((next) => {+ next.prompts = next.prompts.filter((p) => !at(p.t));+ const paint = (next.paint ?? []).filter((p) => !at(p.t));+ if (paint.length) next.paint = paint;+ else delete next.paint;+ });+ }return;}- paintOverlay();void s.paintSeed(g.points, size / 2).then((url) => {writeSeeds((next) => {const field = g.erase ? "erase" : "add";@@ -270,15 +277,10 @@ function BrushSurface({e.currentTarget.setPointerCapture(e.pointerId);s.refreshFrame(clip.id);const p = localPoint(e);- const erase = tool === "erase" || tool === "quickErase";- const quick = tool === "quick" || tool === "quickErase";- gesture.current = { points: [p], erase, quick, lastSeg: 0 };- if (quick) {- if (s.quickPreview([p], erase)) paintOverlay();- } else {- s.paintStroke([p], size / 2, erase);- paintOverlay();- }+ const erase = tool === "erase";+ gesture.current = { points: [p], erase };+ s.paintStroke([p], size / 2, erase);+ paintOverlay();updatePointer(p);setPainting(true);paintLoupe(p);@@ -293,16 +295,8 @@ function BrushSurface({const last = g.points[g.points.length - 1];if (Math.hypot(p.x - last.x, p.y - last.y) < MIN_STEP) return;g.points.push(p);- if (g.quick) {- const now = performance.now();- if (now - g.lastSeg > 60) {- g.lastSeg = now;- if (s.quickPreview(g.points, g.erase)) paintOverlay();- }- } else {- s.paintStroke([last, p], size / 2, g.erase);- paintOverlay();- }+ s.paintStroke([last, p], size / 2, g.erase);+ paintOverlay();paintLoupe(p);};@@ -312,7 +306,6 @@ function BrushSurface({setPainting(false);if (!g) return;if (commit) finishStroke(g);- else sessionRef.current?.dropTentative();};// The same geometry the compositor draws: the picture's rect inside thediff --git a/site/src/cut/components/RemovalPanel.tools.ts b/site/src/cut/components/RemovalPanel.tools.tsindex 8eb822f8..ee304a85 100644--- a/site/src/cut/components/RemovalPanel.tools.ts+++ b/site/src/cut/components/RemovalPanel.tools.ts@@ -8,42 +8,39 @@*/import {- CHROMA_DEFAULT_INTENSITY,- CHROMA_DEFAULT_SOFTNESS,- CHROMA_DEFAULT_SPILL,STROKE_DEFAULT_WIDTH,+ STROKE_FEATHER_MAX,STROKE_OFFSET_MAX,STROKE_STYLE_LABELS,STROKE_STYLES,STROKE_WIDTH_MAX,} from "@donkeycut/effects-kit";-import { num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";+import { bool, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";export const REMOVAL_TOOLS = [{name: "set_removal",- description: `Cut a video clip's background away — the Inspector's Cutout tab, on any track. Modes: "auto" mattes the person in the shot with AI; "custom" mattes whatever \`subject\` describes in a few words ("the dog") and tracks every match through the clip — picking one exact instance by hand is the panel's brush flow, so send the user there for that; "chroma" keys out a backdrop color (green screen) with intensity/softness/spill; "off" removes the whole cutout, stroke and background fill included. The AI mattes prepare in the background — wait_for_renders covers that work — and a long clip tracks in parts automatically, so length needs no special handling. Where the background was, lower tracks or the project background show through; set_removal_background fills that area within the clip itself. Read the background-removal skill for the full recipes.`,+ description: `Cut part of a video clip's picture away — the Inspector's Cutout tab, on any track. \`remove\` picks the direction: "background" (default) keeps the selection and removes everything around it; "subject" removes the selection itself and keeps the rest. \`mode\` picks how the selection is found: "auto" mattes the person in the shot with the free on-device matte — this tool call starts it (in the panel the bake waits for the user's Apply press), and a green-screen or plain-backdrop shot needs nothing more, the matte keys it; "custom" mattes whatever \`subject\` describes in a few words ("the dog") and tracks every match through the clip — picking one exact instance by hand is the panel's brush flow, so send the user there for that; "off" switches the cutout off — the picture shows plain, but the baked matte and every setting stay on the clip, so switching back on is instant and re-bills nothing. The selection is the same in both directions, so flipping \`remove\` on an existing cutout re-bakes nothing. The AI mattes prepare in the background — wait_for_renders covers that work — and a long clip tracks in parts automatically, so length needs no special handling. Where pixels were removed, lower tracks or the project background show through; set_removal_background fills that area within the clip itself. Read the background-removal skill for the full recipes.`,inputSchema: obj({clipId: str("Video clip id"),mode: {type: "string",- enum: ["off", "auto", "custom", "chroma"],- description: "Cutout mode",+ enum: ["off", "auto", "custom"],+ description: "How the selection is found",},+ remove: {+ type: "string",+ enum: ["background", "subject"],+ description:+ 'What goes: "background" (default) keeps the selection, "subject" removes it and keeps the rest of the picture',+ },+ refine: bool(+ 'Auto mode: also run the hosted quality pass for hair and edge detail once the free matte lands — spends credits like generation, so pass it only when the user asks for the upgrade (the panel\'s "Apply")'+ ),subject: str('Custom mode: what to keep, in a few words ("the dog", "the red car") — every match is matted and tracked'),- color: str(- 'Chroma key color "#rrggbb" (omitted: sampled from the footage borders, where a backdrop lives)'- ),- intensity: num(- `Chroma tolerance 0..1 — how far from the key a color still keys out (default ${CHROMA_DEFAULT_INTENSITY})`- ),- softness: num(`Chroma edge rolloff 0..1 (default ${CHROMA_DEFAULT_SOFTNESS})`),- spill: num(- `Chroma spill suppression 0..1 — pulls key-colored fringe off the kept pixels (default ${CHROMA_DEFAULT_SPILL})`- ),},["clipId", "mode"]),@@ -63,6 +60,9 @@ export const REMOVAL_TOOLS = [width: num(`Ink thickness, design px at the 1080 short side, 1..${STROKE_WIDTH_MAX} (default ${STROKE_DEFAULT_WIDTH})`),+ feather: num(+ `Edge softness: the ink blurred by this many design px, 0..${STROKE_FEATHER_MAX} (default 0, crisp)`+ ),offset_x: num(`Offset style: silhouette displacement right, design px, -${STROKE_OFFSET_MAX}..${STROKE_OFFSET_MAX}`),diff --git a/site/src/cut/components/RemovalPanel.tsx b/site/src/cut/components/RemovalPanel.tsxindex b51e1ea3..e240e089 100644--- a/site/src/cut/components/RemovalPanel.tsx+++ b/site/src/cut/components/RemovalPanel.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useRef, useState } from "react";-import { Ban, ChevronLeft, Loader2, WandSparkles } from "lucide-react";+import { ChevronLeft, Loader2 } from "lucide-react";import {Select,SelectContent,@@ -9,30 +9,22 @@ import {SelectTrigger,SelectValue,} from "@/components/ui/select";+import { BRUSH_SIZE_MAX, BRUSH_SIZE_MIN, useBrushUi } from "@/cut/lib/removal/brushUi";import {- BRUSH_SIZE_MAX,- BRUSH_SIZE_MIN,- useBrushUi,- type BrushTool,-} from "@/cut/lib/removal/brushUi";-import {+ cancelMatteBake,confirmMatteBake,ensureMatteBake,retryMatteBake,useMatteBakes,type MatteBakeJob,} from "@/cut/lib/removal/bakeJobs";-import { clipKeyColor, suggestKeyColor } from "@/cut/lib/removal/keyColor";import { HostedErrorText } from "@/cut/components/hostedError";import { useEditor } from "@/cut/lib/store";import { playheadAt } from "@/cut/lib/playhead";-import { usePanelView } from "@/cut/lib/panelViews";import {- CHROMA_DEFAULT_INTENSITY,- CHROMA_DEFAULT_SOFTNESS,- CHROMA_DEFAULT_SPILL,paintStrokeInk,STROKE_DEFAULT_WIDTH,+ STROKE_FEATHER_MAX,STROKE_OFFSET_MAX,STROKE_WIDTH_MAX,} from "@donkeycut/effects-kit";@@ -42,46 +34,41 @@ import {STROKE_STYLE_LABELS,STROKE_STYLES,type ClipRemoval,- type RemovalMode,type StrokeStyleId,type VideoClip,+ type MediaAsset,} from "@/cut/lib/types";+import { PICKED_RING } from "@/cut/lib/assetPick";import { ColorField } from "@/cut/components/ColorField";-import { Row, useSliderCheckpoint } from "@/cut/components/panelBits";+import { Row, Section, useSliderCheckpoint } from "@/cut/components/panelBits";import { parseNumberInput } from "@/cut/components/ScrubValue";import { ValueSlider } from "@/cut/components/ValueSlider";import { cn } from "@/lib/utils";import { ScrollArea } from "@/components/ui/scroll-area";-import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from "@/components/ui/tooltip";/**- * The clip panel's Cutout view: labeled inspector rows. Layer picks what the- * rows below edit — Removal (the mode and its controls), Stroke (ink around- * the kept silhouette), Background (the fill behind it). Removal leads with- * Auto — most people want the background gone in one pick — and brushing sits- * underneath as the refinement. Every write lands on the one `clip.removal`- * field; drafts stream through the transient updater under one checkpoint per- * gesture, the way the color panel writes its grade.+ * The clip panel's Cutout view: one flat pane. A segmented Remove control+ * leads — Off, Background (keep the person, drop the rest), Subject (drop the+ * person, keep the rest), Custom (brush what stays) — and every bake starts+ * from the Apply button, so a pick alone runs nothing.+ * The two complements stack under their own section labels:+ * Stroke (ink around the selection's silhouette) and Fill (the backdrop+ * painted behind the kept picture; its label stays clear of "Background",+ * which the Remove control uses for the direction). Every write lands on the+ * one `clip.removal` field; drafts stream through the transient updater under+ * one checkpoint per gesture, the way the color panel writes its grade.*/-const LAYERS = [- { id: "removal", label: "Removal" },- { id: "stroke", label: "Stroke" },+/** The one choice: what goes, and how the selection is found. Background and+ * Subject share the person matte and differ only in direction; Custom is the+ * brush flow, where the paint marks what stays. */+const TARGETS = [+ { id: "off", label: "Off" },{ id: "background", label: "Background" },-] as const;-type Layer = (typeof LAYERS)[number]["id"];--const MODES: { id: RemovalMode | "off"; label: string }[] = [- { id: "auto", label: "Auto" },+ { id: "subject", label: "Subject" },{ id: "custom", label: "Custom" },- { id: "chroma", label: "Chroma" },- { id: "off", label: "Off" },-];+] as const;+type Target = (typeof TARGETS)[number]["id"];/** Shared write path: transiently while a gesture is live, committed at its* end, one checkpoint per gesture. */@@ -98,48 +85,9 @@ function useRemovalWriter(clip: VideoClip) {return { draft, commit };}-/** One inspector row: a label and a compact dropdown, the shape every row in- * this panel shares. */-function RowSelect<T extends string>({- label,- value,- options,- onChange,- hook,-}: {- label: string;- value: T;- options: readonly { id: T; label: string }[];- onChange: (next: T) => void;- hook: string;-}) {- return (- <Row label={label}>- <Select- value={value}- items={Object.fromEntries(options.map((o) => [o.id, o.label]))}- onValueChange={(v) => onChange(v as T)}- >- <SelectTrigger className={`${hook} h-8 w-36 text-[12px]`}>- <SelectValue />- </SelectTrigger>- <SelectContent>- {options.map((o) => (- <SelectItem key={o.id} value={o.id} className={`${hook}-${o.id} text-[12px]`}>- {o.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </Row>- );-}-export function RemovalPanel({ clip, onBack }: { clip: VideoClip; onBack: () => void }) {- // The open layer holds for the session per clip, so leaving the panel and- // coming back lands on the same rows.- const [layer, setLayer] = usePanelView<Layer>(`cutout-layer:${clip.id}`, "removal");const removal = clip.removal;+ const { commit } = useRemovalWriter(clip);const peeking = useEditor((s) => s.removalPeek === clip.id);// Peek only while held; a switched selection or a closed panel lets go too.@@ -153,10 +101,7 @@ export function RemovalPanel({ clip, onBack }: { clip: VideoClip; onBack: () =>// The bake the clip's AI matte owes, restarted whenever trims or seeds move// it. The doc sweep covers the closed-panel cases; this keeps the open// panel immediate.- const fp =- removal && (removal.mode === "auto" || removal.mode === "custom")- ? removalFingerprint(clip.assetId, removal)- : null;+ const fp = removal && !removal.off ? removalFingerprint(clip.assetId, removal) : null;useEffect(() => {if (fp) ensureMatteBake(clip.id);}, [clip.id, fp, clip.in, clip.out]);@@ -164,13 +109,13 @@ export function RemovalPanel({ clip, onBack }: { clip: VideoClip; onBack: () =>// The brush session follows custom mode while its panel is open.useEffect(() => {const brush = useBrushUi.getState();- if (removal?.mode === "custom") brush.open(clip.id);+ if (removal?.mode === "custom" && !removal.off) brush.open(clip.id);else if (brush.clipId === clip.id) brush.close();return () => {const b = useBrushUi.getState();if (b.clipId === clip.id) b.close();};- }, [clip.id, removal?.mode]);+ }, [clip.id, removal?.mode, removal?.off]);return (<div className="flex min-h-0 flex-1 flex-col">@@ -188,21 +133,11 @@ export function RemovalPanel({ clip, onBack }: { clip: VideoClip; onBack: () =></div></div><ScrollArea- key={layer}className="min-h-0 flex-1"viewportClassName="overscroll-contain"contentClassName="flex flex-col gap-1 px-3.5 pt-1 pb-4">- <RowSelect- label="Layer"- value={layer}- options={LAYERS}- onChange={setLayer}- hook="clip-cutout-layer"- />- {layer === "removal" && <RemovalView clip={clip} />}- {layer === "stroke" && <StrokeView clip={clip} />}- {layer === "background" && <BackgroundView clip={clip} />}+ <RemovalView clip={clip} />{removalActive(removal) && (<Row label="Original"><button@@ -220,7 +155,31 @@ export function RemovalPanel({ clip, onBack }: { clip: VideoClip; onBack: () =></button></Row>)}- {layer === "removal" && <RemovalActions clip={clip} />}+ <RemovalActions clip={clip} />+ {removal && removalActive(removal) && (+ <>+ <Section+ title="Stroke"+ info="Ink drawn around the cutout's silhouette — pick a style, color, and width."+ enabled={!!removal.stroke}+ onEnabledChange={(v) =>+ commit({ ...removal, stroke: v ? { style: "solid", color: "#ffffff" } : undefined })+ }+ >+ <StrokeView clip={clip} />+ </Section>+ <Section+ title="Fill"+ info="A color or image painted into the removed area, inside the clip's own frame."+ enabled={!!removal.backdrop && removal.backdrop.kind !== "none"}+ onEnabledChange={(v) =>+ commit({ ...removal, backdrop: v ? { kind: "color", color: "#101014" } : undefined })+ }+ >+ <BackgroundView clip={clip} />+ </Section>+ </>+ )}</ScrollArea></div>);@@ -230,68 +189,101 @@ export function RemovalPanel({ clip, onBack }: { clip: VideoClip; onBack: () =>/* Removal *//* ------------------------------------------------------------------ */-/** The suggested key: the live frame when a decoder shows the clip, its own- * decoded in-point frame otherwise, and green as the visible last resort the- * user corrects with the eyedropper. */-async function keyColorOf(clip: VideoClip): Promise<string> {- const live = suggestKeyColor(clip.id);- if (live) return live;- const asset = useEditor.getState().assets.find((a) => a.id === clip.assetId);- return (asset && (await clipKeyColor(asset, clip))) || "#00ff00";-}--/** The Mode row: every layer's entry into the cutout. Stroke and Background- * render it too while no mode is picked, so the pick happens in place. */-function ModeRow({ clip }: { clip: VideoClip }) {+/** The Remove control: one segmented row, every option in sight. A pick+ * only sets the direction — Apply starts the bake. Background and Subject+ * share the free person matte, so switching between them just flips the+ * direction and a baked matte carries over. Custom opens the brush flow,+ * where the paint marks what stays. */+function ModePicker({ clip }: { clip: VideoClip }) {const { commit } = useRemovalWriter(clip);const removal = clip.removal;- const mode: RemovalMode | "off" = removal?.mode ?? "off";+ // One job at a time: while a bake runs, the other choices wait — Cancel is+ // the way to change course mid-bake.+ const running = useMatteBakes((s) => s.jobs[clip.id]?.status === "running");+ const target: Target =+ !removal || removal.off+ ? "off"+ : removal.mode === "custom"+ ? "custom"+ : removal.invert+ ? "subject"+ : "background";- const pickMode = (next: RemovalMode | "off") => {- if (next === mode) return;+ const pick = (next: Target) => {+ if (next === target) return;+ // Off keeps the removal and its baked matte on the clip — it just stops+ // rendering and baking — so switching back on costs nothing.if (next === "off") {- commit(undefined);- return;- }- const base: ClipRemoval = { ...removal, mode: next };- if (next === "chroma" && !base.chroma) {- // The key defaults to the footage's border color. A clip away from the- // playhead has no live frame, so its own in-point frame decodes first.- void keyColorOf(clip).then((color) => commit({ ...base, chroma: { color } }));+ commit({ ...removal!, off: true });return;}+ const mode = next === "custom" ? ("custom" as const) : ("auto" as const);+ const base: ClipRemoval = { ...removal, mode };+ delete base.off;+ delete base.invert;+ // A new mode returns to un-applied — its bake waits for Apply. Flipping+ // Background/Subject stays inside one matte, so the ask carries over.+ if (removal?.mode !== mode) delete base.requested;+ if (next === "subject") base.invert = true;if (next === "custom" && !base.seeds) base.seeds = { prompts: [] };commit(base);};return (- <RowSelect- label="Mode"- value={mode}- options={MODES}- onChange={pickMode}- hook="clip-removal-mode"- />+ <div className="pb-1">+ <div className="pb-1.5 text-[13px] text-muted-foreground">Remove</div>+ <div className="clip-removal-target flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">+ {TARGETS.map((o) => (+ <button+ key={o.id}+ type="button"+ aria-pressed={target === o.id}+ disabled={running && target !== o.id}+ className={cn(+ `clip-removal-target-${o.id} whitespace-nowrap rounded-md px-2 py-1 transition-colors`,+ // Every label carries the same padding, sized so all four fit+ // the pane at their natural width — a squeezed row would shrink+ // the last segment's padding. The real options grow from their+ // own width, so leftover space spreads evenly and Off stays at+ // its size.+ o.id !== "off" && "grow",+ target === o.id+ ? "bg-neutral-900 text-white"+ : "text-muted-foreground hover:text-foreground",+ "disabled:pointer-events-none disabled:opacity-40"+ )}+ onClick={() => pick(o.id)}+ >+ {o.label}+ </button>+ ))}+ </div>+ </div>);}function RemovalView({ clip }: { clip: VideoClip }) {- const { draft, commit } = useRemovalWriter(clip);- const removal = clip.removal;- const mode: RemovalMode | "off" = removal?.mode ?? "off";-return (<>- <ModeRow clip={clip} />- {mode === "custom" && <CustomControls clip={clip} />}- {mode === "chroma" && removal?.chroma && (- <ChromaControls removal={removal} draft={draft} commit={commit} />- )}+ <ModePicker clip={clip} />+ {clip.removal?.mode === "custom" && !clip.removal.off && <CustomControls clip={clip} />}</>);}-function BakeStatus({ clipId, job }: { clipId: string; job: MatteBakeJob | undefined }) {+function BakeStatus({+ clipId,+ job,+ label,+ onCancel,+}: {+ clipId: string;+ job: MatteBakeJob | undefined;+ /** What the running bake is actually doing — the work is the selection,+ * shared by both directions, so the line never claims a side. */+ label: string;+ onCancel?: () => void;+}) {if (!job) return null;if (job.status === "error")return (@@ -309,14 +301,29 @@ function BakeStatus({ clipId, job }: { clipId: string; job: MatteBakeJob | undef</div>);return (- <div className="flex items-center gap-2 pt-1 text-[11.5px] text-muted-foreground">- <Loader2 className="size-3 shrink-0 animate-spin" />- <span>{job.quality === "hq" ? "Refining the cutout…" : "Preparing the cutout…"}</span>- <span className="ml-auto font-mono tabular-nums">- {Math.round(job.progress * 100)}%- {job.secondsLeft !== undefined && job.etaAt !== undefined && (- <TickingEta secondsLeft={job.secondsLeft} etaAt={job.etaAt} />+ <div className="flex items-start justify-between gap-2 pt-1 text-[11.5px] text-muted-foreground">+ <span className="flex min-w-0 items-center gap-2 py-0.5">+ <Loader2 className="size-3 shrink-0 animate-spin" />+ <span>{label}</span>+ </span>+ <span className="flex shrink-0 flex-col items-end gap-1">+ {onCancel && (+ <button+ type="button"+ className="clip-removal-cancel rounded-md border border-input px-2 py-0.5 font-medium transition-colors hover:text-foreground"+ onClick={onCancel}+ >+ Cancel+ </button>)}+ <span className="font-mono tabular-nums">+ {Math.round(job.progress * 100)}%+ {job.secondsLeft !== undefined && job.etaAt !== undefined ? (+ <TickingEta secondsLeft={job.secondsLeft} etaAt={job.etaAt} />+ ) : job.startedAt !== undefined ? (+ <TickingElapsed startedAt={job.startedAt} />+ ) : null}+ </span></span></div>);@@ -324,6 +331,18 @@ function BakeStatus({ clipId, job }: { clipId: string; job: MatteBakeJob | undef/** The countdown between progress steps: each estimate ticks down in real* time from the moment it was stamped until the next one replaces it. */+/** The running time, ticking up from the bake's start until the pace+ * estimate lands and the countdown takes the slot. */+function TickingElapsed({ startedAt }: { startedAt: number }) {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const id = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(id);+ }, []);+ const s = Math.max(0, Math.round((now - startedAt) / 1000));+ return `, ${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;+}+function TickingEta({ secondsLeft, etaAt }: { secondsLeft: number; etaAt: number }) {const [now, setNow] = useState(etaAt);useEffect(() => {@@ -337,29 +356,32 @@ function TickingEta({ secondsLeft, etaAt }: { secondsLeft: number; etaAt: numberfunction CustomControls({ clip }: { clip: VideoClip }) {const tool = useBrushUi((s) => s.tool);const size = useBrushUi((s) => s.size);- // The four tools are two axes: what a stroke does (keep or erase) and how- // it lands (smart object pick or plain paint).- const erasing = tool === "erase" || tool === "quickErase";- const smart = tool === "quick" || tool === "quickErase";- const pick = (erase: boolean, sm: boolean): BrushTool =>- sm ? (erase ? "quickErase" : "quick") : erase ? "erase" : "brush";+ const erasing = tool === "erase";// Strokes live on the frames they were drawn on, so after playing away the// overlay looks empty — this seeks back to a stroke frame, cycling through- // them when several frames carry paint.+ // them when several frames carry paint. Only frames inside the clip's+ // current trim count: a trim can move past stored paint, and a seek to a+ // frame the clip no longer plays would land off the clip.const seeds = clip.removal?.seeds;- const strokeTimes = Array.from(- new Set([...(seeds?.prompts ?? []), ...(seeds?.paint ?? [])].map((s) => s.t))- ).sort((a, b) => a - b);+ const strokeTimes = Array.from(new Set((seeds?.paint ?? []).map((s) => s.t)))+ .filter((t) => t >= clip.in - 0.05 && t <= clip.out + 0.05)+ .sort((a, b) => a - b);const showStrokes = () => {if (!strokeTimes.length) return;const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;const srcNow = clip.in + Math.max(0, playheadAt() - clip.start) * speed;const next = strokeTimes.find((t) => t > srcNow + 0.05) ?? strokeTimes[0];- useEditor.getState().seek(clip.start + (next - clip.in) / speed);+ const end = clip.start + (clip.out - clip.in) / speed;+ useEditor+ .getState()+ .seek(Math.min(Math.max(clip.start, clip.start + (next - clip.in) / speed), end - 0.001));};return (<>- <Row label="Tool">+ <Row+ label="Tool"+ info={clip.removal?.invert ? "Paint to pick what goes" : "Paint to pick what stays"}+ ><div className="clip-brush-tool flex rounded-lg border border-input p-0.5">{([false, true] as const).map((erase) => (<button@@ -372,35 +394,12 @@ function CustomControls({ clip }: { clip: VideoClip }) {: "text-muted-foreground hover:text-foreground")}aria-pressed={erasing === erase}- onClick={() => useBrushUi.getState().setTool(pick(erase, smart))}+ onClick={() => useBrushUi.getState().setTool(erase ? "erase" : "brush")}>{erase ? "Erase" : "Brush"}</button>))}</div>- <TooltipProvider>- <Tooltip>- <TooltipTrigger- render={- <button- type="button"- className={cn(- "clip-brush-smart grid size-[30px] place-items-center rounded-lg border transition-colors",- smart- ? "border-neutral-900 bg-neutral-900 text-white"- : "border-input text-muted-foreground hover:text-foreground"- )}- aria-pressed={smart}- aria-label="Smart select"- onClick={() => useBrushUi.getState().setTool(pick(erasing, !smart))}- >- <WandSparkles className="size-3.5" />- </button>- }- />- <TooltipContent side="bottom">Smart select</TooltipContent>- </Tooltip>- </TooltipProvider></Row><div className="clip-brush-size-row"><Row label="Size">@@ -430,36 +429,74 @@ function CustomControls({ clip }: { clip: VideoClip }) {</button></Row>)}- <p className="pt-1 text-[12px] text-muted-foreground">- Paint on the preview to pick what stays.- </p></>);}-/** The panel floor: the bake's status line and its actions. The bake runs- * only from here — Start (auto) or Apply (custom) marks the removal- * requested, so picking a mode by itself never spends compute. */+/** The panel floor: the bake's status line and its actions. Nothing bakes+ * on its own — Apply starts each rung: auto's free person matte, then the+ * hosted quality pass; custom's tracked bake for the painted selection. */function RemovalActions({ clip }: { clip: VideoClip }) {const job = useMatteBakes((s) => s.jobs[clip.id]);const { commit } = useRemovalWriter(clip);const r = clip.removal;- if (!r || (r.mode !== "auto" && r.mode !== "custom")) return null;+ if (!r || r.off) return null;const custom = r.mode === "custom";+ // Paint outside the clip's current trim can't seed this bake (the tracker+ // drops it), so it doesn't count as a selection.+ const inTrim = (t: number) => t >= clip.in - 0.05 && t <= clip.out + 0.05;const hasSelection =- custom && !!(r.seeds?.prompts.length || r.seeds?.paint?.length || r.subject?.trim());+ custom &&+ !!(+ r.seeds?.prompts.some((s) => inTrim(s.t)) ||+ r.seeds?.paint?.some((s) => inTrim(s.t)) ||+ r.subject?.trim()+ );const running = job?.status === "running";+ const showStart = !custom && !r.matte && !r.requested && !running;+ const showRefine = !custom && r.matte?.quality === "local" && !r.refine && !running;+ const showCustom = custom && hasSelection && !running;const start = () => {- commit({ ...r, requested: true });- if (custom) confirmMatteBake(clip.id);- else ensureMatteBake(clip.id);+ if (custom) {+ commit({ ...r, requested: true });+ confirmMatteBake(clip.id);+ } else if (!r.matte) {+ commit({ ...r, requested: true });+ ensureMatteBake(clip.id);+ } else {+ commit({ ...r, refine: true });+ ensureMatteBake(clip.id);+ }};- const showStart = !custom && !r.requested && !running;- const showCustom = custom && hasSelection && !running;+ // Cancel by rung: the quality pass falls back to what stands (auto keeps+ // the quick matte, custom returns to un-applied — its paid ticket resumes+ // a re-Apply); cancelling the free bake clears the ask, so the mode stays+ // picked and the sweep restarts nothing until the next Apply.+ const cancel = !running+ ? undefined+ : () => {+ if (job!.quality === "hq") {+ commit(custom ? { ...r, requested: undefined } : { ...r, refine: undefined });+ } else {+ commit({ ...r, requested: undefined });+ }+ cancelMatteBake(clip.id);+ };return (<>- <BakeStatus clipId={clip.id} job={job} />- {(showStart || showCustom) && (+ <BakeStatus+ clipId={clip.id}+ job={job}+ label={+ custom+ ? "Tracking the selection…"+ : job?.quality === "hq"+ ? "Refining the person matte…"+ : "Finding the person…"+ }+ onCancel={cancel}+ />+ {(showStart || showRefine || showCustom) && (<div className="flex items-center justify-end gap-1.5 pt-1">{showCustom && (<button@@ -481,11 +518,11 @@ function RemovalActions({ clip }: { clip: VideoClip }) {type="button"className={cn("shrink-0 rounded-md bg-neutral-900 px-2.5 py-0.5 text-[11.5px] font-medium text-white transition-colors hover:bg-neutral-700",- custom ? "clip-brush-apply" : "clip-removal-start"+ custom ? "clip-brush-apply" : "clip-removal-refine")}onClick={start}>- {custom ? "Apply" : "Start"}+ Apply</button></div>)}@@ -493,69 +530,28 @@ function RemovalActions({ clip }: { clip: VideoClip }) {);}-function ChromaControls({- removal,- draft,- commit,-}: {- removal: ClipRemoval;- draft: (r: ClipRemoval) => void;- commit: (r: ClipRemoval) => void;-}) {- const key = removal.chroma!;- const setKey = (patch: Partial<typeof key>, live?: boolean) =>- (live ? draft : commit)({ ...removal, chroma: { ...key, ...patch } });- const pct = (v: number | undefined, fallback: number) => Math.round((v ?? fallback) * 100);- const slider = (- label: string,- field: "intensity" | "softness" | "spill",- fallback: number- ) => (- <Row label={label}>- <ValueSlider- label={label}- sliderClassName={`clip-chroma-${field} data-horizontal:w-24`}- valueClassName="w-9 text-muted-foreground"- value={pct(key[field], fallback)}- min={0}- max={100}- step={1}- format={(v) => `${Math.round(v)}%`}- parse={parseNumberInput}- onDraft={(v) => setKey({ [field]: v / 100 }, true)}- onCommit={(v) => setKey({ [field]: v / 100 })}- />- </Row>- );- return (- <>- <Row label="Key color">- <ColorField- value={key.color}- label="Key color"- onBegin={() => {}}- onLive={(hex) => setKey({ color: hex }, true)}- onCommit={(hex) => setKey({ color: hex })}- />- </Row>- {slider("Intensity", "intensity", CHROMA_DEFAULT_INTENSITY)}- {slider("Softness", "softness", CHROMA_DEFAULT_SOFTNESS)}- {slider("Spill", "spill", CHROMA_DEFAULT_SPILL)}- </>- );-}-/* ------------------------------------------------------------------ *//* Stroke *//* ------------------------------------------------------------------ */-/** A blob silhouette drawn into `ctx`, the stand-in subject the style tiles- * ink around. */-function paintBlob(ctx: CanvasRenderingContext2D, w: number, h: number, fill: string) {+/** A person silhouette drawn into `ctx`, the stand-in subject the style+ * tiles ink around: the user-icon figure filled — a floating round head+ * over a shoulder dome, with clear air between the two so the ink traces+ * each shape the way it traces a real matte's edges. Proportions follow the+ * icon's 24-grid (head r 4 at y 7, shoulders 14 wide from y 15 to 21). */+function paintPerson(ctx: CanvasRenderingContext2D, w: number, h: number, fill: string) {+ const s = h;ctx.fillStyle = fill;ctx.beginPath();- ctx.ellipse(w * 0.5, h * 0.62, w * 0.22, h * 0.3, 0, 0, Math.PI * 2);- ctx.ellipse(w * 0.5, h * 0.3, w * 0.13, h * 0.17, 0, 0, Math.PI * 2);+ ctx.arc(w * 0.5, s * 0.3, s * 0.165, 0, Math.PI * 2);+ ctx.fill();+ ctx.beginPath();+ ctx.roundRect(w * 0.5 - s * 0.3, s * 0.61, s * 0.6, s * 0.31, [+ s * 0.155,+ s * 0.155,+ s * 0.05,+ s * 0.05,+ ]);ctx.fill();}@@ -582,7 +578,7 @@ function StrokeTile({sil.width = w;sil.height = h;const sctx = sil.getContext("2d")!;- paintBlob(sctx, w, h, "#ffffff");+ paintPerson(sctx, w, h, "#ffffff");const ink = document.createElement("canvas");ink.width = w;ink.height = h;@@ -591,7 +587,7 @@ function StrokeTile({ictx.globalCompositeOperation = "source-in";ictx.fillStyle = color;ictx.fillRect(0, 0, w, h);- paintBlob(ctx, w, h, "#52525b");+ paintPerson(ctx, w, h, "#52525b");ctx.globalCompositeOperation = "destination-over";ctx.drawImage(ink, 0, 0);ctx.globalCompositeOperation = "source-over";@@ -601,31 +597,30 @@ function StrokeTile({type="button"aria-pressed={selected}className={cn(- `clip-stroke-${style} flex flex-col items-center gap-1 rounded-lg border p-1.5 pb-1 text-[10.5px] font-medium transition-colors`,- selected- ? "border-neutral-900 text-foreground"- : "border-input text-muted-foreground hover:text-foreground"+ `clip-stroke-${style} flex flex-col items-center gap-1.5 text-[10.5px] font-medium outline-none transition-colors`,+ selected ? "text-foreground" : "text-muted-foreground hover:text-foreground")}onClick={onPick}>- <canvas ref={ref} width={96} height={64} className="w-full rounded bg-neutral-950/90" />- {STROKE_STYLE_LABELS[style]}+ <canvas+ ref={ref}+ width={96}+ height={64}+ className={cn(+ "w-full rounded-lg border border-border bg-neutral-950/90",+ selected && PICKED_RING+ )}+ />+ <span className="leading-none">{STROKE_STYLE_LABELS[style]}</span></button>);}+/** The Stroke section, rendered only under an active cutout. */function StrokeView({ clip }: { clip: VideoClip }) {const { draft, commit } = useRemovalWriter(clip);const removal = clip.removal;- if (!removal)- return (- <>- <ModeRow clip={clip} />- <p className="pt-1 text-[12px] text-muted-foreground">- The stroke draws around what the cutout keeps.- </p>- </>- );+ if (!removal) return null;const stroke = removal.stroke;const color = stroke?.color ?? "#ffffff";const setStroke = (patch: Partial<NonNullable<typeof stroke>>, live?: boolean) =>@@ -635,23 +630,7 @@ function StrokeView({ clip }: { clip: VideoClip }) {});return (<>- <div className="grid grid-cols-3 gap-1.5 pt-1">- <button- type="button"- aria-pressed={!stroke}- className={cn(- "clip-stroke-none flex flex-col items-center justify-center gap-1 rounded-lg border p-1.5 pb-1 text-[10.5px] font-medium transition-colors",- !stroke- ? "border-neutral-900 text-foreground"- : "border-input text-muted-foreground hover:text-foreground"- )}- onClick={() => commit({ ...removal, stroke: undefined })}- >- <span className="grid aspect-[3/2] w-full place-items-center rounded bg-neutral-950/90 text-neutral-500">- <Ban className="size-4" />- </span>- None- </button>+ <div className="grid grid-cols-3 gap-2 pt-1">{STROKE_STYLES.map((s) => (<StrokeTilekey={s}@@ -687,6 +666,22 @@ function StrokeView({ clip }: { clip: VideoClip }) {onCommit={(v) => setStroke({ width: v })}/></Row>+ <Row label="Feather">+ <ValueSlider+ label="Feather"+ sliderClassName="clip-stroke-feather data-horizontal:w-24"+ valueClassName="w-9 text-muted-foreground"+ value={stroke.feather ?? 0}+ min={0}+ max={STROKE_FEATHER_MAX}+ step={1}+ snap={[0]}+ format={(v) => `${Math.round(v)}`}+ parse={parseNumberInput}+ onDraft={(v) => setStroke({ feather: v }, true)}+ onCommit={(v) => setStroke({ feather: v || undefined })}+ />+ </Row>{stroke.style === "offset" && (<><Row label="Horizontal">@@ -733,25 +728,34 @@ function StrokeView({ clip }: { clip: VideoClip }) {/* Background *//* ------------------------------------------------------------------ */+/** A backdrop image choice, in the trigger and the dropdown alike: the+ * picture itself leads, since the file's name says nothing about it. */+function BackdropImageOption({ asset, thumb }: { asset: MediaAsset; thumb: string }) {+ return (+ <span className="flex min-w-0 items-center gap-2">+ <img+ src={asset.url}+ alt=""+ draggable={false}+ className={cn("shrink-0 rounded border border-black/10 object-cover", thumb)}+ />+ <span className="truncate">{asset.name}</span>+ </span>+ );+}++/** The Fill section, rendered only under an active cutout. */function BackgroundView({ clip }: { clip: VideoClip }) {const { draft, commit } = useRemovalWriter(clip);const removal = clip.removal;const assets = useEditor((s) => s.assets);const images = assets.filter((a) => a.type === "image" && !a.origin);- if (!removal)- return (- <>- <ModeRow clip={clip} />- <p className="pt-1 text-[12px] text-muted-foreground">- The background fills the area the cutout removes.- </p>- </>- );+ if (!removal) return null;const backdrop = removal.backdrop;const kind = backdrop?.kind ?? "none";const setBackdrop = (b: ClipRemoval["backdrop"], live?: boolean) =>(live ? draft : commit)({ ...removal, backdrop: b });- const pill = (id: "none" | "color" | "image", label: string) => (+ const pill = (id: "color" | "image", label: string) => (<buttonkey={id}type="button"@@ -761,11 +765,9 @@ function BackgroundView({ clip }: { clip: VideoClip }) {)}onClick={() =>setBackdrop(- id === "none"- ? undefined- : id === "color"- ? { kind: "color", color: backdrop?.color ?? "#101014" }- : { kind: "image", color: backdrop?.color, assetId: backdrop?.assetId ?? images[0]?.id }+ id === "color"+ ? { kind: "color", color: backdrop?.color ?? "#101014" }+ : { kind: "image", color: backdrop?.color, assetId: backdrop?.assetId ?? images[0]?.id })}>@@ -775,7 +777,6 @@ function BackgroundView({ clip }: { clip: VideoClip }) {return (<><div className="flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">- {pill("none", "None")}{pill("color", "Color")}{pill("image", "Image")}</div>@@ -795,13 +796,32 @@ function BackgroundView({ clip }: { clip: VideoClip }) {Import an image into Media to use it as the background.</p>) : (- <RowSelect- label="Image"- value={backdrop?.assetId ?? images[0].id}- options={images.map((a) => ({ id: a.id, label: a.name }))}- onChange={(id) => setBackdrop({ kind: "image", assetId: id })}- hook="clip-backdrop-image"- />+ <Row label="Image">+ <Select+ value={backdrop?.assetId ?? images[0].id}+ onValueChange={(id) => setBackdrop({ kind: "image", assetId: id as string })}+ >+ <SelectTrigger className="clip-backdrop-image w-36 py-1 text-[12px]">+ <SelectValue>+ {(id: string) => {+ const a = images.find((i) => i.id === id);+ return a ? <BackdropImageOption asset={a} thumb="h-5 w-8" /> : null;+ }}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {images.map((a) => (+ <SelectItem+ key={a.id}+ value={a.id}+ className={`clip-backdrop-image-${a.id} text-[12px]`}+ >+ <BackdropImageOption asset={a} thumb="h-7 w-11" />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Row>))}</>);diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex c874774f..9dc6cf82 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -52,6 +52,8 @@ import { waveGain } from "@/cut/lib/waveform";import { track0Clips, laneGapAt, sameLane, type LaneRef, clipLen, clipSpeed, getClipSpans, overlayLaneOrder, overlayLayers, projectDuration, resolveTransitions, rippleInsert, useEditor } from "@/cut/lib/store";import type { VideoTrackPlacement } from "@/cut/lib/store";import { playheadAt, setSkim, skimAt, subscribePlayhead, usePlayhead, useSkim } from "@/cut/lib/playhead";+import { useBrushUi } from "@/cut/lib/removal/brushUi";+import { useMatteBakes } from "@/cut/lib/removal/bakeJobs";import { laneHidden, subtitleLaneCount } from "@/cut/lib/subtitles";import { formatTime, formatTimecode } from "@/cut/lib/time";import { EFFECT_LABELS, type EffectId } from "@donkeycut/effects-kit";@@ -3731,6 +3733,7 @@ function ClipView({const lane: LaneKind = clip.track === 0 ? "clip" : "overlayClip";const spine = lane === "clip";const loading = useEditor((s) => s.loadingMedia.has(asset.fileName));+ const baking = useMatteBakes((s) => s.jobs[clip.id]?.status === "running");const speed = clipSpeed(clip);// Every box is its clip's whole footprint. Clips never overlap — a// transition is a render-time blend at the cut, drawn as the bar above the@@ -3844,6 +3847,15 @@ function ClipView({// glance, not just from the thin border.<div className="pointer-events-none absolute inset-0 z-[1] bg-[#0a84ff]/25" />)}+ {baking && !drag && (+ // The bake announces itself where the hover controls live, so it+ // yields to them: gone while the pointer is on the clip, back when it+ // leaves. A clip too narrow for the word keeps the spinner and "C…".+ <span className="tl-cutting-chip pointer-events-none absolute top-1 left-1 z-2 flex items-center gap-1 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] text-white transition-opacity group-hover:opacity-0">+ <Loader2 className="size-2.5 shrink-0 animate-spin" />+ {barW >= 96 ? "Cutting…" : "C…"}+ </span>+ )}{mention &&(drag ? (<span className="tl-dur-chip pointer-events-none absolute top-1 left-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] tabular-nums text-white">@@ -3894,6 +3906,7 @@ function ClipView({) : null}</ClipMenu>)}+ <ClipStrokeMarks clip={clip} spanStart={span.start} speed={speed} pps={pps} barW={barW} />{/* Keys sit on the bar where they fall — pose and mask tracks both —so the animation is visible without opening the inspector. */}{(clip.kf ?? []).map((k) => (@@ -3932,6 +3945,63 @@ function ClipView({);}+/** The clip's brush-stroke frames, as red tabs hanging from the bar's top+ * edge while its brush session is open. A stroke lives on the one frame it+ * was drawn on — the stage overlay shows it only there — so each tab points+ * at a frame that carries paint, and clicking one parks the playhead on it.+ * Tabs, not diamonds or dots: diamonds are keyframes (interpolated values,+ * which seeds aren't) and dots are the beat grid on the bottom edge. */+function ClipStrokeMarks({+ clip,+ spanStart,+ speed,+ pps,+ barW,+}: {+ clip: VideoClip;+ spanStart: number;+ speed: number;+ pps: number;+ barW: number;+}) {+ const open = useBrushUi((s) => s.clipId === clip.id);+ const seeds = clip.removal?.seeds;+ if (!open || clip.removal?.mode !== "custom") return null;+ const times = Array.from(new Set((seeds?.paint ?? []).map((s) => s.t))).filter(+ (t) => t >= clip.in - 0.05 && t <= clip.out + 0.05+ );+ if (times.length === 0) return null;+ return (+ <>+ {times.map((t) => (+ <span+ key={`s${t}`}+ className="tl-stroke-mark pointer-events-auto absolute top-0 z-5 flex h-3 w-3.5 cursor-pointer justify-center"+ style={{+ left: Math.min(barW - 4, Math.max(4, ((t - clip.in) / speed) * pps)),+ transform: "translateX(-50%)",+ }}+ title="Brush stroke"+ onPointerDown={(e) => {+ e.stopPropagation();+ e.preventDefault();+ useEditor.getState().seek(spanStart + (t - clip.in) / speed);+ }}+ >+ <span+ className="h-0 w-0"+ style={{+ borderLeft: "4px solid transparent",+ borderRight: "4px solid transparent",+ borderTop: "5px solid #ff2244",+ }}+ />+ </span>+ ))}+ </>+ );+}+/** The clip's mask keys, on a thin rail under its box: a hairline spanning* the clip's width with a diamond on it per key. The bar itself clips its* children (rounded corners), so the rail is a sibling that follows thediff --git a/site/src/cut/components/panelBits.tsx b/site/src/cut/components/panelBits.tsxindex dd24915f..d36d55ca 100644--- a/site/src/cut/components/panelBits.tsx+++ b/site/src/cut/components/panelBits.tsx@@ -4,6 +4,7 @@ import { useRef } from "react";import { Info, RotateCcw } from "lucide-react";import { useEditor } from "@/cut/lib/store";import { cn } from "@/lib/utils";+import { Switch } from "@/components/ui/switch";import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";/**@@ -98,3 +99,43 @@ export function ResetButton({ title, show, onClick }: { title: string; show: boo</button>);}++/**+ * A named group of rows under a hairline. A section that owns a feature carries+ * the switch that turns it on and holds its rows back until it is, so the panel+ * reads as a short list of what the element actually has and grows only where+ * it was asked to. Pass no `onEnabledChange` for a group that is always open.+ */+export function Section({+ title,+ info,+ enabled,+ onEnabledChange,+ aside,+ children,+}: {+ title: string;+ info?: React.ReactNode;+ enabled?: boolean;+ onEnabledChange?: (enabled: boolean) => void;+ /** Controls that belong to the group as a whole, sat at the end of its title. */+ aside?: React.ReactNode;+ children?: React.ReactNode;+}) {+ const gated = !!onEnabledChange;+ return (+ <section className="mt-1.5 border-t border-border pt-1.5 first:mt-0 first:border-t-0">+ <div className="flex min-h-9 items-center justify-between gap-2">+ <span className="flex min-w-0 items-center gap-1 text-[13px] font-medium">+ <span className="truncate">{title}</span>+ {info && <InfoTip label={title}>{info}</InfoTip>}+ </span>+ {aside}+ {gated && (+ <Switch checked={!!enabled} onCheckedChange={onEnabledChange} aria-label={title} />+ )}+ </div>+ {(!gated || enabled) && children}+ </section>+ );+}diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex ceaae594..e4d12fae 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -81,19 +81,16 @@ function describeRemoval(clip: VideoClip) {return {removal: {mode: rm.mode,+ ...(rm.off ? { off: true } : {}),+ removes: rm.invert ? "subject" : "background",...(rm.subject ? { subject: rm.subject } : {}),- ...(rm.mode === "chroma" && rm.chroma ? { chroma: rm.chroma } : {}),- ...(rm.mode === "auto" || rm.mode === "custom"+ matte: rm.matte ? `ready (${rm.matte.quality === "hq" ? "quality" : "quick"})` : "none",+ ...(job? {- matte: rm.matte ? `ready (${rm.matte.quality === "hq" ? "quality" : "quick"})` : "none",- ...(job- ? {- bake:- job.status === "running"- ? `baking ${job.quality === "hq" ? "quality" : "quick"} (${Math.round(job.progress * 100)}%)`- : `error: ${job.error ?? "failed"}`,- }- : {}),+ bake:+ job.status === "running"+ ? `baking ${job.quality === "hq" ? "quality" : "quick"} (${Math.round(job.progress * 100)}%)`+ : `error: ${job.error ?? "failed"}`,}: {}),...(rm.strokediff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 28d984ec..c903ca2b 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -29,6 +29,7 @@ import {type OverlayAnim,type OverlayAnimStyle,type OverlayLoopStyle,+ STROKE_FEATHER_MAX,STROKE_OFFSET_MAX,STROKE_STYLES,STROKE_WIDTH_MAX,@@ -100,7 +101,6 @@ import {matteBakesAvailable,useMatteBakes,} from "./removal/bakeJobs";-import { clipKeyColor, suggestKeyColor } from "./removal/keyColor";import { blobToInlineAudio, refToInlineAudio, visualRefs, type InlineImage } from "./refMedia";import { characterPrompt, stockAspectDims, stockTitle } from "./stock";import { STOCK_IMAGES } from "./stockManifest";@@ -2059,74 +2059,61 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {return { id: clip.id, boxStyle: boxStyle ?? null };},- set_removal: async (s, input) => {+ set_removal: (s, input) => {const clip = requireItem(s.clips, input.clipId, "video clip");const mode = String(input.mode ?? "");if (mode === "off") {- s.updateClip(clip.id, { removal: undefined });- return { id: clip.id, removal: null };+ // Off keeps the removal and its baked matte on the clip — it just+ // stops rendering and baking — so switching back on costs nothing.+ if (!clip.removal) return { id: clip.id, removal: null };+ s.updateClip(clip.id, { removal: { ...clip.removal, off: true } });+ return { id: clip.id, mode, note: "The cutout is off; its matte and settings stay stored." };}+ // Any on-mode clears a stored Off, whatever else it sets.+ const prev = { ...clip.removal };+ delete prev.off;const bakeNote = matteBakesAvailable? "The cutout matte is baking in the background — wait_for_renders reports when it lands.": "The cutout is set; its matte bakes the next time the project is open in the editor.";+ // The direction: `remove` "subject" inverts the cutout — the selection+ // goes and the rest of the picture stays. Omitted, an existing+ // direction holds; "background" clears it. The selection (and its+ // baked matte) is the same either way, so flipping re-bakes nothing.+ const dir =+ input.remove === "subject"+ ? { invert: true }+ : input.remove === "background"+ ? { invert: undefined }+ : {};if (mode === "auto") {- // The tool call is the explicit start, so the bake is requested here- // the way the panel's Start button requests it.- s.updateClip(clip.id, { removal: { ...clip.removal, mode: "auto", requested: true } });- ensureMatteBake(clip.id);- return { id: clip.id, mode, note: bakeNote };- }- if (mode === "custom") {- const subject = typeof input.subject === "string" ? input.subject.trim() : "";- if (!subject || subject.length > 100)- throw new ToolError('mode "custom" needs `subject` — what to keep, in a few words.');- // A named subject replaces any painted selection: the seeds point at- // whatever the user brushed before, and the words are the new ask.+ // The tool call is the explicit ask, so it carries `requested` — the+ // panel's Apply press. `refine` asks for the hosted quality pass on+ // top; that rung spends credits.+ const refine = input.refine === true ? { refine: true } : {};s.updateClip(clip.id, {- removal: {- ...clip.removal,- mode: "custom",- subject,- seeds: { prompts: [] },- requested: true,- },+ removal: { ...prev, mode: "auto", requested: true, ...refine, ...dir },});- confirmMatteBake(clip.id);- return { id: clip.id, mode, subject, note: bakeNote };- }- if (mode !== "chroma")- throw new ToolError('mode must be "off", "auto", "custom", or "chroma".');- const prev = clip.removal?.chroma;- const explicit =- typeof input.color === "string" && /^#[0-9a-f]{6}$/i.test(input.color)- ? input.color.toLowerCase()- : null;- // The default key comes from the clip's own footage: the live frame- // when a decoder shows it, its decoded in-point frame when the clip is- // away from the playhead or the turn runs headless.- let color = explicit ?? prev?.color ?? suggestKeyColor(clip.id);- if (!color) {- const asset = s.assets.find((a) => a.id === clip.assetId);- color = asset ? await clipKeyColor(asset, clip) : null;+ ensureMatteBake(clip.id);+ return { id: clip.id, mode, note: bakeNote };}- if (!color)- throw new ToolError(- "The clip's picture could not be read for a key suggestion — pass `color` as #rrggbb."- );- const chroma = {- color,- ...(isNum(input.intensity)- ? { intensity: clamp(input.intensity, 0, 1) }- : prev?.intensity !== undefined && { intensity: prev.intensity }),- ...(isNum(input.softness)- ? { softness: clamp(input.softness, 0, 1) }- : prev?.softness !== undefined && { softness: prev.softness }),- ...(isNum(input.spill)- ? { spill: clamp(input.spill, 0, 1) }- : prev?.spill !== undefined && { spill: prev.spill }),- };- s.updateClip(clip.id, { removal: { ...clip.removal, mode: "chroma", chroma } });- return { id: clip.id, mode, chroma };+ if (mode !== "custom") throw new ToolError('mode must be "off", "auto", or "custom".');+ const subject = typeof input.subject === "string" ? input.subject.trim() : "";+ if (!subject || subject.length > 100)+ throw new ToolError('mode "custom" needs `subject` — what to keep, in a few words.');+ // A named subject replaces any painted selection: the seeds point at+ // whatever the user brushed before, and the words are the new ask.+ s.updateClip(clip.id, {+ removal: {+ ...prev,+ mode: "custom",+ subject,+ seeds: { prompts: [] },+ requested: true,+ ...dir,+ },+ });+ confirmMatteBake(clip.id);+ return { id: clip.id, mode, subject, note: bakeNote };},set_removal_stroke: (s, input) => {@@ -2154,6 +2141,9 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {...(isNum(input.width)? { width: clamp(input.width, 1, STROKE_WIDTH_MAX) }: prev?.width !== undefined && { width: prev.width }),+ ...(isNum(input.feather)+ ? input.feather !== 0 && { feather: clamp(input.feather, 0, STROKE_FEATHER_MAX) }+ : prev?.feather !== undefined && { feather: prev.feather }),...(isNum(input.offset_x)? input.offset_x !== 0 && {offsetX: clamp(input.offset_x, -STROKE_OFFSET_MAX, STROKE_OFFSET_MAX),diff --git a/site/src/cut/lib/cutout.ts b/site/src/cut/lib/cutout.tsindex 5ece6a51..625520e6 100644--- a/site/src/cut/lib/cutout.ts+++ b/site/src/cut/lib/cutout.ts@@ -21,7 +21,6 @@ import {withOutline,} from "@donkeycut/effects-kit";import { hostedPost } from "./hosted";-import { touchAlpha, wandAlpha, type WandScratch } from "./removal/touchMask";import { decodeRasterImage, rasterCanvasToDataUrl, rasterCanvasToPng } from "./raster";import { geminiModelRoles } from "@/lib/inference/gemini-models";@@ -147,103 +146,6 @@ export function segmentSubjectAlpha(}}-const TOUCH_MODEL = "/mediapipe/magic_touch.tflite";-type TouchSegmenter = import("@mediapipe/tasks-vision").InteractiveSegmenterLegacy;--let touchOnce: Promise<TouchSegmenter | null> | null = null;--/** The shared interactive (tap-to-select) segmenter, created on first use.- * Null when the runtime assets are missing. */-export function interactiveSegmenter(): Promise<TouchSegmenter | null> {- touchOnce ??= (async () => {- try {- const { FilesetResolver, InteractiveSegmenterLegacy } = await import(- "@mediapipe/tasks-vision"- );- const fileset = await FilesetResolver.forVisionTasks(WASM_BASE);- return await withQuietWasmLogs(() =>- InteractiveSegmenterLegacy.createFromOptions(fileset, {- baseOptions: { modelAssetPath: TOUCH_MODEL },- outputCategoryMask: false,- outputConfidenceMasks: true,- })- );- } catch {- touchOnce = null;- return null;- }- })();- return touchOnce;-}--/** White canvas carrying `alpha`, or null when nearly nothing survived. */-function alphaToCanvas(alpha: Uint8ClampedArray, w: number, h: number): HTMLCanvasElement | null {- const [out, ctx] = canvasOf(w, h);- const img = ctx.createImageData(w, h);- let kept = 0;- for (let i = 0; i < w * h; i++) {- img.data[i * 4] = 255;- img.data[i * 4 + 1] = 255;- img.data[i * 4 + 2] = 255;- img.data[i * 4 + 3] = alpha[i];- if (alpha[i] > 128) kept++;- }- if (kept < w * h * 0.001) return null;- ctx.putImageData(img, 0, 0);- return out;-}--/**- * Select what sits under a tap (or a scribbled path) and return its alpha- * canvas, white where the pick is. Points are frame fractions. The model's- * object pick leads; where it refuses to anchor on the touched spot — a- * backdrop, not an object to it — or anchors on too few pixels to hold a- * selection, the geodesic color wand takes the stroke instead, so flat- * regions select as cleanly as subjects. Null when nothing registers. The- * `source` should be small (≤ ~512px) — the model resamples anyway, and- * quick-brush strokes segment per pointer move; a caller re-segmenting the- * same frame can pass its pixels and a wand scratch to skip the re-reads.- */-export function segmentTouchAlpha(- segmenter: TouchSegmenter,- source: HTMLCanvasElement,- points: { x: number; y: number }[],- opts: { rgba?: Uint8ClampedArray; scratch?: WandScratch } = {}-): HTMLCanvasElement | null {- if (points.length === 0) return null;- const roi =- points.length === 1- ? { keypoint: { x: points[0].x, y: points[0].y } }- : { scribble: points.map((p) => ({ x: p.x, y: p.y })) };- const result = segmenter.segment(source, roi);- let picked: HTMLCanvasElement | null = null;- try {- const masks = result.confidenceMasks;- if (masks?.length) {- // Two masks: background first, the touched object second (mirroring- // the selfie model's layout). A single mask is the object itself.- const conf = masks.length > 1 ? masks[1].getAsFloat32Array() : masks[0].getAsFloat32Array();- const mw = masks[0].width;- const mh = masks[0].height;- const alpha = touchAlpha(conf, mw, mh, points);- picked = alpha ? alphaToCanvas(alpha, mw, mh) : null;- }- } finally {- result.close();- }- if (picked) return picked;- const sw = source.width;- const sh = source.height;- let rgba = opts.rgba;- if (!rgba) {- const sctx = source.getContext("2d");- if (!sctx) return null;- rgba = sctx.getImageData(0, 0, sw, sh).data;- }- const wand = wandAlpha(rgba, sw, sh, points, opts.scratch);- return wand ? alphaToCanvas(wand, sw, sh) : null;-}-/** Person matting, fully on-device. Null when no person registers (callers* fall through to the hosted path). */export async function personCutout(blob: Blob): Promise<HTMLCanvasElement | null> {diff --git a/site/src/cut/lib/removal/bakeJobs.ts b/site/src/cut/lib/removal/bakeJobs.tsindex 54d6dcc8..234606e2 100644--- a/site/src/cut/lib/removal/bakeJobs.ts+++ b/site/src/cut/lib/removal/bakeJobs.ts@@ -6,9 +6,10 @@* `ensureMatteBake` is idempotent — the panel and the doc sweep call it* whenever an AI-mode removal is on, and the store compares the clip's* fingerprint against the stored matte and the bake in flight, so it only- * ever starts work the doc actually owes. The ladder: auto mode bakes the- * free on-device matte first, then the hosted quality pass replaces it when- * the account has credits; custom mode goes straight to the hosted tracker+ * ever starts work the doc actually owes. Every rung starts from an explicit+ * ask: `requested` (the panel's Apply, or the chat tool) starts auto mode's+ * free on-device matte, the hosted quality pass (credits) replaces it once+ * `refine` asks for it, and custom mode goes straight to the hosted tracker* (only it can follow a brushed object). A finished bake lands as a project* asset (origin "matte") and repoints `clip.removal.matte` through a* transient write: background landings stay off the undo stack, and the clip@@ -36,6 +37,9 @@ export interface MatteBakeJob {/** When secondsLeft was stamped, so the panel counts it down between* progress steps. */etaAt?: number;+ /** When the bake started, so the panel shows the running time while the+ * estimate has nothing to stand on yet. */+ startedAt?: number;error?: string;}@@ -129,12 +133,11 @@ const clipOf = (clipId: string): VideoClip | undefined =>* owes no matte at all. */function owedFingerprint(clip: VideoClip | undefined): string | null {const r = clip?.removal;- if (!clip || !r || (r.mode !== "auto" && r.mode !== "custom")) return null;- // Bakes are explicitly started — the panel button or the chat tool sets- // `requested`. Picking a mode alone owes nothing.+ if (!clip || !r || r.off) return null;+ // Every bake waits for its explicit start — the panel's Apply or the chat+ // tool sets `requested` — and a custom bake also needs something to+ // follow: painted seeds or a described subject.if (!r.requested) return null;- // A custom removal with nothing selected yet owes nothing — the tracker- // needs painted seeds or a described subject to follow.if (r.mode === "custom" &&!r.seeds?.prompts.length &&@@ -235,15 +238,16 @@ export function ensureMatteBake(clipId: string, opts: { whileBrushing?: booleanreturn;}// What the ladder owes next. Custom tracks an arbitrary object, so only the- // hosted tracker can bake it; auto gets the free local matte immediately- // and the hosted pass upgrades it.+ // hosted tracker can bake it; auto gets the free local matte immediately,+ // and the hosted pass upgrades it once `refine` asks — the paid rung runs+ // on that explicit click alone.const want: MatteQuality | null =r.mode === "custom"? stored? null: "hq": stored- ? stored.quality === "local"+ ? stored.quality === "local" && r.refine? "hq": null: "local";@@ -268,7 +272,7 @@ export function ensureMatteBake(clipId: string, opts: { whileBrushing?: booleanconst ctl = new AbortController();running.set(clipId, { fp, quality: want, ctl });failed.delete(clipId);- setJob(clipId, { quality: want, status: "running", progress: 0 });+ setJob(clipId, { quality: want, status: "running", progress: 0, startedAt: Date.now() });void runBake(clipId, fp, want, ctl).catch((e: unknown) => {if (running.get(clipId)?.ctl !== ctl) return;running.delete(clipId);@@ -340,6 +344,7 @@ async function runBakeNow(progress: f,secondsLeft,etaAt: secondsLeft !== undefined ? Date.now() : undefined,+ startedAt,});};const projectId = state.projectId;@@ -385,7 +390,8 @@ async function runBakeNow(// the sweep collects it once nothing points at it.running.delete(clipId);setJob(clipId, null);- // Auto mode's local matte just landed: the quality pass is owed next.+ // Re-settle: an auto matte that landed with `refine` set owes the quality+ // pass next; anything else just clears its job.ensureMatteBake(clipId);}diff --git a/site/src/cut/lib/removal/brushSession.ts b/site/src/cut/lib/removal/brushSession.tsnew file mode 100644index 00000000..655be055--- /dev/null+++ b/site/src/cut/lib/removal/brushSession.ts@@ -0,0 +1,215 @@+"use client";++/**+ * The custom-removal brush session: what the brush has painted on the+ * current frame, held as a working mask the stage draws as a red overlay.+ * Every finished stroke also yields its seed record — the paint bitmaps the+ * doc stores, which the hosted tracker replays across the whole clip.+ */++import { matteLumaToAlpha } from "@donkeycut/effects-kit";+import { sampleClipSource } from "../previewCanvas";+import { createRasterCanvas, rasterCanvasToDataUrl, type RasterSurface } from "../raster";+import type { RemovalSeeds } from "../types";++/** Working-mask short side: enough for a crisp overlay, cheap to repaint on+ * every pointer move. */+const WORK_SHORT = 512;+/** Stored paint bitmaps stay small — they seed a tracker, never a render. */+const PAINT_SHORT = 256;++type Point = { x: number; y: number };++export class BrushSession {+ /** The current frame, drawn at working size. */+ private work: RasterSurface;+ /** White where the selection is. */+ private mask: RasterSurface;+ /** Scratch for compositing the mask into the red overlay tint. */+ private view: RasterSurface;+ private w = 2;+ private h = 2;++ private constructor() {+ this.work = createRasterCanvas(2, 2);+ this.mask = createRasterCanvas(2, 2);+ this.view = createRasterCanvas(2, 2);+ }++ static async open(): Promise<BrushSession> {+ return new BrushSession();+ }++ /** Pull the clip's current decoder frame into the working canvas. False+ * when no frame is ready yet. */+ refreshFrame(clipId: string): boolean {+ const src = sampleClipSource(clipId);+ if (!src) return false;+ const sw = Number((src as { width?: number }).width ?? 0) || 16;+ const sh = Number((src as { height?: number }).height ?? 0) || 9;+ const scale = WORK_SHORT / Math.max(1, Math.min(sw, sh));+ const w = Math.max(2, Math.round(sw * scale));+ const h = Math.max(2, Math.round(sh * scale));+ if (this.w !== w || this.h !== h) {+ this.w = w;+ this.h = h;+ this.work.width = w;+ this.work.height = h;+ const m = this.mask.getContext("2d") as CanvasRenderingContext2D | null;+ const keep = m && (this.mask.width > 2 ? this.mask : null);+ const prev = keep ? createRasterCanvas(this.mask.width, this.mask.height) : null;+ if (prev && keep) {+ (prev.getContext("2d") as CanvasRenderingContext2D).drawImage(keep as CanvasImageSource, 0, 0);+ }+ this.mask.width = w;+ this.mask.height = h;+ if (prev && m) m.drawImage(prev as CanvasImageSource, 0, 0, w, h);+ }+ const ctx = this.work.getContext("2d") as CanvasRenderingContext2D | null;+ if (!ctx) return false;+ ctx.drawImage(src, 0, 0, w, h);+ return true;+ }++ /** Paint one stroke into the mask. `radius` is a fraction of the frame's+ * short side. */+ paintStroke(points: Point[], radius: number, erase: boolean): void {+ const ctx = this.mask.getContext("2d") as CanvasRenderingContext2D | null;+ if (!ctx || points.length === 0) return;+ const r = Math.max(1, radius * Math.min(this.w, this.h));+ ctx.globalCompositeOperation = erase ? "destination-out" : "source-over";+ ctx.strokeStyle = "#ffffff";+ ctx.fillStyle = "#ffffff";+ ctx.lineWidth = r * 2;+ ctx.lineCap = "round";+ ctx.lineJoin = "round";+ ctx.beginPath();+ ctx.moveTo(points[0].x * this.w, points[0].y * this.h);+ for (let i = 1; i < points.length; i++) ctx.lineTo(points[i].x * this.w, points[i].y * this.h);+ if (points.length === 1) {+ ctx.arc(points[0].x * this.w, points[0].y * this.h, r, 0, Math.PI * 2);+ ctx.fill();+ } else {+ ctx.stroke();+ }+ ctx.globalCompositeOperation = "source-over";+ }++ /** The stroke's stored paint bitmap: the stroke alone, small grayscale PNG+ * (white marks) for the seed record. */+ async paintSeed(points: Point[], radius: number): Promise<string> {+ const scale = PAINT_SHORT / Math.max(1, Math.min(this.w, this.h));+ const w = Math.max(2, Math.round(this.w * scale));+ const h = Math.max(2, Math.round(this.h * scale));+ const c = createRasterCanvas(w, h);+ const ctx = c.getContext("2d") as CanvasRenderingContext2D;+ ctx.fillStyle = "#000000";+ ctx.fillRect(0, 0, w, h);+ const r = Math.max(1, radius * Math.min(w, h));+ ctx.strokeStyle = "#ffffff";+ ctx.fillStyle = "#ffffff";+ ctx.lineWidth = r * 2;+ ctx.lineCap = "round";+ ctx.lineJoin = "round";+ ctx.beginPath();+ ctx.moveTo(points[0].x * w, points[0].y * h);+ for (let i = 1; i < points.length; i++) ctx.lineTo(points[i].x * w, points[i].y * h);+ if (points.length === 1) {+ ctx.arc(points[0].x * w, points[0].y * h, r, 0, Math.PI * 2);+ ctx.fill();+ } else {+ ctx.stroke();+ }+ return rasterCanvasToDataUrl(c, "image/png");+ }++ /** Rebuild the mask from the paint recorded on the current frame. `at` is+ * the frame's source second; a stroke recorded on another frame stays off+ * this overlay. */+ replaySeeds(+ seeds: RemovalSeeds | undefined,+ decode: (url: string) => Promise<CanvasImageSource | null>,+ at: number+ ): Promise<void> {+ this.reset();+ if (!seeds) return Promise.resolve();+ const paints = (seeds.paint ?? []).filter((p) => Math.abs(p.t - at) < 0.05);+ return (async () => {+ const ctx = this.mask.getContext("2d") as CanvasRenderingContext2D | null;+ if (!ctx) return;+ for (const p of paints) {+ for (const [url, erase] of [+ [p.add, false],+ [p.erase, true],+ ] as const) {+ if (!url) continue;+ const img = await decode(url);+ if (!img) continue;+ ctx.globalCompositeOperation = erase ? "destination-out" : "source-over";+ // The paint is white on black; its luma is the stroke, so cut the+ // black away first via a lightened draw onto a scratch.+ const s = createRasterCanvas(this.w, this.h);+ const sctx = s.getContext("2d") as CanvasRenderingContext2D;+ sctx.drawImage(img, 0, 0, this.w, this.h);+ const px = sctx.getImageData(0, 0, this.w, this.h);+ matteLumaToAlpha(px.data);+ sctx.putImageData(px, 0, 0);+ ctx.drawImage(s as CanvasImageSource, 0, 0);+ }+ }+ ctx.globalCompositeOperation = "source-over";+ })();+ }++ reset(): void {+ const ctx = this.mask.getContext("2d") as CanvasRenderingContext2D | null;+ ctx?.clearRect(0, 0, this.mask.width, this.mask.height);+ }++ /** Whether anything is selected right now. */+ hasSelection(): boolean {+ const ctx = this.mask.getContext("2d") as CanvasRenderingContext2D | null;+ if (!ctx) return false;+ const px = ctx.getImageData(0, 0, this.mask.width, this.mask.height).data;+ for (let i = 3; i < px.length; i += 64) if (px[i] > 32) return true;+ return false;+ }++ /** Paint the selection into a display context as the red overlay. */+ paintOverlay(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ if (this.view.width !== this.w || this.view.height !== this.h) {+ this.view.width = this.w;+ this.view.height = this.h;+ }+ const view = this.view;+ const vctx = view.getContext("2d") as CanvasRenderingContext2D;+ vctx.globalCompositeOperation = "source-over";+ vctx.clearRect(0, 0, this.w, this.h);+ vctx.drawImage(this.mask as CanvasImageSource, 0, 0);+ vctx.globalCompositeOperation = "source-in";+ vctx.fillStyle = "#ff2244";+ vctx.fillRect(0, 0, this.w, this.h);+ ctx.clearRect(0, 0, w, h);+ ctx.globalAlpha = 0.5;+ ctx.imageSmoothingEnabled = true;+ ctx.drawImage(view as CanvasImageSource, 0, 0, w, h);+ ctx.globalAlpha = 1;+ }++ /** The selection mask (white, alpha-carrying) for the stage's red overlay. */+ overlay(): CanvasImageSource {+ return this.mask as CanvasImageSource;+ }++ /** The current frame at working size, for the loupe. */+ frame(): CanvasImageSource {+ return this.work as CanvasImageSource;+ }++ get width() {+ return this.w;+ }+ get height() {+ return this.h;+ }+}diff --git a/site/src/cut/lib/removal/brushUi.ts b/site/src/cut/lib/removal/brushUi.tsindex 1288ddbb..86f111de 100644--- a/site/src/cut/lib/removal/brushUi.ts+++ b/site/src/cut/lib/removal/brushUi.ts@@ -9,7 +9,7 @@import { create } from "zustand";-export type BrushTool = "quick" | "brush" | "quickErase" | "erase";+export type BrushTool = "brush" | "erase";/** Brush diameter bounds, as a fraction of the frame's short side. */export const BRUSH_SIZE_MIN = 0.02;diff --git a/site/src/cut/lib/removal/touchMask.test.ts b/site/src/cut/lib/removal/touchMask.test.tsdeleted file mode 100644index 8bca4766..00000000--- a/site/src/cut/lib/removal/touchMask.test.ts+++ /dev/null@@ -1,167 +0,0 @@-import { describe, expect, test } from "bun:test";-import { TOUCH_FLOOR, touchAlpha, wandAlpha, type WandScratch } from "./touchMask";--/** A confidence field painted from rectangles: [x0, y0, x1, y1, conf]. */-function field(w: number, h: number, rects: [number, number, number, number, number][]) {- const conf = new Float32Array(w * h);- for (const [x0, y0, x1, y1, c] of rects) {- for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) conf[y * w + x] = c;- }- return conf;-}--const opaque = (a: Uint8ClampedArray | null, x: number, y: number, w: number) =>- !!a && a[y * w + x] > 128;--describe("touchAlpha", () => {- test("keeps the touched blob and drops a disconnected one", () => {- const conf = field(20, 10, [- [1, 1, 6, 6, 0.95],- [12, 1, 18, 6, 0.95],- ]);- const a = touchAlpha(conf, 20, 10, [{ x: 3 / 20, y: 3 / 10 }]);- expect(opaque(a, 3, 3, 20)).toBe(true);- expect(opaque(a, 14, 3, 20)).toBe(false);- });-- test("a confident stroke sheds connected low-confidence bleed", () => {- // The touched backdrop reads 0.95; the model bleeds 0.5 onto the- // adjoining subject. The floor alone would keep the bleed.- const conf = field(20, 10, [- [0, 0, 10, 10, 0.95],- [10, 0, 20, 10, 0.5],- ]);- const a = touchAlpha(conf, 20, 10, [{ x: 4 / 20, y: 5 / 10 }]);- expect(opaque(a, 4, 5, 20)).toBe(true);- expect(opaque(a, 15, 5, 20)).toBe(false);- });-- test("a tap the model won't anchor returns null for the wand to take", () => {- // The model put nothing on the touched spot but found an object nearby.- const conf = field(20, 10, [[12, 1, 18, 6, 0.9]]);- expect(touchAlpha(conf, 20, 10, [{ x: 2 / 20, y: 8 / 10 }])).toBeNull();- });-- test("nothing above the floor registers as null", () => {- const conf = field(20, 10, [[0, 0, 20, 10, TOUCH_FLOOR - 0.1]]);- expect(touchAlpha(conf, 20, 10, [{ x: 0.5, y: 0.5 }])).toBeNull();- });-- test("a stroke keeps its first-touch anchor as later samples drag the median down", () => {- // The drag starts on a confident object and runs far into low-confidence- // ground: the tier holds — the object stays picked — and the pick never- // flips to the wand mid-stroke.- const conf = field(20, 10, [- [0, 0, 6, 10, 0.95],- [6, 0, 20, 10, 0.2],- ]);- const a = touchAlpha(conf, 20, 10, [- { x: 2 / 20, y: 5 / 10 },- { x: 8 / 20, y: 5 / 10 },- { x: 12 / 20, y: 5 / 10 },- { x: 16 / 20, y: 5 / 10 },- ]);- expect(opaque(a, 2, 5, 20)).toBe(true);- expect(opaque(a, 12, 5, 20)).toBe(false);- });-- test("a scribble anchors on its median confidence", () => {- // One stroke point grazes the 0.55 bleed; the median holds at 0.95 and- // the bleed still drops.- const conf = field(20, 10, [- [0, 0, 10, 10, 0.95],- [10, 0, 20, 10, 0.55],- ]);- const a = touchAlpha(conf, 20, 10, [- { x: 3 / 20, y: 5 / 10 },- { x: 5 / 20, y: 5 / 10 },- { x: 11 / 20, y: 5 / 10 },- ]);- expect(opaque(a, 4, 5, 20)).toBe(true);- expect(opaque(a, 16, 5, 20)).toBe(false);- });-});--/** An rgba image painted per pixel. */-function image(w: number, h: number, colorAt: (x: number, y: number) => [number, number, number]) {- const rgba = new Uint8ClampedArray(w * h * 4);- for (let y = 0; y < h; y++) {- for (let x = 0; x < w; x++) {- const [r, g, b] = colorAt(x, y);- const i = (y * w + x) * 4;- rgba[i] = r;- rgba[i + 1] = g;- rgba[i + 2] = b;- rgba[i + 3] = 255;- }- }- return rgba;-}--describe("wandAlpha", () => {- test("a flat region selects whole and stops at the boundary", () => {- const rgba = image(24, 12, (x) => (x < 12 ? [20, 20, 40] : [180, 150, 130]));- const a = wandAlpha(rgba, 24, 12, [{ x: 4 / 24, y: 6 / 12 }]);- expect(opaque(a, 1, 1, 24)).toBe(true);- expect(opaque(a, 10, 10, 24)).toBe(true);- expect(opaque(a, 16, 6, 24)).toBe(false);- });-- test("a smooth gradient stays on-signature, a strong edge does not", () => {- const rgba = image(24, 12, (x) => (x < 12 ? [20 + x, 20 + x, 40] : [200, 60, 60]));- const a = wandAlpha(rgba, 24, 12, [{ x: 2 / 24, y: 6 / 12 }]);- expect(opaque(a, 11, 6, 24)).toBe(true);- expect(opaque(a, 14, 6, 24)).toBe(false);- });-- test("the same color across a wide bright gap stays out", () => {- const rgba = image(30, 12, (x) => (x < 10 || x >= 20 ? [30, 30, 30] : [200, 200, 200]));- const a = wandAlpha(rgba, 30, 12, [{ x: 5 / 30, y: 6 / 12 }]);- expect(opaque(a, 8, 6, 30)).toBe(true);- expect(opaque(a, 15, 6, 30)).toBe(false);- expect(opaque(a, 25, 6, 30)).toBe(false);- });-- test("thin off-signature grooves are bridged, the far side joins", () => {- // A slatted wall: faces of 40 with 2px grooves of 8. One tap on a face- // takes the grooves and the faces beyond them.- const face = (x: number) => (x % 8 < 6 ? 40 : 8);- const rgba = image(32, 12, (x) => [face(x), face(x), face(x)]);- const a = wandAlpha(rgba, 32, 12, [{ x: 2 / 32, y: 6 / 12 }]);- expect(opaque(a, 7, 6, 32)).toBe(true);- expect(opaque(a, 20, 6, 32)).toBe(true);- expect(opaque(a, 30, 6, 32)).toBe(true);- });-- test("a scratch reuses the tone field across moves of one stroke", () => {- const rgba = image(24, 12, (x) => (x < 12 ? [20, 20, 40] : [180, 150, 130]));- const scratch: WandScratch = {};- const first = wandAlpha(rgba, 24, 12, [{ x: 4 / 24, y: 6 / 12 }], scratch);- const heldTone = scratch.tone;- expect(heldTone).toBeDefined();- const second = wandAlpha(- rgba,- 24,- 12,- [- { x: 4 / 24, y: 6 / 12 },- { x: 8 / 24, y: 6 / 12 },- ],- scratch- );- expect(scratch.tone).toBe(heldTone!);- expect([...second!]).toEqual([...first!]);- });-- test("a scribble across two tones adds both signatures", () => {- const tone = (x: number) => (Math.floor(x / 6) % 2 === 0 ? 40 : 100);- const rgba = image(24, 12, (x) => [tone(x), tone(x), tone(x)]);- const tap = wandAlpha(rgba, 24, 12, [{ x: 3 / 24, y: 6 / 12 }]);- expect(opaque(tap, 15, 6, 24)).toBe(false);- const scribble = wandAlpha(rgba, 24, 12, [- { x: 3 / 24, y: 6 / 12 },- { x: 8 / 24, y: 6 / 12 },- ]);- expect(opaque(scribble, 15, 6, 24)).toBe(true);- });-});diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 2583b43b..175b3b69 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -95,7 +95,7 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim- Resizes ripple the same way deletes do: while track 0 is the only video track, a track-0 trim or speed change slides everything past the clip's tail — clips, titles, captions, soundtrack — with the moved edge, in both directions, every existing gap keeping its width. With overlay video tracks present, growth pushes the track-0 run and a shrink leaves a gap.- set_speed sets a clip's playback rate; it changes the clip's timeline length and carries the timeline behind it like a trim.- set_transition joins a clip into the next one (0–2s, ${TRANSITION_STYLE_IDS.length} styles); set_animation animates one clip's own entrance/exit — read the transitions-and-fades skill before styling cuts. Splitting or deleting clears the affected transition. A transition is a bar on its own row at an absolute time, so an edit can leave one lining up with nothing: every timeline mutation reports those as \`parkedTransitions\`, and clearing them (remove_transition) is part of finishing the edit. Grading a clip's picture is the color tools (set_color_preset, set_color_grade, set_color_curves, set_color_wheels, set_color_hsl — read the color-grading skill); a stylized post treatment (grain, VHS, halation…) is add_effect, dropped over the stretch of timeline it covers — as is a treatment on the sound (echo, reverb, telephone…).-- Cutting a clip's background away — the AI person matte, the green-screen chroma key, ink around the silhouette, a fill behind the subject — is the cutout suite (set_removal, set_removal_stroke, set_removal_background); read the background-removal skill.+- Cutting a clip's background away — the AI person matte, ink around the silhouette, a fill behind the subject — is the cutout suite (set_removal, set_removal_stroke, set_removal_background); read the background-removal skill.- split_at cuts the track-0 clip under that time into two clips at the exact frame. With a soundtrack or overlay clip selected it splits that instead.- The Media and Library panels take the same gestures: ⌘/⇧-click a tile, or sweep a rubber-band over the grid, and dragging any picked tile onto the timeline lays the whole set down one after another from the drop point.- The user can multi-select (⌘/⇧-click, or sweep a rubber-band over empty track space) across every kind at once — clips, audio, titles, cues. Deleting or copying acts on the whole selection, and dragging any member moves the set as one: every item shifts by the same time, relative spacing kept, while unselected items slide out of the way and flow back. A selection of one kind on the multi-row tracks (audio, titles) also retracks together on a vertical drag, one row past the end opening a new track. A hover chip on each video clip toggles its own audio.@@ -129,13 +129,13 @@ Grade like a colorist: read the image, correct it, then style it — in that ord"background-removal": `# Background removal (Cutout)Every video clip — any track, stills too — can carry a cutout, the Inspector's Cutout tab: the clip's picture keys to an alpha matte, the subject stays, and where the background was, lower tracks or the project background show through. Preview, timeline thumbnails, and export render the same matte. A long clip tracks in parts automatically — cutout length needs no special handling.-- set_removal mode "auto": the AI person matte. A free on-device pass lands in seconds, and a hosted quality pass (spends credits like generation) upgrades hair and edge detail in the background. The tool call starts the matte work itself; in the panel, picking a mode only previews the live matte, and the user's Start (auto) or Apply (custom) press starts it — hand-instructions include that step. Each cutout clip reports under \`removal\` in editor_state videoTrack/overlayVideo — mode, matte readiness ("ready (quick)" / "ready (quality)" / "none"), and a running matte's progress — and wait_for_renders settles on that work, so claims about a finished cutout come from there. Short of credits, the quick matte stands and the panel offers the upgrade.-- set_removal mode "custom" with \`subject\`: an arbitrary object by description — "the dog", "the red car" — matted and tracked through the clip (spends credits, less than a brushed track). Every match of the words is kept, so "cut out the dog" is one call. Picking one exact instance among lookalikes is hands-on: the user picks Custom in the Cutout tab, paints it on the preview with the Brush and Erase tools (the wand toggles Smart select, which grabs the whole object or flat region under the stroke; off by default, strokes paint exact pixels), and presses Apply — the hosted tracker follows those exact strokes; with a subject set too, the strokes refine which instance the words picked.-- set_removal mode "chroma": the green-screen key. The key color plus intensity (tolerance), softness (edge rolloff), and spill (pulls key-colored fringe off the kept pixels); omitting color samples the footage's borders. Footage shot or generated over a solid backdrop keys cleanly and costs nothing.-- set_removal_stroke draws ink around the kept silhouette — glow, hand-drawn, straight cut, solid, offset (a thrown silhouette copy placed with offset_x/offset_y), dotted — with color and width. The die-cut sticker look is a white solid or cut stroke.+- set_removal runs both directions: \`remove\` "background" keeps the selection and drops everything around it; \`remove\` "subject" drops the selection and keeps the rest. The selection is the same either way, so flipping the direction on an existing cutout is instant — no new bake, no new charge.+- set_removal mode "auto": the AI person matte. The free on-device pass starts from one tool call here (in the panel it waits for the user's Apply press) and lands in seconds. The hosted quality pass (spends credits like generation) upgrades hair and edge detail only on an explicit ask: the panel's Apply button, or the tool's \`refine\` flag when the user asks for the upgrade. Custom mode still starts from the user's Apply press (or this tool with \`subject\`) — hand-instructions include that step. Each cutout clip reports under \`removal\` in editor_state videoTrack/overlayVideo — mode, the \`removes\` direction, matte readiness ("ready (quick)" / "ready (quality)" / "none"), and a running matte's progress — and wait_for_renders settles on that work, so claims about a finished cutout come from there. Short of credits, the quick matte stands and the panel offers the upgrade.+- set_removal mode "custom" with \`subject\`: an arbitrary object by description — "the dog", "the red car" — matted and tracked through the clip (spends credits, less than a brushed track). Every match of the words is kept, so "cut out the dog" is one call. Picking one exact instance among lookalikes is hands-on: the user picks Custom in the Cutout tab, paints it on the preview with the Brush and Erase tools (strokes paint exact pixels), and presses Apply — the hosted tracker follows those exact strokes; with a subject set too, the strokes refine which instance the words picked.+- set_removal_stroke draws ink around the kept silhouette — glow, hand-drawn, straight cut, solid, offset (a thrown silhouette copy placed with offset_x/offset_y), dotted — with color, width, and feather (edge softness). The die-cut sticker look is a white solid or cut stroke.- set_removal_background fills in behind the subject inside the clip's own picture: a flat color or a project image. For new scenery behind a person, an image fill here or scenery on a lower track both read; the lower track keeps the scenery independently editable.-Panel geography, for hand-instructions: the Cutout tab is labeled rows, and the Layer dropdown at the top switches the rows between Removal (the mode and its controls), Stroke, and Background (None / Color / Image; the Image grid lists pictures imported into Media). Say "set Layer to Background", never "under the Background settings".-Recipes: "remove the background" on a person = auto. "Cut out the dog" = custom with subject "the dog". "Put me on a beach" = auto + the beach behind (background image or lower track). "Green screen" = chroma. Sticker/die-cut = auto + white cut stroke. A bold silhouette pop = offset stroke in a loud color. Turning the whole thing off = set_removal mode "off", which drops the stroke and background fill with it.`,+Panel geography, for hand-instructions: the Cutout tab is one flat pane. One segmented Remove control at the top holds every choice — Off / Background (keep the person, mode "auto") / Subject (drop the person, mode "auto" with remove "subject") / Custom (the brush flow, mode "custom") — picking Background or Subject starts the free matte at once, Off keeps the cutout stored while showing the plain picture, and while a bake runs the other segments wait — Cancel first to change course. With a cutout on, the Stroke and Fill sections stack underneath, each behind its own on/off switch (Fill offers Color / Image; the Image list shows pictures imported into Media).+Recipes: "remove the background" on a person = auto — green-screen and plain-backdrop shots included, the matte keys them. "Cut out the dog" = custom with subject "the dog". "Put me on a beach" = auto + the beach behind (background image or lower track). Sticker/die-cut = auto + white cut stroke. A bold silhouette pop = offset stroke in a loud color. Turning it off = set_removal mode "off" — the picture shows plain, and the whole cutout (matte, stroke, fill) stays stored, so any on-mode brings it straight back.`,"watching-and-cutting": `# Watching footage & cutting by contentWhen a request depends on what the footage actually contains — "cut the dead air", "clip the best moment", "remove the boring part", "split where the scene changes" — watch it first. Never guess at content you haven't seen.