@nodetool-ai/timeline 0.8.1 → 0.8.2

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 (138) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/authoring.d.ts.map +1 -1
  3. package/dist/authoring.js +46 -6
  4. package/dist/authoring.js.map +1 -1
  5. package/dist/composition.d.ts +11 -1
  6. package/dist/composition.d.ts.map +1 -1
  7. package/dist/composition.js +58 -12
  8. package/dist/composition.js.map +1 -1
  9. package/dist/examples/node.d.ts +18 -0
  10. package/dist/examples/node.d.ts.map +1 -1
  11. package/dist/examples/node.js +26 -0
  12. package/dist/examples/node.js.map +1 -1
  13. package/dist/finish-storyboard.d.ts +36 -0
  14. package/dist/finish-storyboard.d.ts.map +1 -0
  15. package/dist/finish-storyboard.js +554 -0
  16. package/dist/finish-storyboard.js.map +1 -0
  17. package/dist/fonts/google-fonts-fetch.d.ts +53 -0
  18. package/dist/fonts/google-fonts-fetch.d.ts.map +1 -0
  19. package/dist/fonts/google-fonts-fetch.js +184 -0
  20. package/dist/fonts/google-fonts-fetch.js.map +1 -0
  21. package/dist/fonts/google-fonts-node.d.ts +32 -0
  22. package/dist/fonts/google-fonts-node.d.ts.map +1 -0
  23. package/dist/fonts/google-fonts-node.js +60 -0
  24. package/dist/fonts/google-fonts-node.js.map +1 -0
  25. package/dist/fonts/google-fonts.d.ts +105 -0
  26. package/dist/fonts/google-fonts.d.ts.map +1 -0
  27. package/dist/fonts/google-fonts.js +178 -0
  28. package/dist/fonts/google-fonts.js.map +1 -0
  29. package/dist/fonts/index.d.ts +1 -0
  30. package/dist/fonts/index.d.ts.map +1 -1
  31. package/dist/fonts/index.js +1 -0
  32. package/dist/fonts/index.js.map +1 -1
  33. package/dist/index.d.ts +5 -0
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +5 -0
  36. package/dist/index.js.map +1 -1
  37. package/dist/linked.d.ts +2 -1
  38. package/dist/linked.d.ts.map +1 -1
  39. package/dist/linked.js +18 -10
  40. package/dist/linked.js.map +1 -1
  41. package/dist/midi/engines/kits.d.ts +2 -0
  42. package/dist/midi/engines/kits.d.ts.map +1 -1
  43. package/dist/midi/engines/kits.js +146 -0
  44. package/dist/midi/engines/kits.js.map +1 -1
  45. package/dist/midi/index.d.ts +1 -0
  46. package/dist/midi/index.d.ts.map +1 -1
  47. package/dist/midi/index.js +1 -0
  48. package/dist/midi/index.js.map +1 -1
  49. package/dist/midi/instrument.d.ts.map +1 -1
  50. package/dist/midi/instrument.js +5 -0
  51. package/dist/midi/instrument.js.map +1 -1
  52. package/dist/midi/presets.d.ts.map +1 -1
  53. package/dist/midi/presets.js +251 -1
  54. package/dist/midi/presets.js.map +1 -1
  55. package/dist/midi/sampler.d.ts +15 -0
  56. package/dist/midi/sampler.d.ts.map +1 -0
  57. package/dist/midi/sampler.js +72 -0
  58. package/dist/midi/sampler.js.map +1 -0
  59. package/dist/midi/voice.d.ts +4 -1
  60. package/dist/midi/voice.d.ts.map +1 -1
  61. package/dist/midi/voice.js +8 -4
  62. package/dist/midi/voice.js.map +1 -1
  63. package/dist/ops/apply.d.ts +6 -1
  64. package/dist/ops/apply.d.ts.map +1 -1
  65. package/dist/ops/apply.js +843 -201
  66. package/dist/ops/apply.js.map +1 -1
  67. package/dist/ops/index.d.ts +3 -2
  68. package/dist/ops/index.d.ts.map +1 -1
  69. package/dist/ops/index.js +3 -2
  70. package/dist/ops/index.js.map +1 -1
  71. package/dist/ops/op.d.ts +15 -3
  72. package/dist/ops/op.d.ts.map +1 -1
  73. package/dist/ops/op.js +17 -8
  74. package/dist/ops/op.js.map +1 -1
  75. package/dist/ops/parse.d.ts +6 -0
  76. package/dist/ops/parse.d.ts.map +1 -0
  77. package/dist/ops/parse.js +390 -0
  78. package/dist/ops/parse.js.map +1 -0
  79. package/dist/ops/serialize.d.ts +9 -1
  80. package/dist/ops/serialize.d.ts.map +1 -1
  81. package/dist/ops/serialize.js +19 -2
  82. package/dist/ops/serialize.js.map +1 -1
  83. package/dist/ops/types.d.ts +30 -8
  84. package/dist/ops/types.d.ts.map +1 -1
  85. package/dist/ops/types.js +2 -5
  86. package/dist/ops/types.js.map +1 -1
  87. package/dist/production.d.ts.map +1 -1
  88. package/dist/production.js +7 -0
  89. package/dist/production.js.map +1 -1
  90. package/dist/reassemble.d.ts +3 -1
  91. package/dist/reassemble.d.ts.map +1 -1
  92. package/dist/reassemble.js +7 -0
  93. package/dist/reassemble.js.map +1 -1
  94. package/dist/render/canvas2d.d.ts +3 -3
  95. package/dist/render/canvas2d.d.ts.map +1 -1
  96. package/dist/render/draw.d.ts +29 -2
  97. package/dist/render/draw.d.ts.map +1 -1
  98. package/dist/render/draw.js +47 -3
  99. package/dist/render/draw.js.map +1 -1
  100. package/dist/render/layout.d.ts +27 -3
  101. package/dist/render/layout.d.ts.map +1 -1
  102. package/dist/render/layout.js +464 -103
  103. package/dist/render/layout.js.map +1 -1
  104. package/dist/render/sceneModel.d.ts.map +1 -1
  105. package/dist/render/sceneModel.js +76 -27
  106. package/dist/render/sceneModel.js.map +1 -1
  107. package/dist/render/svgPath.d.ts +36 -8
  108. package/dist/render/svgPath.d.ts.map +1 -1
  109. package/dist/render/svgPath.js +303 -30
  110. package/dist/render/svgPath.js.map +1 -1
  111. package/dist/render/textLayout.d.ts +36 -0
  112. package/dist/render/textLayout.d.ts.map +1 -1
  113. package/dist/render/textLayout.js +46 -3
  114. package/dist/render/textLayout.js.map +1 -1
  115. package/dist/render/transform.d.ts +10 -0
  116. package/dist/render/transform.d.ts.map +1 -1
  117. package/dist/render/transform.js +15 -5
  118. package/dist/render/transform.js.map +1 -1
  119. package/dist/source-merge.d.ts +84 -0
  120. package/dist/source-merge.d.ts.map +1 -0
  121. package/dist/source-merge.js +200 -0
  122. package/dist/source-merge.js.map +1 -0
  123. package/dist/storyboard.d.ts +20 -3
  124. package/dist/storyboard.d.ts.map +1 -1
  125. package/dist/storyboard.js +61 -27
  126. package/dist/storyboard.js.map +1 -1
  127. package/dist/storyboardDesignFrame.d.ts +15 -0
  128. package/dist/storyboardDesignFrame.d.ts.map +1 -0
  129. package/dist/storyboardDesignFrame.js +44 -0
  130. package/dist/storyboardDesignFrame.js.map +1 -0
  131. package/dist/storyboardValidation.d.ts +10 -0
  132. package/dist/storyboardValidation.d.ts.map +1 -0
  133. package/dist/storyboardValidation.js +47 -0
  134. package/dist/storyboardValidation.js.map +1 -0
  135. package/dist/types.d.ts +161 -20
  136. package/dist/types.d.ts.map +1 -1
  137. package/dist/types.js.map +1 -1
  138. package/package.json +28 -4
package/dist/ops/apply.js CHANGED
@@ -9,24 +9,34 @@
9
9
  * Everything a pure function cannot know — minting an id, reading an asset,
