@nodetool-ai/timeline 0.8.2 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/animation/compile.d.ts.map +1 -1
  3. package/dist/animation/compile.js +5 -1
  4. package/dist/animation/compile.js.map +1 -1
  5. package/dist/clipAudio.d.ts +32 -0
  6. package/dist/clipAudio.d.ts.map +1 -0
  7. package/dist/clipAudio.js +70 -0
  8. package/dist/clipAudio.js.map +1 -0
  9. package/dist/clipSpeed.d.ts +17 -0
  10. package/dist/clipSpeed.d.ts.map +1 -0
  11. package/dist/clipSpeed.js +58 -0
  12. package/dist/clipSpeed.js.map +1 -0
  13. package/dist/dropResolve.d.ts +14 -6
  14. package/dist/dropResolve.d.ts.map +1 -1
  15. package/dist/dropResolve.js +113 -37
  16. package/dist/dropResolve.js.map +1 -1
  17. package/dist/finish-storyboard.d.ts.map +1 -1
  18. package/dist/finish-storyboard.js +46 -39
  19. package/dist/finish-storyboard.js.map +1 -1
  20. package/dist/fonts/google-fonts.d.ts +6 -0
  21. package/dist/fonts/google-fonts.d.ts.map +1 -1
  22. package/dist/fonts/google-fonts.js +7 -1
  23. package/dist/fonts/google-fonts.js.map +1 -1
  24. package/dist/group.d.ts +16 -4
  25. package/dist/group.d.ts.map +1 -1
  26. package/dist/group.js +53 -6
  27. package/dist/group.js.map +1 -1
  28. package/dist/index.d.ts +4 -0
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +4 -0
  31. package/dist/index.js.map +1 -1
  32. package/dist/interchange.d.ts +8 -0
  33. package/dist/interchange.d.ts.map +1 -1
  34. package/dist/interchange.js +217 -27
  35. package/dist/interchange.js.map +1 -1
  36. package/dist/interchangeImport.d.ts +87 -0
  37. package/dist/interchangeImport.d.ts.map +1 -0
  38. package/dist/interchangeImport.js +404 -0
  39. package/dist/interchangeImport.js.map +1 -0
  40. package/dist/keyframes.d.ts +12 -1
  41. package/dist/keyframes.d.ts.map +1 -1
  42. package/dist/keyframes.js +78 -21
  43. package/dist/keyframes.js.map +1 -1
  44. package/dist/linked.js +1 -1
  45. package/dist/mediaTrack.d.ts +11 -0
  46. package/dist/mediaTrack.d.ts.map +1 -1
  47. package/dist/mediaTrack.js +25 -0
  48. package/dist/mediaTrack.js.map +1 -1
  49. package/dist/midi/edit.d.ts +5 -0
  50. package/dist/midi/edit.d.ts.map +1 -1
  51. package/dist/midi/edit.js +2 -1
  52. package/dist/midi/edit.js.map +1 -1
  53. package/dist/midi/grid.d.ts.map +1 -1
  54. package/dist/midi/grid.js +8 -4
  55. package/dist/midi/grid.js.map +1 -1
  56. package/dist/midi/tempo.d.ts.map +1 -1
  57. package/dist/midi/tempo.js +8 -0
  58. package/dist/midi/tempo.js.map +1 -1
  59. package/dist/ops/apply.d.ts +9 -0
  60. package/dist/ops/apply.d.ts.map +1 -1
  61. package/dist/ops/apply.js +1816 -1425
  62. package/dist/ops/apply.js.map +1 -1
  63. package/dist/ops/parse.d.ts.map +1 -1
  64. package/dist/ops/parse.js +318 -357
  65. package/dist/ops/parse.js.map +1 -1
  66. package/dist/render/draw.d.ts +43 -1
  67. package/dist/render/draw.d.ts.map +1 -1
  68. package/dist/render/draw.js +123 -3
  69. package/dist/render/draw.js.map +1 -1
  70. package/dist/render/frameCompositor.d.ts +31 -3
  71. package/dist/render/frameCompositor.d.ts.map +1 -1
  72. package/dist/render/frameCompositor.js +58 -10
  73. package/dist/render/frameCompositor.js.map +1 -1
  74. package/dist/render/sceneModel.d.ts +18 -6
  75. package/dist/render/sceneModel.d.ts.map +1 -1
  76. package/dist/render/sceneModel.js +231 -85
  77. package/dist/render/sceneModel.js.map +1 -1
  78. package/dist/render/temporal.d.ts +9 -1
  79. package/dist/render/temporal.d.ts.map +1 -1
  80. package/dist/render/temporal.js +18 -1
  81. package/dist/render/temporal.js.map +1 -1
  82. package/dist/render/textLayout.d.ts +6 -0
  83. package/dist/render/textLayout.d.ts.map +1 -1
  84. package/dist/render/textLayout.js +13 -1
  85. package/dist/render/textLayout.js.map +1 -1
  86. package/dist/rippleEdit.d.ts +20 -3
  87. package/dist/rippleEdit.d.ts.map +1 -1
  88. package/dist/rippleEdit.js +89 -17
  89. package/dist/rippleEdit.js.map +1 -1
  90. package/dist/shotLink.d.ts +47 -0
  91. package/dist/shotLink.d.ts.map +1 -0
  92. package/dist/shotLink.js +92 -0
  93. package/dist/shotLink.js.map +1 -0
  94. package/dist/splitClip.d.ts.map +1 -1
  95. package/dist/splitClip.js +16 -2
  96. package/dist/splitClip.js.map +1 -1
  97. package/dist/storyboard.js +1 -1
  98. package/dist/takes.d.ts.map +1 -1
  99. package/dist/takes.js +15 -2
  100. package/dist/takes.js.map +1 -1
  101. package/dist/testing/host-ops.d.ts +16 -0
  102. package/dist/testing/host-ops.d.ts.map +1 -0
  103. package/dist/testing/host-ops.js +378 -0
  104. package/dist/testing/host-ops.js.map +1 -0
  105. package/dist/testing/index.d.ts +3 -0
  106. package/dist/testing/index.d.ts.map +1 -0
  107. package/dist/testing/index.js +3 -0
  108. package/dist/testing/index.js.map +1 -0
  109. package/dist/testing/ops.d.ts +30 -0
  110. package/dist/testing/ops.d.ts.map +1 -0
  111. package/dist/testing/ops.js +814 -0
  112. package/dist/testing/ops.js.map +1 -0
  113. package/dist/transitionAtCut.d.ts +29 -5
  114. package/dist/transitionAtCut.d.ts.map +1 -1
  115. package/dist/transitionAtCut.js +69 -33
  116. package/dist/transitionAtCut.js.map +1 -1
  117. package/dist/trimClip.d.ts +5 -8
  118. package/dist/trimClip.d.ts.map +1 -1
  119. package/dist/trimClip.js +38 -2
  120. package/dist/trimClip.js.map +1 -1
  121. package/dist/types.d.ts +11 -0
  122. package/dist/types.d.ts.map +1 -1
  123. package/dist/types.js.map +1 -1
  124. package/package.json +11 -5
package/dist/ops/apply.js CHANGED
@@ -22,21 +22,24 @@ import { isCropUsable } from "../crop.js";
22
22
  import { DEFAULT_MEDIA_CLIP_DURATION_MS, DEFAULT_MODEL3D_CLIP_DURATION_MS, DEFAULT_MODEL3D_CLIP_NAME, DEFAULT_TEXT_CLIP_COLOR, DEFAULT_TEXT_CLIP_DURATION_MS, clipFitsTrack, makeClip, makeClipVersion, makeTrack, mediaTypeForContentType, trackTypeForMediaType } from "../defaults.js";
23
23
  import { assertAuthorableFontFamily } from "../fonts/catalog.js";
24
24
  import { selectGeneratedMatteVersion } from "../generatedMatte.js";
25
- import { groupDescendantIds, isGroupClip, moveGroup, trimGroup, ungroup } from "../group.js";
26
- import { isMediaTrackStale, resliceTracksForSplitClip, resliceTracksForTrimmedClip } from "../mediaTrack.js";
25
+ import { groupDescendantIds, isGroupClip, moveUnitIds, trimGroup, ungroup } from "../group.js";
26
+ import { isMediaTrackStale, splitClipMediaTracks, resliceTracksForTrimmedClip } from "../mediaTrack.js";
27
27
  import { quantizeNotes, scaleVelocity, transposeNotes } from "../midi/edit.js";
28
28
  import { DEFAULT_MIDI_INSTRUMENT } from "../midi/instrument.js";
29
29
  import { createMidiNote, sortNotes, validateNotes } from "../midi/notes.js";
30
30
  import { findInstrumentPreset, MIDI_INSTRUMENT_PRESETS } from "../midi/presets.js";
31
31
  import { DEFAULT_TEMPO, rescaleClipsForTempo, resolveTempo } from "../midi/tempo.js";
32
+ import { msToTicks } from "../midi/ticks.js";
32
33
  import { computeModel3DBakeHash } from "../model3dBake.js";
33
34
  import { addReframeKeyframe, clearReframe, mediaTrackCanDriveReframe } from "../reframe.js";
34
35
  import { adaptSequenceFormat } from "../retarget.js";
36
+ import { sourceRate } from "../sourceRate.js";
35
37
  import { splitClip } from "../splitClip.js";
36
38
  import { activeTakeIdOf, deleteTake as deleteTakeOnClip, renameTake as renameTakeOnClip, selectTake } from "../takes.js";
37
39
  import { moveTrackOrder } from "../trackOrder.js";
38
- import { applyTransitionAtCutCandidate, planTransitionAtCut } from "../transitionAtCut.js";
39
- import { trimClip } from "../trimClip.js";
40
+ import { applyTransitionAtCutCandidate, transitionGrowthMs, transitionGrowthUnit, transitionLengthAtCut, planTransitionAtCut } from "../transitionAtCut.js";
41
+ import { retimeCaption, trimClip } from "../trimClip.js";
42
+ import { retimeClipSpeed } from "../clipSpeed.js";
40
43
  import { serializeClip, serializeMediaTrack, serializeTrack } from "./serialize.js";
41
44
  /** Units a failed lookup names before it stops and points at get_state. */
42
45
  const MAX_LISTED_UNITS = 12;
@@ -84,6 +87,33 @@ function resolveShortId(units, target, kind) {
84
87
  }
85
88
  return matches[0];
86
89
  }
90
+ /** A unit by exact id, or by an exact unique 12-character prefix of one. */
91
+ function findByIdOrShortId(units, target, kind) {
92
+ return (units.find((unit) => unit.id === target) ??
93
+ resolveShortId(units, target, kind));
94
+ }
95
+ /**
96
+ * The beat one `target` names: an exact id, an exact unique 12-character id
97
+ * prefix, or a 1-based position written as digits only. Anything else is
98
+ * refused, so a hex id that happens to start with a digit is never read as a
99
+ * position. Exported because the browser bridge resolves the same names.
100
+ */
101
+ export function resolveBeatTarget(beats, target) {
102
+ const byId = findByIdOrShortId(beats, target, "beat");
103
+ if (byId) {
104
+ return byId;
105
+ }
106
+ const byPosition = /^\d+$/.test(target)
107
+ ? beats[Number.parseInt(target, 10) - 1]
108
+ : undefined;
109
+ if (byPosition) {
110
+ return byPosition;
111
+ }
112
+ throw new Error(`No beat matches "${target}". Use a beat id or its 1-based position. ` +
113
+ (beats.length
114
+ ? `This plan has ${beats.length} beats.`
115
+ : "This sequence has no beat plan yet; run ui_timeline_plan_beats first."));
116
+ }
87
117
  /**
88
118
  * Name the units a caller could have meant, capped: a 200-clip sequence
89
119
  * listing all of them is one an agent stops reading.
@@ -205,8 +235,29 @@ class OpScope {
205
235
  this.tracks.push(track);
206
236
  return track;
207
237
  }
238
+ /** The first unlocked track of `type`, or a new one: a lock refuses writes. */
208
239
  findOrCreateTrack(type, name) {
209
- return (this.tracks.find((t) => t.type === type) ?? this.addTrack(type, name));
240
+ return (this.tracks.find((t) => t.type === type && !t.locked) ??
241
+ this.addTrack(type, name));
242
+ }
243
+ /**
244
+ * Refuse an edit that writes to a locked clip, a clip on a locked track, or
245
+ * a locked destination track. Every op that changes a clip or places one
246
+ * asks here, so the lock means the same thing on every path.
247
+ */
248
+ assertWritable(clips, destinationTrackId) {
249
+ const tracks = new Map(this.tracks.map((track) => [track.id, track]));
250
+ for (const clip of clips) {
251
+ if (clip.locked || tracks.get(clip.trackId)?.locked) {
252
+ throw new Error(`Clip "${clip.name}" or its track is locked. Unlock it before editing.`);
253
+ }
254
+ }
255
+ if (destinationTrackId !== undefined) {
256
+ const track = tracks.get(destinationTrackId);
257
+ if (track?.locked) {
258
+ throw new Error(`Track "${track.name}" is locked. Unlock it or choose another track.`);
259
+ }
260
+ }
210
261
  }
