Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(timeline): resize a clip when its source range is edited, and fix the camera shadow

Etienne Lescotbf5e59cebb52
diff --git a/electron/ai-edition/agent-tools.test.ts b/electron/ai-edition/agent-tools.test.ts
index e403d7a2b..0cc42ce7b 100644
--- a/electron/ai-edition/agent-tools.test.ts
+++ b/electron/ai-edition/agent-tools.test.ts
@@ -183,6 +183,63 @@ describe("executeAgentTool", () => {
expect(clips[1]).toMatchObject({ timelineStartSec: 10, timelineEndSec: 40 });
});
+ it("setClipRange clamps/drops anchored pills and refreshes the reflowed ones' ms cache", () => {
+ const doc = fixtureDocument();
+ const withZooms: AxcutDocument = {
+ ...doc,
+ zoomRanges: [
+ // On clip_1 (window becomes [0,10]): one inside survives, one past the new end is dropped.
+ {
+ id: "z_in",
+ startMs: 5000,
+ endMs: 8000,
+ clipId: "clip_1",
+ sourceStartSec: 5,
+ sourceEndSec: 8,
+ depth: 3,
+ focus: { cx: 0.5, cy: 0.5 },
+ },
+ {
+ id: "z_out",
+ startMs: 15000,
+ endMs: 20000,
+ clipId: "clip_1",
+ sourceStartSec: 15,
+ sourceEndSec: 20,
+ depth: 3,
+ focus: { cx: 0.5, cy: 0.5 },
+ },
+ // On clip_2 (reflows 30→10): unchanged window, but its derived ms must follow the shift.
+ {
+ id: "z_shift",
+ startMs: 40000,
+ endMs: 45000,
+ clipId: "clip_2",
+ sourceStartSec: 40,
+ sourceEndSec: 45,
+ depth: 3,
+ focus: { cx: 0.5, cy: 0.5 },
+ },
+ ] as unknown as AxcutDocument["zoomRanges"],
+ };
+ const result = executeAgentTool(
+ withZooms,
+ "setClipRange",
+ JSON.stringify({ clipId: "clip_1", sourceStartSec: 0, sourceEndSec: 10 }),
+ );
+ expect(result.ok).toBe(true);
+ const zooms = result.document?.zoomRanges ?? [];
+ expect([...zooms.map((z) => z.id)].sort()).toEqual(["z_in", "z_shift"]);
+ expect(zooms.find((z) => z.id === "z_in")).toMatchObject({
+ sourceStartSec: 5,
+ sourceEndSec: 8,
+ startMs: 5000,
+ endMs: 8000,
+ });
+ // clip_2 moved from tl 30 to tl 10, so z_shift's raw ms drops by 20s.
+ expect(zooms.find((z) => z.id === "z_shift")).toMatchObject({ startMs: 20000, endMs: 25000 });
+ });
+
it("replaceTimeline rebuilds clips and inverse skip ranges", () => {
const doc = fixtureDocument();
// Test the rebuild path: strip user-placed clips first so the tool
diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts
index 02f81e26f..a06f5a429 100644
--- a/electron/ai-edition/agent-tools.ts
+++ b/electron/ai-edition/agent-tools.ts
@@ -10,7 +10,7 @@
import { z } from "zod";
import { createId } from "../../src/lib/ai-edition/document/ids";
-import { replaceTimeline, resequenceClips } from "../../src/lib/ai-edition/document/timeline";
+import { replaceTimeline, setClipSourceRange } from "../../src/lib/ai-edition/document/timeline";
import type { AxcutDocument } from "../../src/lib/ai-edition/schema";
import {
anchorRegionsWithDerivedMs,
@@ -594,25 +594,11 @@ export function executeAgentTool(
}
const sourceStartSec = Math.min(parsed.data.sourceStartSec, parsed.data.sourceEndSec);
const sourceEndSec = Math.max(parsed.data.sourceStartSec, parsed.data.sourceEndSec);
- const clips = resequenceClips(
- document.timeline.clips.map((c) =>
- c.id === clipId
- ? {
- ...c,
- sourceStartSec,
- sourceEndSec,
- // ponytail: zero the timeline span so resequenceClips derives the
- // clip length from the new source range instead of the stale one.
- timelineStartSec: 0,
- timelineEndSec: 0,
- }
- : c,
- ),
- );
- const next: AxcutDocument = {
- ...document,
- timeline: { ...document.timeline, clips },
- };
+ // One shared mutator with the modale + op dispatcher: recomputes the clip's
+ // width from the new source window AND clamps/drops the anchored pills the
+ // trim removed. Hand-rolling it here is exactly what left this façade orphaning
+ // stale pills the other two didn't.
+ const next = setClipSourceRange(document, clipId, sourceStartSec, sourceEndSec);
return {
ok: true,
document: next,
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rs
index 20eec05d4..cc32e0ec7 100644
--- a/poc-d3d/src/compositor.rs
+++ b/poc-d3d/src/compositor.rs
@@ -358,6 +358,12 @@ const SCREEN_SHADOW_SPREAD_FRAC: f32 = 40.0 / SHADOW_TUNING_REF_PX;
const SCREEN_SHADOW_OFFSET_FRAC: f32 = 16.0 / SHADOW_TUNING_REF_PX;
const WEBCAM_SHADOW_SPREAD_FRAC: f32 = 32.0 / SHADOW_TUNING_REF_PX;
const WEBCAM_SHADOW_OFFSET_FRAC: f32 = 12.0 / SHADOW_TUNING_REF_PX;
+/// Opacité FIXE de l'ombre portée de la caméra (layout PiP uniquement). Contrairement à
+/// l'ombre de l'écran — dont l'opacité est pilotée par le slider Shadow (`shadow_scale`) —
+/// l'ombre de la caméra est une ombre légère NON paramétrable : même valeur quelle que soit
+/// la position du slider. Parité avec le preset PiP côté web (`compositeLayout.ts`,
+/// `rgba(0,0,0,0.35)`), dont l'ombre est elle aussi un forfait fixe et PiP-only.
+const WEBCAM_SHADOW_OPACITY: f32 = 0.35;
/// Taille de base du curseur, même convention (34 px réglés contre un cadre 1080).
const CURSOR_BASE_SIZE_FRAC: f32 = 34.0 / SHADOW_TUNING_REF_PX;
@@ -1925,10 +1931,18 @@ impl Compositor {
// miroir = échanger les bornes u du rect source (flip horizontal).
let (u0, u1) = if lp.webcam_mirror { (su1, su0) } else { (su0, su1) };
if lp.has_webcam {
- // L'ombre portée appartient à la bulle flottante : elle se retire avec elle
- // (`shape_fade`), pour qu'au plein écran plus rien n'encadre la caméra.
- if cfg.shadow && shape_fade > 0.0 {
- let strength = 0.5 * lp.shadow_scale * shape_fade;
+ // L'ombre portée appartient à la bulle flottante PiP : elle se retire avec elle
+ // (`shape_fade`), pour qu'au plein écran plus rien n'encadre la caméra. C'est une
+ // ombre légère NON paramétrable — indépendante du slider Shadow, qui ne pilote plus
+ // que l'écran (`WEBCAM_SHADOW_OPACITY`, pas `shadow_scale`) — et propre au PiP : les
+ // blocs side-by-side / top-bottom soudent la caméra à l'écran et n'en portent aucune
+ // (parité `preset.shadow` web, `null` hors PiP dans `compositeLayout.ts`).
+ let webcam_is_block = matches!(
+ scene_preset.as_deref(),
+ Some("dual-frame") | Some("vertical-stack"),
+ );
+ if cfg.shadow && !webcam_is_block && shape_fade > 0.0 {
+ let strength = WEBCAM_SHADOW_OPACITY * shape_fade;
self.draw_shadow(
w_dst,
w_px,
diff --git a/src/lib/ai-edition/document/operations.test.ts b/src/lib/ai-edition/document/operations.test.ts
index fd646c5e9..0f0c5be37 100644
--- a/src/lib/ai-edition/document/operations.test.ts
+++ b/src/lib/ai-edition/document/operations.test.ts
@@ -176,7 +176,7 @@ describe("applyTimelineOperation.restore_full_timeline", () => {
});
describe("applyTimelineOperation.update_clip_range", () => {
- it("trims the named clip and reseats the timeline", () => {
+ it("trims the named clip and reseats the timeline to the new source length", () => {
const result = applyTimelineOperation(makeDoc(), {
type: "update_clip_range",
clipId: "clip_1",
@@ -186,5 +186,57 @@ describe("applyTimelineOperation.update_clip_range", () => {
const clip = result.document.timeline.clips.find((c) => c.id === "clip_1");
expect(clip?.sourceStartSec).toBe(10);
expect(clip?.sourceEndSec).toBe(25);
+ // The clip's width follows its 15s source window, not the stale 60s.
+ expect(clip?.timelineStartSec).toBe(0);
+ expect(clip?.timelineEndSec).toBe(15);
+ });
+
+ it("clamps and drops anchored pills against the narrowed window (façade parity with the modal)", () => {
+ const doc = makeDoc();
+ doc.zoomRanges = [
+ {
+ id: "z_keep",
+ startMs: 12000,
+ endMs: 14000,
+ clipId: "clip_1",
+ sourceStartSec: 12,
+ sourceEndSec: 14,
+ depth: 3,
+ focus: { cx: 0.5, cy: 0.5 },
+ },
+ {
+ id: "z_edge",
+ startMs: 20000,
+ endMs: 30000,
+ clipId: "clip_1",
+ sourceStartSec: 20,
+ sourceEndSec: 30,
+ depth: 3,
+ focus: { cx: 0.5, cy: 0.5 },
+ },
+ {
+ id: "z_drop",
+ startMs: 40000,
+ endMs: 45000,
+ clipId: "clip_1",
+ sourceStartSec: 40,
+ sourceEndSec: 45,
+ depth: 3,
+ focus: { cx: 0.5, cy: 0.5 },
+ },
+ ] as unknown as AxcutDocument["zoomRanges"];
+ const result = applyTimelineOperation(doc, {
+ type: "update_clip_range",
+ clipId: "clip_1",
+ sourceStartSec: 10,
+ sourceEndSec: 25,
+ });
+ const zooms = result.document.zoomRanges;
+ expect(zooms.map((z) => z.id)).toEqual(["z_keep", "z_edge"]);
+ // z_edge (20-30) survives only where it overlaps the [10,25] window → 20-25.
+ expect(zooms.find((z) => z.id === "z_edge")).toMatchObject({
+ sourceStartSec: 20,
+ sourceEndSec: 25,
+ });
});
});
diff --git a/src/lib/ai-edition/document/operations.ts b/src/lib/ai-edition/document/operations.ts
index f355db909..f1a4db6e0 100644
--- a/src/lib/ai-edition/document/operations.ts
+++ b/src/lib/ai-edition/document/operations.ts
@@ -15,9 +15,8 @@ import {
moveClip,
normalizeIntervals,
primaryAssetDuration,
- rederiveRegionMs,
replaceTimeline,
- resequenceClips,
+ setClipSourceRange,
} from "./timeline";
export type AxcutTimelineOperation =
@@ -273,29 +272,13 @@ export function applyTimelineOperation(
return { document: next, summary: "restored full timeline" };
}
case "update_clip_range": {
- const oldClips = document.timeline.clips;
- const clips = oldClips.map((c) => {
- if (c.id !== op.clipId) return c;
- const lo = Math.max(0, Math.min(op.sourceStartSec, op.sourceEndSec));
- const hi = Math.max(lo, Math.max(op.sourceStartSec, op.sourceEndSec));
- return {
- ...c,
- sourceStartSec: lo,
- sourceEndSec: hi,
- timelineStartSec: 0,
- timelineEndSec: 0,
- };
- });
- const newClips = resequenceClips(clips);
- const nextDoc: AxcutDocument = {
- ...document,
- timeline: {
- ...document.timeline,
- clips: newClips,
- },
- preview: { ...document.preview, revision: document.preview.revision + 1 },
+ // Shared clip-trim recipe (width + pill clamp/rederive); this façade adds its
+ // own preview-revision bump so the rendered frame refreshes after the edit.
+ const base = setClipSourceRange(document, op.clipId, op.sourceStartSec, op.sourceEndSec);
+ const finalDoc: AxcutDocument = {
+ ...base,
+ preview: { ...base.preview, revision: base.preview.revision + 1 },
};
- const finalDoc = rederiveRegionMs(nextDoc, newClips);
return {
document: finalDoc,
summary: `trimmed clip to ${formatSec(Math.min(op.sourceStartSec, op.sourceEndSec))}–${formatSec(Math.max(op.sourceStartSec, op.sourceEndSec))}`,
diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.ts
index 912d923fa..c5c402673 100644
--- a/src/lib/ai-edition/document/timeline.test.ts
+++ b/src/lib/ai-edition/document/timeline.test.ts
@@ -7,9 +7,12 @@ import {
moveClip,
normalizeIntervals,
primaryAssetDuration,
+ rederiveRegionMs,
replaceTimeline,
+ resequenceClips,
resolvePlaybackSegments,
restoreFullTimeline,
+ setClipSourceRange,
subtractInterval,
timelineIntervals,
} from "./timeline";
@@ -515,3 +518,179 @@ describe("duplicateClip / moveClip", () => {
expect(next.zoomRanges[0]).toMatchObject({ startMs: 3000, endMs: 5000 });
});
});
+
+function makeZoom(overrides: Partial<AxcutDocument["zoomRanges"][number]> = {}) {
+ return {
+ id: "z1",
+ startMs: 0,
+ endMs: 0,
+ clipId: "clip_a",
+ sourceStartSec: 0,
+ sourceEndSec: 0,
+ depth: 3 as const,
+ focus: { cx: 0.5, cy: 0.5 },
+ ...overrides,
+ };
+}
+
+describe("resequenceClips recomputes a clip's length from its source window when its extent is zeroed", () => {
+ it("uses the source length (not the stale timeline length) once the timeline extent is 0", () => {
+ // The clip's OLD width was 10s; its source window was just narrowed to 3s and its
+ // timeline extent zeroed (the signal both the Edit modal and the agent use). The
+ // resequenced clip must be 3s wide, not the stale 10s.
+ const [clip] = resequenceClips([
+ makeClip({ sourceStartSec: 2, sourceEndSec: 5, timelineStartSec: 0, timelineEndSec: 0 }),
+ ]);
+ expect(clip.timelineStartSec).toBe(0);
+ expect(clip.timelineEndSec).toBe(3);
+ });
+});
+
+describe("rederiveRegionMs — clamps anchored regions to their clip's kept source window", () => {
+ const twoClipDoc = () =>
+ makeDoc({
+ timeline: {
+ ...makeDoc().timeline,
+ clips: [
+ makeClip({ id: "clip_a", sourceStartSec: 0, sourceEndSec: 10, timelineEndSec: 10 }),
+ ],
+ },
+ });
+
+ it("shortens a fragment that overhangs a tail-trimmed clip to the surviving overlap", () => {
+ // Clip window narrowed to [0,7]; a zoom authored at source 6-8 keeps only 6-7.
+ const doc = twoClipDoc();
+ doc.timeline.clips[0].sourceEndSec = 7;
+ doc.zoomRanges = [makeZoom({ sourceStartSec: 6, sourceEndSec: 8, startMs: 6000, endMs: 8000 })];
+ const next = rederiveRegionMs(doc, doc.timeline.clips);
+ expect(next.zoomRanges).toHaveLength(1);
+ expect(next.zoomRanges[0]).toMatchObject({
+ sourceStartSec: 6,
+ sourceEndSec: 7,
+ startMs: 6000,
+ endMs: 7000,
+ });
+ });
+
+ it("clamps a fragment's head into a clip trimmed at the front", () => {
+ // Head trimmed: clip window is now [4,10]; a zoom at source 3-6 keeps only 4-6, and
+ // its raw span starts at the clip's own start (timelineStart + (4-4) = 0).
+ const doc = twoClipDoc();
+ doc.timeline.clips[0].sourceStartSec = 4;
+ doc.zoomRanges = [makeZoom({ sourceStartSec: 3, sourceEndSec: 6, startMs: 3000, endMs: 6000 })];
+ const next = rederiveRegionMs(doc, doc.timeline.clips);
+ expect(next.zoomRanges[0]).toMatchObject({
+ sourceStartSec: 4,
+ sourceEndSec: 6,
+ startMs: 0,
+ endMs: 2000,
+ });
+ });
+
+ it("drops a fragment that falls entirely outside the narrowed window", () => {
+ const doc = twoClipDoc();
+ doc.timeline.clips[0].sourceEndSec = 5;
+ doc.zoomRanges = [makeZoom({ sourceStartSec: 6, sourceEndSec: 8, startMs: 6000, endMs: 8000 })];
+ const next = rederiveRegionMs(doc, doc.timeline.clips);
+ expect(next.zoomRanges).toHaveLength(0);
+ });
+
+ it("leaves a fragment untouched when its clip is not probed yet (no real window)", () => {
+ // An unprobed clip has no meaningful sourceEndSec; clamping it would nuke every
+ // fragment, so the guard skips it and only refreshes the ms cache.
+ const doc = twoClipDoc();
+ doc.timeline.clips[0].sourceEndSec = undefined;
+ doc.zoomRanges = [makeZoom({ sourceStartSec: 6, sourceEndSec: 8, startMs: 6000, endMs: 8000 })];
+ const next = rederiveRegionMs(doc, doc.timeline.clips);
+ expect(next.zoomRanges).toHaveLength(1);
+ expect(next.zoomRanges[0]).toMatchObject({ sourceStartSec: 6, sourceEndSec: 8 });
+ });
+
+ it("is a no-op for a fragment already inside its clip's window", () => {
+ const doc = twoClipDoc();
+ doc.zoomRanges = [makeZoom({ sourceStartSec: 3, sourceEndSec: 4, startMs: 3000, endMs: 4000 })];
+ const next = rederiveRegionMs(doc, doc.timeline.clips);
+ expect(next.zoomRanges[0]).toMatchObject({
+ sourceStartSec: 3,
+ sourceEndSec: 4,
+ startMs: 3000,
+ endMs: 4000,
+ });
+ });
+});
+
+describe("setClipSourceRange — the one shared clip-trim mutator", () => {
+ const doc = () =>
+ makeDoc({
+ timeline: {
+ ...makeDoc().timeline,
+ clips: [
+ makeClip({ id: "clip_a", sourceStartSec: 0, sourceEndSec: 10, timelineEndSec: 10 }),
+ makeClip({
+ id: "clip_b",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 10,
+ timelineEndSec: 20,
+ }),
+ ],
+ },
+ zoomRanges: [
+ makeZoom({
+ id: "z_in",
+ clipId: "clip_a",
+ sourceStartSec: 2,
+ sourceEndSec: 3,
+ startMs: 2000,
+ endMs: 3000,
+ }),
+ makeZoom({
+ id: "z_out",
+ clipId: "clip_a",
+ sourceStartSec: 6,
+ sourceEndSec: 8,
+ startMs: 6000,
+ endMs: 8000,
+ }),
+ makeZoom({
+ id: "z_after",
+ clipId: "clip_b",
+ sourceStartSec: 2,
+ sourceEndSec: 4,
+ startMs: 12000,
+ endMs: 14000,
+ }),
+ ] as unknown as AxcutDocument["zoomRanges"],
+ });
+
+ it("recomputes the clip width from the new source window and reflows downstream", () => {
+ const next = setClipSourceRange(doc(), "clip_a", 0, 4);
+ expect(next.timeline.clips[0]).toMatchObject({ timelineStartSec: 0, timelineEndSec: 4 });
+ // clip_b reflows to start where the trimmed clip now ends.
+ expect(next.timeline.clips[1]).toMatchObject({ timelineStartSec: 4, timelineEndSec: 14 });
+ });
+
+ it("clamps/drops the trimmed clip's pills and refreshes the reflowed clip's ms cache", () => {
+ const next = setClipSourceRange(doc(), "clip_a", 0, 4);
+ const byId = Object.fromEntries(next.zoomRanges.map((z) => [z.id, z]));
+ // z_in survives inside [0,4]; z_out sat past the new 4s end → gone.
+ expect(Object.keys(byId).sort()).toEqual(["z_after", "z_in"]);
+ expect(byId.z_in).toMatchObject({ startMs: 2000, endMs: 3000 });
+ // clip_b moved from tl 10 to tl 4, so z_after's derived ms drops by 6s.
+ expect(byId.z_after).toMatchObject({ startMs: 6000, endMs: 8000 });
+ });
+
+ it("orders reversed bounds, clamps negatives, and no-ops an unknown clip", () => {
+ const reversed = setClipSourceRange(doc(), "clip_a", 8, -3);
+ expect(reversed.timeline.clips[0]).toMatchObject({ sourceStartSec: 0, sourceEndSec: 8 });
+ const untouched = setClipSourceRange(doc(), "clip_missing", 0, 2);
+ expect(untouched.timeline.clips.map((c) => c.id)).toEqual(["clip_a", "clip_b"]);
+ expect(untouched.timeline.clips[0]).toMatchObject({ sourceEndSec: 10, timelineEndSec: 10 });
+ });
+
+ it("does not bump preview.revision (the caller owns that)", () => {
+ const before = doc();
+ const next = setClipSourceRange(before, "clip_a", 0, 4);
+ expect(next.preview.revision).toBe(before.preview.revision);
+ });
+});
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 2b836ff90..18eb05d41 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -257,37 +257,57 @@ function mapAllRegionCollections(
};
}
+/** A clamped fragment this short has no surviving content — treat it as fully
+ * trimmed away and drop it (also absorbs boundary rounding). Matches the coalescer's
+ * touch epsilon (`coalesceByIdentity`). */
+const REGION_WINDOW_EPSILON_SEC = 0.001;
+
/**
- * Re-derive the transition `startMs`/`endMs` cache of every clip-anchored modifier
- * from its anchor + the given clip layout.
+ * Reconcile every clip-anchored modifier with the given clip layout: clamp each
+ * fragment to its clip's CURRENT kept source window, drop the ones with nothing left,
+ * and refresh the transition `startMs`/`endMs` cache from the (possibly clamped) anchor.
*
- * Structural ops that PRESERVE clip identity (move / duplicate / trim) leave the
- * anchors valid — a fragment travels with its clip by `clipId` — so nothing is
- * reprojected; only the derived cache moves. That is what let the old
- * `reprojectDocumentRegions` / `reprojectRegionsForReorder` machinery go away.
- * A fragment whose anchor clip no longer exists is dropped (its content is gone, and
- * the display coalescer drops it too). Not-yet-anchored regions pass through
- * untouched. Guards the empty-clip case so a transient wipe can't delete everything.
+ * Structural ops that PRESERVE a clip's source window (move / duplicate / reorder) leave
+ * the anchors inside their window, so the clamp is a no-op and only the derived cache
+ * moves — that is what let the old `reprojectDocumentRegions` / `reprojectRegionsForReorder`
+ * machinery go away. A source-range EDIT (the clip's Edit modal / the agent's
+ * `update_clip_range`) narrows the window: a fragment now beyond it has lost its content,
+ * so it is shortened to the surviving overlap or dropped when it falls entirely outside —
+ * the same intersection the export/native path (`projectRegionsToSource`) already applies,
+ * now folded in here so the STORED document and the timeline pills match it and no façade
+ * can forget it. A fragment whose anchor clip no longer exists is dropped (content gone).
+ * A not-yet-probed clip (no real source window) is left un-clamped so a transient
+ * zero-width window can't nuke its fragments. Not-yet-anchored regions pass through
+ * untouched; the empty-clip case is guarded so a transient wipe can't delete everything.
*/
export function rederiveRegionMs(document: AxcutDocument, clips: AxcutClip[]): AxcutDocument {
if (clips.length === 0) return document;
+ const clipById = new Map(clips.map((c) => [c.id, c]));
return mapAllRegionCollections(document, (regions) =>
regions.flatMap((region) => {
if (!isAnchored(region)) {
return [region];
}
+ const clip = clipById.get(region.clipId);
+ if (!clip) return [];
+ let { sourceStartSec, sourceEndSec } = region;
+ // Only clamp against a real, probed window — an unprobed clip has
+ // `sourceEndSec` at/below `sourceStartSec` and must not shave its fragments.
+ if (clip.sourceEndSec !== undefined && clip.sourceEndSec > clip.sourceStartSec) {
+ sourceStartSec = Math.max(sourceStartSec, clip.sourceStartSec);
+ sourceEndSec = Math.min(sourceEndSec, clip.sourceEndSec);
+ if (sourceEndSec - sourceStartSec <= REGION_WINDOW_EPSILON_SEC) return [];
+ }
const span = anchoredToRawSpanSec(
- {
- clipId: region.clipId,
- sourceStartSec: region.sourceStartSec,
- sourceEndSec: region.sourceEndSec,
- },
+ { clipId: region.clipId, sourceStartSec, sourceEndSec },
clips,
);
if (!span) return [];
return [
{
...region,
+ sourceStartSec,
+ sourceEndSec,
startMs: Math.round(span.startSec * 1000),
endMs: Math.round(span.endSec * 1000),
},
@@ -514,6 +534,42 @@ export function duplicateClip(
return rederiveRegionMs(updatedDoc, newClips);
}
+/**
+ * The single mutator for "narrow/extend a clip's own source in/out" — the edit the
+ * clip's Edit modal, the renderer op dispatcher, and the LLM's `setClipRange` tool all
+ * perform. Extracted here (like `moveClip` / `duplicateClip`) so the recipe lives in one
+ * place instead of being re-derived per façade, which is what let the three drift apart
+ * (stale width, un-clamped pills). Pure; does NOT touch `preview.revision` — a caller that
+ * needs a preview refresh bumps it itself, so this stays a plain document→document transform.
+ *
+ * Recipe: clamp + order the range, zero the clip's timeline extent so `resequenceClips`
+ * recomputes its RAW length from the new source window (a raw clip's timeline length equals
+ * its source length), lay everything back-to-back, then `rederiveRegionMs` clamps every
+ * anchored pill to the clip's kept window (dropping what the trim removed) and refreshes the
+ * derived ms of the clips that reflowed. An unknown `clipId` is a no-op.
+ */
+export function setClipSourceRange(
+ document: AxcutDocument,
+ clipId: string,
+ sourceStartSec: number,
+ sourceEndSec: number,
+): AxcutDocument {
+ const clamp = (n: number) => (Number.isFinite(n) ? Math.max(0, n) : 0);
+ const lo = Math.min(clamp(sourceStartSec), clamp(sourceEndSec));
+ const hi = Math.max(clamp(sourceStartSec), clamp(sourceEndSec));
+ const arr = document.timeline.clips.map((c) =>
+ c.id === clipId
+ ? { ...c, sourceStartSec: lo, sourceEndSec: hi, timelineStartSec: 0, timelineEndSec: 0 }
+ : c,
+ );
+ const newClips = resequenceClips(arr);
+ const next: AxcutDocument = {
+ ...document,
+ timeline: { ...document.timeline, clips: newClips },
+ };
+ return rederiveRegionMs(next, newClips);
+}
+
export function restoreFullTimeline(document: AxcutDocument): AxcutDocument {
const duration = primaryAssetDuration(document);
if (duration <= 0) return document;
diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts
index 3192f4e5e..c5bd8cf73 100644
--- a/src/lib/ai-edition/store/useTimeline.test.ts
+++ b/src/lib/ai-edition/store/useTimeline.test.ts
@@ -382,3 +382,92 @@ describe("useTimeline backfills missing source dimensions on load", () => {
expect(bridgeMocks.save).not.toHaveBeenCalled();
});
});
+
+describe("useTimeline.updateClipSourceRange (Edit-clip modal)", () => {
+ const anchoredZoom = (id: string, s: number, e: number) => ({
+ id,
+ startMs: s * 1000,
+ endMs: e * 1000,
+ clipId: "clip_a",
+ sourceStartSec: s,
+ sourceEndSec: e,
+ depth: 3 as const,
+ focus: { cx: 0.5, cy: 0.5 },
+ });
+
+ beforeEach(() => {
+ useProjectStore.getState().clear();
+ for (const mock of Object.values(bridgeMocks)) mock.mockReset();
+ bridgeMocks.save.mockImplementation(async (doc: typeof sampleDoc) => ({
+ success: true,
+ document: doc,
+ }));
+ useProjectStore.setState({
+ projectId: "proj_test",
+ document: {
+ ...sampleDoc,
+ schemaVersion: 5,
+ zoomRanges: [anchoredZoom("z_keep", 2, 3), anchoredZoom("z_drop", 6, 8)],
+ } as unknown as typeof sampleDoc,
+ revision: 1,
+ status: "ready",
+ error: null,
+ });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("shrinks the clip's timeline width to match the narrowed source window", async () => {
+ const { result } = renderHook(() => useTimeline());
+ // Trim the 10s clip down to its first 4s of source.
+ await act(async () => {
+ await result.current.updateClipSourceRange("clip_a", 0, 4);
+ });
+ const clip = useProjectStore.getState().document?.timeline.clips[0];
+ expect(clip).toMatchObject({ sourceStartSec: 0, sourceEndSec: 4 });
+ // The width followed the edit instead of keeping its stale 10s extent.
+ expect(clip?.timelineStartSec).toBe(0);
+ expect(clip?.timelineEndSec).toBe(4);
+ });
+
+ it("drops a pill sitting over the truncated tail and keeps the one that survives", async () => {
+ const { result } = renderHook(() => useTimeline());
+ await act(async () => {
+ await result.current.updateClipSourceRange("clip_a", 0, 4);
+ });
+ const zooms = useProjectStore.getState().document?.zoomRanges ?? [];
+ // z_keep (source 2-3) stays; z_drop (source 6-8) is entirely past the new 4s end.
+ expect(zooms.map((z) => z.id)).toEqual(["z_keep"]);
+ expect(zooms[0]).toMatchObject({
+ sourceStartSec: 2,
+ sourceEndSec: 3,
+ startMs: 2000,
+ endMs: 3000,
+ });
+ });
+
+ it("shortens a pill that straddles the new clip end to the surviving overlap", async () => {
+ useProjectStore.setState({
+ document: {
+ ...sampleDoc,
+ schemaVersion: 5,
+ zoomRanges: [anchoredZoom("z_edge", 3, 7)],
+ } as unknown as typeof sampleDoc,
+ });
+ const { result } = renderHook(() => useTimeline());
+ await act(async () => {
+ await result.current.updateClipSourceRange("clip_a", 0, 5);
+ });
+ const zooms = useProjectStore.getState().document?.zoomRanges ?? [];
+ expect(zooms).toHaveLength(1);
+ // 3-7 clamped to the [0,5] window → 3-5.
+ expect(zooms[0]).toMatchObject({
+ sourceStartSec: 3,
+ sourceEndSec: 5,
+ startMs: 3000,
+ endMs: 5000,
+ });
+ });
+});
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index 3d433b69b..b80d636f1 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -13,6 +13,7 @@ import {
PLACEHOLDER_DURATION_SEC,
rederiveRegionMs,
resequenceClips,
+ setClipSourceRange,
} from "../document/timeline";
import type { AxcutClipCropRegion, AxcutDocument } from "../schema";
import { probeVideoDimensions, probeVideoDuration } from "../timeline/duration";
@@ -871,25 +872,12 @@ export function useTimeline() {
// effective duration, so every clip is resequenced back-to-back afterward —
// same invariant as insertClipAt/moveClip/removeClip — instead of leaving
// downstream clips at their old timeline positions (which would overlap).
+ // The whole recipe (resequence width + clamp/rederive pills) lives in the one
+ // pure `setClipSourceRange`, shared with the op dispatcher and the LLM tool.
const updateClipSourceRange = useCallback(
async (clipId: string, sourceStartSec: number, sourceEndSec: number) => {
if (!document) return;
- const clamp = (n: number) => (Number.isFinite(n) ? Math.max(0, n) : 0);
- const s = clamp(sourceStartSec);
- const e = clamp(sourceEndSec);
- const oldClips = document.timeline.clips;
- const arr = oldClips.map((c) =>
- c.id === clipId
- ? { ...c, sourceStartSec: Math.min(s, e), sourceEndSec: Math.max(s, e) }
- : c,
- );
- const newClips = resequenceClips(arr);
- const next: AxcutDocument = {
- ...document,
- timeline: { ...document.timeline, clips: newClips },
- };
- const finalDoc = rederiveRegionMs(next, newClips);
- await saveDocument(finalDoc);
+ await saveDocument(setClipSourceRange(document, clipId, sourceStartSec, sourceEndSec));
},
[document, saveDocument],
);