10
10
  * baking a JS animation body, loading a composition, parsing SVG path data —
11
11
  * arrives on {@link TimelineOpContext}. This module imports nothing from
12
- * `src/render` or `@nodetool-ai/gpu`, so mobile compiles it from source (AS2).
12
+ * `src/render` or `@nodetool-ai/gpu`, so editing needs no renderer (AS2).
13
13
  */
14
- import { buildEffect, buildMask, buildTimeRemap, buildTransition, resolveDeleteTrackArgs, resolveMoveTrackArgs, resolveShapeArg } from "@nodetool-ai/protocol/api-schemas/timeline-tool-params.js";
14
+ import { isShortResourceId } from "@nodetool-ai/protocol";
15
+ import { buildEffect, buildMask, buildTimeRemap, buildTransition, resolveDeleteTrackArgs, resolveMoveTrackArgs, resolveShapeArg, textStyleParams } from "@nodetool-ai/protocol/api-schemas/timeline-tool-params.js";
16
+ import { staggerClipAnimations } from "../animation/beat.js";
15
17
  import { ANIMATION_PRESETS, buildBakedAnimation, CUSTOM_ANIMATION_CONTRACT, CUSTOM_ANIMATION_PRESET_ID, normalizeCustomCurves, resolveCustomMask, typewriterTiming } from "../animation/index.js";
18
+ import { model3dStyleWithPatch, shapeStyleWithDefaults, textStyleWithDefaults } from "../authoredStyles.js";
16
19
  import { beatCountToCover, buildBeatGrid, snapClipsToGrid } from "../beats.js";
17
20
  import { instantiateComposition } from "../composition.js";
18
- import { DEFAULT_MEDIA_CLIP_DURATION_MS, DEFAULT_MODEL3D_CLIP_DURATION_MS, DEFAULT_MODEL3D_CLIP_NAME, DEFAULT_TEXT_CLIP_DURATION_MS, makeClip, makeClipVersion, makeTrack, mediaTypeForContentType, trackTypeForMediaType } from "../defaults.js";
21
+ import { isCropUsable } from "../crop.js";
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
+ import { assertAuthorableFontFamily } from "../fonts/catalog.js";
19
24
  import { selectGeneratedMatteVersion } from "../generatedMatte.js";
25
+ import { groupDescendantIds, isGroupClip, moveGroup, trimGroup, ungroup } from "../group.js";
26
+ import { isMediaTrackStale, resliceTracksForSplitClip, resliceTracksForTrimmedClip } from "../mediaTrack.js";
27
+ import { quantizeNotes, scaleVelocity, transposeNotes } from "../midi/edit.js";
28
+ import { DEFAULT_MIDI_INSTRUMENT } from "../midi/instrument.js";
29
+ import { createMidiNote, sortNotes, validateNotes } from "../midi/notes.js";
30
+ import { findInstrumentPreset, MIDI_INSTRUMENT_PRESETS } from "../midi/presets.js";
31
+ import { DEFAULT_TEMPO, rescaleClipsForTempo, resolveTempo } from "../midi/tempo.js";
20
32
  import { computeModel3DBakeHash } from "../model3dBake.js";
21
- import { model3dStyleWithPatch, shapeStyleWithDefaults, textStyleWithDefaults } from "../authoredStyles.js";
22
- import { isGroupClip, moveGroup, trimGroup, ungroup } from "../group.js";
23
- import { isCropUsable } from "../crop.js";
33
+ import { addReframeKeyframe, clearReframe, mediaTrackCanDriveReframe } from "../reframe.js";
34
+ import { adaptSequenceFormat } from "../retarget.js";
24
35
  import { splitClip } from "../splitClip.js";
25
36
  import { activeTakeIdOf, deleteTake as deleteTakeOnClip, renameTake as renameTakeOnClip, selectTake } from "../takes.js";
26
37
  import { moveTrackOrder } from "../trackOrder.js";
27
- import { trimClip } from "../trimClip.js";
28
38
  import { applyTransitionAtCutCandidate, planTransitionAtCut } from "../transitionAtCut.js";
29
- import { resliceTracksForSplitClip, resliceTracksForTrimmedClip } from "../mediaTrack.js";
39
+ import { trimClip } from "../trimClip.js";
30
40
  import { serializeClip, serializeMediaTrack, serializeTrack } from "./serialize.js";
31
41
  /** Units a failed lookup names before it stops and points at get_state. */
32
42
  const MAX_LISTED_UNITS = 12;
@@ -44,26 +54,44 @@ export function resolveClipTarget(state, target) {
44
54
  throw new Error(`"selected" requires exactly one selected clip (currently ${selected.length}).`);
45
55
  }
46
56
  const clip = state.clips.find((c) => c.id === selected[0]);
47
- if (!clip)
57
+ if (!clip) {
48
58
  throw new Error("Selected clip no longer exists.");
59
+ }
49
60
  return clip;
50
61
  }
51
62
  const byId = state.clips.find((c) => c.id === target);
52
- if (byId)
63
+ if (byId) {
53
64
  return byId;
65
+ }
66
+ const prefix = resolveShortId(state.clips, target, "clip");
67
+ if (prefix) {
68
+ return prefix;
69
+ }
54
70
  const lower = target.toLowerCase();
55
71
  const byName = state.clips.find((c) => c.name.toLowerCase() === lower);
56
- if (byName)
72
+ if (byName) {
57
73
  return byName;
74
+ }
58
75
  throw new Error(`No clip found matching "${target}". ${listUnits(state.clips, "clip")}`);
59
76
  }
77
+ function resolveShortId(units, target, kind) {
78
+ if (!isShortResourceId(target)) {
79
+ return undefined;
80
+ }
81
+ const matches = units.filter((unit) => unit.id.startsWith(target));
82
+ if (matches.length > 1) {
83
+ throw new Error(`Prefix "${target}" matches more than one ${kind}; use a full id.`);
84
+ }
85
+ return matches[0];
86
+ }
60
87
  /**
61
88
  * Name the units a caller could have meant, capped: a 200-clip sequence
62
89
  * listing all of them is one an agent stops reading.
63
90
  */
64
91
  function listUnits(units, kind) {
65
- if (units.length === 0)
92
+ if (units.length === 0) {
66
93
  return `The timeline has no ${kind}s yet.`;
94
+ }
67
95
  const shown = units
68
96
  .slice(0, MAX_LISTED_UNITS)
69
97
  .map((u) => `${u.id} ("${u.name}")`)
@@ -135,8 +163,9 @@ class OpScope {
135
163
  this.ctx = ctx;
136
164
  }
137
165
  touch(...ids) {
138
- for (const id of ids)
166
+ for (const id of ids) {
139
167
  this.changed.add(id);
168
+ }
140
169
  }
141
170
  get tracks() {
142
171
  return this.state.tracks;
@@ -169,20 +198,35 @@ class OpScope {
169
198
  name: name ?? `${capitalize(type)} ${index + 1}`,
170
199
  index
171
200
  });
201
+ if (type === "midi") {
202
+ track.instrument = structuredClone(this.ctx.defaultMidiInstrument ?? DEFAULT_MIDI_INSTRUMENT);
203
+ this.state.tempo ??= structuredClone(DEFAULT_TEMPO);
204
+ }
172
205
  this.tracks.push(track);
173
206
  return track;
174
207
  }