211
262
  resolveTrack(idOrName) {
212
263
  const byId = this.tracks.find((t) => t.id === idOrName);
@@ -278,20 +329,13 @@ class OpScope {
278
329
  return resolveClipTarget(this.state, target);
279
330
  }
280
331
  editTargets(clip) {
281
- const children = isGroupClip(clip)
282
- ? groupDescendantIds(this.clips, clip.id)
283
- : new Set();
284
- const targets = this.clips.filter((candidate) => candidate.id === clip.id ||
285
- children.has(candidate.id) ||
286
- (this.ctx.followLinks !== false &&
287
- clip.linkId &&
288
- candidate.linkId === clip.linkId));
289
- const tracks = new Map(this.tracks.map((track) => [track.id, track]));
290
- for (const target of targets) {
291
- if (target.locked || tracks.get(target.trackId)?.locked) {
292
- throw new Error(`Clip "${target.name}" or its track is locked. Unlock it before editing.`);
293
- }
294
- }
332
+ // A group's children and, when links are followed, every partner of the
333
+ // clip or of a child: the whole unit the editor would move.
334
+ const unit = moveUnitIds(this.clips, [clip.id], {
335
+ followLinks: this.ctx.followLinks !== false
336
+ });
337
+ const targets = this.clips.filter((candidate) => unit.has(candidate.id));
338
+ this.assertWritable(targets);
295
339
  return targets;
296
340
  }
297
341
  assertPictureTrack(track) {
@@ -307,12 +351,59 @@ class OpScope {
307
351
  }
308
352
  return next;
309
353
  }
354
+ /**
355
+ * How far a clip's source reaches, for capping a trim that grows it: the
356
+ * asset's own duration when the host knows it. An imported audio or video
357
+ * clip whose length nobody knows may not grow past its current out-point,
358
+ * the rule the editor's keyboard trim applies. Undefined means no cap — a
359
+ * picture with no running time, or a generated clip a regeneration can
360
+ * lengthen.
361
+ */
362
+ async sourceLimitMs(clip) {
363
+ if (clip.mediaType !== "audio" && clip.mediaType !== "video") {
364
+ return undefined;
365
+ }
366
+ if (!clip.currentAssetId) {
367
+ return undefined;
368
+ }
369
+ const known = await this.knownSourceMs(clip);
370
+ if (known !== undefined) {
371
+ return known;
372
+ }
373
+ if (clip.sourceType !== "imported") {
374
+ return undefined;
375
+ }
376
+ return (clip.outPointMs ??
377
+ (clip.inPointMs ?? 0) + clip.durationMs * sourceRate(clip));
378
+ }
379
+ /**
380
+ * The length of a clip's audio or video asset when the host knows it.
381
+ * Undefined for anything else, including an asset it cannot read.
382
+ */
383
+ async knownSourceMs(clip) {
384
+ if (clip.mediaType !== "audio" && clip.mediaType !== "video") {
385
+ return undefined;
386
+ }
387
+ const assetId = clip.currentAssetId;
388
+ if (!assetId) {
389
+ return undefined;
390
+ }
391
+ let known;
392
+ try {
393
+ known = (await this.ctx.resolveAsset?.(assetId))?.durationMs;
394
+ }
395
+ catch {
396
+ // An unreadable asset is an unknown length.
397
+ known = undefined;
398
+ }
399
+ return known !== undefined && known > 0 ? known : undefined;
400
+ }
310
401
  /**
311
402
  * The body of `trim_clip`, shared with `set_clip_params`: a caller that
312
403
  * sends `durationMs` alongside a style change means the same edit either
313
404
  * way, and two copies of the group-trim rule would drift.
314
405
  */
315
- applyTrim(clip, patch) {
406
+ applyTrim(clip, patch, maxSourceMs) {
316
407
  if (patch.durationMs === undefined &&
317
408
  patch.inPointMs === undefined &&
318
409
  patch.outPointMs === undefined) {
@@ -322,18 +413,51 @@ class OpScope {
322
413
  throw new Error("inPointMs cannot be negative.");
323
414
  }
324
415
  const prospective = patch.durationMs !== undefined && !isGroupClip(clip)
325
- ? trimClip(clip, "end", patch.durationMs - clip.durationMs)
416
+ ? trimSourceBounded(clip, patch.durationMs - clip.durationMs, maxSourceMs)
326
417
  : clip;
327
418
  const sourceIn = patch.inPointMs ?? prospective.inPointMs ?? 0;
328
419
  const sourceOut = patch.outPointMs ?? prospective.outPointMs;
329
420
  if (sourceOut !== undefined && sourceOut <= sourceIn) {
330
421
  throw new Error("outPointMs must be greater than inPointMs.");
331
422
  }
423
+ if (maxSourceMs !== undefined &&
424
+ patch.outPointMs !== undefined &&
425
+ patch.outPointMs > maxSourceMs) {
426
+ throw new Error(`outPointMs ${patch.outPointMs} is past the end of the source (${maxSourceMs}ms).`);
427
+ }
332
428
  if (isGroupClip(clip) &&
333
429
  (patch.inPointMs !== undefined || patch.outPointMs !== undefined)) {
334
430
  throw new Error("Groups carry no source media; trim their duration instead.");
335
431
  }
336
432
  const targets = this.editTargets(clip);
433
+ // An in-point alone is a slip: the window keeps its length and moves
434
+ // through the source, so the out-point moves with it — and a linked
435
+ // partner slips by the same timeline amount, or picture and sound part.
436
+ if (patch.inPointMs !== undefined &&
437
+ patch.durationMs === undefined &&
438
+ patch.outPointMs === undefined) {
439
+ const slipMs = (patch.inPointMs - (clip.inPointMs ?? 0)) / sourceRate(clip);
440
+ const slipped = targets.map((target) => {
441
+ const inPointMs = target.id === clip.id
442
+ ? patch.inPointMs
443
+ : (target.inPointMs ?? 0) + slipMs * sourceRate(target);
444
+ if (inPointMs < 0) {
445
+ throw new Error(`Linked clip "${target.name}" has no source before its in-point to slip into.`);
446
+ }
447
+ return { target, inPointMs };
448
+ });
449
+ for (const { target, inPointMs } of slipped) {
450
+ target.inPointMs = inPointMs;
451
+ target.outPointMs = inPointMs + target.durationMs * sourceRate(target);
452
+ // Words are timed on the clip's clock; the media moved under it.
453
+ if (target.caption) {
454
+ target.caption = retimeCaption(target.caption, -slipMs);
455
+ }
456
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, target);
457
+ this.touch(target.id);
458
+ }
459
+ return clip;
460
+ }
337
461
  if (targets.length > 1 &&
338
462
  patch.durationMs !== undefined &&
339
463
  !isGroupClip(clip)) {
@@ -342,7 +466,9 @@ class OpScope {
342
466
  if (target.durationMs + delta <= 0) {
343
467
  throw new Error("Linked trim would remove a clip. Shorten the trim or unlink it first.");
344
468
  }
345
- const trimmed = trimClip(target, "end", delta);
469
+ const trimmed = target.id === clip.id
470
+ ? trimSourceBounded(target, delta, maxSourceMs)
471
+ : trimClip(target, "end", delta);
346
472
  if (target.id === clip.id) {
347
473
  if (patch.inPointMs !== undefined) {
348
474
  trimmed.inPointMs = patch.inPointMs;
@@ -381,7 +507,7 @@ class OpScope {
381
507
  if (patch.durationMs <= 0) {
382
508
  throw new Error(`durationMs must be greater than 0 (got ${patch.durationMs}); delete the clip instead of trimming it to nothing`);
383
509
  }
384
- next = this.replaceClip(clip, trimClip(clip, "end", patch.durationMs - clip.durationMs));
510
+ next = this.replaceClip(clip, trimSourceBounded(clip, patch.durationMs - clip.durationMs, maxSourceMs));
385
511
  }
386
512
  if (patch.inPointMs !== undefined) {
387
513
  next.inPointMs = patch.inPointMs;
@@ -397,12 +523,50 @@ class OpScope {
397
523
  this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, next);
398
524
  return next;
399
525
  }
526
+ /**
527
+ * Move a clip's head by `deltaMs` (positive grows it earlier), for the clip
528
+ * and every linked partner, keeping each one's end where it was. A group
529
+ * carries its children with the edge (D4).
530
+ */
531
+ applyHeadTrim(clip, deltaMs) {
532
+ const targets = this.editTargets(clip);
533
+ if (isGroupClip(clip)) {
534
+ this.clips = trimGroup(this.clips, clip.id, "start", deltaMs);
535
+ }
536
+ else {
537
+ // Every partner is trimmed before any is written, so one that runs out
538
+ // of source leaves the whole group as it was.
539
+ const trimmed = targets.map((target) => ({
540
+ target,
541
+ next: trimClip(target, "start", deltaMs)
542
+ }));
543
+ for (const { target, next } of trimmed) {
544
+ this.replaceClip(target, next);
545
+ }
546
+ }
547
+ for (const target of targets) {
548
+ const next = this.resolveClip(target.id);
549
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, next);
550
+ this.touch(next.id);
551
+ }
552
+ return this.resolveClip(clip.id);
553
+ }
400
554
  /** The body of `move_clip`, shared with `set_clip_params`. */
401
555
  applyMove(clip, patch) {
402
556
  if (patch.startMs === undefined && patch.trackId === undefined) {
403
557
  return clip;
404
558
  }
405
559
  const targets = this.editTargets(clip);
560
+ // The destination is checked before anything moves, so a refused track
561
+ // leaves the clip and its partners where they were.
562
+ let destination;
563
+ if (patch.trackId !== undefined) {
564
+ destination = this.resolveTrack(patch.trackId);
565
+ this.assertWritable([], destination.id);
566
+ if (!clipFitsTrack(clip.mediaType, destination.type)) {
567
+ throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip and cannot go on ${destination.type} track "${destination.name}".`);
568
+ }
569
+ }
406
570
  if (targets.length > 1 &&
407
571
  patch.startMs !== undefined &&
408
572
  !isGroupClip(clip)) {
@@ -412,31 +576,34 @@ class OpScope {
412
576
  target.startMs += delta;
413
577
  this.touch(target.id);
414
578
  }
415
- if (patch.trackId !== undefined) {
416
- clip.trackId = this.resolveTrack(patch.trackId).id;
579
+ if (destination) {
580
+ clip.trackId = destination.id;
417
581
  }
418
582
  return clip;
419
583
  }
420
584
  // Moving a group moves what it holds by the same delta (D4). Children keep
421
585
  // their own tracks, so their z-order is untouched (I9) — only the group
422
586
  // itself takes a new `trackId`.
423
- let moved = clip;
424
587
  if (isGroupClip(clip) && patch.startMs !== undefined) {
425
- const nextStartMs = Math.max(0, patch.startMs);
426
- this.clips = moveGroup(this.clips, clip.id, nextStartMs - clip.startMs);
427
- moved = this.clips.find((c) => c.id === clip.id);
588
+ // One delta for the whole unit, clamped by its earliest member, so a
589
+ // child's J-cut partner keeps its offset at zero.
590
+ const minimum = Math.min(...targets.map((target) => target.startMs));
591
+ const delta = Math.max(-minimum, patch.startMs - clip.startMs);
592
+ for (const target of targets) {
593
+ target.startMs += delta;
594
+ }
428
595
  this.touch(...targets.map((target) => target.id));
429
596
  }
430
597
  else if (patch.startMs !== undefined) {
431
598
  clip.startMs = Math.max(0, patch.startMs);
432
599
  }
433
- if (patch.trackId !== undefined) {
434
- moved.trackId = this.resolveTrack(patch.trackId).id;
600
+ if (destination) {
601
+ clip.trackId = destination.id;
435
602
  }
436
603
  if (patch.startMs !== undefined || patch.trackId !== undefined) {
437
- this.touch(moved.id);
604
+ this.touch(clip.id);
438
605
  }
439
- return moved;
606
+ return clip;
440
607
  }
441
608
  /** Resolve a marker by id, or by case-insensitive label. */
442
609
  resolveMarker(target) {
@@ -493,6 +660,23 @@ class OpScope {
493
660
  return serializeTrack(this.state, track);
494
661
  }
495
662
  }
663
+ /**
664
+ * `trimClip` on the end edge, capped at the source length when one is known.
665
+ * The refusal names the limit, which the engine's own message does not.
666
+ */
667
+ function trimSourceBounded(clip, deltaMs, maxSourceMs) {
668
+ try {
669
+ return trimClip(clip, "end", deltaMs, maxSourceMs);
670
+ }
671
+ catch (error) {
672
+ if (maxSourceMs !== undefined &&
673
+ error instanceof Error &&
674
+ error.message.includes("beyond source out-point")) {
675
+ throw new Error(`Clip "${clip.name}" cannot be longer than its source: the source ends at ${maxSourceMs}ms.`);
676
+ }
677
+ throw error;
678
+ }
679
+ }
496
680
  function rejectUnknownClipParams(patch) {
497
681
  for (const key of Object.keys(patch)) {
498
682
  if (CLIP_PARAM_KEYS.includes(key)) {
@@ -620,1473 +804,1652 @@ async function buildCustomAnimation(scope, clip, input) {
620
804
  custom
621
805
  };
622
806
  }
623
- /** Dispatch one op against `scope`. Throws on refusal; the caller maps it. */
624
- async function runOp(scope, op) {
625
- const state = scope.state;
626
- switch (op.op) {
627
- case "get_state": {
628
- const durationMs = scope.clips.reduce((m, c) => Math.max(m, c.startMs + c.durationMs), 0);
629
- return {
630
- ok: true,
631
- fps: state.fps,
632
- width: state.width,
633
- height: state.height,
634
- durationMs,
635
- playheadMs: state.playheadMs,
636
- selectedClipIds: [...state.selectedClipIds],
637
- tempo: state.tempo,
638
- tracks: scope.tracks.map((t) => scope.trackOut(t)),
639
- clips: scope.clips.map((c) => scope.clipOut(c)),
640
- mediaTracks: scope.mediaTracks.map(serializeMediaTrack),
641
- markers: state.markers.map((m) => ({ ...m }))
642
- };
643
- }
644
- case "add_track":
645
- case "move_track":
646
- case "delete_track":
647
- return runTrackOp(scope, op);
648
- case "add_text_clip": {
649
- const track = op.trackId
650
- ? scope.resolveTrack(op.trackId)
651
- : scope.findOrCreateTrack("overlay", "Text");
652
- // `style` wins over a top-level twin: a caller that sent both meant the
653
- // bag it named.
654
- scope.assertPictureTrack(track);
655
- const s = { ...(op.loose ?? {}), ...(op.style ?? {}) };
656
- const clip = makeClip({
657
- id: scope.ctx.newId("clip"),
658
- trackId: track.id,
659
- name: op.name ?? op.text,
660
- startMs: op.startMs ?? scope.trackEndMs(track.id),
661
- durationMs: op.durationMs ?? DEFAULT_TEXT_CLIP_DURATION_MS,
662
- mediaType: "text",
663
- sourceType: "imported",
664
- status: "generated",
665
- textStyle: textStyleWithDefaults(op.text, s)
807
+ function runMidiNoteEdit(scope, op) {
808
+ const clip = scope.resolveMidiClip(op.clip);
809
+ scope.assertWritable([clip]);
810
+ const before = clip.notes ?? [];
811
+ const notes = op.op === "transpose_clip"
812
+ ? transposeNotes(before, op.semitones)
813
+ : op.op === "scale_velocity"
814
+ ? scaleVelocity(before, op.factor)
815
+ : quantizeNotes(before, {
816
+ division: op.division,
817
+ strength: op.strength,
818
+ target: op.target,
819
+ // The grid is anchored at `tempo.offsetMs`, as the editor draws it.
820
+ phaseTick: msToTicks(resolveTempo(scope.state).offsetMs -
821
+ clip.startMs +
822
+ (clip.inPointMs ?? 0), resolveTempo(scope.state).bpm)
666
823
  });
667
- if (op.opacity !== undefined) {
668
- clip.opacity = op.opacity;
669
- }
670
- if (op.transform) {
671
- clip.transform = mergeClipTransform(clip.transform, op.transform);
672
- }
673
- scope.clips.push(clip);
674
- state.selectedClipIds = [clip.id];
675
- scope.touch(clip.id);
676
- return { ok: true, clip: scope.clipOut(clip) };
824
+ clip.notes = notes;
825
+ scope.touch(clip.id);
826
+ const result = {
827
+ ok: true,
828
+ clip: scope.clipOut(clip),
829
+ noteCount: notes.length
830
+ };
831
+ if (op.op === "quantize_notes") {
832
+ result.movedNoteCount = notes.filter((note, i) => note.startTick !== before[i]?.startTick ||
833
+ note.durationTick !== before[i]?.durationTick).length;
834
+ }
835
+ return result;
836
+ }
837
+ function runBeatEdit(scope, op) {
838
+ const beats = scope.state.setup?.beats ?? [];
839
+ const found = resolveBeatTarget(beats, op.beat);
840
+ const next = { ...found };
841
+ if (op.op === "update_beat") {
842
+ if (op.prompt !== undefined) {
843
+ next.prompt = op.prompt;
677
844
  }
678
- case "add_media_clip": {
679
- const resolveAsset = scope.ctx.resolveAsset;
680
- if (!resolveAsset) {
681
- throw new Error("This timeline surface cannot look up assets, so an existing asset cannot be placed here.");
682
- }
683
- const found = await resolveAsset(op.asset);
684
- if (!found) {
685
- throw new Error(`No asset found for "${op.asset}". Pass an asset id or an asset:// URI from list_assets.`);
686
- }
687
- const mediaType = found.contentType.toLowerCase().startsWith("model/") ||
688
- /\.(glb|gltf)$/i.test(found.name)
689
- ? "model3d"
690
- : mediaTypeForContentType(found.contentType);
691
- if (!mediaType) {
692
- throw new Error(`Asset "${found.name}" is ${found.contentType}, which is not video, image, or audio and cannot go on a timeline.`);
693
- }
694
- if (mediaType !== "image" &&
695
- mediaType !== "model3d" &&
696
- op.durationMs === undefined &&
697
- !found.durationMs &&
698
- !scope.ctx.allowUnknownMediaDuration) {
699
- throw new Error(`Asset "${found.name}" has no known duration. Supply durationMs or import media that can be probed.`);
700
- }
701
- const track = op.trackId
702
- ? scope.resolveTrack(op.trackId)
703
- : scope.findOrCreateTrack(mediaType === "model3d" ? "video" : trackTypeForMediaType(mediaType));
704
- if (!clipFitsTrack(mediaType, track.type)) {
705
- throw new Error(`Asset "${found.name}" is not compatible with ${track.type} track "${track.name}".`);
706
- }
707
- const init = {
708
- id: scope.ctx.newId("clip"),
709
- trackId: track.id,
710
- name: op.name ?? found.name,
711
- startMs: op.startMs ?? scope.trackEndMs(track.id),
712
- durationMs: op.durationMs ?? found.durationMs ?? DEFAULT_MEDIA_CLIP_DURATION_MS,
713
- mediaType,
714
- sourceType: "imported",
715
- status: "generated",
716
- currentAssetId: found.id
717
- };
718
- if (mediaType === "model3d") {
719
- init.model3dStyle = model3dStyleWithPatch(undefined, undefined);
720
- }
721
- if (found.thumbnailAssetId) {
722
- init.thumbnailAssetId = found.thumbnailAssetId;
723
- }
724
- const clip = makeClip(init);
725
- if (op.transform) {
726
- clip.transform = mergeClipTransform(clip.transform, op.transform);
727
- }
728
- scope.clips.push(clip);
729
- state.selectedClipIds = [clip.id];
730
- scope.touch(clip.id);
731
- return { ok: true, clip: scope.clipOut(clip) };
845
+ if (op.durationMs !== undefined) {
846
+ next.duration_ms = Math.max(1, Math.round(op.durationMs));
732
847
  }
733
- case "add_shape_clip": {
734
- const track = op.trackId
735
- ? scope.resolveTrack(op.trackId)
736
- : scope.findOrCreateTrack("overlay", "Shapes");
737
- scope.assertPictureTrack(track);
738
- const shapeArg = resolveShapeArg(op.shape, op.shapeStyle, op.loose ?? {});
739
- const clip = makeClip({
740
- id: scope.ctx.newId("clip"),
741
- trackId: track.id,
742
- name: op.name ?? capitalize(shapeArg.kind),
743
- startMs: op.startMs ?? scope.trackEndMs(track.id),
744
- durationMs: op.durationMs ?? DEFAULT_TEXT_CLIP_DURATION_MS,
745
- mediaType: "shape",
746
- sourceType: "imported",
747
- status: "generated",
748
- shapeStyle: shapeStyleWithDefaults(shapeArg)
749
- });
750
- if (op.opacity !== undefined) {
751
- clip.opacity = op.opacity;
752
- }
753
- if (op.transform) {
754
- clip.transform = mergeClipTransform(clip.transform, op.transform);
755
- }
756
- scope.clips.push(clip);
757
- state.selectedClipIds = [clip.id];
758
- scope.touch(clip.id);
759
- return { ok: true, clip: scope.clipOut(clip) };
848
+ if (op.transition !== undefined) {
849
+ next.transition = op.transition ?? undefined;
760
850
  }
761
- case "add_model3d_clip": {
762
- const assetId = op.assetId.trim();
763
- if (!assetId) {
764
- throw new Error("add_model3d_clip needs the glTF's asset id — a 3D clip draws its " +
765
- "asset the way an image clip draws its image. list_assets prints " +
766
- "the ids.");
767
- }
768
- // 3D is picture (D1), so it lands where a title lands: the first overlay
769
- // track, or one made for it.
770
- const track = op.trackId
771
- ? scope.resolveTrack(op.trackId)
772
- : scope.findOrCreateTrack("overlay", "3D");
773
- scope.assertPictureTrack(track);
774
- const clip = makeClip({
775
- id: scope.ctx.newId("clip"),
776
- trackId: track.id,
777
- name: DEFAULT_MODEL3D_CLIP_NAME,
778
- startMs: op.startMs ?? scope.trackEndMs(track.id),
779
- durationMs: op.durationMs ?? DEFAULT_MODEL3D_CLIP_DURATION_MS,
780
- mediaType: "model3d",
781
- sourceType: "imported",
782
- status: "generated",
783
- currentAssetId: assetId,
784
- model3dStyle: model3dStyleWithPatch(undefined, op.style)
785
- });
786
- if (op.transform) {
787
- clip.transform = mergeClipTransform(clip.transform, op.transform);
788
- }
789
- scope.clips.push(clip);
790
- state.selectedClipIds = [clip.id];
791
- scope.touch(clip.id);
792
- return { ok: true, clip: scope.clipOut(clip) };
851
+ if (op.voiceover !== undefined) {
852
+ next.voiceover = op.voiceover;
793
853
  }
794
- case "set_model3d_style": {
795
- const clip = scope.resolveClip(op.target);
796
- if (clip.mediaType !== "model3d") {
797
- throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip, not a 3D clip — ` +
798
- "model3dStyle names a camera, an animation and lighting for a " +
799
- "glTF, and nothing else reads it.");
800
- }
801
- clip.model3dStyle = model3dStyleWithPatch(clip.model3dStyle, op.patch);
802
- scope.touch(clip.id);
803
- return { ok: true, clip: scope.clipOut(clip) };
854
+ if (op.music !== undefined) {
855
+ next.music = op.music;
804
856
  }
805
- case "bake_model3d_clip": {
806
- const clip = scope.resolveClip(op.target);
807
- if (clip.mediaType !== "model3d") {
808
- throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip, not a 3D clip — ` +
809
- "only a 3D clip has a camera, lighting and a glTF to render.");
810
- }
811
- const style = clip.model3dStyle;
812
- if (!style) {
813
- throw new Error(`Clip "${clip.name}" has no model3dStyle, so nothing names the ` +
814
- "camera, lighting or animation a bake would render.");
815
- }
816
- if (!clip.currentAssetId) {
817
- throw new Error(`Clip "${clip.name}" has no glTF asset to bake — a 3D clip draws ` +
818
- "its asset the way an image clip draws its image.");
819
- }
820
- const sequence = {
821
- fps: state.fps,
822
- width: state.width,
823
- height: state.height
824
- };
825
- const dependencyHash = computeModel3DBakeHash(clip, sequence);
826
- if (!scope.ctx.bakeModel3DClip) {
827
- return {
828
- ok: true,
829
- clip: scope.clipOut(clip),
830
- bakeStarted: false,
831
- note: "This surface has no Blender renderer, so nothing was baked."
832
- };
833
- }
834
- const baked = await scope.ctx.bakeModel3DClip({
835
- clip,
836
- sequence,
837
- dependencyHash
838
- });
839
- const now = (scope.ctx.now ?? (() => new Date().toISOString()))();
840
- clip.model3dStyle = {
841
- ...style,
842
- bake: { assetId: baked.assetId, dependencyHash }
843
- };
844
- // The bake joins the clip's own version history, so an earlier one can
845
- // be restored the way an earlier generation can.
846
- clip.versions = [
847
- ...(clip.versions ?? []),
848
- makeClipVersion({
849
- id: scope.ctx.newId("version"),
850
- createdAt: now,
851
- workflowUpdatedAt: now,
852
- jobId: baked.jobId ?? "",
853
- assetId: baked.assetId,
854
- dependencyHash
855
- })
856
- ];
857
- scope.touch(clip.id);
858
- return { ok: true, clip: scope.clipOut(clip), bakeStarted: true };
859
- }
860
- case "add_group": {
861
- // Resolve every child before anything is written: a half-applied group
862
- // leaves the caller with an empty group and no idea which of its clips
863
- // moved.
864
- const targets = (op.children ?? []).map((ref) => scope.resolveClip(ref));
865
- const track = op.trackId
866
- ? scope.resolveTrack(op.trackId)
867
- : scope.findOrCreateTrack("overlay", "Groups");
868
- const group = makeClip({
869
- id: scope.ctx.newId("clip"),
870
- trackId: track.id,
871
- name: op.name,
872
- startMs: op.startMs,
873
- durationMs: op.durationMs,
874
- mediaType: "group",
875
- sourceType: "imported",
876
- status: "generated"
877
- });
878
- if (op.transform) {
879
- group.transform = mergeClipTransform(group.transform, op.transform);
880
- }
881
- scope.clips.push(group);
882
- for (const child of targets) {
883
- child.parentId = group.id;
884
- scope.touch(child.id);
885
- }
886
- state.selectedClipIds = [group.id];
887
- scope.touch(group.id);
857
+ }
858
+ const previous = scope.state.setup;
859
+ scope.state.setup = {
860
+ ...previous,
861
+ stage: previous?.stage ?? "review",
862
+ brief: previous?.brief ?? "",
863
+ format: previous?.format,
864
+ voiceover: previous?.voiceover,
865
+ beats: op.op === "remove_beat"
866
+ ? beats.filter((b) => b.id !== found.id)
867
+ : beats.map((b) => (b.id === found.id ? next : b))
868
+ };
869
+ return op.op === "remove_beat"
870
+ ? { ok: true, removed: { ...found } }
871
+ : { ok: true, beat: { ...next } };
872
+ }
873
+ /** One handler per op, so each is checked against its own op type. */
874
+ const OP_HANDLERS = {
875
+ get_state: (scope) => {
876
+ const state = scope.state;
877
+ const durationMs = scope.clips.reduce((m, c) => Math.max(m, c.startMs + c.durationMs), 0);
878
+ return {
879
+ ok: true,
880
+ fps: state.fps,
881
+ width: state.width,
882
+ height: state.height,
883
+ durationMs,
884
+ playheadMs: state.playheadMs,
885
+ selectedClipIds: [...state.selectedClipIds],
886
+ tempo: state.tempo,
887
+ tracks: scope.tracks.map((t) => scope.trackOut(t)),
888
+ clips: scope.clips.map((c) => scope.clipOut(c)),
889
+ mediaTracks: scope.mediaTracks.map(serializeMediaTrack),
890
+ markers: state.markers.map((m) => ({ ...m }))
891
+ };
892
+ },
893
+ add_track: runTrackOp,
894
+ move_track: runTrackOp,
895
+ delete_track: runTrackOp,
896
+ add_text_clip: (scope, op) => {
897
+ const state = scope.state;
898
+ const track = op.trackId
899
+ ? scope.resolveTrack(op.trackId)
900
+ : scope.findOrCreateTrack("overlay", "Text");
901
+ // `style` wins over a top-level twin: a caller that sent both meant the
902
+ // bag it named.
903
+ scope.assertPictureTrack(track);
904
+ scope.assertWritable([], track.id);
905
+ const s = { ...(op.loose ?? {}), ...(op.style ?? {}) };
906
+ const clip = makeClip({
907
+ id: scope.ctx.newId("clip"),
908
+ trackId: track.id,
909
+ name: op.name ?? op.text,
910
+ startMs: op.startMs ?? scope.trackEndMs(track.id),
911
+ durationMs: op.durationMs ?? DEFAULT_TEXT_CLIP_DURATION_MS,
912
+ mediaType: "text",
913
+ sourceType: "imported",
914
+ status: "generated",
915
+ textStyle: textStyleWithDefaults(op.text, s)
916
+ });
917
+ if (op.opacity !== undefined) {
918
+ clip.opacity = op.opacity;
919
+ }
920
+ if (op.transform) {
921
+ clip.transform = mergeClipTransform(clip.transform, op.transform);
922
+ }
923
+ scope.clips.push(clip);
924
+ state.selectedClipIds = [clip.id];
925
+ scope.touch(clip.id);
926
+ return { ok: true, clip: scope.clipOut(clip) };
927
+ },
928
+ add_media_clip: async (scope, op) => {
929
+ const state = scope.state;
930
+ const resolveAsset = scope.ctx.resolveAsset;
931
+ if (!resolveAsset) {
932
+ throw new Error("This timeline surface cannot look up assets, so an existing asset cannot be placed here.");
933
+ }
934
+ const found = await resolveAsset(op.asset);
935
+ if (!found) {
936
+ throw new Error(`No asset found for "${op.asset}". Pass an asset id or an asset:// URI from list_assets.`);
937
+ }
938
+ const mediaType = found.contentType.toLowerCase().startsWith("model/") ||
939
+ /\.(glb|gltf)$/i.test(found.name)
940
+ ? "model3d"
941
+ : mediaTypeForContentType(found.contentType);
942
+ if (!mediaType) {
943
+ throw new Error(`Asset "${found.name}" is ${found.contentType}, which is not video, image, or audio and cannot go on a timeline.`);
944
+ }
945
+ if (mediaType !== "image" &&
946
+ mediaType !== "model3d" &&
947
+ op.durationMs === undefined &&
948
+ !found.durationMs &&
949
+ !scope.ctx.allowUnknownMediaDuration) {
950
+ throw new Error(`Asset "${found.name}" has no known duration. Supply durationMs or import media that can be probed.`);
951
+ }
952
+ const track = op.trackId
953
+ ? scope.resolveTrack(op.trackId)
954
+ : scope.findOrCreateTrack(mediaType === "model3d" ? "video" : trackTypeForMediaType(mediaType));
955
+ if (!clipFitsTrack(mediaType, track.type)) {
956
+ throw new Error(`Asset "${found.name}" is not compatible with ${track.type} track "${track.name}".`);
957
+ }
958
+ scope.assertWritable([], track.id);
959
+ const init = {
960
+ id: scope.ctx.newId("clip"),
961
+ trackId: track.id,
962
+ name: op.name ?? found.name,
963
+ startMs: op.startMs ?? scope.trackEndMs(track.id),
964
+ durationMs: op.durationMs ?? found.durationMs ?? DEFAULT_MEDIA_CLIP_DURATION_MS,
965
+ mediaType,
966
+ sourceType: "imported",
967
+ status: "generated",
968
+ currentAssetId: found.id
969
+ };
970
+ if (mediaType === "model3d") {
971
+ init.model3dStyle = model3dStyleWithPatch(undefined, undefined);
972
+ }
973
+ if (found.thumbnailAssetId) {
974
+ init.thumbnailAssetId = found.thumbnailAssetId;
975
+ }
976
+ const clip = makeClip(init);
977
+ if (op.transform) {
978
+ clip.transform = mergeClipTransform(clip.transform, op.transform);
979
+ }
980
+ scope.clips.push(clip);
981
+ state.selectedClipIds = [clip.id];
982
+ scope.touch(clip.id);
983
+ return { ok: true, clip: scope.clipOut(clip) };
984
+ },
985
+ add_shape_clip: (scope, op) => {
986
+ const state = scope.state;
987
+ const track = op.trackId
988
+ ? scope.resolveTrack(op.trackId)
989
+ : scope.findOrCreateTrack("overlay", "Shapes");
990
+ scope.assertPictureTrack(track);
991
+ scope.assertWritable([], track.id);
992
+ const shapeArg = resolveShapeArg(op.shape, op.shapeStyle, op.loose ?? {});
993
+ const clip = makeClip({
994
+ id: scope.ctx.newId("clip"),
995
+ trackId: track.id,
996
+ name: op.name ?? capitalize(shapeArg.kind),
997
+ startMs: op.startMs ?? scope.trackEndMs(track.id),
998
+ durationMs: op.durationMs ?? DEFAULT_TEXT_CLIP_DURATION_MS,
999
+ mediaType: "shape",
1000
+ sourceType: "imported",
1001
+ status: "generated",
1002
+ shapeStyle: shapeStyleWithDefaults(shapeArg)
1003
+ });
1004
+ if (op.opacity !== undefined) {
1005
+ clip.opacity = op.opacity;
1006
+ }
1007
+ if (op.transform) {
1008
+ clip.transform = mergeClipTransform(clip.transform, op.transform);
1009
+ }
1010
+ scope.clips.push(clip);
1011
+ state.selectedClipIds = [clip.id];
1012
+ scope.touch(clip.id);
1013
+ return { ok: true, clip: scope.clipOut(clip) };
1014
+ },
1015
+ add_model3d_clip: async (scope, op) => {
1016
+ const state = scope.state;
1017
+ const assetId = op.assetId.trim();
1018
+ if (!assetId) {
1019
+ throw new Error("add_model3d_clip needs the glTF's asset id — a 3D clip draws its " +
1020
+ "asset the way an image clip draws its image. list_assets prints " +
1021
+ "the ids.");
1022
+ }
1023
+ // 3D is picture (D1), so it lands where a title lands: the first overlay
1024
+ // track, or one made for it.
1025
+ const track = op.trackId
1026
+ ? scope.resolveTrack(op.trackId)
1027
+ : scope.findOrCreateTrack("overlay", "3D");
1028
+ scope.assertPictureTrack(track);
1029
+ scope.assertWritable([], track.id);
1030
+ // The id is stored on the clip and read back by every renderer, so a
1031
+ // short or `asset://` form resolves to the asset's full id here. A
1032
+ // 12-character prefix nothing resolves would store a dangling id.
1033
+ const found = await scope.ctx.resolveAsset?.(assetId);
1034
+ if (!found && isShortResourceId(assetId)) {
1035
+ throw new Error(`No asset found for "${assetId}". Pass the glTF's asset id from list_assets.`);
1036
+ }
1037
+ const currentAssetId = found?.id ?? assetId;
1038
+ const clip = makeClip({
1039
+ id: scope.ctx.newId("clip"),
1040
+ trackId: track.id,
1041
+ name: DEFAULT_MODEL3D_CLIP_NAME,
1042
+ startMs: op.startMs ?? scope.trackEndMs(track.id),
1043
+ durationMs: op.durationMs ?? DEFAULT_MODEL3D_CLIP_DURATION_MS,
1044
+ mediaType: "model3d",
1045
+ sourceType: "imported",
1046
+ status: "generated",
1047
+ currentAssetId,
1048
+ model3dStyle: model3dStyleWithPatch(undefined, op.style)
1049
+ });
1050
+ if (op.transform) {
1051
+ clip.transform = mergeClipTransform(clip.transform, op.transform);
1052
+ }
1053
+ scope.clips.push(clip);
1054
+ state.selectedClipIds = [clip.id];
1055
+ scope.touch(clip.id);
1056
+ return { ok: true, clip: scope.clipOut(clip) };
1057
+ },
1058
+ set_model3d_style: (scope, op) => {
1059
+ const clip = scope.resolveClip(op.target);
1060
+ if (clip.mediaType !== "model3d") {
1061
+ throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip, not a 3D clip — ` +
1062
+ "model3dStyle names a camera, an animation and lighting for a " +
1063
+ "glTF, and nothing else reads it.");
1064
+ }
1065
+ clip.model3dStyle = model3dStyleWithPatch(clip.model3dStyle, op.patch);
1066
+ scope.touch(clip.id);
1067
+ return { ok: true, clip: scope.clipOut(clip) };
1068
+ },
1069
+ bake_model3d_clip: async (scope, op) => {
1070
+ const state = scope.state;
1071
+ const clip = scope.resolveClip(op.target);
1072
+ if (clip.mediaType !== "model3d") {
1073
+ throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip, not a 3D clip — ` +
1074
+ "only a 3D clip has a camera, lighting and a glTF to render.");
1075
+ }
1076
+ const style = clip.model3dStyle;
1077
+ if (!style) {
1078
+ throw new Error(`Clip "${clip.name}" has no model3dStyle, so nothing names the ` +
1079
+ "camera, lighting or animation a bake would render.");
1080
+ }
1081
+ if (!clip.currentAssetId) {
1082
+ throw new Error(`Clip "${clip.name}" has no glTF asset to bake — a 3D clip draws ` +
1083
+ "its asset the way an image clip draws its image.");
1084
+ }
1085
+ const sequence = {
1086
+ fps: state.fps,
1087
+ width: state.width,
1088
+ height: state.height
1089
+ };
1090
+ const dependencyHash = computeModel3DBakeHash(clip, sequence);
1091
+ if (!scope.ctx.bakeModel3DClip) {
888
1092
  return {
889
1093
  ok: true,
890
- clip: scope.clipOut(group),
891
- children: targets.map((c) => c.id)
1094
+ clip: scope.clipOut(clip),
1095
+ bakeStarted: false,
1096
+ note: "This surface has no Blender renderer, so nothing was baked."
892
1097
  };
893
1098
  }
894
- case "generate_clip": {
895
- const mediaType = op.kind === "text-to-video"
896
- ? "video"
897
- : op.kind === "text-to-image"
898
- ? "image"
899
- : "audio";
900
- const track = op.trackId
901
- ? scope.resolveTrack(op.trackId)
902
- : op.kind === "text-to-audio"
903
- ? scope.findOrCreateTrack("audio")
904
- : scope.findOrCreateTrack("video");
905
- const generationStarted = op.autoGenerate !== false;
906
- const clip = makeClip({
907
- id: scope.ctx.newId("clip"),
908
- trackId: track.id,
909
- name: op.prompt,
910
- startMs: op.startMs ?? scope.trackEndMs(track.id),
911
- durationMs: op.durationMs ?? (op.kind === "text-to-audio" ? 3000 : 5000),
912
- mediaType,
913
- sourceType: "generated",
914
- bindingKind: op.kind,
915
- status: generationStarted ? "generating" : "draft",
916
- prompt: op.prompt,
917
- provider: op.provider,
918
- model: op.model,
919
- voice: op.voice,
920
- width: op.width,
921
- height: op.height,
922
- aspectRatio: op.aspectRatio,
923
- resolution: op.resolution
924
- });
925
- scope.clips.push(clip);
926
- state.selectedClipIds = [clip.id];
927
- scope.touch(clip.id);
928
- const result = { ok: true, clip: scope.clipOut(clip), generationStarted };
929
- if (!generationStarted) {
930
- result.note = "Generation not started (autoGenerate=false).";
931
- }
932
- return result;
933
- }
934
- case "split_clip": {
935
- const clip = scope.resolveClip(op.target);
936
- const at = op.atMs ?? state.playheadMs;
937
- if (at <= clip.startMs || at >= clip.startMs + clip.durationMs) {
938
- throw new Error(`Split time ${at}ms is outside clip "${clip.name}".`);
939
- }
940
- const targets = scope
941
- .editTargets(clip)
942
- .filter((target) => at > target.startMs && at < target.startMs + target.durationMs);
943
- const leftLink = targets.length > 1 ? scope.ctx.newId("link") : undefined;
944
- const rightLink = targets.length > 1 ? scope.ctx.newId("link") : undefined;
945
- const halves = [];
946
- for (const target of targets) {
947
- const [left, right] = splitClip(target, at);
948
- left.id = scope.ctx.newId("clip");
949
- right.id = scope.ctx.newId("clip");
950
- if (targets.length > 1) {
951
- left.linkId = leftLink;
952
- right.linkId = rightLink;
953
- }
954
- const idx = scope.clips.findIndex((c) => c.id === target.id);
955
- scope.clips.splice(idx, 1, left, right);
956
- state.selectedClipIds = state.selectedClipIds.filter((id) => id !== target.id);
957
- scope.touch(target.id, left.id, right.id);
958
- scope.mediaTracks = resliceTracksForSplitClip(scope.mediaTracks, target.id, left, right, () => scope.ctx.newId("track"));
959
- halves.push(left, right);
960
- }
961
- return { ok: true, clips: halves.map((half) => scope.clipOut(half)) };
1099
+ const baked = await scope.ctx.bakeModel3DClip({
1100
+ clip,
1101
+ sequence,
1102
+ dependencyHash
1103
+ });
1104
+ const now = (scope.ctx.now ?? (() => new Date().toISOString()))();
1105
+ clip.model3dStyle = {
1106
+ ...style,
1107
+ bake: { assetId: baked.assetId, dependencyHash }
1108
+ };
1109
+ // The bake joins the clip's own version history, so an earlier one can
1110
+ // be restored the way an earlier generation can.
1111
+ clip.versions = [
1112
+ ...(clip.versions ?? []),
1113
+ makeClipVersion({
1114
+ id: scope.ctx.newId("version"),
1115
+ createdAt: now,
1116
+ workflowUpdatedAt: now,
1117
+ jobId: baked.jobId ?? "",
1118
+ assetId: baked.assetId,
1119
+ dependencyHash
1120
+ })
1121
+ ];
1122
+ scope.touch(clip.id);
1123
+ return { ok: true, clip: scope.clipOut(clip), bakeStarted: true };
1124
+ },
1125
+ add_group: (scope, op) => {
1126
+ const state = scope.state;
1127
+ // Resolve every child before anything is written: a half-applied group
1128
+ // leaves the caller with an empty group and no idea which of its clips
1129
+ // moved.
1130
+ const targets = (op.children ?? []).map((ref) => scope.resolveClip(ref));
1131
+ const track = op.trackId
1132
+ ? scope.resolveTrack(op.trackId)
1133
+ : scope.findOrCreateTrack("overlay", "Groups");
1134
+ scope.assertWritable(targets, track.id);
1135
+ const group = makeClip({
1136
+ id: scope.ctx.newId("clip"),
1137
+ trackId: track.id,
1138
+ name: op.name,
1139
+ startMs: op.startMs,
1140
+ durationMs: op.durationMs,
1141
+ mediaType: "group",
1142
+ sourceType: "imported",
1143
+ status: "generated"
1144
+ });
1145
+ if (op.transform) {
1146
+ group.transform = mergeClipTransform(group.transform, op.transform);
962
1147
  }
963
- case "trim_clip": {
964
- const trimmed = scope.applyTrim(scope.resolveClip(op.target), {
965
- durationMs: op.durationMs,
966
- inPointMs: op.inPointMs,
967
- outPointMs: op.outPointMs
968
- });
969
- scope.mediaTracks = resliceTracksForTrimmedClip(scope.mediaTracks, trimmed);
970
- return { ok: true, clip: scope.clipOut(trimmed) };
1148
+ scope.clips.push(group);
1149
+ for (const child of targets) {
1150
+ child.parentId = group.id;
1151
+ scope.touch(child.id);
971
1152
  }
972
- case "move_clip": {
973
- const moved = scope.applyMove(scope.resolveClip(op.target), {
974
- startMs: op.startMs,
975
- trackId: op.trackId
976
- });
977
- return { ok: true, clip: scope.clipOut(moved) };
978
- }
979
- case "delete_clip": {
980
- const clip = scope.resolveClip(op.target);
981
- scope.editTargets(clip);
982
- // Deleting a group deletes the parent, not the picture: its children stay
983
- // where they are and stop inheriting (D4). Leaving them with a `parentId`
984
- // nothing answers is what the validator calls a dangling parent.
985
- const wasChild = scope.clips
986
- .filter((c) => c.parentId === clip.id)
987
- .map((c) => c.id);
988
- const remaining = isGroupClip(clip)
989
- ? ungroup(scope.clips, clip.id)
990
- : scope.clips;
991
- const out = scope.clipOut(clip);
992
- scope.clips = remaining.filter((c) => c.id !== clip.id);
993
- if (clip.linkId) {
994
- const remainingLinked = scope.clips.filter((candidate) => candidate.linkId === clip.linkId);
995
- if (remainingLinked.length === 1) {
996
- delete remainingLinked[0].linkId;
997
- scope.touch(remainingLinked[0].id);
1153
+ state.selectedClipIds = [group.id];
1154
+ scope.touch(group.id);
1155
+ return {
1156
+ ok: true,
1157
+ clip: scope.clipOut(group),
1158
+ children: targets.map((c) => c.id)
1159
+ };
1160
+ },
1161
+ generate_clip: (scope, op) => {
1162
+ const state = scope.state;
1163
+ const mediaType = op.kind === "text-to-video"
1164
+ ? "video"
1165
+ : op.kind === "text-to-image"
1166
+ ? "image"
1167
+ : "audio";
1168
+ const track = op.trackId
1169
+ ? scope.resolveTrack(op.trackId)
1170
+ : op.kind === "text-to-audio"
1171
+ ? scope.findOrCreateTrack("audio")
1172
+ : scope.findOrCreateTrack("video");
1173
+ if (!clipFitsTrack(mediaType, track.type)) {
1174
+ throw new Error(`A ${op.kind} clip is ${mediaType} and cannot go on ${track.type} track "${track.name}".`);
1175
+ }
1176
+ scope.assertWritable([], track.id);
1177
+ const generationStarted = op.autoGenerate !== false;
1178
+ const clip = makeClip({
1179
+ id: scope.ctx.newId("clip"),
1180
+ trackId: track.id,
1181
+ name: op.prompt,
1182
+ startMs: op.startMs ?? scope.trackEndMs(track.id),
1183
+ durationMs: op.durationMs ?? (op.kind === "text-to-audio" ? 3000 : 5000),
1184
+ mediaType,
1185
+ sourceType: "generated",
1186
+ bindingKind: op.kind,
1187
+ status: generationStarted ? "generating" : "draft",
1188
+ prompt: op.prompt,
1189
+ provider: op.provider,
1190
+ model: op.model,
1191
+ voice: op.voice,
1192
+ width: op.width,
1193
+ height: op.height,
1194
+ aspectRatio: op.aspectRatio,
1195
+ resolution: op.resolution
1196
+ });
1197
+ scope.clips.push(clip);
1198
+ state.selectedClipIds = [clip.id];
1199
+ scope.touch(clip.id);
1200
+ const result = { ok: true, clip: scope.clipOut(clip), generationStarted };
1201
+ if (!generationStarted) {
1202
+ result.note = "Generation not started (autoGenerate=false).";
1203
+ }
1204
+ return result;
1205
+ },
1206
+ split_clip: (scope, op) => {
1207
+ const state = scope.state;
1208
+ const clip = scope.resolveClip(op.target);
1209
+ const at = op.atMs ?? state.playheadMs;
1210
+ if (at <= clip.startMs || at >= clip.startMs + clip.durationMs) {
1211
+ throw new Error(`Split time ${at}ms is outside clip "${clip.name}".`);
1212
+ }
1213
+ const targets = scope
1214
+ .editTargets(clip)
1215
+ .filter((target) => at > target.startMs && at < target.startMs + target.durationMs);
1216
+ const leftLink = targets.length > 1 ? scope.ctx.newId("link") : undefined;
1217
+ const rightLink = targets.length > 1 ? scope.ctx.newId("link") : undefined;
1218
+ const halves = [];
1219
+ for (const target of targets) {
1220
+ const [cutLeft, cutRight] = splitClip(target, at);
1221
+ cutLeft.id = scope.ctx.newId("clip");
1222
+ cutRight.id = scope.ctx.newId("clip");
1223
+ if (targets.length > 1) {
1224
+ cutLeft.linkId = leftLink;
1225
+ cutRight.linkId = rightLink;
1226
+ }
1227
+ const split = splitClipMediaTracks(scope.mediaTracks, target.id, cutLeft, cutRight, () => scope.ctx.newId("track"));
1228
+ const { left, right } = split;
1229
+ scope.mediaTracks = split.mediaTracks;
1230
+ const idx = scope.clips.findIndex((c) => c.id === target.id);
1231
+ scope.clips.splice(idx, 1, left, right);
1232
+ state.selectedClipIds = state.selectedClipIds.filter((id) => id !== target.id);
1233
+ scope.touch(target.id, left.id, right.id);
1234
+ halves.push(left, right);
1235
+ }
1236
+ return { ok: true, clips: halves.map((half) => scope.clipOut(half)) };
1237
+ },
1238
+ trim_clip: async (scope, op) => {
1239
+ const clip = scope.resolveClip(op.target);
1240
+ const trimmed = scope.applyTrim(clip, {
1241
+ durationMs: op.durationMs,
1242
+ inPointMs: op.inPointMs,
1243
+ outPointMs: op.outPointMs
1244
+ }, await scope.sourceLimitMs(clip));
1245
+ scope.mediaTracks = resliceTracksForTrimmedClip(scope.mediaTracks, trimmed);
1246
+ return { ok: true, clip: scope.clipOut(trimmed) };
1247
+ },
1248
+ move_clip: (scope, op) => {
1249
+ const moved = scope.applyMove(scope.resolveClip(op.target), {
1250
+ startMs: op.startMs,
1251
+ trackId: op.trackId
1252
+ });
1253
+ return { ok: true, clip: scope.clipOut(moved) };
1254
+ },
1255
+ delete_clip: (scope, op) => {
1256
+ const state = scope.state;
1257
+ const clip = scope.resolveClip(op.target);
1258
+ scope.editTargets(clip);
1259
+ // Deleting a group deletes the parent, not the picture: its children stay
1260
+ // where they are and stop inheriting (D4). Leaving them with a `parentId`
1261
+ // nothing answers is what the validator calls a dangling parent.
1262
+ const wasChild = scope.clips
1263
+ .filter((c) => c.parentId === clip.id)
1264
+ .map((c) => c.id);
1265
+ const remaining = isGroupClip(clip)
1266
+ ? ungroup(scope.clips, clip.id)
1267
+ : scope.clips;
1268
+ const out = scope.clipOut(clip);
1269
+ scope.clips = remaining.filter((c) => c.id !== clip.id);
1270
+ if (clip.linkId) {
1271
+ const remainingLinked = scope.clips.filter((candidate) => candidate.linkId === clip.linkId);
1272
+ if (remainingLinked.length === 1) {
1273
+ delete remainingLinked[0].linkId;
1274
+ scope.touch(remainingLinked[0].id);
1275
+ }
1276
+ }
1277
+ state.selectedClipIds = state.selectedClipIds.filter((id) => id !== clip.id);
1278
+ scope.touch(clip.id, ...wasChild);
1279
+ return { ok: true, deleted: out };
1280
+ },
1281
+ duplicate_clip: (scope, op) => {
1282
+ const src = scope.resolveClip(op.target);
1283
+ const offsetMs = src.durationMs + (op.gapMs ?? 0);
1284
+ if (!Number.isFinite(offsetMs) || src.startMs + offsetMs < 0) {
1285
+ throw new Error(`gapMs ${op.gapMs} would place the copy of "${src.name}" before zero.`);
1286
+ }
1287
+ // A group's copy carries copies of what it holds, at the same offset, so
1288
+ // the duplicate draws what the original draws.
1289
+ const descendants = isGroupClip(src)
1290
+ ? groupDescendantIds(scope.clips, src.id)
1291
+ : new Set();
1292
+ const sources = [
1293
+ src,
1294
+ ...scope.clips.filter((clip) => descendants.has(clip.id))
1295
+ ];
1296
+ for (const clip of sources) {
1297
+ scope.assertWritable([], clip.trackId);
1298
+ }
1299
+ const freshIds = new Map(sources.map((clip) => [clip.id, scope.ctx.newId("clip")]));
1300
+ // A link whose members are all copied stays a link among the copies,
1301
+ // under a fresh id; a lone half is copied unlinked.
1302
+ const linkCounts = new Map();
1303
+ for (const clip of sources) {
1304
+ if (clip.linkId !== undefined && clip.id !== src.id) {
1305
+ linkCounts.set(clip.linkId, (linkCounts.get(clip.linkId) ?? 0) + 1);
1306
+ }
1307
+ }
1308
+ const freshLinks = new Map();
1309
+ const copies = sources.map((clip) => {
1310
+ const copy = structuredClone(clip);
1311
+ copy.id = freshIds.get(clip.id);
1312
+ copy.startMs += offsetMs;
1313
+ copy.locked = false;
1314
+ if (copy.parentId !== undefined && clip.id !== src.id) {
1315
+ copy.parentId = freshIds.get(copy.parentId) ?? copy.parentId;
1316
+ }
1317
+ const linkId = clip.linkId;
1318
+ if (linkId !== undefined &&
1319
+ clip.id !== src.id &&
1320
+ (linkCounts.get(linkId) ?? 0) >= 2) {
1321
+ let fresh = freshLinks.get(linkId);
1322
+ if (fresh === undefined) {
1323
+ fresh = scope.ctx.newId("link");
1324
+ freshLinks.set(linkId, fresh);
998
1325
  }
1326
+ copy.linkId = fresh;
1327
+ }
1328
+ else {
1329
+ delete copy.linkId;
1330
+ }
1331
+ // A generated clip's copy is a variation to regenerate, so it starts
1332
+ // as a draft. Imported media keeps its asset and draws the same frames.
1333
+ if (clip.sourceType === "generated") {
1334
+ copy.status = "draft";
1335
+ copy.versions = [];
1336
+ delete copy.currentAssetId;
1337
+ delete copy.lastGeneratedHash;
1338
+ delete copy.activeTakeId;
999
1339
  }
1000
- state.selectedClipIds = state.selectedClipIds.filter((id) => id !== clip.id);
1001
- scope.touch(clip.id, ...wasChild);
1002
- return { ok: true, deleted: out };
1003
- }
1004
- case "duplicate_clip": {
1005
- const src = scope.resolveClip(op.target);
1006
- const copy = structuredClone(src);
1007
- copy.id = scope.ctx.newId("clip");
1008
- copy.startMs += src.durationMs + (op.gapMs ?? 0);
1009
- copy.status = "draft";
1010
- copy.locked = false;
1011
- copy.versions = [];
1012
- delete copy.currentAssetId;
1013
- delete copy.lastGeneratedHash;
1014
- delete copy.activeTakeId;
1015
- delete copy.linkId;
1016
1340
  copy.animations = copy.animations?.map((animation) => ({
1017
1341
  ...animation,
1018
1342
  id: scope.ctx.newId("anim")
1019
1343
  }));
1020
- scope.clips.push(copy);
1021
- scope.touch(copy.id);
1022
- return { ok: true, clip: scope.clipOut(copy) };
1023
- }
1024
- case "set_clip_params": {
1025
- let clip = scope.resolveClip(op.target);
1026
- const patch = { ...op.patch };
1027
- rejectUnknownClipParams(patch);
1028
- // Timing belongs to move_clip and trim_clip, but a caller sending it here
1029
- // means one edit either way — so apply it through the same code rather
1030
- // than dropping it or making them call twice.
1031
- clip = scope.applyTrim(clip, {
1032
- durationMs: patch.durationMs,
1033
- inPointMs: patch.inPointMs,
1034
- outPointMs: patch.outPointMs
1035
- });
1036
- clip = scope.applyMove(clip, {
1037
- startMs: patch.startMs,
1038
- trackId: patch.trackId
1039
- });
1040
- if (patch.fontSizePx !== undefined) {
1041
- // Shorthand for the one text field callers reach for by name.
1042
- const style = patch.textStyle ?? clip.textStyle;
1043
- if (!style) {
1044
- throw new Error(`Clip "${clip.name}" carries no text to size; fontSizePx applies to a text clip's textStyle.`);
1045
- }
1046
- patch.textStyle = { ...style, fontSizePx: patch.fontSizePx };
1047
- }
1048
- if (patch.name !== undefined) {
1049
- clip.name = patch.name;
1050
- }
1051
- if (patch.opacity !== undefined) {
1052
- clip.opacity = patch.opacity;
1053
- }
1054
- if (patch.transform !== undefined) {
1055
- clip.transform = mergeClipTransform(clip.transform, patch.transform);
1056
- }
1057
- if (patch.speedMultiplier !== undefined) {
1058
- clip.speedMultiplier = patch.speedMultiplier;
1059
- }
1060
- if (patch.volumeDb !== undefined) {
1061
- clip.volumeDb = patch.volumeDb;
1062
- }
1063
- if (patch.fadeInMs !== undefined) {
1064
- clip.fadeInMs = patch.fadeInMs;
1065
- }
1066
- if (patch.fadeOutMs !== undefined) {
1067
- clip.fadeOutMs = patch.fadeOutMs;
1068
- }
1069
- if (patch.fadeInShape !== undefined) {
1070
- clip.fadeInShape = patch.fadeInShape;
1071
- }
1072
- if (patch.fadeOutShape !== undefined) {
1073
- clip.fadeOutShape = patch.fadeOutShape;
1074
- }
1075
- if (patch.blendMode !== undefined) {
1076
- clip.blendMode = patch.blendMode;
1077
- }
1078
- if (patch.borderRadius !== undefined) {
1079
- clip.borderRadius = patch.borderRadius;
1080
- }
1081
- if (patch.crop !== undefined) {
1082
- // Null is how a caller puts the whole source back; leaving the field
1083
- // with all-zero insets would store a crop that means nothing.
1084
- if (patch.crop === null) {
1085
- delete clip.crop;
1086
- }
1087
- else {
1088
- if (!isCropUsable(patch.crop)) {
1089
- throw new Error(`Crop on clip "${clip.name}" keeps no picture: left + right and ` +
1090
- "top + bottom must each stay below 1.");
1091
- }
1092
- clip.crop = patch.crop;
1093
- }
1094
- }
1095
- if (patch.hidden !== undefined) {
1096
- clip.hidden = patch.hidden;
1097
- }
1098
- if (patch.muted !== undefined) {
1099
- clip.muted = patch.muted;
1100
- }
1101
- if (patch.locked !== undefined) {
1102
- clip.locked = patch.locked;
1103
- }
1104
- if (patch.textStyle !== undefined) {
1105
- const parsed = textStyleParams.safeParse({
1106
- color: DEFAULT_TEXT_CLIP_COLOR,
1107
- ...clip.textStyle,
1108
- ...patch.textStyle
1109
- });
1110
- if (!parsed.success) {
1111
- throw new Error(`Clip "${clip.name}" has no text style yet, so this patch still needs ${parsed.error.issues.map((issue) => issue.path.join(".")).join(", ")}.`);
1112
- }
1113
- assertAuthorableFontFamily(parsed.data.fontFamily);
1114
- clip.textStyle = parsed.data;
1115
- }
1116
- if (patch.shapeStyle !== undefined) {
1117
- clip.shapeStyle = shapeStyleWithDefaults(patch.shapeStyle);
1118
- }
1119
- if (patch.captionStyle !== undefined) {
1120
- // The style rides on the clip's caption, so a clip with no words to
1121
- // draw has nowhere to put it. Say so rather than storing a look nothing
1122
- // renders.
1123
- if (!clip.caption) {
1124
- throw new Error(`Clip "${clip.name}" carries no caption to style.`);
1125
- }
1126
- clip.caption = { ...clip.caption, style: patch.captionStyle };
1344
+ return copy;
1345
+ });
1346
+ scope.clips.push(...copies);
1347
+ scope.touch(...copies.map((copy) => copy.id));
1348
+ const result = {
1349
+ ok: true,
1350
+ clip: scope.clipOut(copies[0])
1351
+ };
1352
+ if (copies.length > 1) {
1353
+ result.children = copies.slice(1).map((copy) => copy.id);
1354
+ }
1355
+ return result;
1356
+ },
1357
+ set_clip_params: async (scope, op) => {
1358
+ let clip = scope.resolveClip(op.target);
1359
+ const patch = { ...op.patch };
1360
+ rejectUnknownClipParams(patch);
1361
+ // Timing belongs to move_clip and trim_clip, but a caller sending it here
1362
+ // means one edit either way — so apply it through the same code rather
1363
+ // than dropping it or making them call twice.
1364
+ clip = scope.applyTrim(clip, {
1365
+ durationMs: patch.durationMs,
1366
+ inPointMs: patch.inPointMs,
1367
+ outPointMs: patch.outPointMs
1368
+ }, patch.durationMs === undefined && patch.outPointMs === undefined
1369
+ ? undefined
1370
+ : await scope.sourceLimitMs(clip));
1371
+ clip = scope.applyMove(clip, {
1372
+ startMs: patch.startMs,
1373
+ trackId: patch.trackId
1374
+ });
1375
+ if (patch.fontSizePx !== undefined) {
1376
+ // Shorthand for the one text field callers reach for by name.
1377
+ const style = patch.textStyle ?? clip.textStyle;
1378
+ if (!style) {
1379
+ throw new Error(`Clip "${clip.name}" carries no text to size; fontSizePx applies to a text clip's textStyle.`);
1127
1380
  }
1128
- scope.touch(clip.id);
1129
- return { ok: true, clip: scope.clipOut(clip) };
1381
+ patch.textStyle = { ...style, fontSizePx: patch.fontSizePx };
1130
1382
  }
1131
- case "set_parent": {
1132
- const clip = scope.resolveClip(op.target);
1133
- scope.touch(clip.id);
1134
- if (op.parentId === null) {
1135
- delete clip.parentId;
1136
- return { ok: true, clip: scope.clipOut(clip) };
1137
- }
1138
- const parent = scope.resolveClip(op.parentId);
1139
- if (parent.mediaType !== "group") {
1140
- throw new Error(`"${parent.name}" is a ${parent.mediaType} clip, not a group — parent to a clip created with add_group. ${scope.validUnits(scope.clips.filter((c) => c.mediaType === "group"), "group")}`);
1141
- }
1142
- // A cycle renders unparented and warns, so refusing it here is the only
1143
- // place it can still be fixed.
1144
- let cursor = parent;
1145
- while (cursor) {
1146
- if (cursor.id === clip.id) {
1147
- throw new Error(`"${parent.name}" is inside "${clip.name}" — parenting them would make a cycle.`);
1148
- }
1149
- const next = cursor.parentId;
1150
- cursor = next ? scope.clips.find((c) => c.id === next) : undefined;
1151
- }
1152
- clip.parentId = parent.id;
1153
- return { ok: true, clip: scope.clipOut(clip) };
1383
+ if (patch.name !== undefined) {
1384
+ clip.name = patch.name;
1154
1385
  }
1155
- case "set_transition": {
1156
- const clip = scope.resolveClip(op.target);
1157
- if (op.transition === null) {
1158
- delete clip.transitionIn;
1159
- }
1160
- else {
1161
- clip.transitionIn = buildTransition(op.transition);
1162
- }
1163
- scope.touch(clip.id);
1164
- return { ok: true, clip: scope.clipOut(clip) };
1386
+ if (patch.opacity !== undefined) {
1387
+ clip.opacity = patch.opacity;
1165
1388
  }
1166
- case "apply_transition_at_cut": {
1167
- const planned = planTransitionAtCut(scope.clips, op);
1168
- if (!planned.ok) {
1169
- throw new Error(planned.error);
1170
- }
1171
- const applied = applyTransitionAtCutCandidate(scope.clips, planned.candidate);
1172
- if (!applied.ok) {
1173
- throw new Error(applied.error);
1389
+ if (patch.transform !== undefined) {
1390
+ clip.transform = mergeClipTransform(clip.transform, patch.transform);
1391
+ }
1392
+ if (patch.speedMultiplier !== undefined) {
1393
+ // The editor's rule: the source window stays, the duration scales, and
1394
+ // linked partners change speed with the clip.
1395
+ const unit = scope.editTargets(clip);
1396
+ scope.clips = retimeClipSpeed(scope.clips, new Set(unit.map((member) => member.id)), patch.speedMultiplier);
1397
+ for (const member of unit) {
1398
+ scope.touch(member.id);
1174
1399
  }
1175
- scope.clips = applied.clips;
1176
- scope.touch(planned.candidate.outgoingClipId, planned.candidate.incomingClipId);
1177
- return {
1178
- ok: true,
1179
- candidate: planned.candidate,
1180
- operation: planned.candidate.operation,
1181
- description: applied.description
1182
- };
1400
+ clip = scope.resolveClip(clip.id);
1183
1401
  }
1184
- case "set_mask": {
1185
- const clip = scope.resolveClip(op.target);
1186
- if (op.mask === null) {
1187
- delete clip.mask;
1402
+ if (patch.volumeDb !== undefined) {
1403
+ clip.volumeDb = patch.volumeDb;
1404
+ }
1405
+ if (patch.fadeInMs !== undefined) {
1406
+ clip.fadeInMs = patch.fadeInMs;
1407
+ }
1408
+ if (patch.fadeOutMs !== undefined) {
1409
+ clip.fadeOutMs = patch.fadeOutMs;
1410
+ }
1411
+ if (patch.fadeInShape !== undefined) {
1412
+ clip.fadeInShape = patch.fadeInShape;
1413
+ }
1414
+ if (patch.fadeOutShape !== undefined) {
1415
+ clip.fadeOutShape = patch.fadeOutShape;
1416
+ }
1417
+ if (patch.blendMode !== undefined) {
1418
+ clip.blendMode = patch.blendMode;
1419
+ }
1420
+ if (patch.borderRadius !== undefined) {
1421
+ clip.borderRadius = patch.borderRadius;
1422
+ }
1423
+ if (patch.crop !== undefined) {
1424
+ // Null is how a caller puts the whole source back; leaving the field
1425
+ // with all-zero insets would store a crop that means nothing.
1426
+ if (patch.crop === null) {
1427
+ delete clip.crop;
1188
1428
  }
1189
1429
  else {
1190
- if (op.mask.kind === "path" && !op.mask.d?.trim()) {
1191
- throw new Error("A path mask needs `d` with SVG path data.");
1430
+ if (!isCropUsable(patch.crop)) {
1431
+ throw new Error(`Crop on clip "${clip.name}" keeps no picture: left + right and ` +
1432
+ "top + bottom must each stay below 1.");
1192
1433
  }
1193
- clip.mask = buildMask(op.mask, scope.ctx.parseSvgPath);
1434
+ clip.crop = patch.crop;
1194
1435
  }
1195
- scope.touch(clip.id);
1196
- return { ok: true, clip: scope.clipOut(clip) };
1197
1436
  }
1198
- case "set_matte": {
1199
- const clip = scope.resolveClip(op.target);
1200
- scope.touch(clip.id);
1201
- if (op.matte === null) {
1202
- delete clip.matte;
1203
- return { ok: true, clip: scope.clipOut(clip) };
1204
- }
1205
- const source = scope.resolveClip(op.matte.source);
1206
- if (source.id === clip.id) {
1207
- throw new Error(`"${clip.name}" cannot be its own matte source — name another clip.`);
1208
- }
1209
- const matteOut = {
1210
- sourceClipId: source.id,
1211
- mode: op.matte.mode
1212
- };
1213
- if (op.matte.invert !== undefined) {
1214
- matteOut.invert = op.matte.invert;
1215
- }
1216
- clip.matte = matteOut;
1217
- return { ok: true, clip: scope.clipOut(clip) };
1437
+ if (patch.hidden !== undefined) {
1438
+ clip.hidden = patch.hidden;
1218
1439
  }
1219
- case "set_generated_matte": {
1220
- const clip = scope.resolveClip(op.target);
1221
- scope.touch(clip.id);
1222
- if (op.clear === true) {
1223
- delete clip.generatedMatte;
1224
- return { ok: true, clip: scope.clipOut(clip), generatedMatte: null };
1225
- }
1226
- if (!clip.generatedMatte) {
1227
- throw new Error(`"${clip.name}" carries no generated matte. Run isolate_subject on ` +
1228
- "it first; this op only adjusts one that exists.");
1229
- }
1230
- if (op.selectVersionAssetId !== undefined) {
1231
- clip.generatedMatte = selectGeneratedMatteVersion(clip, op.selectVersionAssetId).generatedMatte;
1232
- }
1233
- // The knobs are the user's, so an absent field leaves the stored value
1234
- // alone rather than resetting it to a default the caller did not name.
1235
- const matte = clip.generatedMatte;
1236
- if (op.invert !== undefined) {
1237
- matte.invert = op.invert;
1238
- }
1239
- if (op.strength !== undefined) {
1240
- matte.strength = Math.min(1, Math.max(0, op.strength));
1241
- }
1242
- if (op.featherPx !== undefined) {
1243
- matte.featherPx = Math.max(0, op.featherPx);
1244
- }
1245
- return { ok: true, clip: scope.clipOut(clip), generatedMatte: matte };
1440
+ if (patch.muted !== undefined) {
1441
+ clip.muted = patch.muted;
1246
1442
  }
1247
- case "set_time_remap": {
1248
- const clip = scope.resolveClip(op.target);
1249
- if (op.timeRemap === null) {
1250
- delete clip.timeRemap;
1251
- }
1252
- else {
1253
- clip.timeRemap = buildTimeRemap(op.timeRemap);
1254
- }
1255
- scope.touch(clip.id);
1256
- return { ok: true, clip: scope.clipOut(clip) };
1443
+ if (patch.locked !== undefined) {
1444
+ clip.locked = patch.locked;
1257
1445
  }
1258
- case "set_effects": {
1259
- const clip = scope.resolveClip(op.target);
1260
- const list = op.effects.map(buildEffect);
1261
- if (list.length === 0) {
1262
- delete clip.effects;
1263
- }
1264
- else {
1265
- clip.effects = list;
1266
- }
1267
- scope.touch(clip.id);
1446
+ if (patch.textStyle !== undefined) {
1447
+ const parsed = textStyleParams.safeParse({
1448
+ color: DEFAULT_TEXT_CLIP_COLOR,
1449
+ ...clip.textStyle,
1450
+ ...patch.textStyle
1451
+ });
1452
+ if (!parsed.success) {
1453
+ throw new Error(`Clip "${clip.name}" has no text style yet, so this patch still needs ${parsed.error.issues.map((issue) => issue.path.join(".")).join(", ")}.`);
1454
+ }
1455
+ assertAuthorableFontFamily(parsed.data.fontFamily);
1456
+ clip.textStyle = parsed.data;
1457
+ }
1458
+ if (patch.shapeStyle !== undefined) {
1459
+ clip.shapeStyle = shapeStyleWithDefaults(patch.shapeStyle);
1460
+ }
1461
+ if (patch.captionStyle !== undefined) {
1462
+ // The style rides on the clip's caption, so a clip with no words to
1463
+ // draw has nowhere to put it. Say so rather than storing a look nothing
1464
+ // renders.
1465
+ if (!clip.caption) {
1466
+ throw new Error(`Clip "${clip.name}" carries no caption to style.`);
1467
+ }
1468
+ clip.caption = { ...clip.caption, style: patch.captionStyle };
1469
+ }
1470
+ scope.touch(clip.id);
1471
+ return { ok: true, clip: scope.clipOut(clip) };
1472
+ },
1473
+ set_parent: (scope, op) => {
1474
+ const clip = scope.resolveClip(op.target);
1475
+ scope.assertWritable([clip]);
1476
+ scope.touch(clip.id);
1477
+ if (op.parentId === null) {
1478
+ delete clip.parentId;
1268
1479
  return { ok: true, clip: scope.clipOut(clip) };
1269
1480
  }
1270
- case "set_clip_binding": {
1271
- const clip = scope.resolveClip(op.target);
1272
- if (clip.sourceType !== "generated") {
1273
- throw new Error(`"${clip.name}" is not a generated clip — ui_timeline_set_clip_binding only applies to clips created with ui_timeline_generate_clip.`);
1274
- }
1275
- if (op.prompt !== undefined) {
1276
- clip.prompt = op.prompt;
1277
- }
1278
- if (op.negativePrompt !== undefined) {
1279
- clip.negativePrompt = op.negativePrompt;
1280
- }
1281
- if (op.provider !== undefined) {
1282
- clip.provider = op.provider;
1283
- }
1284
- if (op.model !== undefined) {
1285
- clip.model = op.model;
1286
- }
1287
- if (op.voice !== undefined) {
1288
- clip.voice = op.voice;
1289
- }
1290
- if (op.width !== undefined) {
1291
- clip.width = op.width;
1292
- }
1293
- if (op.height !== undefined) {
1294
- clip.height = op.height;
1295
- }
1296
- if (op.aspectRatio !== undefined) {
1297
- clip.aspectRatio = op.aspectRatio;
1298
- }
1299
- if (op.resolution !== undefined) {
1300
- clip.resolution = op.resolution;
1301
- }
1302
- if (op.strength !== undefined) {
1303
- clip.strength = op.strength;
1304
- }
1305
- if (op.numInferenceSteps !== undefined) {
1306
- clip.numInferenceSteps = op.numInferenceSteps;
1307
- }
1308
- if (op.seed !== undefined) {
1309
- clip.seed = op.seed;
1310
- }
1311
- const bindingChanged = Object.keys(op).some((key) => key !== "op" &&
1312
- key !== "target" &&
1313
- key !== "regenerate" &&
1314
- op[key] !== undefined);
1315
- if (bindingChanged && (clip.lastGeneratedHash || clip.currentAssetId)) {
1316
- clip.status = "stale";
1317
- }
1318
- if (op.regenerate) {
1319
- clip.status = "queued";
1481
+ const parent = scope.resolveClip(op.parentId);
1482
+ if (parent.mediaType !== "group") {
1483
+ throw new Error(`"${parent.name}" is a ${parent.mediaType} clip, not a group — parent to a clip created with add_group. ${scope.validUnits(scope.clips.filter((c) => c.mediaType === "group"), "group")}`);
1484
+ }
1485
+ // A cycle renders unparented and warns, so refusing it here is the only
1486
+ // place it can still be fixed.
1487
+ let cursor = parent;
1488
+ while (cursor) {
1489
+ if (cursor.id === clip.id) {
1490
+ throw new Error(`"${parent.name}" is inside "${clip.name}" — parenting them would make a cycle.`);
1491
+ }
1492
+ const next = cursor.parentId;
1493
+ cursor = next ? scope.clips.find((c) => c.id === next) : undefined;
1494
+ }
1495
+ clip.parentId = parent.id;
1496
+ return { ok: true, clip: scope.clipOut(clip) };
1497
+ },
1498
+ set_transition: (scope, op) => {
1499
+ const clip = scope.resolveClip(op.target);
1500
+ scope.assertWritable([clip]);
1501
+ if (op.transition === null) {
1502
+ delete clip.transitionIn;
1503
+ }
1504
+ else {
1505
+ clip.transitionIn = buildTransition(op.transition);
1506
+ }
1507
+ scope.touch(clip.id);
1508
+ return { ok: true, clip: scope.clipOut(clip) };
1509
+ },
1510
+ apply_transition_at_cut: async (scope, op) => {
1511
+ const outgoing = scope.resolveClip(op.outgoingClipId);
1512
+ const incoming = scope.resolveClip(op.incomingClipId);
1513
+ const planned = planTransitionAtCut(scope.clips, {
1514
+ ...op,
1515
+ outgoingClipId: outgoing.id,
1516
+ incomingClipId: incoming.id
1517
+ });
1518
+ if (!planned.ok) {
1519
+ throw new Error(planned.error);
1520
+ }
1521
+ scope.assertWritable([incoming]);
1522
+ // The outgoing clip grows under the transition with the partners that
1523
+ // end with it, so each is a write the lock refuses. Like the editor, it
1524
+ // is capped at a source length the host knows and free otherwise.
1525
+ const growth = transitionGrowthMs(outgoing, incoming, transitionLengthAtCut(outgoing, incoming, planned.candidate.durationMs));
1526
+ const unit = growth > 0 ? transitionGrowthUnit(scope.clips, outgoing) : [];
1527
+ scope.assertWritable(unit);
1528
+ const limits = new Map();
1529
+ for (const member of unit) {
1530
+ limits.set(member.id, await scope.knownSourceMs(member));
1531
+ }
1532
+ const applied = applyTransitionAtCutCandidate(scope.clips, planned.candidate, { sourceDurationMs: (clip) => limits.get(clip.id) });
1533
+ if (!applied.ok) {
1534
+ throw new Error(applied.error);
1535
+ }
1536
+ const before = new Map(scope.clips.map((clip) => [clip.id, clip]));
1537
+ scope.clips = applied.clips;
1538
+ for (const clip of scope.clips) {
1539
+ if (before.get(clip.id) !== clip) {
1540
+ scope.mediaTracks = resliceTracksForTrimmedClip(scope.mediaTracks, clip);
1541
+ scope.touch(clip.id);
1320
1542
  }
1321
- scope.touch(clip.id);
1322
- return { ok: true, clip: scope.clipOut(clip) };
1323
1543
  }
1324
- case "animate_clip": {
1325
- const clip = scope.resolveClip(op.target);
1326
- if (clip.mediaType !== "text" &&
1327
- op.animations.some((input) => input.stagger !== undefined)) {
1328
- throw new Error(`Stagger applies only to text clips; "${clip.name}" is ${clip.mediaType}.`);
1329
- }
1330
- const built = [];
1331
- for (const input of op.animations) {
1332
- if (input.preset === CUSTOM_ANIMATION_PRESET_ID) {
1333
- // `{preset: "custom", custom: {curves}}` reads as naturally as the
1334
- // flat form, so lift it rather than refusing it.
1335
- built.push(await buildCustomAnimation(scope, clip, liftCustom(input)));
1336
- continue;
1337
- }
1338
- const preset = ANIMATION_PRESETS.find((p) => p.id === input.preset);
1339
- if (!preset) {
1340
- const ids = ANIMATION_PRESETS.map((p) => p.id).join(", ");
1341
- throw new Error(`Unknown animation preset "${input.preset}". Valid presets: ${ids}, ${CUSTOM_ANIMATION_PRESET_ID}.`);
1342
- }
1343
- if (!preset.roles.includes(input.role)) {
1344
- throw new Error(`Preset "${input.preset}" does not support role "${input.role}". Valid roles for "${input.preset}": ${preset.roles.join(", ")}.`);
1345
- }
1346
- if (input.preset === "typewriter" && clip.mediaType !== "text") {
1347
- throw new Error('Preset "typewriter" requires a text clip.');
1348
- }
1349
- const timing = input.preset === "typewriter"
1350
- ? typewriterTiming(clip.textStyle?.text ?? "", clip.durationMs - (input.delayMs ?? 0), input.durationMs, input.stagger)
1351
- : null;
1352
- built.push({
1353
- id: scope.ctx.newId("anim"),
1354
- role: input.role,
1355
- enabled: input.enabled,
1356
- preset: input.preset,
1357
- durationMs: timing?.durationMs ?? input.durationMs ?? preset.defaultDurationMs,
1358
- delayMs: input.delayMs,
1359
- easing: input.easing,
1360
- params: input.params,
1361
- stagger: timing?.stagger ?? input.stagger,
1362
- caret: input.preset === "typewriter" ? input.caret : undefined
1363
- });
1364
- }
1365
- clip.animations =
1366
- op.mode === "add" ? [...(clip.animations ?? []), ...built] : built;
1367
- scope.touch(clip.id);
1544
+ return {
1545
+ ok: true,
1546
+ candidate: planned.candidate,
1547
+ operation: planned.candidate.operation,
1548
+ description: applied.description
1549
+ };
1550
+ },
1551
+ set_mask: (scope, op) => {
1552
+ const clip = scope.resolveClip(op.target);
1553
+ if (op.mask === null) {
1554
+ delete clip.mask;
1555
+ }
1556
+ else {
1557
+ if (op.mask.kind === "path" && !op.mask.d?.trim()) {
1558
+ throw new Error("A path mask needs `d` with SVG path data.");
1559
+ }
1560
+ clip.mask = buildMask(op.mask, scope.ctx.parseSvgPath);
1561
+ }
1562
+ scope.touch(clip.id);
1563
+ return { ok: true, clip: scope.clipOut(clip) };
1564
+ },
1565
+ set_matte: (scope, op) => {
1566
+ const clip = scope.resolveClip(op.target);
1567
+ scope.touch(clip.id);
1568
+ if (op.matte === null) {
1569
+ delete clip.matte;
1368
1570
  return { ok: true, clip: scope.clipOut(clip) };
1369
1571
  }
1370
- case "set_baked_animation": {
1371
- const clip = scope.resolveClip(op.target);
1372
- const outcome = buildBakedAnimation(clip, op.animation, () => scope.ctx.newId("anim"));
1373
- clip.animations = outcome.animations;
1374
- scope.touch(clip.id);
1375
- return {
1376
- ok: true,
1377
- clip: scope.clipOut(clip),
1378
- animationId: outcome.animationId,
1379
- keyframeCount: outcome.animation.custom?.curves[0]?.keyframes.length ?? 0,
1380
- replaced: outcome.replaced
1381
- };
1572
+ const source = scope.resolveClip(op.matte.source);
1573
+ if (source.id === clip.id) {
1574
+ throw new Error(`"${clip.name}" cannot be its own matte source — name another clip.`);
1382
1575
  }
1383
- case "clear_animations": {
1384
- const clip = scope.resolveClip(op.target);
1385
- clip.animations = op.role
1386
- ? (clip.animations ?? []).filter((a) => a.role !== op.role)
1387
- : [];
1388
- scope.touch(clip.id);
1389
- return { ok: true, clip: scope.clipOut(clip) };
1390
- }
1391
- case "list_animation_presets": {
1392
- const presets = ANIMATION_PRESETS.map((p) => ({
1393
- id: p.id,
1394
- roles: p.roles,
1395
- defaultDurationMs: p.defaultDurationMs,
1396
- defaultEasing: p.defaultEasing,
1397
- params: p.params,
1398
- describe: p.describe
1399
- }));
1576
+ const matteOut = {
1577
+ sourceClipId: source.id,
1578
+ mode: op.matte.mode
1579
+ };
1580
+ if (op.matte.invert !== undefined) {
1581
+ matteOut.invert = op.matte.invert;
1582
+ }
1583
+ clip.matte = matteOut;
1584
+ return { ok: true, clip: scope.clipOut(clip) };
1585
+ },
1586
+ set_generated_matte: (scope, op) => {
1587
+ const clip = scope.resolveClip(op.target);
1588
+ scope.touch(clip.id);
1589
+ if (op.clear === true) {
1590
+ delete clip.generatedMatte;
1591
+ return { ok: true, clip: scope.clipOut(clip), generatedMatte: null };
1592
+ }
1593
+ if (!clip.generatedMatte) {
1594
+ throw new Error(`"${clip.name}" carries no generated matte. Run isolate_subject on ` +
1595
+ "it first; this op only adjusts one that exists.");
1596
+ }
1597
+ if (op.selectVersionAssetId !== undefined) {
1598
+ clip.generatedMatte = selectGeneratedMatteVersion(clip, op.selectVersionAssetId).generatedMatte;
1599
+ }
1600
+ // The knobs are the user's, so an absent field leaves the stored value
1601
+ // alone rather than resetting it to a default the caller did not name.
1602
+ const matte = clip.generatedMatte;
1603
+ if (op.invert !== undefined) {
1604
+ matte.invert = op.invert;
1605
+ }
1606
+ if (op.strength !== undefined) {
1607
+ matte.strength = Math.min(1, Math.max(0, op.strength));
1608
+ }
1609
+ if (op.featherPx !== undefined) {
1610
+ matte.featherPx = Math.max(0, op.featherPx);
1611
+ }
1612
+ return { ok: true, clip: scope.clipOut(clip), generatedMatte: matte };
1613
+ },
1614
+ set_time_remap: (scope, op) => {
1615
+ const clip = scope.resolveClip(op.target);
1616
+ scope.assertWritable([clip]);
1617
+ if (op.timeRemap === null) {
1618
+ delete clip.timeRemap;
1619
+ }
1620
+ else {
1621
+ clip.timeRemap = buildTimeRemap(op.timeRemap);
1622
+ }
1623
+ scope.touch(clip.id);
1624
+ return { ok: true, clip: scope.clipOut(clip) };
1625
+ },
1626
+ set_effects: (scope, op) => {
1627
+ const clip = scope.resolveClip(op.target);
1628
+ const list = op.effects.map(buildEffect);
1629
+ if (list.length === 0) {
1630
+ delete clip.effects;
1631
+ }
1632
+ else {
1633
+ clip.effects = list;
1634
+ }
1635
+ scope.touch(clip.id);
1636
+ return { ok: true, clip: scope.clipOut(clip) };
1637
+ },
1638
+ set_clip_binding: (scope, op) => {
1639
+ const clip = scope.resolveClip(op.target);
1640
+ if (clip.sourceType !== "generated") {
1641
+ throw new Error(`"${clip.name}" is not a generated clip — ui_timeline_set_clip_binding only applies to clips created with ui_timeline_generate_clip.`);
1642
+ }
1643
+ if (op.prompt !== undefined) {
1644
+ clip.prompt = op.prompt;
1645
+ }
1646
+ if (op.negativePrompt !== undefined) {
1647
+ clip.negativePrompt = op.negativePrompt;
1648
+ }
1649
+ if (op.provider !== undefined) {
1650
+ clip.provider = op.provider;
1651
+ }
1652
+ if (op.model !== undefined) {
1653
+ clip.model = op.model;
1654
+ }
1655
+ if (op.voice !== undefined) {
1656
+ clip.voice = op.voice;
1657
+ }
1658
+ if (op.width !== undefined) {
1659
+ clip.width = op.width;
1660
+ }
1661
+ if (op.height !== undefined) {
1662
+ clip.height = op.height;
1663
+ }
1664
+ if (op.aspectRatio !== undefined) {
1665
+ clip.aspectRatio = op.aspectRatio;
1666
+ }
1667
+ if (op.resolution !== undefined) {
1668
+ clip.resolution = op.resolution;
1669
+ }
1670
+ if (op.strength !== undefined) {
1671
+ clip.strength = op.strength;
1672
+ }
1673
+ if (op.numInferenceSteps !== undefined) {
1674
+ clip.numInferenceSteps = op.numInferenceSteps;
1675
+ }
1676
+ if (op.seed !== undefined) {
1677
+ clip.seed = op.seed;
1678
+ }
1679
+ const bindingChanged = Object.keys(op).some((key) => key !== "op" &&
1680
+ key !== "target" &&
1681
+ key !== "regenerate" &&
1682
+ op[key] !== undefined);
1683
+ if (bindingChanged && (clip.lastGeneratedHash || clip.currentAssetId)) {
1684
+ clip.status = "stale";
1685
+ }
1686
+ scope.touch(clip.id);
1687
+ // No op starts a generation job: the browser runs one itself after this
1688
+ // edit lands. Marking the clip queued here would promise a job that no
1689
+ // runner on this surface will ever start.
1690
+ if (op.regenerate) {
1400
1691
  return {
1401
1692
  ok: true,
1402
- presets,
1403
- custom: CUSTOM_ANIMATION_CONTRACT,
1404
- properties: CUSTOM_ANIMATION_CONTRACT.properties
1693
+ clip: scope.clipOut(clip),
1694
+ regenerationStarted: false,
1695
+ note: "The binding was saved, but this surface cannot run generation jobs. Regenerate the clip from the timeline editor."
1405
1696
  };
1406
1697
  }
1407
- case "select_clip": {
1408
- if (!op.target) {
1409
- state.selectedClipIds = [];
1410
- return { ok: true, selected: null };
1411
- }
1412
- const clip = scope.resolveClip(op.target);
1413
- state.selectedClipIds = [clip.id];
1414
- return { ok: true, selected: scope.clipOut(clip) };
1415
- }
1416
- case "seek": {
1417
- state.playheadMs = Math.max(0, op.timeMs);
1418
- return { ok: true, playheadMs: state.playheadMs };
1698
+ return { ok: true, clip: scope.clipOut(clip) };
1699
+ },
1700
+ animate_clip: async (scope, op) => {
1701
+ const clip = scope.resolveClip(op.target);
1702
+ if (clip.mediaType !== "text" &&
1703
+ op.animations.some((input) => input.stagger !== undefined)) {
1704
+ throw new Error(`Stagger applies only to text clips; "${clip.name}" is ${clip.mediaType}.`);
1705
+ }
1706
+ const built = [];
1707
+ for (const input of op.animations) {
1708
+ if (input.preset === CUSTOM_ANIMATION_PRESET_ID) {
1709
+ // `{preset: "custom", custom: {curves}}` reads as naturally as the
1710
+ // flat form, so lift it rather than refusing it.
1711
+ built.push(await buildCustomAnimation(scope, clip, liftCustom(input)));
1712
+ continue;
1713
+ }
1714
+ const preset = ANIMATION_PRESETS.find((p) => p.id === input.preset);
1715
+ if (!preset) {
1716
+ const ids = ANIMATION_PRESETS.map((p) => p.id).join(", ");
1717
+ throw new Error(`Unknown animation preset "${input.preset}". Valid presets: ${ids}, ${CUSTOM_ANIMATION_PRESET_ID}.`);
1718
+ }
1719
+ if (!preset.roles.includes(input.role)) {
1720
+ throw new Error(`Preset "${input.preset}" does not support role "${input.role}". Valid roles for "${input.preset}": ${preset.roles.join(", ")}.`);
1721
+ }
1722
+ if (input.preset === "typewriter" && clip.mediaType !== "text") {
1723
+ throw new Error('Preset "typewriter" requires a text clip.');
1724
+ }
1725
+ const timing = input.preset === "typewriter"
1726
+ ? typewriterTiming(clip.textStyle?.text ?? "", clip.durationMs - (input.delayMs ?? 0), input.durationMs, input.stagger)
1727
+ : null;
1728
+ built.push({
1729
+ id: scope.ctx.newId("anim"),
1730
+ role: input.role,
1731
+ enabled: input.enabled,
1732
+ preset: input.preset,
1733
+ durationMs: timing?.durationMs ?? input.durationMs ?? preset.defaultDurationMs,
1734
+ delayMs: input.delayMs,
1735
+ easing: input.easing,
1736
+ params: input.params,
1737
+ stagger: timing?.stagger ?? input.stagger,
1738
+ caret: input.preset === "typewriter" ? input.caret : undefined
1739
+ });
1419
1740
  }
1420
- case "add_marker": {
1421
- if (op.timeMs < 0) {
1422
- throw new Error(`A marker cannot sit before zero; got ${op.timeMs}ms.`);
1741
+ clip.animations =
1742
+ op.mode === "add" ? [...(clip.animations ?? []), ...built] : built;
1743
+ scope.touch(clip.id);
1744
+ return { ok: true, clip: scope.clipOut(clip) };
1745
+ },
1746
+ set_baked_animation: (scope, op) => {
1747
+ const clip = scope.resolveClip(op.target);
1748
+ const outcome = buildBakedAnimation(clip, op.animation, () => scope.ctx.newId("anim"));
1749
+ clip.animations = outcome.animations;
1750
+ scope.touch(clip.id);
1751
+ return {
1752
+ ok: true,
1753
+ clip: scope.clipOut(clip),
1754
+ animationId: outcome.animationId,
1755
+ keyframeCount: outcome.animation.custom?.curves[0]?.keyframes.length ?? 0,
1756
+ replaced: outcome.replaced
1757
+ };
1758
+ },
1759
+ clear_animations: (scope, op) => {
1760
+ const clip = scope.resolveClip(op.target);
1761
+ clip.animations = op.role
1762
+ ? (clip.animations ?? []).filter((a) => a.role !== op.role)
1763
+ : [];
1764
+ scope.touch(clip.id);
1765
+ return { ok: true, clip: scope.clipOut(clip) };
1766
+ },
1767
+ list_animation_presets: (_scope) => {
1768
+ const presets = ANIMATION_PRESETS.map((p) => ({
1769
+ id: p.id,
1770
+ roles: p.roles,
1771
+ defaultDurationMs: p.defaultDurationMs,
1772
+ defaultEasing: p.defaultEasing,
1773
+ params: p.params,
1774
+ describe: p.describe
1775
+ }));
1776
+ return {
1777
+ ok: true,
1778
+ presets,
1779
+ custom: CUSTOM_ANIMATION_CONTRACT,
1780
+ properties: CUSTOM_ANIMATION_CONTRACT.properties
1781
+ };
1782
+ },
1783
+ select_clip: (scope, op) => {
1784
+ const state = scope.state;
1785
+ if (!op.target) {
1786
+ state.selectedClipIds = [];
1787
+ return { ok: true, selected: null };
1788
+ }
1789
+ const clip = scope.resolveClip(op.target);
1790
+ state.selectedClipIds = [clip.id];
1791
+ return { ok: true, selected: scope.clipOut(clip) };
1792
+ },
1793
+ seek: (scope, op) => {
1794
+ const state = scope.state;
1795
+ state.playheadMs = Math.max(0, op.timeMs);
1796
+ return { ok: true, playheadMs: state.playheadMs };
1797
+ },
1798
+ add_marker: (scope, op) => {
1799
+ const state = scope.state;
1800
+ if (op.timeMs < 0) {
1801
+ throw new Error(`A marker cannot sit before zero; got ${op.timeMs}ms.`);
1802
+ }
1803
+ const marker = {
1804
+ id: scope.ctx.newId("marker"),
1805
+ timeMs: Math.round(op.timeMs),
1806
+ label: op.label ?? ""
1807
+ };
1808
+ if (op.color !== undefined) {
1809
+ marker.color = op.color;
1810
+ }
1811
+ if (op.note !== undefined) {
1812
+ marker.note = op.note;
1813
+ }
1814
+ state.markers.push(marker);
1815
+ return { ok: true, marker: { ...marker } };
1816
+ },
1817
+ delete_marker: (scope, op) => {
1818
+ const state = scope.state;
1819
+ const marker = scope.resolveMarker(op.target);
1820
+ state.markers = state.markers.filter((m) => m.id !== marker.id);
1821
+ return { ok: true, deleted: { ...marker } };
1822
+ },
1823
+ set_markers_from_beats: (scope, op) => {
1824
+ const state = scope.state;
1825
+ const grid = buildBeatGrid({
1826
+ onsetsMs: op.onsets_ms,
1827
+ bpm: op.bpm,
1828
+ offsetMs: op.offset_ms,
1829
+ count: op.count
1830
+ });
1831
+ const stem = (op.label ?? "Beat").trim() || "Beat";
1832
+ const taken = new Set(state.markers.map((m) => m.timeMs));
1833
+ const added = [];
1834
+ const skipped = [];
1835
+ for (const [index, timeMs] of grid.entries()) {
1836
+ if (taken.has(timeMs)) {
1837
+ skipped.push(timeMs);
1838
+ continue;
1423
1839
  }
1424
1840
  const marker = {
1425
1841
  id: scope.ctx.newId("marker"),
1426
- timeMs: Math.round(op.timeMs),
1427
- label: op.label ?? ""
1842
+ timeMs,
1843
+ label: `${stem} ${index + 1}`
1428
1844
  };
1429
- if (op.color !== undefined) {
1430
- marker.color = op.color;
1431
- }
1432
- if (op.note !== undefined) {
1433
- marker.note = op.note;
1434
- }
1435
1845
  state.markers.push(marker);
1436
- return { ok: true, marker: { ...marker } };
1437
- }
1438
- case "delete_marker": {
1439
- const marker = scope.resolveMarker(op.target);
1440
- state.markers = state.markers.filter((m) => m.id !== marker.id);
1441
- return { ok: true, deleted: { ...marker } };
1442
- }
1443
- case "set_markers_from_beats": {
1444
- const grid = buildBeatGrid({
1445
- onsetsMs: op.onsets_ms,
1446
- bpm: op.bpm,
1447
- offsetMs: op.offset_ms,
1448
- count: op.count
1449
- });
1450
- const stem = (op.label ?? "Beat").trim() || "Beat";
1451
- const taken = new Set(state.markers.map((m) => m.timeMs));
1452
- const added = [];
1453
- const skipped = [];
1454
- for (const [index, timeMs] of grid.entries()) {
1455
- if (taken.has(timeMs)) {
1456
- skipped.push(timeMs);
1457
- continue;
1458
- }
1459
- const marker = {
1460
- id: scope.ctx.newId("marker"),
1461
- timeMs,
1462
- label: `${stem} ${index + 1}`
1463
- };
1464
- state.markers.push(marker);
1465
- taken.add(timeMs);
1466
- added.push(marker);
1467
- }
1468
- return {
1469
- ok: true,
1470
- grid: {
1471
- count: grid.length,
1472
- firstMs: grid[0],
1473
- lastMs: grid[grid.length - 1]
1474
- },
1475
- added: added.map((m) => ({ ...m })),
1476
- skipped_times_ms: skipped,
1477
- markers: state.markers.length
1478
- };
1846
+ taken.add(timeMs);
1847
+ added.push(marker);
1479
1848
  }
1480
- case "snap_to_beats": {
1481
- const named = op.targets === undefined || op.targets === "all"
1482
- ? undefined
1483
- : op.targets;
1484
- const { clips: targeted, missing } = scope.resolveSnapTargets(named);
1485
- const offsetMs = op.offset_ms ?? 0;
1486
- // A tempo grid has to reach the last boundary being snapped, so its
1487
- // length comes from the targets rather than from the caller.
1488
- const reachMs = targeted.reduce((end, clip) => Math.max(end, clip.startMs + clip.durationMs), 0);
1489
- const grid = buildBeatGrid({
1490
- onsetsMs: op.onsets_ms,
1491
- bpm: op.bpm,
1492
- offsetMs: op.offset_ms,
1493
- count: op.bpm === undefined
1494
- ? undefined
1495
- : beatCountToCover(op.bpm, offsetMs, reachMs)
1496
- });
1497
- const options = {};
1498
- if (op.tolerance_ms !== undefined) {
1499
- options.toleranceMs = op.tolerance_ms;
1500
- }
1501
- if (op.mode !== undefined) {
1502
- options.mode = op.mode;
1849
+ return {
1850
+ ok: true,
1851
+ grid: {
1852
+ count: grid.length,
1853
+ firstMs: grid[0],
1854
+ lastMs: grid[grid.length - 1]
1855
+ },
1856
+ added: added.map((m) => ({ ...m })),
1857
+ skipped_times_ms: skipped,
1858
+ markers: state.markers.length
1859
+ };
1860
+ },
1861
+ snap_to_beats: (scope, op) => {
1862
+ const named = op.targets === undefined || op.targets === "all" ? undefined : op.targets;
1863
+ const resolved = scope.resolveSnapTargets(named);
1864
+ const missing = resolved.missing;
1865
+ // Each clip is snapped through move/trim, which carry a group's children
1866
+ // and a link's partners. Snapping those as well would move them again,
1867
+ // so one root per group and per link is snapped and the rest follow it.
1868
+ const targetedIds = new Set(resolved.clips.map((clip) => clip.id));
1869
+ const parentOf = new Map(scope.clips.map((clip) => [clip.id, clip.parentId]));
1870
+ const followLinks = scope.ctx.followLinks !== false;
1871
+ const seenLinks = new Set();
1872
+ const targeted = resolved.clips.filter((clip) => {
1873
+ const visited = new Set();
1874
+ let parentId = clip.parentId;
1875
+ while (parentId !== undefined && !visited.has(parentId)) {
1876
+ if (targetedIds.has(parentId)) {
1877
+ return false;
1878
+ }
1879
+ visited.add(parentId);
1880
+ parentId = parentOf.get(parentId);
1503
1881
  }
1504
- if (op.action !== undefined) {
1505
- options.action = op.action;
1882
+ if (followLinks && clip.linkId !== undefined) {
1883
+ if (seenLinks.has(clip.linkId)) {
1884
+ return false;
1885
+ }
1886
+ seenLinks.add(clip.linkId);
1506
1887
  }
1507
- const result = snapClipsToGrid(targeted.map((clip) => ({
1508
- id: clip.id,
1509
- startMs: clip.startMs,
1510
- durationMs: clip.durationMs
1511
- })), grid, options);
1512
- const byId = new Map(targeted.map((clip) => [clip.id, clip]));
1513
- const reported = result.clips.map((entry) => {
1514
- const clip = byId.get(entry.clipId);
1515
- if (entry.snapped && clip) {
1516
- // Through the same ops the caller would use: a group carries its
1517
- // children (D4) and a trim carries the source points, neither of
1518
- // which a raw startMs/durationMs write does.
1519
- try {
1520
- if (entry.after.durationMs === entry.before.durationMs) {
1521
- scope.applyMove(clip, { startMs: entry.after.startMs });
1888
+ return true;
1889
+ });
1890
+ const offsetMs = op.offset_ms ?? 0;
1891
+ // A tempo grid has to reach the last boundary being snapped, so its
1892
+ // length comes from the targets rather than from the caller.
1893
+ const reachMs = targeted.reduce((end, clip) => Math.max(end, clip.startMs + clip.durationMs), 0);
1894
+ const grid = buildBeatGrid({
1895
+ onsetsMs: op.onsets_ms,
1896
+ bpm: op.bpm,
1897
+ offsetMs: op.offset_ms,
1898
+ count: op.bpm === undefined
1899
+ ? undefined
1900
+ : beatCountToCover(op.bpm, offsetMs, reachMs)
1901
+ });
1902
+ const options = {};
1903
+ if (op.tolerance_ms !== undefined) {
1904
+ options.toleranceMs = op.tolerance_ms;
1905
+ }
1906
+ if (op.mode !== undefined) {
1907
+ options.mode = op.mode;
1908
+ }
1909
+ if (op.action !== undefined) {
1910
+ options.action = op.action;
1911
+ }
1912
+ const result = snapClipsToGrid(targeted.map((clip) => ({
1913
+ id: clip.id,
1914
+ startMs: clip.startMs,
1915
+ durationMs: clip.durationMs
1916
+ })), grid, options);
1917
+ const byId = new Map(targeted.map((clip) => [clip.id, clip]));
1918
+ const reported = result.clips.map((entry) => {
1919
+ const clip = byId.get(entry.clipId);
1920
+ if (entry.snapped && clip) {
1921
+ // Through the same ops the caller would use: a group carries its
1922
+ // children (D4) and a trim carries the source points, neither of
1923
+ // which a raw startMs/durationMs write does.
1924
+ try {
1925
+ if (entry.after.durationMs === entry.before.durationMs) {
1926
+ scope.applyMove(clip, { startMs: entry.after.startMs });
1927
+ }
1928
+ else {
1929
+ // A trim moves only the edge that snapped: a snapped start is a
1930
+ // head trim, so the in-point follows it and the out-point stays.
1931
+ let trimmed = clip;
1932
+ const headDelta = entry.before.startMs - entry.after.startMs;
1933
+ if (headDelta !== 0) {
1934
+ trimmed = scope.applyHeadTrim(trimmed, headDelta);
1522
1935
  }
1523
- else {
1524
- const trimmed = scope.applyTrim(clip, {
1525
- durationMs: entry.after.durationMs
1936
+ const tailDelta = entry.after.endMs - entry.before.endMs;
1937
+ if (tailDelta !== 0) {
1938
+ scope.applyTrim(trimmed, {
1939
+ durationMs: trimmed.durationMs + tailDelta
1526
1940
  });
1527
- scope.applyMove(trimmed, { startMs: entry.after.startMs });
1528
1941
  }
1529
1942
  }
1530
- catch (error) {
1531
- return {
1532
- ...entry,
1533
- snapped: false,
1534
- after: entry.before,
1535
- delta: { startMs: 0, endMs: 0 },
1536
- reason: error instanceof Error ? error.message : String(error),
1537
- clipName: clip.name
1538
- };
1539
- }
1540
- }
1541
- return { ...entry, clipName: clip?.name ?? null };
1542
- });
1543
- // A name nothing matched is a skip like any other: the caller has to see
1544
- // it in the same list, not infer it from a shorter one.
1545
- for (const target of missing) {
1546
- reported.push({
1547
- clipId: target,
1548
- clipName: null,
1549
- snapped: false,
1550
- before: { startMs: 0, endMs: 0, durationMs: 0 },
1551
- after: { startMs: 0, endMs: 0, durationMs: 0 },
1552
- delta: { startMs: 0, endMs: 0 },
1553
- reason: `no clip matches "${target}"`
1554
- });
1555
- }
1556
- return {
1557
- ok: true,
1558
- grid: {
1559
- count: grid.length,
1560
- firstMs: grid[0],
1561
- lastMs: grid[grid.length - 1]
1562
- },
1563
- toleranceMs: result.toleranceMs,
1564
- mode: result.mode,
1565
- action: result.action,
1566
- snapped: reported.filter((entry) => entry.snapped).length,
1567
- skipped: reported.filter((entry) => !entry.snapped).length,
1568
- clips: reported
1569
- };
1570
- }
1571
- case "insert_composition": {
1572
- const loader = scope.ctx.loadComposition;
1573
- if (!loader) {
1574
- throw new Error("This surface has no composition library, so insert_composition cannot resolve a template.");
1575
- }
1576
- const composition = await loader.get(op.composition_id);
1577
- if (!composition) {
1578
- const available = await loader.listIds();
1579
- throw new Error(`No composition with id "${op.composition_id}". ` +
1580
- (available.length > 0
1581
- ? `Available: ${available.join(", ")}.`
1582
- : "This install has none — save one with save_composition."));
1583
- }
1584
- const minted = instantiateComposition(composition, {
1585
- startMs: op.startMs,
1586
- params: op.params,
1587
- newId: () => scope.ctx.newId("clip")
1588
- });
1589
- // Template track ids are names, not document ids. Two clips overlapping
1590
- // on one track auto-dissolve into each other, so each template track
1591
- // becomes a track of its own — created front-most first, because the
1592
- // lowest track index draws on top (I9).
1593
- const templateTracks = [];
1594
- for (const child of composition.children) {
1595
- if (!templateTracks.includes(child.trackId)) {
1596
- templateTracks.push(child.trackId);
1597
1943
  }
1598
- }
1599
- const mapped = new Map();
1600
- for (const name of [...templateTracks].reverse()) {
1601
- const existing = scope.tracks.find((t) => t.type === "overlay" && t.name === name);
1602
- mapped.set(name, (existing ?? scope.addTrack("overlay", name)).id);
1603
- }
1604
- // The group draws nothing, but it still occupies its track's timeline,
1605
- // and a group sharing a track with one of its children reads as an
1606
- // overlap. It gets a track named after the composition instead.
1607
- const groupTrack = op.trackId
1608
- ? scope.resolveTrack(op.trackId)
1609
- : (scope.tracks.find((t) => t.type === "overlay" && t.name === composition.name) ?? scope.addTrack("overlay", composition.name));
1610
- const [group, ...children] = minted;
1611
- group.trackId = groupTrack.id;
1612
- for (const [index, child] of children.entries()) {
1613
- child.trackId =
1614
- mapped.get(composition.children[index].trackId) ?? groupTrack.id;
1615
- }
1616
- scope.clips.push(group, ...children);
1617
- state.selectedClipIds = [group.id];
1618
- scope.touch(group.id, ...children.map((c) => c.id));
1619
- return {
1620
- ok: true,
1621
- compositionId: composition.id,
1622
- clip: scope.clipOut(group),
1623
- children: children.map((child) => scope.clipOut(child)),
1624
- params: group.compositionParams ?? {}
1625
- };
1626
- }
1627
- case "list_takes": {
1628
- const clip = scope.resolveClip(op.target);
1629
- const versions = clip.versions ?? [];
1630
- const activeId = activeTakeIdOf(clip);
1631
- return {
1632
- ok: true,
1633
- takes: versions.map((v) => ({
1634
- id: v.id,
1635
- label: v.label,
1636
- source: v.source,
1637
- provider: v.provider,
1638
- model: v.model,
1639
- createdAt: v.createdAt,
1640
- costCredits: v.costCredits,
1641
- durationMs: v.durationMs,
1642
- status: v.status,
1643
- favorite: v.favorite,
1644
- active: v.id === activeId
1645
- })),
1646
- activeTakeId: activeId ?? null
1647
- };
1648
- }
1649
- case "select_take": {
1650
- const clip = scope.resolveClip(op.target);
1651
- if (clip.mediaType === "model3d") {
1652
- throw new Error(`Clip "${clip.name}" is a 3D clip — its version history includes ` +
1653
- "bake renders that must not replace the glTF source. Take " +
1654
- "selection is not available for model3d clips yet.");
1655
- }
1656
- const version = (clip.versions ?? []).find((v) => v.id === op.takeId);
1657
- if (!version) {
1658
- throw new Error(`No take "${op.takeId}" on "${clip.name}". ${scope.validUnits((clip.versions ?? []).map((v) => ({
1659
- id: v.id,
1660
- name: v.label ?? v.id
1661
- })), "take")}`);
1662
- }
1663
- if (version.status !== "success") {
1664
- throw new Error(`Take "${op.takeId}" on "${clip.name}" did not finish successfully ` +
1665
- `(status: ${version.status}) — only a successful take can be selected.`);
1666
- }
1667
- const next = selectTake(clip, op.takeId);
1668
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1669
- scope.touch(clip.id);
1670
- return { ok: true, clip: scope.clipOut(next) };
1671
- }
1672
- case "rename_take": {
1673
- const clip = scope.resolveClip(op.target);
1674
- if (!(clip.versions ?? []).some((v) => v.id === op.takeId)) {
1675
- throw new Error(`No take "${op.takeId}" on "${clip.name}". ${scope.validUnits((clip.versions ?? []).map((v) => ({
1676
- id: v.id,
1677
- name: v.label ?? v.id
1678
- })), "take")}`);
1679
- }
1680
- const next = renameTakeOnClip(clip, op.takeId, op.label);
1681
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1682
- scope.touch(clip.id);
1683
- return { ok: true, clip: scope.clipOut(next) };
1684
- }
1685
- case "delete_take": {
1686
- const clip = scope.resolveClip(op.target);
1687
- const { clip: next, error } = deleteTakeOnClip(clip, op.takeId);
1688
- if (error) {
1689
- throw new Error(error);
1690
- }
1691
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1692
- scope.touch(clip.id);
1693
- return { ok: true, clip: scope.clipOut(next) };
1694
- }
1695
- // Subject/object tracks (P0 AI Video, Phase 2). The async provider call
1696
- // that fills a track's samples is the `track_object` capability, not an
1697
- // op — these four are the structural/synchronous surface over it.
1698
- case "list_tracks": {
1699
- const clipId = op.target ? scope.resolveClip(op.target).id : undefined;
1700
- const tracks = scope.mediaTracks.filter((t) => clipId === undefined || t.clipId === clipId);
1701
- return {
1702
- ok: true,
1703
- tracks: tracks.map((t) => ({
1704
- id: t.id,
1705
- clipId: t.clipId,
1706
- name: t.name,
1707
- kind: t.kind,
1708
- status: t.status,
1709
- sourceStartMs: t.sourceStartMs,
1710
- sourceEndMs: t.sourceEndMs,
1711
- sampleCount: t.samples.length,
1712
- confidence: t.confidence
1713
- }))
1714
- };
1715
- }
1716
- case "delete_track_object": {
1717
- const track = scope.mediaTracks.find((t) => t.id === op.trackId);
1718
- if (!track) {
1719
- throw new Error(`No track "${op.trackId}". ${scope.validUnits(scope.mediaTracks.map((t) => ({ id: t.id, name: t.name })), "track")}`);
1720
- }
1721
- scope.mediaTracks = scope.mediaTracks.filter((t) => t.id !== op.trackId);
1722
- const unboundClipIds = [];
1723
- scope.clips = scope.clips.map((c) => {
1724
- if (c.trackBinding?.trackId !== op.trackId) {
1725
- return c;
1944
+ catch (error) {
1945
+ return {
1946
+ ...entry,
1947
+ snapped: false,
1948
+ after: entry.before,
1949
+ delta: { startMs: 0, endMs: 0 },
1950
+ reason: error instanceof Error ? error.message : String(error),
1951
+ clipName: clip.name
1952
+ };
1726
1953
  }
1727
- unboundClipIds.push(c.id);
1728
- const { trackBinding: _dropped, ...rest } = c;
1729
- return rest;
1730
- });
1731
- scope.touch(...unboundClipIds);
1732
- return { ok: true, deleted: { id: track.id, name: track.name } };
1733
- }
1734
- case "bind_to_track": {
1735
- const clip = scope.resolveClip(op.target);
1736
- const track = scope.mediaTracks.find((t) => t.id === op.trackId);
1737
- if (!track) {
1738
- throw new Error(`No track "${op.trackId}". ${scope.validUnits(scope.mediaTracks.map((t) => ({ id: t.id, name: t.name })), "track")}`);
1739
- }
1740
- if (op.mode !== "position" && op.mode !== "position_scale") {
1741
- throw new Error(`bind_to_track mode "${op.mode}" is not implemented yet — only ` +
1742
- `"position" and "position_scale" affect rendering in this build. ` +
1743
- "The field accepts the other modes so a document can name the " +
1744
- "intent without a schema migration later, but binding to one " +
1745
- "today would be a no-op, so the call is refused instead.");
1746
- }
1747
- const binding = { trackId: op.trackId, mode: op.mode };
1748
- if (op.offset !== undefined) {
1749
- binding.offset = op.offset;
1750
- }
1751
- if (op.scale !== undefined) {
1752
- binding.scale = op.scale;
1753
- }
1754
- if (op.rotationOffset !== undefined) {
1755
- binding.rotationOffset = op.rotationOffset;
1756
1954
  }
1757
- if (op.smoothing !== undefined) {
1758
- binding.smoothing = op.smoothing;
1759
- }
1760
- const next = { ...clip, trackBinding: binding };
1761
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1762
- scope.touch(clip.id);
1763
- return { ok: true, clip: scope.clipOut(next) };
1764
- }
1765
- case "unbind_track": {
1766
- const clip = scope.resolveClip(op.target);
1767
- if (!clip.trackBinding) {
1768
- return { ok: true, clip: scope.clipOut(clip) };
1769
- }
1770
- const { trackBinding: _dropped, ...next } = clip;
1771
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1772
- scope.touch(clip.id);
1773
- return { ok: true, clip: scope.clipOut(next) };
1774
- }
1775
- case "add_midi_clip": {
1776
- const track = op.track
1777
- ? scope.resolveMidiTrack(op.track)
1778
- : scope.findOrCreateTrack("midi");
1779
- const name = op.name ?? "Phrase";
1780
- const clip = makeClip({
1781
- id: scope.ctx.newId("clip"),
1782
- trackId: track.id,
1783
- name,
1784
- startMs: op.start_ms ?? scope.trackEndMs(track.id),
1785
- durationMs: op.duration_ms,
1786
- mediaType: "midi",
1787
- sourceType: "imported",
1788
- status: "generated",
1789
- notes: scope.buildNotes(op.notes, name)
1955
+ return { ...entry, clipName: clip?.name ?? null };
1956
+ });
1957
+ // A name nothing matched is a skip like any other: the caller has to see
1958
+ // it in the same list, not infer it from a shorter one.
1959
+ for (const target of missing) {
1960
+ reported.push({
1961
+ clipId: target,
1962
+ clipName: null,
1963
+ snapped: false,
1964
+ before: { startMs: 0, endMs: 0, durationMs: 0 },
1965
+ after: { startMs: 0, endMs: 0, durationMs: 0 },
1966
+ delta: { startMs: 0, endMs: 0 },
1967
+ reason: `no clip matches "${target}"`
1790
1968
  });
1791
- scope.clips.push(clip);
1792
- scope.state.selectedClipIds = [clip.id];
1793
- scope.touch(clip.id);
1794
- return { ok: true, clip: scope.clipOut(clip) };
1795
1969
  }
1796
- case "set_notes": {
1797
- const clip = scope.resolveMidiClip(op.clip);
1798
- clip.notes = scope.buildNotes(op.notes, clip.name);
1799
- scope.touch(clip.id);
1970
+ return {
1971
+ ok: true,
1972
+ grid: {
1973
+ count: grid.length,
1974
+ firstMs: grid[0],
1975
+ lastMs: grid[grid.length - 1]
1976
+ },
1977
+ toleranceMs: result.toleranceMs,
1978
+ mode: result.mode,
1979
+ action: result.action,
1980
+ snapped: reported.filter((entry) => entry.snapped).length,
1981
+ skipped: reported.filter((entry) => !entry.snapped).length,
1982
+ clips: reported
1983
+ };
1984
+ },
1985
+ insert_composition: async (scope, op) => {
1986
+ const state = scope.state;
1987
+ const loader = scope.ctx.loadComposition;
1988
+ if (!loader) {
1989
+ throw new Error("This surface has no composition library, so insert_composition cannot resolve a template.");
1990
+ }
1991
+ const composition = await loader.get(op.composition_id);
1992
+ if (!composition) {
1993
+ const available = await loader.listIds();
1994
+ throw new Error(`No composition with id "${op.composition_id}". ` +
1995
+ (available.length > 0
1996
+ ? `Available: ${available.join(", ")}.`
1997
+ : "This install has none — save one with save_composition."));
1998
+ }
1999
+ const minted = instantiateComposition(composition, {
2000
+ startMs: op.startMs,
2001
+ params: op.params,
2002
+ newId: () => scope.ctx.newId("clip")
2003
+ });
2004
+ // Template track ids are names, not document ids. Two clips overlapping
2005
+ // on one track auto-dissolve into each other, so each template track
2006
+ // becomes a track of its own — created front-most first, because the
2007
+ // lowest track index draws on top (I9).
2008
+ const templateTracks = [];
2009
+ for (const child of composition.children) {
2010
+ if (!templateTracks.includes(child.trackId)) {
2011
+ templateTracks.push(child.trackId);
2012
+ }
2013
+ }
2014
+ const mapped = new Map();
2015
+ for (const name of [...templateTracks].reverse()) {
2016
+ const existing = scope.tracks.find((t) => t.type === "overlay" && t.name === name && !t.locked);
2017
+ mapped.set(name, (existing ?? scope.addTrack("overlay", name)).id);
2018
+ }
2019
+ // The group draws nothing, but it still occupies its track's timeline,
2020
+ // and a group sharing a track with one of its children reads as an
2021
+ // overlap. It gets a track named after the composition instead.
2022
+ const groupTrack = op.trackId
2023
+ ? scope.resolveTrack(op.trackId)
2024
+ : (scope.tracks.find((t) => t.type === "overlay" && t.name === composition.name && !t.locked) ?? scope.addTrack("overlay", composition.name));
2025
+ scope.assertWritable([], groupTrack.id);
2026
+ const [group, ...children] = minted;
2027
+ group.trackId = groupTrack.id;
2028
+ for (const [index, child] of children.entries()) {
2029
+ child.trackId =
2030
+ mapped.get(composition.children[index].trackId) ?? groupTrack.id;
2031
+ }
2032
+ scope.clips.push(group, ...children);
2033
+ state.selectedClipIds = [group.id];
2034
+ scope.touch(group.id, ...children.map((c) => c.id));
2035
+ return {
2036
+ ok: true,
2037
+ compositionId: composition.id,
2038
+ clip: scope.clipOut(group),
2039
+ children: children.map((child) => scope.clipOut(child)),
2040
+ params: group.compositionParams ?? {}
2041
+ };
2042
+ },
2043
+ list_takes: (scope, op) => {
2044
+ const clip = scope.resolveClip(op.target);
2045
+ const versions = clip.versions ?? [];
2046
+ const activeId = activeTakeIdOf(clip);
2047
+ return {
2048
+ ok: true,
2049
+ takes: versions.map((v) => ({
2050
+ id: v.id,
2051
+ label: v.label,
2052
+ source: v.source,
2053
+ provider: v.provider,
2054
+ model: v.model,
2055
+ createdAt: v.createdAt,
2056
+ costCredits: v.costCredits,
2057
+ durationMs: v.durationMs,
2058
+ status: v.status,
2059
+ favorite: v.favorite,
2060
+ active: v.id === activeId
2061
+ })),
2062
+ activeTakeId: activeId ?? null
2063
+ };
2064
+ },
2065
+ select_take: (scope, op) => {
2066
+ const clip = scope.resolveClip(op.target);
2067
+ scope.assertWritable([clip]);
2068
+ if (clip.mediaType === "model3d") {
2069
+ throw new Error(`Clip "${clip.name}" is a 3D clip — its version history includes ` +
2070
+ "bake renders that must not replace the glTF source. Take " +
2071
+ "selection is not available for model3d clips yet.");
2072
+ }
2073
+ const version = findByIdOrShortId(clip.versions ?? [], op.takeId, "take");
2074
+ if (!version) {
2075
+ throw new Error(`No take "${op.takeId}" on "${clip.name}". ${scope.validUnits((clip.versions ?? []).map((v) => ({
2076
+ id: v.id,
2077
+ name: v.label ?? v.id
2078
+ })), "take")}`);
2079
+ }
2080
+ if (version.status !== "success") {
2081
+ throw new Error(`Take "${op.takeId}" on "${clip.name}" did not finish successfully ` +
2082
+ `(status: ${version.status}) — only a successful take can be selected.`);
2083
+ }
2084
+ const next = selectTake(clip, version.id);
2085
+ scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
2086
+ scope.touch(clip.id);
2087
+ return { ok: true, clip: scope.clipOut(next) };
2088
+ },
2089
+ rename_take: (scope, op) => {
2090
+ const clip = scope.resolveClip(op.target);
2091
+ scope.assertWritable([clip]);
2092
+ const take = findByIdOrShortId(clip.versions ?? [], op.takeId, "take");
2093
+ if (!take) {
2094
+ throw new Error(`No take "${op.takeId}" on "${clip.name}". ${scope.validUnits((clip.versions ?? []).map((v) => ({
2095
+ id: v.id,
2096
+ name: v.label ?? v.id
2097
+ })), "take")}`);
2098
+ }
2099
+ const next = renameTakeOnClip(clip, take.id, op.label);
2100
+ scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
2101
+ scope.touch(clip.id);
2102
+ return { ok: true, clip: scope.clipOut(next) };
2103
+ },
2104
+ delete_take: (scope, op) => {
2105
+ const clip = scope.resolveClip(op.target);
2106
+ scope.assertWritable([clip]);
2107
+ const take = findByIdOrShortId(clip.versions ?? [], op.takeId, "take");
2108
+ const { clip: next, error } = deleteTakeOnClip(clip, take?.id ?? op.takeId);
2109
+ if (error) {
2110
+ throw new Error(error);
2111
+ }
2112
+ scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
2113
+ scope.touch(clip.id);
2114
+ return { ok: true, clip: scope.clipOut(next) };
2115
+ },
2116
+ // Subject/object tracks (P0 AI Video, Phase 2). The async provider call
2117
+ // that fills a track's samples is the `track_object` capability, not an
2118
+ // op — these four are the structural/synchronous surface over it.
2119
+ list_tracks: (scope, op) => {
2120
+ const clipId = op.target ? scope.resolveClip(op.target).id : undefined;
2121
+ const tracks = scope.mediaTracks.filter((t) => clipId === undefined || t.clipId === clipId);
2122
+ return {
2123
+ ok: true,
2124
+ tracks: tracks.map((t) => ({
2125
+ id: t.id,
2126
+ clipId: t.clipId,
2127
+ name: t.name,
2128
+ kind: t.kind,
2129
+ status: t.status,
2130
+ sourceStartMs: t.sourceStartMs,
2131
+ sourceEndMs: t.sourceEndMs,
2132
+ sampleCount: t.samples.length,
2133
+ confidence: t.confidence
2134
+ }))
2135
+ };
2136
+ },
2137
+ delete_track_object: (scope, op) => {
2138
+ const track = findByIdOrShortId(scope.mediaTracks, op.trackId, "track");
2139
+ if (!track) {
2140
+ throw new Error(`No track "${op.trackId}". ${scope.validUnits(scope.mediaTracks.map((t) => ({ id: t.id, name: t.name })), "track")}`);
2141
+ }
2142
+ scope.mediaTracks = scope.mediaTracks.filter((t) => t.id !== track.id);
2143
+ const unboundClipIds = [];
2144
+ scope.clips = scope.clips.map((c) => {
2145
+ if (c.trackBinding?.trackId !== track.id) {
2146
+ return c;
2147
+ }
2148
+ unboundClipIds.push(c.id);
2149
+ const { trackBinding: _dropped, ...rest } = c;
2150
+ return rest;
2151
+ });
2152
+ scope.touch(...unboundClipIds);
2153
+ return { ok: true, deleted: { id: track.id, name: track.name } };
2154
+ },
2155
+ bind_to_track: (scope, op) => {
2156
+ const clip = scope.resolveClip(op.target);
2157
+ const track = findByIdOrShortId(scope.mediaTracks, op.trackId, "track");
2158
+ if (!track) {
2159
+ throw new Error(`No track "${op.trackId}". ${scope.validUnits(scope.mediaTracks.map((t) => ({ id: t.id, name: t.name })), "track")}`);
2160
+ }
2161
+ if (op.mode !== "position" && op.mode !== "position_scale") {
2162
+ throw new Error(`bind_to_track mode "${op.mode}" is not implemented yet — only ` +
2163
+ `"position" and "position_scale" affect rendering in this build. ` +
2164
+ "The field accepts the other modes so a document can name the " +
2165
+ "intent without a schema migration later, but binding to one " +
2166
+ "today would be a no-op, so the call is refused instead.");
2167
+ }
2168
+ const binding = { trackId: track.id, mode: op.mode };
2169
+ if (op.offset !== undefined) {
2170
+ binding.offset = op.offset;
2171
+ }
2172
+ if (op.scale !== undefined) {
2173
+ binding.scale = op.scale;
2174
+ }
2175
+ if (op.rotationOffset !== undefined) {
2176
+ binding.rotationOffset = op.rotationOffset;
2177
+ }
2178
+ if (op.smoothing !== undefined) {
2179
+ binding.smoothing = op.smoothing;
2180
+ }
2181
+ const next = { ...clip, trackBinding: binding };
2182
+ scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
2183
+ scope.touch(clip.id);
2184
+ return { ok: true, clip: scope.clipOut(next) };
2185
+ },
2186
+ unbind_track: (scope, op) => {
2187
+ const clip = scope.resolveClip(op.target);
2188
+ if (!clip.trackBinding) {
1800
2189
  return { ok: true, clip: scope.clipOut(clip) };
1801
2190
  }
1802
- case "set_tempo": {
1803
- const previous = resolveTempo(scope.state);
1804
- const tempo = {
1805
- bpm: op.bpm,
1806
- offsetMs: op.offset_ms ?? previous.offsetMs,
1807
- timeSignature: {
1808
- beatsPerBar: op.beats_per_bar ?? previous.timeSignature.beatsPerBar,
1809
- beatUnit: op.beat_unit ?? previous.timeSignature.beatUnit
1810
- }
1811
- };
1812
- scope.clips = rescaleClipsForTempo(scope.clips, scope.tracks, previous, tempo);
1813
- scope.state.tempo = tempo;
1814
- const rescaledClipIds = scope.clips
1815
- .filter((c) => c.mediaType === "midi")
1816
- .map((c) => c.id);
1817
- scope.touch(...rescaledClipIds);
1818
- return { ok: true, tempo, previousTempo: previous, rescaledClipIds };
1819
- }
1820
- case "set_track_instrument": {
1821
- const track = scope.resolveMidiTrack(op.track);
1822
- let instrument;
1823
- if ("preset" in op.instrument) {
1824
- const preset = findInstrumentPreset(op.instrument.preset);
1825
- if (!preset) {
1826
- throw new Error(`No instrument preset named "${op.instrument.preset}". Valid presets: ${MIDI_INSTRUMENT_PRESETS.map((p) => `${p.id} ("${p.name}")`).join(", ")}.`);
1827
- }
1828
- instrument = structuredClone(preset.instrument);
2191
+ const { trackBinding: _dropped, ...next } = clip;
2192
+ scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
2193
+ scope.touch(clip.id);
2194
+ return { ok: true, clip: scope.clipOut(next) };
2195
+ },
2196
+ add_midi_clip: (scope, op) => {
2197
+ const track = op.track
2198
+ ? scope.resolveMidiTrack(op.track)
2199
+ : scope.findOrCreateTrack("midi");
2200
+ scope.assertWritable([], track.id);
2201
+ const name = op.name ?? "Phrase";
2202
+ const clip = makeClip({
2203
+ id: scope.ctx.newId("clip"),
2204
+ trackId: track.id,
2205
+ name,
2206
+ startMs: op.start_ms ?? scope.trackEndMs(track.id),
2207
+ durationMs: op.duration_ms,
2208
+ mediaType: "midi",
2209
+ sourceType: "imported",
2210
+ status: "generated",
2211
+ notes: scope.buildNotes(op.notes, name)
2212
+ });
2213
+ scope.clips.push(clip);
2214
+ scope.state.selectedClipIds = [clip.id];
2215
+ scope.touch(clip.id);
2216
+ return { ok: true, clip: scope.clipOut(clip) };
2217
+ },
2218
+ set_notes: (scope, op) => {
2219
+ const clip = scope.resolveMidiClip(op.clip);
2220
+ scope.assertWritable([clip]);
2221
+ clip.notes = scope.buildNotes(op.notes, clip.name);
2222
+ scope.touch(clip.id);
2223
+ return { ok: true, clip: scope.clipOut(clip) };
2224
+ },
2225
+ set_tempo: (scope, op) => {
2226
+ const previous = resolveTempo(scope.state);
2227
+ const tempo = {
2228
+ bpm: op.bpm,
2229
+ offsetMs: op.offset_ms ?? previous.offsetMs,
2230
+ timeSignature: {
2231
+ beatsPerBar: op.beats_per_bar ?? previous.timeSignature.beatsPerBar,
2232
+ beatUnit: op.beat_unit ?? previous.timeSignature.beatUnit
1829
2233
  }
1830
- else {
1831
- instrument = structuredClone(op.instrument);
2234
+ };
2235
+ scope.clips = rescaleClipsForTempo(scope.clips, scope.tracks, previous, tempo);
2236
+ scope.state.tempo = tempo;
2237
+ const rescaledClipIds = scope.clips
2238
+ .filter((c) => c.mediaType === "midi")
2239
+ .map((c) => c.id);
2240
+ scope.touch(...rescaledClipIds);
2241
+ return { ok: true, tempo, previousTempo: previous, rescaledClipIds };
2242
+ },
2243
+ set_track_instrument: async (scope, op) => {
2244
+ const track = scope.resolveMidiTrack(op.track);
2245
+ scope.assertWritable([], track.id);
2246
+ let instrument;
2247
+ if ("preset" in op.instrument) {
2248
+ const preset = findInstrumentPreset(op.instrument.preset);
2249
+ if (!preset) {
2250
+ throw new Error(`No instrument preset named "${op.instrument.preset}". Valid presets: ${MIDI_INSTRUMENT_PRESETS.map((p) => `${p.id} ("${p.name}")`).join(", ")}.`);
2251
+ }
2252
+ instrument = structuredClone(preset.instrument);
2253
+ }
2254
+ else {
2255
+ instrument = structuredClone(op.instrument);
2256
+ }
2257
+ if (instrument.type === "sampler" && instrument.zones.length) {
2258
+ const resolveAsset = scope.ctx.resolveAsset;
2259
+ if (!resolveAsset) {
2260
+ throw new Error("Sample assets cannot be resolved on this host");
1832
2261
  }
1833
- if (instrument.type === "sampler" && instrument.zones.length) {
1834
- const resolveAsset = scope.ctx.resolveAsset;
1835
- if (!resolveAsset) {
1836
- throw new Error("Sample assets cannot be resolved on this host");
2262
+ instrument.zones = await Promise.all(instrument.zones.map(async (zone) => {
2263
+ const asset = await resolveAsset(zone.assetId);
2264
+ if (!asset || !asset.contentType.startsWith("audio/")) {
2265
+ throw new Error(`Audio sample unavailable: ${zone.name}`);
1837
2266
  }
1838
- instrument.zones = await Promise.all(instrument.zones.map(async (zone) => {
1839
- const asset = await resolveAsset(zone.assetId);
1840
- if (!asset || !asset.contentType.startsWith("audio/")) {
1841
- throw new Error(`Audio sample unavailable: ${zone.name}`);
1842
- }
1843
- return { ...zone, assetId: asset.id };
1844
- }));
1845
- }
1846
- track.instrument = instrument;
1847
- return { ok: true, track: scope.trackOut(track) };
1848
- }
1849
- case "transpose_clip":
1850
- case "quantize_notes":
1851
- case "scale_velocity": {
1852
- const clip = scope.resolveMidiClip(op.clip);
1853
- const before = clip.notes ?? [];
1854
- const notes = op.op === "transpose_clip"
1855
- ? transposeNotes(before, op.semitones)
1856
- : op.op === "scale_velocity"
1857
- ? scaleVelocity(before, op.factor)
1858
- : quantizeNotes(before, {
1859
- division: op.division,
1860
- strength: op.strength,
1861
- target: op.target
1862
- });
1863
- clip.notes = notes;
1864
- scope.touch(clip.id);
1865
- const result = {
1866
- ok: true,
1867
- clip: scope.clipOut(clip),
1868
- noteCount: notes.length
1869
- };
1870
- if (op.op === "quantize_notes") {
1871
- result.movedNoteCount = notes.filter((note, i) => note.startTick !== before[i]?.startTick ||
1872
- note.durationTick !== before[i]?.durationTick).length;
1873
- }
1874
- return result;
2267
+ return { ...zone, assetId: asset.id };
2268
+ }));
1875
2269
  }
1876
- case "set_reframe_subject": {
1877
- const clip = scope.resolveClip(op.clip_id);
1878
- const track = scope.mediaTracks.find((t) => t.id === op.track_id && t.clipId === clip.id);
2270
+ track.instrument = instrument;
2271
+ return { ok: true, track: scope.trackOut(track) };
2272
+ },
2273
+ transpose_clip: runMidiNoteEdit,
2274
+ quantize_notes: runMidiNoteEdit,
2275
+ scale_velocity: runMidiNoteEdit,
2276
+ set_reframe_subject: (scope, op) => {
2277
+ const clip = scope.resolveClip(op.clip_id);
2278
+ const track = findByIdOrShortId(scope.mediaTracks.filter((t) => t.clipId === clip.id), op.track_id, "track");
2279
+ if (!track) {
2280
+ throw new Error(`No track "${op.track_id}" belongs to clip "${clip.name}". ${scope.validUnits(scope.mediaTracks.filter((t) => t.clipId === clip.id), "track")}`);
2281
+ }
2282
+ if (track.status !== "ready") {
2283
+ throw new Error(`Track "${track.name}" is ${track.status}; Smart Reframe can only follow a ready track.`);
2284
+ }
2285
+ if (!mediaTrackCanDriveReframe(track) || isMediaTrackStale(track, clip)) {
2286
+ throw new Error(`Track "${track.name}" has no current analysis for clip "${clip.name}".`);
2287
+ }
2288
+ const previous = clip.reframe ?? {
2289
+ mode: "track"
2290
+ };
2291
+ clip.reframe = {
2292
+ ...previous,
2293
+ mode: "track",
2294
+ trackId: track.id,
2295
+ sourceAssetId: clip.currentAssetId,
2296
+ safeMargin: op.safe_margin ?? previous.safeMargin,
2297
+ smoothing: op.smoothing ?? previous.smoothing
2298
+ };
2299
+ scope.touch(clip.id);
2300
+ return { ok: true, clip: scope.clipOut(clip) };
2301
+ },
2302
+ add_reframe_keyframe: (scope, op) => {
2303
+ const clip = scope.resolveClip(op.clip_id);
2304
+ clip.reframe ??= { mode: "auto" };
2305
+ const keyframe = {
2306
+ sourceMs: op.source_ms,
2307
+ x: op.x,
2308
+ y: op.y,
2309
+ zoom: op.zoom
2310
+ };
2311
+ clip.reframe = addReframeKeyframe(clip.reframe, keyframe);
2312
+ scope.touch(clip.id);
2313
+ return { ok: true, clip: scope.clipOut(clip), keyframe };
2314
+ },
2315
+ clear_reframe: (scope, op) => {
2316
+ const clip = scope.resolveClip(op.clip_id);
2317
+ const next = clearReframe(clip);
2318
+ scope.replaceClip(clip, next);
2319
+ scope.touch(clip.id);
2320
+ return { ok: true, clip: scope.clipOut(next) };
2321
+ },
2322
+ retarget_format: async (scope, op) => {
2323
+ // Keys and values may be short ids; the adaptation reads full ones.
2324
+ const trackIdByClipId = {};
2325
+ for (const [clipId, trackId] of Object.entries(op.track_ids ?? {})) {
2326
+ const clip = findByIdOrShortId(scope.clips, clipId, "clip");
2327
+ if (!clip) {
2328
+ throw new Error(`track_ids names unknown clip "${clipId}". ${scope.validUnits(scope.clips, "clip")}`);
2329
+ }
2330
+ const track = findByIdOrShortId(scope.mediaTracks.filter((t) => t.clipId === clip.id), trackId, "track");
1879
2331
  if (!track) {
1880
- throw new Error(`No track "${op.track_id}" belongs to clip "${clip.name}". ${scope.validUnits(scope.mediaTracks.filter((t) => t.clipId === clip.id), "track")}`);
2332
+ throw new Error(`Track "${trackId}" does not belong to clip "${clip.name}". ${scope.validUnits(scope.mediaTracks.filter((t) => t.clipId === clip.id), "track")}`);
1881
2333
  }
1882
2334
  if (track.status !== "ready") {
1883
- throw new Error(`Track "${track.name}" is ${track.status}; Smart Reframe can only follow a ready track.`);
1884
- }
1885
- if (!mediaTrackCanDriveReframe(track) || isMediaTrackStale(track, clip)) {
1886
- throw new Error(`Track "${track.name}" has no current analysis for clip "${clip.name}".`);
1887
- }
1888
- const previous = clip.reframe ?? {
1889
- mode: "track"
1890
- };
1891
- clip.reframe = {
1892
- ...previous,
1893
- mode: "track",
1894
- trackId: track.id,
1895
- sourceAssetId: clip.currentAssetId,
1896
- safeMargin: op.safe_margin ?? previous.safeMargin,
1897
- smoothing: op.smoothing ?? previous.smoothing
1898
- };
1899
- scope.touch(clip.id);
1900
- return { ok: true, clip: scope.clipOut(clip) };
1901
- }
1902
- case "add_reframe_keyframe": {
1903
- const clip = scope.resolveClip(op.clip_id);
1904
- clip.reframe ??= { mode: "auto" };
1905
- const keyframe = {
1906
- sourceMs: op.source_ms,
1907
- x: op.x,
1908
- y: op.y,
1909
- zoom: op.zoom
1910
- };
1911
- clip.reframe = addReframeKeyframe(clip.reframe, keyframe);
1912
- scope.touch(clip.id);
1913
- return { ok: true, clip: scope.clipOut(clip), keyframe };
1914
- }
1915
- case "clear_reframe": {
1916
- const clip = scope.resolveClip(op.clip_id);
1917
- const next = clearReframe(clip);
1918
- scope.replaceClip(clip, next);
1919
- scope.touch(clip.id);
1920
- return { ok: true, clip: scope.clipOut(next) };
1921
- }
1922
- case "retarget_format": {
1923
- for (const [clipId, trackId] of Object.entries(op.track_ids ?? {})) {
1924
- const clip = scope.clips.find((c) => c.id === clipId);
1925
- if (!clip) {
1926
- throw new Error(`track_ids names unknown clip "${clipId}". ${scope.validUnits(scope.clips, "clip")}`);
1927
- }
1928
- const track = scope.mediaTracks.find((t) => t.id === trackId && t.clipId === clip.id);
1929
- if (!track) {
1930
- throw new Error(`Track "${trackId}" does not belong to clip "${clip.name}". ${scope.validUnits(scope.mediaTracks.filter((t) => t.clipId === clip.id), "track")}`);
1931
- }
1932
- if (track.status !== "ready") {
1933
- throw new Error(`Track "${track.name}" is ${track.status}; a format adaptation can only follow a ready track.`);
1934
- }
1935
- }
1936
- const now = scope.ctx.now?.() ?? new Date().toISOString();
1937
- const { selectedClipIds: _selected, playheadMs: _playhead, setup: _setup, ...document } = scope.state;
1938
- const source = {
1939
- ...document,
1940
- id: scope.ctx.sequence?.id ?? "seq_eval",
1941
- projectId: scope.ctx.sequence?.projectId ?? "",
1942
- name: scope.ctx.sequence?.name ?? "Sequence",
1943
- durationMs: scope.clips.reduce((end, c) => Math.max(end, c.startMs + c.durationMs), 0),
1944
- createdAt: now,
1945
- updatedAt: now,
1946
- camera2d: scope.state.camera2d ?? null
1947
- };
1948
- if (scope.state.setup) {
1949
- source.setup = scope.state.setup;
1950
- }
1951
- const adapted = adaptSequenceFormat(source, op.aspect_ratio, {
1952
- strategy: op.strategy,
1953
- safeMargin: op.safe_margin,
1954
- trackIdByClipId: op.track_ids
1955
- });
1956
- const stored = scope.ctx.retargetFormat
1957
- ? await scope.ctx.retargetFormat(adapted.sequence)
1958
- : { sequenceId: adapted.sequence.id, name: adapted.sequence.name };
1959
- return {
1960
- ok: true,
1961
- sourceSequenceId: source.id,
1962
- sequenceId: stored.sequenceId,
1963
- name: stored.name ?? adapted.sequence.name,
1964
- width: adapted.sequence.width,
1965
- height: adapted.sequence.height,
1966
- strategy: op.strategy,
1967
- croppedClipIds: adapted.croppedClipIds
1968
- };
1969
- }
1970
- case "stagger_animations": {
1971
- const clips = op.clip_ids.map((id) => scope.resolveClip(id));
1972
- const ids = clips.map((c) => c.id);
1973
- if (new Set(ids).size !== ids.length) {
1974
- throw new Error("clip_ids must contain distinct clip IDs.");
1975
- }
1976
- for (const clip of clips) {
1977
- if (!clip.animations?.length) {
1978
- throw new Error(`Clip "${clip.name}" has no animations to stagger.`);
1979
- }
1980
- }
1981
- scope.clips = staggerClipAnimations(scope.clips, ids, op.offset_ms);
1982
- scope.touch(...ids);
1983
- return {
1984
- ok: true,
1985
- clips: ids.map((id) => scope.clipOut(scope.resolveClip(id)))
1986
- };
1987
- }
1988
- case "set_setup": {
1989
- const previous = scope.state.setup;
1990
- scope.state.setup = {
1991
- ...previous,
1992
- stage: op.stage ?? previous?.stage ?? "idea",
1993
- brief: op.brief ?? previous?.brief ?? "",
1994
- format: op.format ?? previous?.format,
1995
- voiceover: op.voiceover ?? previous?.voiceover,
1996
- beats: previous?.beats
1997
- };
1998
- return { ok: true, setup: structuredClone(scope.state.setup) };
1999
- }
2000
- case "plan_beats": {
2001
- if (!op.beats?.length) {
2002
- throw new Error("This surface has no Director: pass `beats` with the plan you want. Each beat needs a prompt and a durationMs.");
2003
- }
2004
- const beats = op.beats.map((beat) => ({
2005
- id: scope.ctx.newId("beat"),
2006
- prompt: beat.prompt,
2007
- duration_ms: Math.max(1, Math.round(beat.durationMs)),
2008
- transition: beat.transition,
2009
- voiceover: beat.voiceover,
2010
- music: beat.music
2011
- }));
2012
- const previous = scope.state.setup;
2013
- scope.state.setup = {
2014
- ...previous,
2015
- stage: "review",
2016
- brief: previous?.brief ?? "",
2017
- format: previous?.format,
2018
- voiceover: previous?.voiceover,
2019
- beats
2020
- };
2021
- return {
2022
- ok: true,
2023
- beats: structuredClone(beats),
2024
- clipsCreated: 0,
2025
- jobsStarted: 0
2026
- };
2335
+ throw new Error(`Track "${track.name}" is ${track.status}; a format adaptation can only follow a ready track.`);
2336
+ }
2337
+ trackIdByClipId[clip.id] = track.id;
2338
+ }
2339
+ const now = scope.ctx.now?.() ?? new Date().toISOString();
2340
+ const { selectedClipIds: _selected, playheadMs: _playhead, setup: _setup, ...document } = scope.state;
2341
+ const source = {
2342
+ ...document,
2343
+ id: scope.ctx.sequence?.id ?? "seq_eval",
2344
+ projectId: scope.ctx.sequence?.projectId ?? "",
2345
+ name: scope.ctx.sequence?.name ?? "Sequence",
2346
+ durationMs: scope.clips.reduce((end, c) => Math.max(end, c.startMs + c.durationMs), 0),
2347
+ createdAt: now,
2348
+ updatedAt: now,
2349
+ camera2d: scope.state.camera2d ?? null
2350
+ };
2351
+ if (scope.state.setup) {
2352
+ source.setup = scope.state.setup;
2027
2353
  }
2028
- case "update_beat":
2029
- case "remove_beat": {
2030
- const beats = scope.state.setup?.beats ?? [];
2031
- const position = Number.parseInt(op.beat, 10);
2032
- const found = beats.find((b) => b.id === op.beat) ??
2033
- (Number.isFinite(position) ? beats[position - 1] : undefined);
2034
- if (!found) {
2035
- throw new Error(`No beat matches "${op.beat}". Use a beat id or its 1-based position. ` +
2036
- (beats.length
2037
- ? `This plan has ${beats.length} beats.`
2038
- : "This sequence has no beat plan yet; run ui_timeline_plan_beats first."));
2039
- }
2040
- const next = { ...found };
2041
- if (op.op === "update_beat") {
2042
- if (op.prompt !== undefined) {
2043
- next.prompt = op.prompt;
2044
- }
2045
- if (op.durationMs !== undefined) {
2046
- next.duration_ms = Math.max(1, Math.round(op.durationMs));
2047
- }
2048
- if (op.transition !== undefined) {
2049
- next.transition = op.transition ?? undefined;
2050
- }
2051
- if (op.voiceover !== undefined) {
2052
- next.voiceover = op.voiceover;
2053
- }
2054
- if (op.music !== undefined) {
2055
- next.music = op.music;
2056
- }
2057
- }
2058
- const previous = scope.state.setup;
2059
- scope.state.setup = {
2060
- ...previous,
2061
- stage: previous?.stage ?? "review",
2062
- brief: previous?.brief ?? "",
2063
- format: previous?.format,
2064
- voiceover: previous?.voiceover,
2065
- beats: op.op === "remove_beat"
2066
- ? beats.filter((b) => b.id !== found.id)
2067
- : beats.map((b) => (b.id === found.id ? next : b))
2068
- };
2069
- return op.op === "remove_beat"
2070
- ? { ok: true, removed: { ...found } }
2071
- : { ok: true, beat: { ...next } };
2354
+ const adapted = adaptSequenceFormat(source, op.aspect_ratio, {
2355
+ strategy: op.strategy,
2356
+ safeMargin: op.safe_margin,
2357
+ trackIdByClipId: op.track_ids ? trackIdByClipId : undefined
2358
+ });
2359
+ const stored = scope.ctx.retargetFormat
2360
+ ? await scope.ctx.retargetFormat(adapted.sequence)
2361
+ : { sequenceId: adapted.sequence.id, name: adapted.sequence.name };
2362
+ return {
2363
+ ok: true,
2364
+ sourceSequenceId: source.id,
2365
+ sequenceId: stored.sequenceId,
2366
+ name: stored.name ?? adapted.sequence.name,
2367
+ width: adapted.sequence.width,
2368
+ height: adapted.sequence.height,
2369
+ strategy: op.strategy,
2370
+ croppedClipIds: adapted.croppedClipIds
2371
+ };
2372
+ },
2373
+ stagger_animations: (scope, op) => {
2374
+ const clips = op.clip_ids.map((id) => scope.resolveClip(id));
2375
+ const ids = clips.map((c) => c.id);
2376
+ if (new Set(ids).size !== ids.length) {
2377
+ throw new Error("clip_ids must contain distinct clip IDs.");
2072
2378
  }
2073
- case "generate_from_beats": {
2074
- if (!scope.ctx.generateFromBeats) {
2075
- throw new Error("This surface cannot generate from beats: no generation host is wired.");
2076
- }
2077
- const outcome = await scope.ctx.generateFromBeats(scope.state, op);
2078
- if (outcome.error) {
2079
- throw new Error(outcome.error);
2379
+ for (const clip of clips) {
2380
+ if (!clip.animations?.length) {
2381
+ throw new Error(`Clip "${clip.name}" has no animations to stagger.`);
2080
2382
  }
2081
- Object.assign(scope.state, outcome.state);
2082
- scope.touch(...outcome.changedClipIds);
2083
- return outcome.result;
2084
- }
2085
- default: {
2086
- const unknown = op;
2087
- throw new Error(`Unknown timeline op "${unknown.op}".`);
2088
2383
  }
2384
+ scope.clips = staggerClipAnimations(scope.clips, ids, op.offset_ms);
2385
+ scope.touch(...ids);
2386
+ return {
2387
+ ok: true,
2388
+ clips: ids.map((id) => scope.clipOut(scope.resolveClip(id)))
2389
+ };
2390
+ },
2391
+ set_setup: (scope, op) => {
2392
+ const previous = scope.state.setup;
2393
+ scope.state.setup = {
2394
+ ...previous,
2395
+ stage: op.stage ?? previous?.stage ?? "idea",
2396
+ brief: op.brief ?? previous?.brief ?? "",
2397
+ format: op.format ?? previous?.format,
2398
+ voiceover: op.voiceover ?? previous?.voiceover,
2399
+ beats: previous?.beats
2400
+ };
2401
+ return { ok: true, setup: structuredClone(scope.state.setup) };
2402
+ },
2403
+ plan_beats: (scope, op) => {
2404
+ if (!op.beats?.length) {
2405
+ throw new Error("This surface has no Director: pass `beats` with the plan you want. Each beat needs a prompt and a durationMs.");
2406
+ }
2407
+ const beats = op.beats.map((beat) => ({
2408
+ id: scope.ctx.newId("beat"),
2409
+ prompt: beat.prompt,
2410
+ duration_ms: Math.max(1, Math.round(beat.durationMs)),
2411
+ transition: beat.transition,
2412
+ voiceover: beat.voiceover,
2413
+ music: beat.music
2414
+ }));
2415
+ const previous = scope.state.setup;
2416
+ scope.state.setup = {
2417
+ ...previous,
2418
+ stage: "review",
2419
+ brief: previous?.brief ?? "",
2420
+ format: previous?.format,
2421
+ voiceover: previous?.voiceover,
2422
+ beats
2423
+ };
2424
+ return {
2425
+ ok: true,
2426
+ beats: structuredClone(beats),
2427
+ clipsCreated: 0,
2428
+ jobsStarted: 0
2429
+ };
2430
+ },
2431
+ update_beat: runBeatEdit,
2432
+ remove_beat: runBeatEdit,
2433
+ generate_from_beats: async (scope, op) => {
2434
+ if (!scope.ctx.generateFromBeats) {
2435
+ throw new Error("This surface cannot generate from beats: no generation host is wired.");
2436
+ }
2437
+ const outcome = await scope.ctx.generateFromBeats(scope.state, op);
2438
+ if (outcome.error) {
2439
+ throw new Error(outcome.error);
2440
+ }
2441
+ Object.assign(scope.state, outcome.state);
2442
+ scope.touch(...outcome.changedClipIds);
2443
+ return outcome.result;
2089
2444
  }
2445
+ };
2446
+ /** Dispatch one op against `scope`. Throws on refusal; the caller maps it. */
2447
+ async function runOp(scope, op) {
2448
+ if (!Object.hasOwn(OP_HANDLERS, op.op)) {
2449
+ throw new Error(`Unknown timeline op "${op.op}".`);
2450
+ }
2451
+ const handler = OP_HANDLERS[op.op];
2452
+ return handler(scope, op);
2090
2453
  }
2091
2454
  /** Deep copy of the document, so a failed op leaves the caller's state alone. */
2092
2455
  function cloneState(state) {
@@ -2180,7 +2543,13 @@ function runTrackOp(scope, op) {
2180
2543
  case "delete_track": {
2181
2544
  const { target, deleteClips } = resolveDeleteTrackArgs(op);
2182
2545
  const track = scope.resolveTrack(target);
2546
+ // The editor's removeTrack refuses a locked track, and a locked clip is
2547
+ // not deleted by deleting the track under it.
2548
+ scope.assertWritable([], track.id);
2183
2549
  const onIt = scope.clips.filter((c) => c.trackId === track.id);
2550
+ if (deleteClips) {
2551
+ scope.assertWritable(onIt);
2552
+ }
2184
2553
  if (onIt.length > 0 && !deleteClips) {
2185
2554
  throw new Error(`Track "${track.name}" still holds ${onIt.length} clip(s): ` +
2186
2555
  `${onIt.map((c) => c.id).join(", ")}. Move them first, or pass ` +
@@ -2200,6 +2569,28 @@ function runTrackOp(scope, op) {
2200
2569
  scope.touch(clip.id);
2201
2570
  }
2202
2571
  }
2572
+ // A link left with one member is no link, the rule delete_clip applies.
2573
+ const removedLinks = new Set(onIt.flatMap((clip) => (clip.linkId ? [clip.linkId] : [])));
2574
+ for (const linkId of removedLinks) {
2575
+ const remainingLinked = scope.clips.filter((c) => c.linkId === linkId);
2576
+ if (remainingLinked.length === 1) {
2577
+ delete remainingLinked[0].linkId;
2578
+ scope.touch(remainingLinked[0].id);
2579
+ }
2580
+ }
2581
+ // Subject tracks belong to a clip; they go with it, and a clip bound to
2582
+ // one of them is released the way delete_track_object releases it.
2583
+ const droppedMediaTracks = new Set(scope.mediaTracks.filter((t) => removed.has(t.clipId)).map((t) => t.id));
2584
+ if (droppedMediaTracks.size > 0) {
2585
+ scope.mediaTracks = scope.mediaTracks.filter((t) => !droppedMediaTracks.has(t.id));
2586
+ for (const clip of scope.clips) {
2587
+ if (clip.trackBinding &&
2588
+ droppedMediaTracks.has(clip.trackBinding.trackId)) {
2589
+ delete clip.trackBinding;
2590
+ scope.touch(clip.id);
2591
+ }
2592
+ }
2593
+ }
2203
2594
  scope.touch(...removedClipIds);
2204
2595
  state.selectedClipIds = state.selectedClipIds.filter((id) => !removed.has(id));
2205
2596
  const remaining = scope.tracks.filter((t) => t.id !== track.id);