175
- findOrCreateTrack(type) {
176
- return this.tracks.find((t) => t.type === type) ?? this.addTrack(type);
208
+ findOrCreateTrack(type, name) {
209
+ return (this.tracks.find((t) => t.type === type) ?? this.addTrack(type, name));
177
210
  }
178
211
  resolveTrack(idOrName) {
179
212
  const byId = this.tracks.find((t) => t.id === idOrName);
180
- if (byId)
213
+ if (byId) {
181
214
  return byId;
215
+ }
216
+ if (isShortResourceId(idOrName)) {
217
+ const matches = this.tracks.filter((track) => track.id.startsWith(idOrName));
218
+ if (matches.length === 1 && matches[0]) {
219
+ return matches[0];
220
+ }
221
+ if (matches.length > 1) {
222
+ throw new Error(`Short track id "${idOrName}" matches more than one track; use the full id or name.`);
223
+ }
224
+ }
182
225
  const lower = idOrName.toLowerCase();
183
226
  const byName = this.tracks.find((t) => t.name.toLowerCase() === lower);
184
- if (byName)
227
+ if (byName) {
185
228
  return byName;
229
+ }
186
230
  throw new Error(`No track found matching "${idOrName}". ${this.validUnits(this.tracks, "track")}`);
187
231
  }
188
232
  trackEndMs(trackId) {
@@ -190,14 +234,77 @@ class OpScope {
190
234
  .filter((c) => c.trackId === trackId)
191
235
  .reduce((m, c) => Math.max(m, c.startMs + c.durationMs), 0);
192
236
  }
237
+ resolveMidiTrack(target) {
238
+ const track = this.resolveTrack(target);
239
+ if (track.type !== "midi") {
240
+ throw new Error(`Track "${track.name}" is a ${track.type} track — notes are played by a midi track's instrument. ${this.validUnits(this.tracks.filter((t) => t.type === "midi"), "midi track")}`);
241
+ }
242
+ return track;
243
+ }
244
+ resolveMidiClip(target) {
245
+ const clip = this.resolveClip(target);
246
+ if (clip.mediaType !== "midi") {
247
+ throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip — only a midi clip carries notes. Place one with add_midi_clip.`);
248
+ }
249
+ return clip;
250
+ }
251
+ buildNotes(input, name) {
252
+ const reserved = new Set((input ?? []).flatMap((note) => (note.id ? [note.id] : [])));
253
+ const mintNote = () => {
254
+ let id = this.ctx.newId("note");
255
+ while (reserved.has(id)) {
256
+ id = this.ctx.newId("note");
257
+ }
258
+ reserved.add(id);
259
+ return id;
260
+ };
261
+ const notes = (input ?? []).map((n) => createMidiNote({
262
+ id: n.id ?? mintNote(),
263
+ pitch: n.pitch,
264
+ velocity: n.velocity,
265
+ startTick: n.start_tick,
266
+ durationTick: n.duration_tick
267
+ }));
268
+ const problems = validateNotes(notes);
269
+ if (problems.length) {
270
+ throw new Error(`Clip "${name}" was not given its notes — ${problems.length} problem(s): ` +
271
+ problems
272
+ .map((p) => (p.noteId ? `${p.noteId}: ${p.message}` : p.message))
273
+ .join(" "));
274
+ }
275
+ return sortNotes(notes);
276
+ }
193
277
  resolveClip(target) {
194
278
  return resolveClipTarget(this.state, target);
195
279
  }
280
+ 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
+ }
295
+ return targets;
296
+ }
297
+ assertPictureTrack(track) {
298
+ if (track.type !== "video" && track.type !== "overlay") {
299
+ throw new Error(`Authored clips require a video or overlay track; "${track.name}" is ${track.type}.`);
300
+ }
301
+ }
196
302
  /** Swap an engine-returned clip into `clips`, keeping the array's order. */
197
303
  replaceClip(clip, next) {
198
304
  const index = this.clips.findIndex((c) => c.id === clip.id);
199
- if (index >= 0)
305
+ if (index >= 0) {
200
306
  this.clips[index] = next;
307
+ }
201
308
  return next;
202
309
  }
203
310
  /**
@@ -206,13 +313,64 @@ class OpScope {
206
313
  * way, and two copies of the group-trim rule would drift.
207
314
  */
208
315
  applyTrim(clip, patch) {
316
+ if (patch.durationMs === undefined &&
317
+ patch.inPointMs === undefined &&
318
+ patch.outPointMs === undefined) {
319
+ return clip;
320
+ }
321
+ if (patch.inPointMs !== undefined && patch.inPointMs < 0) {
322
+ throw new Error("inPointMs cannot be negative.");
323
+ }
324
+ const prospective = patch.durationMs !== undefined && !isGroupClip(clip)
325
+ ? trimClip(clip, "end", patch.durationMs - clip.durationMs)
326
+ : clip;
327
+ const sourceIn = patch.inPointMs ?? prospective.inPointMs ?? 0;
328
+ const sourceOut = patch.outPointMs ?? prospective.outPointMs;
329
+ if (sourceOut !== undefined && sourceOut <= sourceIn) {
330
+ throw new Error("outPointMs must be greater than inPointMs.");
331
+ }
332
+ if (isGroupClip(clip) &&
333
+ (patch.inPointMs !== undefined || patch.outPointMs !== undefined)) {
334
+ throw new Error("Groups carry no source media; trim their duration instead.");
335
+ }
336
+ const targets = this.editTargets(clip);
337
+ if (targets.length > 1 &&
338
+ patch.durationMs !== undefined &&
339
+ !isGroupClip(clip)) {
340
+ const delta = patch.durationMs - clip.durationMs;
341
+ const trimmedTargets = targets.map((target) => {
342
+ if (target.durationMs + delta <= 0) {
343
+ throw new Error("Linked trim would remove a clip. Shorten the trim or unlink it first.");
344
+ }
345
+ const trimmed = trimClip(target, "end", delta);
346
+ if (target.id === clip.id) {
347
+ if (patch.inPointMs !== undefined) {
348
+ trimmed.inPointMs = patch.inPointMs;
349
+ }
350
+ if (patch.outPointMs !== undefined) {
351
+ trimmed.outPointMs = patch.outPointMs;
352
+ }
353
+ }
354
+ return { target, trimmed };
355
+ });
356
+ for (const { target, trimmed } of trimmedTargets) {
357
+ this.replaceClip(target, trimmed);
358
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, trimmed);
359
+ this.touch(trimmed.id);
360
+ }
361
+ return this.resolveClip(clip.id);
362
+ }
209
363
  // A group carries what it holds (D4): shortening one pulls its children
210
364
  // inside the window that leaves, rather than leaving them hanging past an
211
365
  // edge nothing draws.
212
366
  if (isGroupClip(clip) && patch.durationMs !== undefined) {
213
367
  this.clips = trimGroup(this.clips, clip.id, "end", patch.durationMs - clip.durationMs);
214
368
  const next = this.clips.find((c) => c.id === clip.id);
215
- this.touch(...this.clips.filter((c) => c.parentId === clip.id).map((c) => c.id));
369
+ for (const target of targets) {
370
+ const trimmed = this.resolveClip(target.id);
371
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, trimmed);
372
+ this.touch(trimmed.id);
373
+ }
216
374
  this.touch(next.id);
217
375
  return next;
218
376
  }
@@ -225,35 +383,40 @@ class OpScope {
225
383
  }
226
384
  next = this.replaceClip(clip, trimClip(clip, "end", patch.durationMs - clip.durationMs));
227
385
  }
228
- if (patch.inPointMs !== undefined)
386
+ if (patch.inPointMs !== undefined) {
229
387
  next.inPointMs = patch.inPointMs;
230
- if (patch.outPointMs !== undefined)
388
+ }
389
+ if (patch.outPointMs !== undefined) {
231
390
  next.outPointMs = patch.outPointMs;
391
+ }
232
392
  if (patch.durationMs !== undefined ||
233
393
  patch.inPointMs !== undefined ||
234
394
  patch.outPointMs !== undefined) {
235
395
  this.touch(next.id);
236
396
  }
397
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, next);
237
398
  return next;
238
399
  }
239
- /**
240
- * Trim the start edge: hold the clip's end and move its start to `startMs`.
241
- * A group pulls its children with it (D4); anything else goes through the
242
- * engine so the source in-point follows the edge.
243
- */
244
- applyTrimStart(clip, startMs) {
245
- const deltaMs = clip.startMs - Math.max(0, startMs);
246
- if (deltaMs === 0)
247
- return clip;
248
- this.touch(clip.id);
249
- if (isGroupClip(clip)) {
250
- this.clips = trimGroup(this.clips, clip.id, "start", deltaMs);
251
- return this.clips.find((c) => c.id === clip.id);
252
- }
253
- return this.replaceClip(clip, trimClip(clip, "start", deltaMs));
254
- }
255
400
  /** The body of `move_clip`, shared with `set_clip_params`. */
256
401
  applyMove(clip, patch) {
402
+ if (patch.startMs === undefined && patch.trackId === undefined) {
403
+ return clip;
404
+ }
405
+ const targets = this.editTargets(clip);
406
+ if (targets.length > 1 &&
407
+ patch.startMs !== undefined &&
408
+ !isGroupClip(clip)) {
409
+ const minimum = Math.min(...targets.map((target) => target.startMs));
410
+ const delta = Math.max(-minimum, patch.startMs - clip.startMs);
411
+ for (const target of targets) {
412
+ target.startMs += delta;
413
+ this.touch(target.id);
414
+ }
415
+ if (patch.trackId !== undefined) {
416
+ clip.trackId = this.resolveTrack(patch.trackId).id;
417
+ }
418
+ return clip;
419
+ }
257
420
  // Moving a group moves what it holds by the same delta (D4). Children keep
258
421
  // their own tracks, so their z-order is untouched (I9) — only the group
259
422
  // itself takes a new `trackId`.
@@ -262,7 +425,7 @@ class OpScope {
262
425
  const nextStartMs = Math.max(0, patch.startMs);
263
426
  this.clips = moveGroup(this.clips, clip.id, nextStartMs - clip.startMs);
264
427
  moved = this.clips.find((c) => c.id === clip.id);
265
- this.touch(...this.clips.filter((c) => c.parentId === clip.id).map((c) => c.id));
428
+ this.touch(...targets.map((target) => target.id));
266
429
  }
267
430
  else if (patch.startMs !== undefined) {
268
431
  clip.startMs = Math.max(0, patch.startMs);
@@ -278,12 +441,18 @@ class OpScope {
278
441
  /** Resolve a marker by id, or by case-insensitive label. */
279
442
  resolveMarker(target) {
280
443
  const byId = this.state.markers.find((m) => m.id === target);
281
- if (byId)
444
+ if (byId) {
282
445
  return byId;
446
+ }
447
+ const prefix = resolveShortId(this.state.markers, target, "marker");
448
+ if (prefix) {
449
+ return prefix;
450
+ }
283
451
  const lower = target.toLowerCase();
284
452
  const byLabel = this.state.markers.find((m) => m.label.toLowerCase() === lower);
285
- if (byLabel)
453
+ if (byLabel) {
286
454
  return byLabel;
455
+ }
287
456
  const known = this.state.markers
288
457
  .map((m) => `${m.id} ("${m.label}") at ${m.timeMs}ms`)
289
458
  .join(", ");
@@ -306,8 +475,9 @@ class OpScope {
306
475
  for (const target of targets) {
307
476
  try {
308
477
  const clip = this.resolveClip(target);
309
- if (!resolved.includes(clip))
478
+ if (!resolved.includes(clip)) {
310
479
  resolved.push(clip);
480
+ }
311
481
  }
312
482
  catch {
313
483
  // Recorded as a skip in the op's own report, with the reason.
@@ -325,8 +495,9 @@ class OpScope {
325
495
  }
326
496
  function rejectUnknownClipParams(patch) {
327
497
  for (const key of Object.keys(patch)) {
328
- if (CLIP_PARAM_KEYS.includes(key))
498
+ if (CLIP_PARAM_KEYS.includes(key)) {
329
499
  continue;
500
+ }
330
501
  const elsewhere = CLIP_PARAM_ELSEWHERE[key];
331
502
  if (elsewhere) {
332
503
  throw new Error(`set_clip_params does not change \`${key}\`; use ${elsewhere}.`);
@@ -341,8 +512,9 @@ function rejectUnknownClipParams(patch) {
341
512
  * animation with neither curves nor code.
342
513
  */
343
514
  function liftCustom(input) {
344
- if (!input.custom)
515
+ if (!input.custom) {
345
516
  return input;
517
+ }
346
518
  const { custom, ...rest } = input;
347
519
  return {
348
520
  ...rest,
@@ -357,8 +529,9 @@ function liftCustom(input) {
357
529
  * not stagger, matching the un-staggered block case.
358
530
  */
359
531
  function staggerUnitCount(clip, stagger) {
360
- if (!stagger || clip.mediaType !== "text")
532
+ if (!stagger || clip.mediaType !== "text") {
361
533
  return 0;
534
+ }
362
535
  const text = clip.textStyle?.text ?? "";
363
536
  return text
364
537
  .trim()
@@ -390,15 +563,16 @@ async function buildCustomAnimation(scope, clip, input) {
390
563
  let maskInput;
391
564
  if (hasCurves) {
392
565
  const normalized = normalizeCustomCurves(input.curves);
393
- if (!normalized.ok)
566
+ if (!normalized.ok) {
394
567
  throw new Error(normalized.error);
568
+ }
395
569
  curves = normalized.curves;
396
570
  maskInput = input.mask;
397
571
  }
398
572
  else {
399
573
  const bake = scope.ctx.bakeAnimation;
400
574
  if (!bake) {
401
- throw new Error("This surface cannot run `code`: no animation baker is wired to it. Pass `curves` instead, or bake the body through POST /api/timelines/animations/bake.");
575
+ throw new Error("This surface cannot run `code`: no animation baker is wired to it. Pass `curves` instead, or use edit_timeline to bake the body.");
402
576
  }
403
577
  const baked = await bake({
404
578
  code,
@@ -413,25 +587,30 @@ async function buildCustomAnimation(scope, clip, input) {
413
587
  throw new Error(baked.error ?? "The animation body returned no curves.");
414
588
  }
415
589
  const normalized = normalizeCustomCurves(baked.curves);
416
- if (!normalized.ok)
590
+ if (!normalized.ok) {
417
591
  throw new Error(normalized.error);
592
+ }
418
593
  curves = normalized.curves;
419
594
  maskInput = baked.mask ?? input.mask;
420
595
  }
421
596
  const mask = resolveCustomMask(curves, maskInput);
422
- if (!mask.ok)
597
+ if (!mask.ok) {
423
598
  throw new Error(mask.error);
599
+ }
424
600
  const custom = {
425
601
  curves,
426
602
  bakedAt: (scope.ctx.now ?? (() => new Date().toISOString()))()
427
603
  };
428
- if (hasCode)
604
+ if (hasCode) {
429
605
  custom.code = code;
430
- if (mask.mask)
606
+ }
607
+ if (mask.mask) {
431
608
  custom.mask = mask.mask;
609
+ }
432
610
  return {
433
611
  id: scope.ctx.newId("anim"),
434
612
  role: input.role,
613
+ enabled: input.enabled,
435
614
  preset: CUSTOM_ANIMATION_PRESET_ID,
436
615
  durationMs,
437
616
  delayMs: input.delayMs,
@@ -455,86 +634,24 @@ async function runOp(scope, op) {
455
634
  durationMs,
456
635
  playheadMs: state.playheadMs,
457
636
  selectedClipIds: [...state.selectedClipIds],
637
+ tempo: state.tempo,
458
638
  tracks: scope.tracks.map((t) => scope.trackOut(t)),
459
639
  clips: scope.clips.map((c) => scope.clipOut(c)),
460
640
  mediaTracks: scope.mediaTracks.map(serializeMediaTrack),
461
641
  markers: state.markers.map((m) => ({ ...m }))
462
642
  };
463
643
  }
464
- case "add_track": {
465
- const track = scope.addTrack(op.type, op.name);
466
- return { ok: true, track: scope.trackOut(track) };
467
- }
468
- case "move_track": {
469
- const { target, toIndex, before, after } = resolveMoveTrackArgs(op);
470
- const track = scope.resolveTrack(target);
471
- const destination = {};
472
- if (toIndex !== undefined)
473
- destination.toIndex = toIndex;
474
- if (before !== undefined)
475
- destination.beforeId = scope.resolveTrack(before).id;
476
- if (after !== undefined)
477
- destination.afterId = scope.resolveTrack(after).id;
478
- const orderedIds = moveTrackOrder(scope.tracks, track.id, destination);
479
- const byId = new Map(scope.tracks.map((t) => [t.id, t]));
480
- // The array order is what `get_state` prints, so keep it and the indices
481
- // saying the same thing.
482
- scope.tracks.length = 0;
483
- orderedIds.forEach((id, i) => {
484
- const moved = byId.get(id);
485
- moved.index = i;
486
- scope.tracks.push(moved);
487
- });
488
- return {
489
- ok: true,
490
- track: scope.trackOut(track),
491
- tracks: scope.tracks.map((t) => scope.trackOut(t))
492
- };
493
- }
494
- case "delete_track": {
495
- const { target, deleteClips } = resolveDeleteTrackArgs(op);
496
- const track = scope.resolveTrack(target);
497
- const onIt = scope.clips.filter((c) => c.trackId === track.id);
498
- if (onIt.length > 0 && !deleteClips) {
499
- throw new Error(`Track "${track.name}" still holds ${onIt.length} clip(s): ` +
500
- `${onIt.map((c) => c.id).join(", ")}. Move them first, or pass ` +
501
- "deleteClips: true to delete them with the track.");
502
- }
503
- const removedClipIds = onIt.map((c) => c.id);
504
- const kept = scope.clips.filter((c) => c.trackId !== track.id);
505
- scope.clips.length = 0;
506
- scope.clips.push(...kept);
507
- // A parent that went with the track would leave its children pointing at
508
- // a clip that no longer exists, which the validator reads as a broken
509
- // document rather than a deletion.
510
- for (const clip of scope.clips) {
511
- if (clip.parentId && removedClipIds.includes(clip.parentId)) {
512
- delete clip.parentId;
513
- scope.touch(clip.id);
514
- }
515
- }
516
- scope.touch(...removedClipIds);
517
- state.selectedClipIds = state.selectedClipIds.filter((id) => !removedClipIds.includes(id));
518
- const remaining = scope.tracks.filter((t) => t.id !== track.id);
519
- scope.tracks.length = 0;
520
- // Index is z-order, so the stack has to close over the gap.
521
- remaining.forEach((t, i) => {
522
- t.index = i;
523
- scope.tracks.push(t);
524
- });
525
- return {
526
- ok: true,
527
- deleted: { id: track.id, name: track.name, type: track.type },
528
- deletedClipIds: removedClipIds,
529
- tracks: scope.tracks.map((t) => scope.trackOut(t))
530
- };
531
- }
644
+ case "add_track":
645
+ case "move_track":
646
+ case "delete_track":
647
+ return runTrackOp(scope, op);
532
648
  case "add_text_clip": {
533
649
  const track = op.trackId
534
650
  ? scope.resolveTrack(op.trackId)
535
- : scope.findOrCreateTrack("overlay");
651
+ : scope.findOrCreateTrack("overlay", "Text");
536
652
  // `style` wins over a top-level twin: a caller that sent both meant the
537
653
  // bag it named.
654
+ scope.assertPictureTrack(track);
538
655
  const s = { ...(op.loose ?? {}), ...(op.style ?? {}) };
539
656
  const clip = makeClip({
540
657
  id: scope.ctx.newId("clip"),
@@ -547,10 +664,12 @@ async function runOp(scope, op) {
547
664
  status: "generated",
548
665
  textStyle: textStyleWithDefaults(op.text, s)
549
666
  });
550
- if (op.opacity !== undefined)
667
+ if (op.opacity !== undefined) {
551
668
  clip.opacity = op.opacity;
552
- if (op.transform)
669
+ }
670
+ if (op.transform) {
553
671
  clip.transform = mergeClipTransform(clip.transform, op.transform);
672
+ }
554
673
  scope.clips.push(clip);
555
674
  state.selectedClipIds = [clip.id];
556
675
  scope.touch(clip.id);
@@ -565,18 +684,26 @@ async function runOp(scope, op) {
565
684
  if (!found) {
566
685
  throw new Error(`No asset found for "${op.asset}". Pass an asset id or an asset:// URI from list_assets.`);
567
686
  }
568
- const mediaType = mediaTypeForContentType(found.contentType);
687
+ const mediaType = found.contentType.toLowerCase().startsWith("model/") ||
688
+ /\.(glb|gltf)$/i.test(found.name)
689
+ ? "model3d"
690
+ : mediaTypeForContentType(found.contentType);
569
691
  if (!mediaType) {
570
692
  throw new Error(`Asset "${found.name}" is ${found.contentType}, which is not video, image, or audio and cannot go on a timeline.`);
571
693
  }
572
694
  if (mediaType !== "image" &&
695
+ mediaType !== "model3d" &&
573
696
  op.durationMs === undefined &&
574
- !found.durationMs) {
697
+ !found.durationMs &&
698
+ !scope.ctx.allowUnknownMediaDuration) {
575
699
  throw new Error(`Asset "${found.name}" has no known duration. Supply durationMs or import media that can be probed.`);
576
700
  }
577
701
  const track = op.trackId
578
702
  ? scope.resolveTrack(op.trackId)
579
- : scope.findOrCreateTrack(trackTypeForMediaType(mediaType));
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
+ }
580
707
  const init = {
581
708
  id: scope.ctx.newId("clip"),
582
709
  trackId: track.id,
@@ -588,11 +715,16 @@ async function runOp(scope, op) {
588
715
  status: "generated",
589
716
  currentAssetId: found.id
590
717
  };
591
- if (found.thumbnailAssetId)
718
+ if (mediaType === "model3d") {
719
+ init.model3dStyle = model3dStyleWithPatch(undefined, undefined);
720
+ }
721
+ if (found.thumbnailAssetId) {
592
722
  init.thumbnailAssetId = found.thumbnailAssetId;
723
+ }
593
724
  const clip = makeClip(init);
594
- if (op.transform)
725
+ if (op.transform) {
595
726
  clip.transform = mergeClipTransform(clip.transform, op.transform);
727
+ }
596
728
  scope.clips.push(clip);
597
729
  state.selectedClipIds = [clip.id];
598
730
  scope.touch(clip.id);
@@ -601,7 +733,8 @@ async function runOp(scope, op) {
601
733
  case "add_shape_clip": {
602
734
  const track = op.trackId
603
735
  ? scope.resolveTrack(op.trackId)
604
- : scope.findOrCreateTrack("overlay");
736
+ : scope.findOrCreateTrack("overlay", "Shapes");
737
+ scope.assertPictureTrack(track);
605
738
  const shapeArg = resolveShapeArg(op.shape, op.shapeStyle, op.loose ?? {});
606
739
  const clip = makeClip({
607
740
  id: scope.ctx.newId("clip"),
@@ -614,10 +747,12 @@ async function runOp(scope, op) {
614
747
  status: "generated",
615
748
  shapeStyle: shapeStyleWithDefaults(shapeArg)
616
749
  });
617
- if (op.opacity !== undefined)
750
+ if (op.opacity !== undefined) {
618
751
  clip.opacity = op.opacity;
619
- if (op.transform)
752
+ }
753
+ if (op.transform) {
620
754
  clip.transform = mergeClipTransform(clip.transform, op.transform);
755
+ }
621
756
  scope.clips.push(clip);
622
757
  state.selectedClipIds = [clip.id];
623
758
  scope.touch(clip.id);
@@ -634,7 +769,8 @@ async function runOp(scope, op) {
634
769
  // track, or one made for it.
635
770
  const track = op.trackId
636
771
  ? scope.resolveTrack(op.trackId)
637
- : scope.findOrCreateTrack("overlay");
772
+ : scope.findOrCreateTrack("overlay", "3D");
773
+ scope.assertPictureTrack(track);
638
774
  const clip = makeClip({
639
775
  id: scope.ctx.newId("clip"),
640
776
  trackId: track.id,
@@ -647,8 +783,9 @@ async function runOp(scope, op) {
647
783
  currentAssetId: assetId,
648
784
  model3dStyle: model3dStyleWithPatch(undefined, op.style)
649
785
  });
650
- if (op.transform)
786
+ if (op.transform) {
651
787
  clip.transform = mergeClipTransform(clip.transform, op.transform);
788
+ }
652
789
  scope.clips.push(clip);
653
790
  state.selectedClipIds = [clip.id];
654
791
  scope.touch(clip.id);
@@ -727,7 +864,7 @@ async function runOp(scope, op) {
727
864
  const targets = (op.children ?? []).map((ref) => scope.resolveClip(ref));
728
865
  const track = op.trackId
729
866
  ? scope.resolveTrack(op.trackId)
730
- : scope.findOrCreateTrack("overlay");
867
+ : scope.findOrCreateTrack("overlay", "Groups");
731
868
  const group = makeClip({
732
869
  id: scope.ctx.newId("clip"),
733
870
  trackId: track.id,
@@ -738,8 +875,9 @@ async function runOp(scope, op) {
738
875
  sourceType: "imported",
739
876
  status: "generated"
740
877
  });
741
- if (op.transform)
878
+ if (op.transform) {
742
879
  group.transform = mergeClipTransform(group.transform, op.transform);
880
+ }
743
881
  scope.clips.push(group);
744
882
  for (const child of targets) {
745
883
  child.parentId = group.id;
@@ -763,9 +901,7 @@ async function runOp(scope, op) {
763
901
  ? scope.resolveTrack(op.trackId)
764
902
  : op.kind === "text-to-audio"
765
903
  ? scope.findOrCreateTrack("audio")
766
- : op.kind === "text-to-video"
767
- ? scope.findOrCreateTrack("video")
768
- : (scope.tracks.find((t) => t.type === "video" || t.type === "overlay") ?? scope.findOrCreateTrack("video"));
904
+ : scope.findOrCreateTrack("video");
769
905
  const generationStarted = op.autoGenerate !== false;
770
906
  const clip = makeClip({
771
907
  id: scope.ctx.newId("clip"),
@@ -798,15 +934,31 @@ async function runOp(scope, op) {
798
934
  case "split_clip": {
799
935
  const clip = scope.resolveClip(op.target);
800
936
  const at = op.atMs ?? state.playheadMs;
801
- const [left, right] = splitClip(clip, at);
802
- left.id = scope.ctx.newId("clip");
803
- right.id = scope.ctx.newId("clip");
804
- const idx = scope.clips.findIndex((c) => c.id === clip.id);
805
- scope.clips.splice(idx, 1, left, right);
806
- state.selectedClipIds = state.selectedClipIds.filter((id) => id !== clip.id);
807
- scope.touch(clip.id, left.id, right.id);
808
- scope.mediaTracks = resliceTracksForSplitClip(scope.mediaTracks, clip.id, left, right, () => scope.ctx.newId("track"));
809
- return { ok: true, clips: [scope.clipOut(left), scope.clipOut(right)] };
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)) };
810
962
  }
811
963
  case "trim_clip": {
812
964
  const trimmed = scope.applyTrim(scope.resolveClip(op.target), {
@@ -826,6 +978,7 @@ async function runOp(scope, op) {
826
978
  }
827
979
  case "delete_clip": {
828
980
  const clip = scope.resolveClip(op.target);
981
+ scope.editTargets(clip);
829
982
  // Deleting a group deletes the parent, not the picture: its children stay
830
983
  // where they are and stop inheriting (D4). Leaving them with a `parentId`
831
984
  // nothing answers is what the validator calls a dangling parent.
@@ -837,24 +990,34 @@ async function runOp(scope, op) {
837
990
  : scope.clips;
838
991
  const out = scope.clipOut(clip);
839
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);
998
+ }
999
+ }
840
1000
  state.selectedClipIds = state.selectedClipIds.filter((id) => id !== clip.id);
841
1001
  scope.touch(clip.id, ...wasChild);
842
1002
  return { ok: true, deleted: out };
843
1003
  }
844
1004
  case "duplicate_clip": {
845
1005
  const src = scope.resolveClip(op.target);
846
- const copy = {
847
- ...src,
848
- id: scope.ctx.newId("clip"),
849
- startMs: src.startMs + src.durationMs + (op.gapMs ?? 0),
850
- versions: [],
851
- animations: src.animations?.map((a) => ({
852
- ...a,
853
- id: scope.ctx.newId("anim")
854
- }))
855
- };
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
+ copy.animations = copy.animations?.map((animation) => ({
1017
+ ...animation,
1018
+ id: scope.ctx.newId("anim")
1019
+ }));
856
1020
  scope.clips.push(copy);
857
- state.selectedClipIds = [copy.id];
858
1021
  scope.touch(copy.id);
859
1022
  return { ok: true, clip: scope.clipOut(copy) };
860
1023
  }
@@ -882,32 +1045,39 @@ async function runOp(scope, op) {
882
1045
  }
883
1046
  patch.textStyle = { ...style, fontSizePx: patch.fontSizePx };
884
1047
  }
885
- if (patch.name !== undefined)
1048
+ if (patch.name !== undefined) {
886
1049
  clip.name = patch.name;
887
- if (patch.opacity !== undefined)
1050
+ }
1051
+ if (patch.opacity !== undefined) {
888
1052
  clip.opacity = patch.opacity;
1053
+ }
889
1054
  if (patch.transform !== undefined) {
890
1055
  clip.transform = mergeClipTransform(clip.transform, patch.transform);
891
1056
  }
892
1057
  if (patch.speedMultiplier !== undefined) {
893
1058
  clip.speedMultiplier = patch.speedMultiplier;
894
1059
  }
895
- if (patch.volumeDb !== undefined)
1060
+ if (patch.volumeDb !== undefined) {
896
1061
  clip.volumeDb = patch.volumeDb;
897
- if (patch.fadeInMs !== undefined)
1062
+ }
1063
+ if (patch.fadeInMs !== undefined) {
898
1064
  clip.fadeInMs = patch.fadeInMs;
899
- if (patch.fadeOutMs !== undefined)
1065
+ }
1066
+ if (patch.fadeOutMs !== undefined) {
900
1067
  clip.fadeOutMs = patch.fadeOutMs;
901
- if (patch.fadeInShape !== undefined)
1068
+ }
1069
+ if (patch.fadeInShape !== undefined) {
902
1070
  clip.fadeInShape = patch.fadeInShape;
1071
+ }
903
1072
  if (patch.fadeOutShape !== undefined) {
904
1073
  clip.fadeOutShape = patch.fadeOutShape;
905
1074
  }
906
1075
  if (patch.blendMode !== undefined) {
907
1076
  clip.blendMode = patch.blendMode;
908
1077
  }
909
- if (patch.borderRadius !== undefined)
1078
+ if (patch.borderRadius !== undefined) {
910
1079
  clip.borderRadius = patch.borderRadius;
1080
+ }
911
1081
  if (patch.crop !== undefined) {
912
1082
  // Null is how a caller puts the whole source back; leaving the field
913
1083
  // with all-zero insets would store a crop that means nothing.
@@ -922,16 +1092,30 @@ async function runOp(scope, op) {
922
1092
  clip.crop = patch.crop;
923
1093
  }
924
1094
  }
925
- if (patch.hidden !== undefined)
1095
+ if (patch.hidden !== undefined) {
926
1096
  clip.hidden = patch.hidden;
927
- if (patch.muted !== undefined)
1097
+ }
1098
+ if (patch.muted !== undefined) {
928
1099
  clip.muted = patch.muted;
929
- if (patch.locked !== undefined)
1100
+ }
1101
+ if (patch.locked !== undefined) {
930
1102
  clip.locked = patch.locked;
931
- if (patch.textStyle !== undefined)
932
- clip.textStyle = patch.textStyle;
933
- if (patch.shapeStyle !== undefined)
934
- clip.shapeStyle = patch.shapeStyle;
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
+ }
935
1119
  if (patch.captionStyle !== undefined) {
936
1120
  // The style rides on the clip's caption, so a clip with no words to
937
1121
  // draw has nowhere to put it. Say so rather than storing a look nothing
@@ -981,11 +1165,13 @@ async function runOp(scope, op) {
981
1165
  }
982
1166
  case "apply_transition_at_cut": {
983
1167
  const planned = planTransitionAtCut(scope.clips, op);
984
- if (!planned.ok)
1168
+ if (!planned.ok) {
985
1169
  throw new Error(planned.error);
1170
+ }
986
1171
  const applied = applyTransitionAtCutCandidate(scope.clips, planned.candidate);
987
- if (!applied.ok)
1172
+ if (!applied.ok) {
988
1173
  throw new Error(applied.error);
1174
+ }
989
1175
  scope.clips = applied.clips;
990
1176
  scope.touch(planned.candidate.outgoingClipId, planned.candidate.incomingClipId);
991
1177
  return {
@@ -1001,6 +1187,9 @@ async function runOp(scope, op) {
1001
1187
  delete clip.mask;
1002
1188
  }
1003
1189
  else {
1190
+ if (op.mask.kind === "path" && !op.mask.d?.trim()) {
1191
+ throw new Error("A path mask needs `d` with SVG path data.");
1192
+ }
1004
1193
  clip.mask = buildMask(op.mask, scope.ctx.parseSvgPath);
1005
1194
  }
1006
1195
  scope.touch(clip.id);
@@ -1021,8 +1210,9 @@ async function runOp(scope, op) {
1021
1210
  sourceClipId: source.id,
1022
1211
  mode: op.matte.mode
1023
1212
  };
1024
- if (op.matte.invert !== undefined)
1213
+ if (op.matte.invert !== undefined) {
1025
1214
  matteOut.invert = op.matte.invert;
1215
+ }
1026
1216
  clip.matte = matteOut;
1027
1217
  return { ok: true, clip: scope.clipOut(clip) };
1028
1218
  }
@@ -1043,8 +1233,9 @@ async function runOp(scope, op) {
1043
1233
  // The knobs are the user's, so an absent field leaves the stored value
1044
1234
  // alone rather than resetting it to a default the caller did not name.
1045
1235
  const matte = clip.generatedMatte;
1046
- if (op.invert !== undefined)
1236
+ if (op.invert !== undefined) {
1047
1237
  matte.invert = op.invert;
1238
+ }
1048
1239
  if (op.strength !== undefined) {
1049
1240
  matte.strength = Math.min(1, Math.max(0, op.strength));
1050
1241
  }
@@ -1081,36 +1272,61 @@ async function runOp(scope, op) {
1081
1272
  if (clip.sourceType !== "generated") {
1082
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.`);
1083
1274
  }
1084
- if (op.prompt !== undefined)
1275
+ if (op.prompt !== undefined) {
1085
1276
  clip.prompt = op.prompt;
1086
- if (op.negativePrompt !== undefined)
1277
+ }
1278
+ if (op.negativePrompt !== undefined) {
1087
1279
  clip.negativePrompt = op.negativePrompt;
1088
- if (op.provider !== undefined)
1280
+ }
1281
+ if (op.provider !== undefined) {
1089
1282
  clip.provider = op.provider;
1090
- if (op.model !== undefined)
1283
+ }
1284
+ if (op.model !== undefined) {
1091
1285
  clip.model = op.model;
1092
- if (op.voice !== undefined)
1286
+ }
1287
+ if (op.voice !== undefined) {
1093
1288
  clip.voice = op.voice;
1094
- if (op.width !== undefined)
1289
+ }
1290
+ if (op.width !== undefined) {
1095
1291
  clip.width = op.width;
1096
- if (op.height !== undefined)
1292
+ }
1293
+ if (op.height !== undefined) {
1097
1294
  clip.height = op.height;
1098
- if (op.aspectRatio !== undefined)
1295
+ }
1296
+ if (op.aspectRatio !== undefined) {
1099
1297
  clip.aspectRatio = op.aspectRatio;
1100
- if (op.resolution !== undefined)
1298
+ }
1299
+ if (op.resolution !== undefined) {
1101
1300
  clip.resolution = op.resolution;
1102
- if (op.strength !== undefined)
1301
+ }
1302
+ if (op.strength !== undefined) {
1103
1303
  clip.strength = op.strength;
1304
+ }
1104
1305
  if (op.numInferenceSteps !== undefined) {
1105
1306
  clip.numInferenceSteps = op.numInferenceSteps;
1106
1307
  }
1107
- if (op.regenerate)
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) {
1108
1319
  clip.status = "queued";
1320
+ }
1109
1321
  scope.touch(clip.id);
1110
1322
  return { ok: true, clip: scope.clipOut(clip) };
1111
1323
  }
1112
1324
  case "animate_clip": {
1113
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
+ }
1114
1330
  const built = [];
1115
1331
  for (const input of op.animations) {
1116
1332
  if (input.preset === CUSTOM_ANIMATION_PRESET_ID) {
@@ -1136,6 +1352,7 @@ async function runOp(scope, op) {
1136
1352
  built.push({
1137
1353
  id: scope.ctx.newId("anim"),
1138
1354
  role: input.role,
1355
+ enabled: input.enabled,
1139
1356
  preset: input.preset,
1140
1357
  durationMs: timing?.durationMs ?? input.durationMs ?? preset.defaultDurationMs,
1141
1358
  delayMs: input.delayMs,
@@ -1209,10 +1426,12 @@ async function runOp(scope, op) {
1209
1426
  timeMs: Math.round(op.timeMs),
1210
1427
  label: op.label ?? ""
1211
1428
  };
1212
- if (op.color !== undefined)
1429
+ if (op.color !== undefined) {
1213
1430
  marker.color = op.color;
1214
- if (op.note !== undefined)
1431
+ }
1432
+ if (op.note !== undefined) {
1215
1433
  marker.note = op.note;
1434
+ }
1216
1435
  state.markers.push(marker);
1217
1436
  return { ok: true, marker: { ...marker } };
1218
1437
  }
@@ -1276,12 +1495,15 @@ async function runOp(scope, op) {
1276
1495
  : beatCountToCover(op.bpm, offsetMs, reachMs)
1277
1496
  });
1278
1497
  const options = {};
1279
- if (op.tolerance_ms !== undefined)
1498
+ if (op.tolerance_ms !== undefined) {
1280
1499
  options.toleranceMs = op.tolerance_ms;
1281
- if (op.mode !== undefined)
1500
+ }
1501
+ if (op.mode !== undefined) {
1282
1502
  options.mode = op.mode;
1283
- if (op.action !== undefined)
1503
+ }
1504
+ if (op.action !== undefined) {
1284
1505
  options.action = op.action;
1506
+ }
1285
1507
  const result = snapClipsToGrid(targeted.map((clip) => ({
1286
1508
  id: clip.id,
1287
1509
  startMs: clip.startMs,
@@ -1299,11 +1521,10 @@ async function runOp(scope, op) {
1299
1521
  scope.applyMove(clip, { startMs: entry.after.startMs });
1300
1522
  }
1301
1523
  else {
1302
- let trimmed = clip;
1303
- if (entry.after.startMs !== entry.before.startMs) {
1304
- trimmed = scope.applyTrimStart(clip, entry.after.startMs);
1305
- }
1306
- scope.applyTrim(trimmed, { durationMs: entry.after.durationMs });
1524
+ const trimmed = scope.applyTrim(clip, {
1525
+ durationMs: entry.after.durationMs
1526
+ });
1527
+ scope.applyMove(trimmed, { startMs: entry.after.startMs });
1307
1528
  }
1308
1529
  }
1309
1530
  catch (error) {
@@ -1342,8 +1563,8 @@ async function runOp(scope, op) {
1342
1563
  toleranceMs: result.toleranceMs,
1343
1564
  mode: result.mode,
1344
1565
  action: result.action,
1345
- snapped: result.snapped,
1346
- skipped: result.skipped + missing.length,
1566
+ snapped: reported.filter((entry) => entry.snapped).length,
1567
+ skipped: reported.filter((entry) => !entry.snapped).length,
1347
1568
  clips: reported
1348
1569
  };
1349
1570
  }
@@ -1500,8 +1721,9 @@ async function runOp(scope, op) {
1500
1721
  scope.mediaTracks = scope.mediaTracks.filter((t) => t.id !== op.trackId);
1501
1722
  const unboundClipIds = [];
1502
1723
  scope.clips = scope.clips.map((c) => {
1503
- if (c.trackBinding?.trackId !== op.trackId)
1724
+ if (c.trackBinding?.trackId !== op.trackId) {
1504
1725
  return c;
1726
+ }
1505
1727
  unboundClipIds.push(c.id);
1506
1728
  const { trackBinding: _dropped, ...rest } = c;
1507
1729
  return rest;
@@ -1523,15 +1745,18 @@ async function runOp(scope, op) {
1523
1745
  "today would be a no-op, so the call is refused instead.");
1524
1746
  }
1525
1747
  const binding = { trackId: op.trackId, mode: op.mode };
1526
- if (op.offset !== undefined)
1748
+ if (op.offset !== undefined) {
1527
1749
  binding.offset = op.offset;
1528
- if (op.scale !== undefined)
1750
+ }
1751
+ if (op.scale !== undefined) {
1529
1752
  binding.scale = op.scale;
1753
+ }
1530
1754
  if (op.rotationOffset !== undefined) {
1531
1755
  binding.rotationOffset = op.rotationOffset;
1532
1756
  }
1533
- if (op.smoothing !== undefined)
1757
+ if (op.smoothing !== undefined) {
1534
1758
  binding.smoothing = op.smoothing;
1759
+ }
1535
1760
  const next = { ...clip, trackBinding: binding };
1536
1761
  scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1537
1762
  scope.touch(clip.id);
@@ -1547,6 +1772,316 @@ async function runOp(scope, op) {
1547
1772
  scope.touch(clip.id);
1548
1773
  return { ok: true, clip: scope.clipOut(next) };
1549
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)
1790
+ });
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
+ }
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);
1800
+ return { ok: true, clip: scope.clipOut(clip) };
1801
+ }
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);
1829
+ }
1830
+ else {
1831
+ instrument = structuredClone(op.instrument);
1832
+ }
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");
1837
+ }
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;
1875
+ }
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);
1879
+ 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")}`);
1881
+ }
1882
+ 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
+ };
2027
+ }
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 } };
2072
+ }
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);
2080
+ }
2081
+ Object.assign(scope.state, outcome.state);
2082
+ scope.touch(...outcome.changedClipIds);
2083
+ return outcome.result;
2084
+ }
1550
2085
  default: {
1551
2086
  const unknown = op;
1552
2087
  throw new Error(`Unknown timeline op "${unknown.op}".`);
@@ -1556,12 +2091,16 @@ async function runOp(scope, op) {
1556
2091
  /** Deep copy of the document, so a failed op leaves the caller's state alone. */
1557
2092
  function cloneState(state) {
1558
2093
  return {
2094
+ ...state,
2095
+ tempo: state.tempo,
2096
+ setup: state.setup ? structuredClone(state.setup) : state.setup,
1559
2097
  fps: state.fps,
1560
2098
  width: state.width,
1561
2099
  height: state.height,
1562
2100
  tracks: state.tracks.map((t) => structuredClone(t)),
1563
2101
  clips: state.clips.map((c) => structuredClone(c)),
1564
2102
  markers: state.markers.map((m) => structuredClone(m)),
2103
+ storyboardMaterializations: state.storyboardMaterializations?.map((entry) => structuredClone(entry)),
1565
2104
  mediaTracks: (state.mediaTracks ?? []).map((t) => structuredClone(t)),
1566
2105
  playheadMs: state.playheadMs,
1567
2106
  selectedClipIds: [...state.selectedClipIds]
@@ -1592,4 +2131,107 @@ export async function applyTimelineOp(state, op, ctx) {
1592
2131
  };
1593
2132
  }
1594
2133
  }
2134
+ function serializeTracks(state) {
2135
+ const clipCount = new Map();
2136
+ for (const clip of state.clips) {
2137
+ clipCount.set(clip.trackId, (clipCount.get(clip.trackId) ?? 0) + 1);
2138
+ }
2139
+ return state.tracks.map((track) => serializeTrack(state, track, clipCount.get(track.id) ?? 0));
2140
+ }
2141
+ function runTrackOp(scope, op) {
2142
+ const state = scope.state;
2143
+ switch (op.op) {
2144
+ case "add_track": {
2145
+ const track = scope.addTrack(op.type, op.name);
2146
+ return { ok: true, track: scope.trackOut(track) };
2147
+ }
2148
+ case "move_track": {
2149
+ const { target, toIndex, before, after } = resolveMoveTrackArgs(op);
2150
+ const track = scope.resolveTrack(target);
2151
+ const destination = {};
2152
+ if (toIndex !== undefined) {
2153
+ destination.toIndex = toIndex;
2154
+ }
2155
+ if (before !== undefined) {
2156
+ destination.beforeId = scope.resolveTrack(before).id;
2157
+ }
2158
+ if (after !== undefined) {
2159
+ destination.afterId = scope.resolveTrack(after).id;
2160
+ }
2161
+ const orderedIds = moveTrackOrder(scope.tracks, track.id, destination);
2162
+ const byId = new Map(scope.tracks.map((t) => [t.id, t]));
2163
+ // The array order is what `get_state` prints, so keep it and the indices
2164
+ // saying the same thing.
2165
+ scope.tracks.length = 0;
2166
+ orderedIds.forEach((id, i) => {
2167
+ const moved = byId.get(id);
2168
+ if (!moved) {
2169
+ throw new Error(`Track "${id}" no longer exists.`);
2170
+ }
2171
+ moved.index = i;
2172
+ scope.tracks.push(moved);
2173
+ });
2174
+ return {
2175
+ ok: true,
2176
+ track: scope.trackOut(track),
2177
+ tracks: serializeTracks(scope.state)
2178
+ };
2179
+ }
2180
+ case "delete_track": {
2181
+ const { target, deleteClips } = resolveDeleteTrackArgs(op);
2182
+ const track = scope.resolveTrack(target);
2183
+ const onIt = scope.clips.filter((c) => c.trackId === track.id);
2184
+ if (onIt.length > 0 && !deleteClips) {
2185
+ throw new Error(`Track "${track.name}" still holds ${onIt.length} clip(s): ` +
2186
+ `${onIt.map((c) => c.id).join(", ")}. Move them first, or pass ` +
2187
+ "deleteClips: true to delete them with the track.");
2188
+ }
2189
+ const removedClipIds = onIt.map((c) => c.id);
2190
+ const removed = new Set(removedClipIds);
2191
+ const kept = scope.clips.filter((c) => c.trackId !== track.id);
2192
+ scope.clips.length = 0;
2193
+ scope.clips.push(...kept);
2194
+ // A parent that went with the track would leave its children pointing at
2195
+ // a clip that no longer exists, which the validator reads as a broken
2196
+ // document rather than a deletion.
2197
+ for (const clip of scope.clips) {
2198
+ if (clip.parentId && removed.has(clip.parentId)) {
2199
+ delete clip.parentId;
2200
+ scope.touch(clip.id);
2201
+ }
2202
+ }
2203
+ scope.touch(...removedClipIds);
2204
+ state.selectedClipIds = state.selectedClipIds.filter((id) => !removed.has(id));
2205
+ const remaining = scope.tracks.filter((t) => t.id !== track.id);
2206
+ scope.tracks.length = 0;
2207
+ // Index is z-order, so the stack has to close over the gap.
2208
+ remaining.forEach((t, i) => {
2209
+ t.index = i;
2210
+ scope.tracks.push(t);
2211
+ });
2212
+ return {
2213
+ ok: true,
2214
+ deleted: { id: track.id, name: track.name, type: track.type },
2215
+ deletedClipIds: removedClipIds,
2216
+ tracks: serializeTracks(scope.state)
2217
+ };
2218
+ }
2219
+ }
2220
+ }
2221
+ /** Synchronous document edits for hosts whose editor actions are synchronous. */
2222
+ export function applyTimelineTrackOp(state, op, ctx) {
2223
+ const scope = new OpScope(cloneState(state), ctx);
2224
+ try {
2225
+ const result = runTrackOp(scope, op);
2226
+ return { state: scope.state, result, changedClipIds: [...scope.changed] };
2227
+ }
2228
+ catch (error) {
2229
+ return {
2230
+ state,
2231
+ result: {},
2232
+ changedClipIds: [],
2233
+ error: error instanceof Error ? error.message : String(error)
2234
+ };
2235
+ }
2236
+ }
1595
2237
  //# sourceMappingURL=apply.js.map