@nodetool-ai/timeline 0.8.1 → 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 (226) 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/authoring.d.ts.map +1 -1
  6. package/dist/authoring.js +46 -6
  7. package/dist/authoring.js.map +1 -1
  8. package/dist/clipAudio.d.ts +32 -0
  9. package/dist/clipAudio.d.ts.map +1 -0
  10. package/dist/clipAudio.js +70 -0
  11. package/dist/clipAudio.js.map +1 -0
  12. package/dist/clipSpeed.d.ts +17 -0
  13. package/dist/clipSpeed.d.ts.map +1 -0
  14. package/dist/clipSpeed.js +58 -0
  15. package/dist/clipSpeed.js.map +1 -0
  16. package/dist/composition.d.ts +11 -1
  17. package/dist/composition.d.ts.map +1 -1
  18. package/dist/composition.js +58 -12
  19. package/dist/composition.js.map +1 -1
  20. package/dist/dropResolve.d.ts +14 -6
  21. package/dist/dropResolve.d.ts.map +1 -1
  22. package/dist/dropResolve.js +113 -37
  23. package/dist/dropResolve.js.map +1 -1
  24. package/dist/examples/node.d.ts +18 -0
  25. package/dist/examples/node.d.ts.map +1 -1
  26. package/dist/examples/node.js +26 -0
  27. package/dist/examples/node.js.map +1 -1
  28. package/dist/finish-storyboard.d.ts +36 -0
  29. package/dist/finish-storyboard.d.ts.map +1 -0
  30. package/dist/finish-storyboard.js +561 -0
  31. package/dist/finish-storyboard.js.map +1 -0
  32. package/dist/fonts/google-fonts-fetch.d.ts +53 -0
  33. package/dist/fonts/google-fonts-fetch.d.ts.map +1 -0
  34. package/dist/fonts/google-fonts-fetch.js +184 -0
  35. package/dist/fonts/google-fonts-fetch.js.map +1 -0
  36. package/dist/fonts/google-fonts-node.d.ts +32 -0
  37. package/dist/fonts/google-fonts-node.d.ts.map +1 -0
  38. package/dist/fonts/google-fonts-node.js +60 -0
  39. package/dist/fonts/google-fonts-node.js.map +1 -0
  40. package/dist/fonts/google-fonts.d.ts +111 -0
  41. package/dist/fonts/google-fonts.d.ts.map +1 -0
  42. package/dist/fonts/google-fonts.js +184 -0
  43. package/dist/fonts/google-fonts.js.map +1 -0
  44. package/dist/fonts/index.d.ts +1 -0
  45. package/dist/fonts/index.d.ts.map +1 -1
  46. package/dist/fonts/index.js +1 -0
  47. package/dist/fonts/index.js.map +1 -1
  48. package/dist/group.d.ts +16 -4
  49. package/dist/group.d.ts.map +1 -1
  50. package/dist/group.js +53 -6
  51. package/dist/group.js.map +1 -1
  52. package/dist/index.d.ts +9 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +9 -0
  55. package/dist/index.js.map +1 -1
  56. package/dist/interchange.d.ts +8 -0
  57. package/dist/interchange.d.ts.map +1 -1
  58. package/dist/interchange.js +217 -27
  59. package/dist/interchange.js.map +1 -1
  60. package/dist/interchangeImport.d.ts +87 -0
  61. package/dist/interchangeImport.d.ts.map +1 -0
  62. package/dist/interchangeImport.js +404 -0
  63. package/dist/interchangeImport.js.map +1 -0
  64. package/dist/keyframes.d.ts +12 -1
  65. package/dist/keyframes.d.ts.map +1 -1
  66. package/dist/keyframes.js +78 -21
  67. package/dist/keyframes.js.map +1 -1
  68. package/dist/linked.d.ts +2 -1
  69. package/dist/linked.d.ts.map +1 -1
  70. package/dist/linked.js +19 -11
  71. package/dist/linked.js.map +1 -1
  72. package/dist/mediaTrack.d.ts +11 -0
  73. package/dist/mediaTrack.d.ts.map +1 -1
  74. package/dist/mediaTrack.js +25 -0
  75. package/dist/mediaTrack.js.map +1 -1
  76. package/dist/midi/edit.d.ts +5 -0
  77. package/dist/midi/edit.d.ts.map +1 -1
  78. package/dist/midi/edit.js +2 -1
  79. package/dist/midi/edit.js.map +1 -1
  80. package/dist/midi/engines/kits.d.ts +2 -0
  81. package/dist/midi/engines/kits.d.ts.map +1 -1
  82. package/dist/midi/engines/kits.js +146 -0
  83. package/dist/midi/engines/kits.js.map +1 -1
  84. package/dist/midi/grid.d.ts.map +1 -1
  85. package/dist/midi/grid.js +8 -4
  86. package/dist/midi/grid.js.map +1 -1
  87. package/dist/midi/index.d.ts +1 -0
  88. package/dist/midi/index.d.ts.map +1 -1
  89. package/dist/midi/index.js +1 -0
  90. package/dist/midi/index.js.map +1 -1
  91. package/dist/midi/instrument.d.ts.map +1 -1
  92. package/dist/midi/instrument.js +5 -0
  93. package/dist/midi/instrument.js.map +1 -1
  94. package/dist/midi/presets.d.ts.map +1 -1
  95. package/dist/midi/presets.js +251 -1
  96. package/dist/midi/presets.js.map +1 -1
  97. package/dist/midi/sampler.d.ts +15 -0
  98. package/dist/midi/sampler.d.ts.map +1 -0
  99. package/dist/midi/sampler.js +72 -0
  100. package/dist/midi/sampler.js.map +1 -0
  101. package/dist/midi/tempo.d.ts.map +1 -1
  102. package/dist/midi/tempo.js +8 -0
  103. package/dist/midi/tempo.js.map +1 -1
  104. package/dist/midi/voice.d.ts +4 -1
  105. package/dist/midi/voice.d.ts.map +1 -1
  106. package/dist/midi/voice.js +8 -4
  107. package/dist/midi/voice.js.map +1 -1
  108. package/dist/ops/apply.d.ts +15 -1
  109. package/dist/ops/apply.d.ts.map +1 -1
  110. package/dist/ops/apply.js +2123 -1090
  111. package/dist/ops/apply.js.map +1 -1
  112. package/dist/ops/index.d.ts +3 -2
  113. package/dist/ops/index.d.ts.map +1 -1
  114. package/dist/ops/index.js +3 -2
  115. package/dist/ops/index.js.map +1 -1
  116. package/dist/ops/op.d.ts +15 -3
  117. package/dist/ops/op.d.ts.map +1 -1
  118. package/dist/ops/op.js +17 -8
  119. package/dist/ops/op.js.map +1 -1
  120. package/dist/ops/parse.d.ts +6 -0
  121. package/dist/ops/parse.d.ts.map +1 -0
  122. package/dist/ops/parse.js +351 -0
  123. package/dist/ops/parse.js.map +1 -0
  124. package/dist/ops/serialize.d.ts +9 -1
  125. package/dist/ops/serialize.d.ts.map +1 -1
  126. package/dist/ops/serialize.js +19 -2
  127. package/dist/ops/serialize.js.map +1 -1
  128. package/dist/ops/types.d.ts +30 -8
  129. package/dist/ops/types.d.ts.map +1 -1
  130. package/dist/ops/types.js +2 -5
  131. package/dist/ops/types.js.map +1 -1
  132. package/dist/production.d.ts.map +1 -1
  133. package/dist/production.js +7 -0
  134. package/dist/production.js.map +1 -1
  135. package/dist/reassemble.d.ts +3 -1
  136. package/dist/reassemble.d.ts.map +1 -1
  137. package/dist/reassemble.js +7 -0
  138. package/dist/reassemble.js.map +1 -1
  139. package/dist/render/canvas2d.d.ts +3 -3
  140. package/dist/render/canvas2d.d.ts.map +1 -1
  141. package/dist/render/draw.d.ts +72 -3
  142. package/dist/render/draw.d.ts.map +1 -1
  143. package/dist/render/draw.js +168 -4
  144. package/dist/render/draw.js.map +1 -1
  145. package/dist/render/frameCompositor.d.ts +31 -3
  146. package/dist/render/frameCompositor.d.ts.map +1 -1
  147. package/dist/render/frameCompositor.js +58 -10
  148. package/dist/render/frameCompositor.js.map +1 -1
  149. package/dist/render/layout.d.ts +27 -3
  150. package/dist/render/layout.d.ts.map +1 -1
  151. package/dist/render/layout.js +464 -103
  152. package/dist/render/layout.js.map +1 -1
  153. package/dist/render/sceneModel.d.ts +18 -6
  154. package/dist/render/sceneModel.d.ts.map +1 -1
  155. package/dist/render/sceneModel.js +288 -93
  156. package/dist/render/sceneModel.js.map +1 -1
  157. package/dist/render/svgPath.d.ts +36 -8
  158. package/dist/render/svgPath.d.ts.map +1 -1
  159. package/dist/render/svgPath.js +303 -30
  160. package/dist/render/svgPath.js.map +1 -1
  161. package/dist/render/temporal.d.ts +9 -1
  162. package/dist/render/temporal.d.ts.map +1 -1
  163. package/dist/render/temporal.js +18 -1
  164. package/dist/render/temporal.js.map +1 -1
  165. package/dist/render/textLayout.d.ts +42 -0
  166. package/dist/render/textLayout.d.ts.map +1 -1
  167. package/dist/render/textLayout.js +59 -4
  168. package/dist/render/textLayout.js.map +1 -1
  169. package/dist/render/transform.d.ts +10 -0
  170. package/dist/render/transform.d.ts.map +1 -1
  171. package/dist/render/transform.js +15 -5
  172. package/dist/render/transform.js.map +1 -1
  173. package/dist/rippleEdit.d.ts +20 -3
  174. package/dist/rippleEdit.d.ts.map +1 -1
  175. package/dist/rippleEdit.js +89 -17
  176. package/dist/rippleEdit.js.map +1 -1
  177. package/dist/shotLink.d.ts +47 -0
  178. package/dist/shotLink.d.ts.map +1 -0
  179. package/dist/shotLink.js +92 -0
  180. package/dist/shotLink.js.map +1 -0
  181. package/dist/source-merge.d.ts +84 -0
  182. package/dist/source-merge.d.ts.map +1 -0
  183. package/dist/source-merge.js +200 -0
  184. package/dist/source-merge.js.map +1 -0
  185. package/dist/splitClip.d.ts.map +1 -1
  186. package/dist/splitClip.js +16 -2
  187. package/dist/splitClip.js.map +1 -1
  188. package/dist/storyboard.d.ts +20 -3
  189. package/dist/storyboard.d.ts.map +1 -1
  190. package/dist/storyboard.js +62 -28
  191. package/dist/storyboard.js.map +1 -1
  192. package/dist/storyboardDesignFrame.d.ts +15 -0
  193. package/dist/storyboardDesignFrame.d.ts.map +1 -0
  194. package/dist/storyboardDesignFrame.js +44 -0
  195. package/dist/storyboardDesignFrame.js.map +1 -0
  196. package/dist/storyboardValidation.d.ts +10 -0
  197. package/dist/storyboardValidation.d.ts.map +1 -0
  198. package/dist/storyboardValidation.js +47 -0
  199. package/dist/storyboardValidation.js.map +1 -0
  200. package/dist/takes.d.ts.map +1 -1
  201. package/dist/takes.js +15 -2
  202. package/dist/takes.js.map +1 -1
  203. package/dist/testing/host-ops.d.ts +16 -0
  204. package/dist/testing/host-ops.d.ts.map +1 -0
  205. package/dist/testing/host-ops.js +378 -0
  206. package/dist/testing/host-ops.js.map +1 -0
  207. package/dist/testing/index.d.ts +3 -0
  208. package/dist/testing/index.d.ts.map +1 -0
  209. package/dist/testing/index.js +3 -0
  210. package/dist/testing/index.js.map +1 -0
  211. package/dist/testing/ops.d.ts +30 -0
  212. package/dist/testing/ops.d.ts.map +1 -0
  213. package/dist/testing/ops.js +814 -0
  214. package/dist/testing/ops.js.map +1 -0
  215. package/dist/transitionAtCut.d.ts +29 -5
  216. package/dist/transitionAtCut.d.ts.map +1 -1
  217. package/dist/transitionAtCut.js +69 -33
  218. package/dist/transitionAtCut.js.map +1 -1
  219. package/dist/trimClip.d.ts +5 -8
  220. package/dist/trimClip.d.ts.map +1 -1
  221. package/dist/trimClip.js +38 -2
  222. package/dist/trimClip.js.map +1 -1
  223. package/dist/types.d.ts +172 -20
  224. package/dist/types.d.ts.map +1 -1
  225. package/dist/types.js.map +1 -1
  226. package/package.json +34 -4
package/dist/ops/apply.js CHANGED
@@ -9,24 +9,37 @@
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, moveUnitIds, trimGroup, ungroup } from "../group.js";
26
+ import { isMediaTrackStale, splitClipMediaTracks, 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";
32
+ import { msToTicks } from "../midi/ticks.js";
20
33
  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";
34
+ import { addReframeKeyframe, clearReframe, mediaTrackCanDriveReframe } from "../reframe.js";
35
+ import { adaptSequenceFormat } from "../retarget.js";
36
+ import { sourceRate } from "../sourceRate.js";
24
37
  import { splitClip } from "../splitClip.js";
25
38
  import { activeTakeIdOf, deleteTake as deleteTakeOnClip, renameTake as renameTakeOnClip, selectTake } from "../takes.js";
26
39
  import { moveTrackOrder } from "../trackOrder.js";
27
- import { trimClip } from "../trimClip.js";
28
- import { applyTransitionAtCutCandidate, planTransitionAtCut } from "../transitionAtCut.js";
29
- import { resliceTracksForSplitClip, resliceTracksForTrimmedClip } from "../mediaTrack.js";
40
+ import { applyTransitionAtCutCandidate, transitionGrowthMs, transitionGrowthUnit, transitionLengthAtCut, planTransitionAtCut } from "../transitionAtCut.js";
41
+ import { retimeCaption, trimClip } from "../trimClip.js";
42
+ import { retimeClipSpeed } from "../clipSpeed.js";
30
43
  import { serializeClip, serializeMediaTrack, serializeTrack } from "./serialize.js";
31
44
  /** Units a failed lookup names before it stops and points at get_state. */
32
45
  const MAX_LISTED_UNITS = 12;
@@ -44,26 +57,71 @@ export function resolveClipTarget(state, target) {
44
57
  throw new Error(`"selected" requires exactly one selected clip (currently ${selected.length}).`);
45
58
  }
46
59
  const clip = state.clips.find((c) => c.id === selected[0]);
47
- if (!clip)
60
+ if (!clip) {
48
61
  throw new Error("Selected clip no longer exists.");
62
+ }
49
63
  return clip;
50
64
  }
51
65
  const byId = state.clips.find((c) => c.id === target);
52
- if (byId)
66
+ if (byId) {
53
67
  return byId;
68
+ }
69
+ const prefix = resolveShortId(state.clips, target, "clip");
70
+ if (prefix) {
71
+ return prefix;
72
+ }
54
73
  const lower = target.toLowerCase();
55
74
  const byName = state.clips.find((c) => c.name.toLowerCase() === lower);
56
- if (byName)
75
+ if (byName) {
57
76
  return byName;
77
+ }
58
78
  throw new Error(`No clip found matching "${target}". ${listUnits(state.clips, "clip")}`);
59
79
  }
80
+ function resolveShortId(units, target, kind) {
81
+ if (!isShortResourceId(target)) {
82
+ return undefined;
83
+ }
84
+ const matches = units.filter((unit) => unit.id.startsWith(target));
85
+ if (matches.length > 1) {
86
+ throw new Error(`Prefix "${target}" matches more than one ${kind}; use a full id.`);
87
+ }
88
+ return matches[0];
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
+ }
60
117
  /**
61
118
  * Name the units a caller could have meant, capped: a 200-clip sequence
62
119
  * listing all of them is one an agent stops reading.
63
120
  */
64
121
  function listUnits(units, kind) {
65
- if (units.length === 0)
122
+ if (units.length === 0) {
66
123
  return `The timeline has no ${kind}s yet.`;
124
+ }
67
125
  const shown = units
68
126
  .slice(0, MAX_LISTED_UNITS)
69
127
  .map((u) => `${u.id} ("${u.name}")`)
@@ -135,8 +193,9 @@ class OpScope {
135
193
  this.ctx = ctx;
136
194
  }
137
195
  touch(...ids) {
138
- for (const id of ids)
196
+ for (const id of ids) {
139
197
  this.changed.add(id);
198
+ }
140
199
  }
141
200
  get tracks() {
142
201
  return this.state.tracks;
@@ -169,20 +228,56 @@ class OpScope {
169
228
  name: name ?? `${capitalize(type)} ${index + 1}`,
170
229
  index
171
230
  });
231
+ if (type === "midi") {
232
+ track.instrument = structuredClone(this.ctx.defaultMidiInstrument ?? DEFAULT_MIDI_INSTRUMENT);
233
+ this.state.tempo ??= structuredClone(DEFAULT_TEMPO);
234
+ }
172
235
  this.tracks.push(track);
173
236
  return track;
174
237
  }
175
- findOrCreateTrack(type) {
176
- return this.tracks.find((t) => t.type === type) ?? this.addTrack(type);
238
+ /** The first unlocked track of `type`, or a new one: a lock refuses writes. */
239
+ findOrCreateTrack(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
+ }
177
261
  }
178
262
  resolveTrack(idOrName) {
179
263
  const byId = this.tracks.find((t) => t.id === idOrName);
180
- if (byId)
264
+ if (byId) {
181
265
  return byId;
266
+ }
267
+ if (isShortResourceId(idOrName)) {
268
+ const matches = this.tracks.filter((track) => track.id.startsWith(idOrName));
269
+ if (matches.length === 1 && matches[0]) {
270
+ return matches[0];
271
+ }
272
+ if (matches.length > 1) {
273
+ throw new Error(`Short track id "${idOrName}" matches more than one track; use the full id or name.`);
274
+ }
275
+ }
182
276
  const lower = idOrName.toLowerCase();
183
277
  const byName = this.tracks.find((t) => t.name.toLowerCase() === lower);
184
- if (byName)
278
+ if (byName) {
185
279
  return byName;
280
+ }
186
281
  throw new Error(`No track found matching "${idOrName}". ${this.validUnits(this.tracks, "track")}`);
187
282
  }
188
283
  trackEndMs(trackId) {
@@ -190,29 +285,218 @@ class OpScope {
190
285
  .filter((c) => c.trackId === trackId)
191
286
  .reduce((m, c) => Math.max(m, c.startMs + c.durationMs), 0);
192
287
  }
288
+ resolveMidiTrack(target) {
289
+ const track = this.resolveTrack(target);
290
+ if (track.type !== "midi") {
291
+ 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")}`);
292
+ }
293
+ return track;
294
+ }
295
+ resolveMidiClip(target) {
296
+ const clip = this.resolveClip(target);
297
+ if (clip.mediaType !== "midi") {
298
+ throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip — only a midi clip carries notes. Place one with add_midi_clip.`);
299
+ }
300
+ return clip;
301
+ }
302
+ buildNotes(input, name) {
303
+ const reserved = new Set((input ?? []).flatMap((note) => (note.id ? [note.id] : [])));
304
+ const mintNote = () => {
305
+ let id = this.ctx.newId("note");
306
+ while (reserved.has(id)) {
307
+ id = this.ctx.newId("note");
308
+ }
309
+ reserved.add(id);
310
+ return id;
311
+ };
312
+ const notes = (input ?? []).map((n) => createMidiNote({
313
+ id: n.id ?? mintNote(),
314
+ pitch: n.pitch,
315
+ velocity: n.velocity,
316
+ startTick: n.start_tick,
317
+ durationTick: n.duration_tick
318
+ }));
319
+ const problems = validateNotes(notes);
320
+ if (problems.length) {
321
+ throw new Error(`Clip "${name}" was not given its notes — ${problems.length} problem(s): ` +
322
+ problems
323
+ .map((p) => (p.noteId ? `${p.noteId}: ${p.message}` : p.message))
324
+ .join(" "));
325
+ }
326
+ return sortNotes(notes);
327
+ }
193
328
  resolveClip(target) {
194
329
  return resolveClipTarget(this.state, target);
195
330
  }
331
+ editTargets(clip) {
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);
339
+ return targets;
340
+ }
341
+ assertPictureTrack(track) {
342
+ if (track.type !== "video" && track.type !== "overlay") {
343
+ throw new Error(`Authored clips require a video or overlay track; "${track.name}" is ${track.type}.`);
344
+ }
345
+ }
196
346
  /** Swap an engine-returned clip into `clips`, keeping the array's order. */
197
347
  replaceClip(clip, next) {
198
348
  const index = this.clips.findIndex((c) => c.id === clip.id);
199
- if (index >= 0)
349
+ if (index >= 0) {
200
350
  this.clips[index] = next;
351
+ }
201
352
  return next;
202
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
+ }
203
401
  /**
204
402
  * The body of `trim_clip`, shared with `set_clip_params`: a caller that
205
403
  * sends `durationMs` alongside a style change means the same edit either
206
404
  * way, and two copies of the group-trim rule would drift.
207
405
  */
208
- applyTrim(clip, patch) {
406
+ applyTrim(clip, patch, maxSourceMs) {
407
+ if (patch.durationMs === undefined &&
408
+ patch.inPointMs === undefined &&
409
+ patch.outPointMs === undefined) {
410
+ return clip;
411
+ }
412
+ if (patch.inPointMs !== undefined && patch.inPointMs < 0) {
413
+ throw new Error("inPointMs cannot be negative.");
414
+ }
415
+ const prospective = patch.durationMs !== undefined && !isGroupClip(clip)
416
+ ? trimSourceBounded(clip, patch.durationMs - clip.durationMs, maxSourceMs)
417
+ : clip;
418
+ const sourceIn = patch.inPointMs ?? prospective.inPointMs ?? 0;
419
+ const sourceOut = patch.outPointMs ?? prospective.outPointMs;
420
+ if (sourceOut !== undefined && sourceOut <= sourceIn) {
421
+ throw new Error("outPointMs must be greater than inPointMs.");
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
+ }
428
+ if (isGroupClip(clip) &&
429
+ (patch.inPointMs !== undefined || patch.outPointMs !== undefined)) {
430
+ throw new Error("Groups carry no source media; trim their duration instead.");
431
+ }
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
+ }
461
+ if (targets.length > 1 &&
462
+ patch.durationMs !== undefined &&
463
+ !isGroupClip(clip)) {
464
+ const delta = patch.durationMs - clip.durationMs;
465
+ const trimmedTargets = targets.map((target) => {
466
+ if (target.durationMs + delta <= 0) {
467
+ throw new Error("Linked trim would remove a clip. Shorten the trim or unlink it first.");
468
+ }
469
+ const trimmed = target.id === clip.id
470
+ ? trimSourceBounded(target, delta, maxSourceMs)
471
+ : trimClip(target, "end", delta);
472
+ if (target.id === clip.id) {
473
+ if (patch.inPointMs !== undefined) {
474
+ trimmed.inPointMs = patch.inPointMs;
475
+ }
476
+ if (patch.outPointMs !== undefined) {
477
+ trimmed.outPointMs = patch.outPointMs;
478
+ }
479
+ }
480
+ return { target, trimmed };
481
+ });
482
+ for (const { target, trimmed } of trimmedTargets) {
483
+ this.replaceClip(target, trimmed);
484
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, trimmed);
485
+ this.touch(trimmed.id);
486
+ }
487
+ return this.resolveClip(clip.id);
488
+ }
209
489
  // A group carries what it holds (D4): shortening one pulls its children
210
490
  // inside the window that leaves, rather than leaving them hanging past an
211
491
  // edge nothing draws.
212
492
  if (isGroupClip(clip) && patch.durationMs !== undefined) {
213
493
  this.clips = trimGroup(this.clips, clip.id, "end", patch.durationMs - clip.durationMs);
214
494
  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));
495
+ for (const target of targets) {
496
+ const trimmed = this.resolveClip(target.id);
497
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, trimmed);
498
+ this.touch(trimmed.id);
499
+ }
216
500
  this.touch(next.id);
217
501
  return next;
218
502
  }
@@ -223,67 +507,119 @@ class OpScope {
223
507
  if (patch.durationMs <= 0) {
224
508
  throw new Error(`durationMs must be greater than 0 (got ${patch.durationMs}); delete the clip instead of trimming it to nothing`);
225
509
  }
226
- next = this.replaceClip(clip, trimClip(clip, "end", patch.durationMs - clip.durationMs));
510
+ next = this.replaceClip(clip, trimSourceBounded(clip, patch.durationMs - clip.durationMs, maxSourceMs));
227
511
  }
228
- if (patch.inPointMs !== undefined)
512
+ if (patch.inPointMs !== undefined) {
229
513
  next.inPointMs = patch.inPointMs;
230
- if (patch.outPointMs !== undefined)
514
+ }
515
+ if (patch.outPointMs !== undefined) {
231
516
  next.outPointMs = patch.outPointMs;
517
+ }
232
518
  if (patch.durationMs !== undefined ||
233
519
  patch.inPointMs !== undefined ||
234
520
  patch.outPointMs !== undefined) {
235
521
  this.touch(next.id);
236
522
  }
523
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, next);
237
524
  return next;
238
525
  }
239
526
  /**
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.
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).
243
530
  */
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);
531
+ applyHeadTrim(clip, deltaMs) {
532
+ const targets = this.editTargets(clip);
249
533
  if (isGroupClip(clip)) {
250
534
  this.clips = trimGroup(this.clips, clip.id, "start", deltaMs);
251
- return this.clips.find((c) => c.id === clip.id);
252
535
  }
253
- return this.replaceClip(clip, trimClip(clip, "start", deltaMs));
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);
254
553
  }
255
554
  /** The body of `move_clip`, shared with `set_clip_params`. */
256
555
  applyMove(clip, patch) {
556
+ if (patch.startMs === undefined && patch.trackId === undefined) {
557
+ return clip;
558
+ }
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
+ }
570
+ if (targets.length > 1 &&
571
+ patch.startMs !== undefined &&
572
+ !isGroupClip(clip)) {
573
+ const minimum = Math.min(...targets.map((target) => target.startMs));
574
+ const delta = Math.max(-minimum, patch.startMs - clip.startMs);
575
+ for (const target of targets) {
576
+ target.startMs += delta;
577
+ this.touch(target.id);
578
+ }
579
+ if (destination) {
580
+ clip.trackId = destination.id;
581
+ }
582
+ return clip;
583
+ }
257
584
  // Moving a group moves what it holds by the same delta (D4). Children keep
258
585
  // their own tracks, so their z-order is untouched (I9) — only the group
259
586
  // itself takes a new `trackId`.
260
- let moved = clip;
261
587
  if (isGroupClip(clip) && patch.startMs !== undefined) {
262
- const nextStartMs = Math.max(0, patch.startMs);
263
- this.clips = moveGroup(this.clips, clip.id, nextStartMs - clip.startMs);
264
- moved = this.clips.find((c) => c.id === clip.id);
265
- this.touch(...this.clips.filter((c) => c.parentId === clip.id).map((c) => c.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
+ }
595
+ this.touch(...targets.map((target) => target.id));
266
596
  }
267
597
  else if (patch.startMs !== undefined) {
268
598
  clip.startMs = Math.max(0, patch.startMs);
269
599
  }
270
- if (patch.trackId !== undefined) {
271
- moved.trackId = this.resolveTrack(patch.trackId).id;
600
+ if (destination) {
601
+ clip.trackId = destination.id;
272
602
  }
273
603
  if (patch.startMs !== undefined || patch.trackId !== undefined) {
274
- this.touch(moved.id);
604
+ this.touch(clip.id);
275
605
  }
276
- return moved;
606
+ return clip;
277
607
  }
278
608
  /** Resolve a marker by id, or by case-insensitive label. */
279
609
  resolveMarker(target) {
280
610
  const byId = this.state.markers.find((m) => m.id === target);
281
- if (byId)
611
+ if (byId) {
282
612
  return byId;
613
+ }
614
+ const prefix = resolveShortId(this.state.markers, target, "marker");
615
+ if (prefix) {
616
+ return prefix;
617
+ }
283
618
  const lower = target.toLowerCase();
284
619
  const byLabel = this.state.markers.find((m) => m.label.toLowerCase() === lower);
285
- if (byLabel)
620
+ if (byLabel) {
286
621
  return byLabel;
622
+ }
287
623
  const known = this.state.markers
288
624
  .map((m) => `${m.id} ("${m.label}") at ${m.timeMs}ms`)
289
625
  .join(", ");
@@ -306,8 +642,9 @@ class OpScope {
306
642
  for (const target of targets) {
307
643
  try {
308
644
  const clip = this.resolveClip(target);
309
- if (!resolved.includes(clip))
645
+ if (!resolved.includes(clip)) {
310
646
  resolved.push(clip);
647
+ }
311
648
  }
312
649
  catch {
313
650
  // Recorded as a skip in the op's own report, with the reason.
@@ -323,10 +660,28 @@ class OpScope {
323
660
  return serializeTrack(this.state, track);
324
661
  }
325
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
+ }
326
680
  function rejectUnknownClipParams(patch) {
327
681
  for (const key of Object.keys(patch)) {
328
- if (CLIP_PARAM_KEYS.includes(key))
682
+ if (CLIP_PARAM_KEYS.includes(key)) {
329
683
  continue;
684
+ }
330
685
  const elsewhere = CLIP_PARAM_ELSEWHERE[key];
331
686
  if (elsewhere) {
332
687
  throw new Error(`set_clip_params does not change \`${key}\`; use ${elsewhere}.`);
@@ -341,8 +696,9 @@ function rejectUnknownClipParams(patch) {
341
696
  * animation with neither curves nor code.
342
697
  */
343
698
  function liftCustom(input) {
344
- if (!input.custom)
699
+ if (!input.custom) {
345
700
  return input;
701
+ }
346
702
  const { custom, ...rest } = input;
347
703
  return {
348
704
  ...rest,
@@ -357,8 +713,9 @@ function liftCustom(input) {
357
713
  * not stagger, matching the un-staggered block case.
358
714
  */
359
715
  function staggerUnitCount(clip, stagger) {
360
- if (!stagger || clip.mediaType !== "text")
716
+ if (!stagger || clip.mediaType !== "text") {
361
717
  return 0;
718
+ }
362
719
  const text = clip.textStyle?.text ?? "";
363
720
  return text
364
721
  .trim()
@@ -390,15 +747,16 @@ async function buildCustomAnimation(scope, clip, input) {
390
747
  let maskInput;
391
748
  if (hasCurves) {
392
749
  const normalized = normalizeCustomCurves(input.curves);
393
- if (!normalized.ok)
750
+ if (!normalized.ok) {
394
751
  throw new Error(normalized.error);
752
+ }
395
753
  curves = normalized.curves;
396
754
  maskInput = input.mask;
397
755
  }
398
756
  else {
399
757
  const bake = scope.ctx.bakeAnimation;
400
758
  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.");
759
+ 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
760
  }
403
761
  const baked = await bake({
404
762
  code,
@@ -413,25 +771,30 @@ async function buildCustomAnimation(scope, clip, input) {
413
771
  throw new Error(baked.error ?? "The animation body returned no curves.");
414
772
  }
415
773
  const normalized = normalizeCustomCurves(baked.curves);
416
- if (!normalized.ok)
774
+ if (!normalized.ok) {
417
775
  throw new Error(normalized.error);
776
+ }
418
777
  curves = normalized.curves;
419
778
  maskInput = baked.mask ?? input.mask;
420
779
  }
421
780
  const mask = resolveCustomMask(curves, maskInput);
422
- if (!mask.ok)
781
+ if (!mask.ok) {
423
782
  throw new Error(mask.error);
783
+ }
424
784
  const custom = {
425
785
  curves,
426
786
  bakedAt: (scope.ctx.now ?? (() => new Date().toISOString()))()
427
787
  };
428
- if (hasCode)
788
+ if (hasCode) {
429
789
  custom.code = code;
430
- if (mask.mask)
790
+ }
791
+ if (mask.mask) {
431
792
  custom.mask = mask.mask;
793
+ }
432
794
  return {
433
795
  id: scope.ctx.newId("anim"),
434
796
  role: input.role,
797
+ enabled: input.enabled,
435
798
  preset: CUSTOM_ANIMATION_PRESET_ID,
436
799
  durationMs,
437
800
  delayMs: input.delayMs,
@@ -441,1127 +804,1666 @@ async function buildCustomAnimation(scope, clip, input) {
441
804
  custom
442
805
  };
443
806
  }
444
- /** Dispatch one op against `scope`. Throws on refusal; the caller maps it. */
445
- async function runOp(scope, op) {
446
- const state = scope.state;
447
- switch (op.op) {
448
- case "get_state": {
449
- const durationMs = scope.clips.reduce((m, c) => Math.max(m, c.startMs + c.durationMs), 0);
450
- return {
451
- ok: true,
452
- fps: state.fps,
453
- width: state.width,
454
- height: state.height,
455
- durationMs,
456
- playheadMs: state.playheadMs,
457
- selectedClipIds: [...state.selectedClipIds],
458
- tracks: scope.tracks.map((t) => scope.trackOut(t)),
459
- clips: scope.clips.map((c) => scope.clipOut(c)),
460
- mediaTracks: scope.mediaTracks.map(serializeMediaTrack),
461
- markers: state.markers.map((m) => ({ ...m }))
462
- };
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)
823
+ });
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;
463
844
  }
464
- case "add_track": {
465
- const track = scope.addTrack(op.type, op.name);
466
- return { ok: true, track: scope.trackOut(track) };
845
+ if (op.durationMs !== undefined) {
846
+ next.duration_ms = Math.max(1, Math.round(op.durationMs));
467
847
  }
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
- };
848
+ if (op.transition !== undefined) {
849
+ next.transition = op.transition ?? undefined;
493
850
  }
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
- });
851
+ if (op.voiceover !== undefined) {
852
+ next.voiceover = op.voiceover;
853
+ }
854
+ if (op.music !== undefined) {
855
+ next.music = op.music;
856
+ }
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) {
525
1092
  return {
526
1093
  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))
1094
+ clip: scope.clipOut(clip),
1095
+ bakeStarted: false,
1096
+ note: "This surface has no Blender renderer, so nothing was baked."
530
1097
  };
531
1098
  }
532
- case "add_text_clip": {
533
- const track = op.trackId
534
- ? scope.resolveTrack(op.trackId)
535
- : scope.findOrCreateTrack("overlay");
536
- // `style` wins over a top-level twin: a caller that sent both meant the
537
- // bag it named.
538
- const s = { ...(op.loose ?? {}), ...(op.style ?? {}) };
539
- const clip = makeClip({
540
- id: scope.ctx.newId("clip"),
541
- trackId: track.id,
542
- name: op.name ?? op.text,
543
- startMs: op.startMs ?? scope.trackEndMs(track.id),
544
- durationMs: op.durationMs ?? DEFAULT_TEXT_CLIP_DURATION_MS,
545
- mediaType: "text",
546
- sourceType: "imported",
547
- status: "generated",
548
- textStyle: textStyleWithDefaults(op.text, s)
549
- });
550
- if (op.opacity !== undefined)
551
- clip.opacity = op.opacity;
552
- if (op.transform)
553
- clip.transform = mergeClipTransform(clip.transform, op.transform);
554
- scope.clips.push(clip);
555
- state.selectedClipIds = [clip.id];
556
- scope.touch(clip.id);
557
- return { ok: true, clip: scope.clipOut(clip) };
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);
558
1147
  }
559
- case "add_media_clip": {
560
- const resolveAsset = scope.ctx.resolveAsset;
561
- if (!resolveAsset) {
562
- throw new Error("This timeline surface cannot look up assets, so an existing asset cannot be placed here.");
563
- }
564
- const found = await resolveAsset(op.asset);
565
- if (!found) {
566
- throw new Error(`No asset found for "${op.asset}". Pass an asset id or an asset:// URI from list_assets.`);
567
- }
568
- const mediaType = mediaTypeForContentType(found.contentType);
569
- if (!mediaType) {
570
- throw new Error(`Asset "${found.name}" is ${found.contentType}, which is not video, image, or audio and cannot go on a timeline.`);
571
- }
572
- if (mediaType !== "image" &&
573
- op.durationMs === undefined &&
574
- !found.durationMs) {
575
- throw new Error(`Asset "${found.name}" has no known duration. Supply durationMs or import media that can be probed.`);
576
- }
577
- const track = op.trackId
578
- ? scope.resolveTrack(op.trackId)
579
- : scope.findOrCreateTrack(trackTypeForMediaType(mediaType));
580
- const init = {
581
- id: scope.ctx.newId("clip"),
582
- trackId: track.id,
583
- name: op.name ?? found.name,
584
- startMs: op.startMs ?? scope.trackEndMs(track.id),
585
- durationMs: op.durationMs ?? found.durationMs ?? DEFAULT_MEDIA_CLIP_DURATION_MS,
586
- mediaType,
587
- sourceType: "imported",
588
- status: "generated",
589
- currentAssetId: found.id
590
- };
591
- if (found.thumbnailAssetId)
592
- init.thumbnailAssetId = found.thumbnailAssetId;
593
- const clip = makeClip(init);
594
- if (op.transform)
595
- clip.transform = mergeClipTransform(clip.transform, op.transform);
596
- scope.clips.push(clip);
597
- state.selectedClipIds = [clip.id];
598
- scope.touch(clip.id);
599
- return { ok: true, clip: scope.clipOut(clip) };
1148
+ scope.clips.push(group);
1149
+ for (const child of targets) {
1150
+ child.parentId = group.id;
1151
+ scope.touch(child.id);
600
1152
  }
601
- case "add_shape_clip": {
602
- const track = op.trackId
603
- ? scope.resolveTrack(op.trackId)
604
- : scope.findOrCreateTrack("overlay");
605
- const shapeArg = resolveShapeArg(op.shape, op.shapeStyle, op.loose ?? {});
606
- const clip = makeClip({
607
- id: scope.ctx.newId("clip"),
608
- trackId: track.id,
609
- name: op.name ?? capitalize(shapeArg.kind),
610
- startMs: op.startMs ?? scope.trackEndMs(track.id),
611
- durationMs: op.durationMs ?? DEFAULT_TEXT_CLIP_DURATION_MS,
612
- mediaType: "shape",
613
- sourceType: "imported",
614
- status: "generated",
615
- shapeStyle: shapeStyleWithDefaults(shapeArg)
616
- });
617
- if (op.opacity !== undefined)
618
- clip.opacity = op.opacity;
619
- if (op.transform)
620
- clip.transform = mergeClipTransform(clip.transform, op.transform);
621
- scope.clips.push(clip);
622
- state.selectedClipIds = [clip.id];
623
- scope.touch(clip.id);
624
- return { ok: true, clip: scope.clipOut(clip) };
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}".`);
625
1212
  }
626
- case "add_model3d_clip": {
627
- const assetId = op.assetId.trim();
628
- if (!assetId) {
629
- throw new Error("add_model3d_clip needs the glTF's asset id — a 3D clip draws its " +
630
- "asset the way an image clip draws its image. list_assets prints " +
631
- "the ids.");
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);
632
1275
  }
633
- // 3D is picture (D1), so it lands where a title lands: the first overlay
634
- // track, or one made for it.
635
- const track = op.trackId
636
- ? scope.resolveTrack(op.trackId)
637
- : scope.findOrCreateTrack("overlay");
638
- const clip = makeClip({
639
- id: scope.ctx.newId("clip"),
640
- trackId: track.id,
641
- name: DEFAULT_MODEL3D_CLIP_NAME,
642
- startMs: op.startMs ?? scope.trackEndMs(track.id),
643
- durationMs: op.durationMs ?? DEFAULT_MODEL3D_CLIP_DURATION_MS,
644
- mediaType: "model3d",
645
- sourceType: "imported",
646
- status: "generated",
647
- currentAssetId: assetId,
648
- model3dStyle: model3dStyleWithPatch(undefined, op.style)
649
- });
650
- if (op.transform)
651
- clip.transform = mergeClipTransform(clip.transform, op.transform);
652
- scope.clips.push(clip);
653
- state.selectedClipIds = [clip.id];
654
- scope.touch(clip.id);
655
- return { ok: true, clip: scope.clipOut(clip) };
656
1276
  }
657
- case "set_model3d_style": {
658
- const clip = scope.resolveClip(op.target);
659
- if (clip.mediaType !== "model3d") {
660
- throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip, not a 3D clip — ` +
661
- "model3dStyle names a camera, an animation and lighting for a " +
662
- "glTF, and nothing else reads it.");
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);
663
1306
  }
664
- clip.model3dStyle = model3dStyleWithPatch(clip.model3dStyle, op.patch);
665
- scope.touch(clip.id);
666
- return { ok: true, clip: scope.clipOut(clip) };
667
1307
  }
668
- case "bake_model3d_clip": {
669
- const clip = scope.resolveClip(op.target);
670
- if (clip.mediaType !== "model3d") {
671
- throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip, not a 3D clip — ` +
672
- "only a 3D clip has a camera, lighting and a glTF to render.");
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);
1325
+ }
1326
+ copy.linkId = fresh;
673
1327
  }
674
- const style = clip.model3dStyle;
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;
1339
+ }
1340
+ copy.animations = copy.animations?.map((animation) => ({
1341
+ ...animation,
1342
+ id: scope.ctx.newId("anim")
1343
+ }));
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;
675
1378
  if (!style) {
676
- throw new Error(`Clip "${clip.name}" has no model3dStyle, so nothing names the ` +
677
- "camera, lighting or animation a bake would render.");
1379
+ throw new Error(`Clip "${clip.name}" carries no text to size; fontSizePx applies to a text clip's textStyle.`);
678
1380
  }
679
- if (!clip.currentAssetId) {
680
- throw new Error(`Clip "${clip.name}" has no glTF asset to bake — a 3D clip draws ` +
681
- "its asset the way an image clip draws its image.");
682
- }
683
- const sequence = {
684
- fps: state.fps,
685
- width: state.width,
686
- height: state.height
687
- };
688
- const dependencyHash = computeModel3DBakeHash(clip, sequence);
689
- if (!scope.ctx.bakeModel3DClip) {
690
- return {
691
- ok: true,
692
- clip: scope.clipOut(clip),
693
- bakeStarted: false,
694
- note: "This surface has no Blender renderer, so nothing was baked."
695
- };
696
- }
697
- const baked = await scope.ctx.bakeModel3DClip({
698
- clip,
699
- sequence,
700
- dependencyHash
701
- });
702
- const now = (scope.ctx.now ?? (() => new Date().toISOString()))();
703
- clip.model3dStyle = {
704
- ...style,
705
- bake: { assetId: baked.assetId, dependencyHash }
706
- };
707
- // The bake joins the clip's own version history, so an earlier one can
708
- // be restored the way an earlier generation can.
709
- clip.versions = [
710
- ...(clip.versions ?? []),
711
- makeClipVersion({
712
- id: scope.ctx.newId("version"),
713
- createdAt: now,
714
- workflowUpdatedAt: now,
715
- jobId: baked.jobId ?? "",
716
- assetId: baked.assetId,
717
- dependencyHash
718
- })
719
- ];
720
- scope.touch(clip.id);
721
- return { ok: true, clip: scope.clipOut(clip), bakeStarted: true };
722
- }
723
- case "add_group": {
724
- // Resolve every child before anything is written: a half-applied group
725
- // leaves the caller with an empty group and no idea which of its clips
726
- // moved.
727
- const targets = (op.children ?? []).map((ref) => scope.resolveClip(ref));
728
- const track = op.trackId
729
- ? scope.resolveTrack(op.trackId)
730
- : scope.findOrCreateTrack("overlay");
731
- const group = makeClip({
732
- id: scope.ctx.newId("clip"),
733
- trackId: track.id,
734
- name: op.name,
735
- startMs: op.startMs,
736
- durationMs: op.durationMs,
737
- mediaType: "group",
738
- sourceType: "imported",
739
- status: "generated"
740
- });
741
- if (op.transform)
742
- group.transform = mergeClipTransform(group.transform, op.transform);
743
- scope.clips.push(group);
744
- for (const child of targets) {
745
- child.parentId = group.id;
746
- scope.touch(child.id);
747
- }
748
- state.selectedClipIds = [group.id];
749
- scope.touch(group.id);
750
- return {
751
- ok: true,
752
- clip: scope.clipOut(group),
753
- children: targets.map((c) => c.id)
754
- };
1381
+ patch.textStyle = { ...style, fontSizePx: patch.fontSizePx };
755
1382
  }
756
- case "generate_clip": {
757
- const mediaType = op.kind === "text-to-video"
758
- ? "video"
759
- : op.kind === "text-to-image"
760
- ? "image"
761
- : "audio";
762
- const track = op.trackId
763
- ? scope.resolveTrack(op.trackId)
764
- : op.kind === "text-to-audio"
765
- ? 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"));
769
- const generationStarted = op.autoGenerate !== false;
770
- const clip = makeClip({
771
- id: scope.ctx.newId("clip"),
772
- trackId: track.id,
773
- name: op.prompt,
774
- startMs: op.startMs ?? scope.trackEndMs(track.id),
775
- durationMs: op.durationMs ?? (op.kind === "text-to-audio" ? 3000 : 5000),
776
- mediaType,
777
- sourceType: "generated",
778
- bindingKind: op.kind,
779
- status: generationStarted ? "generating" : "draft",
780
- prompt: op.prompt,
781
- provider: op.provider,
782
- model: op.model,
783
- voice: op.voice,
784
- width: op.width,
785
- height: op.height,
786
- aspectRatio: op.aspectRatio,
787
- resolution: op.resolution
788
- });
789
- scope.clips.push(clip);
790
- state.selectedClipIds = [clip.id];
791
- scope.touch(clip.id);
792
- const result = { ok: true, clip: scope.clipOut(clip), generationStarted };
793
- if (!generationStarted) {
794
- result.note = "Generation not started (autoGenerate=false).";
795
- }
796
- return result;
797
- }
798
- case "split_clip": {
799
- const clip = scope.resolveClip(op.target);
800
- 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)] };
810
- }
811
- case "trim_clip": {
812
- const trimmed = scope.applyTrim(scope.resolveClip(op.target), {
813
- durationMs: op.durationMs,
814
- inPointMs: op.inPointMs,
815
- outPointMs: op.outPointMs
816
- });
817
- scope.mediaTracks = resliceTracksForTrimmedClip(scope.mediaTracks, trimmed);
818
- return { ok: true, clip: scope.clipOut(trimmed) };
1383
+ if (patch.name !== undefined) {
1384
+ clip.name = patch.name;
819
1385
  }
820
- case "move_clip": {
821
- const moved = scope.applyMove(scope.resolveClip(op.target), {
822
- startMs: op.startMs,
823
- trackId: op.trackId
824
- });
825
- return { ok: true, clip: scope.clipOut(moved) };
826
- }
827
- case "delete_clip": {
828
- const clip = scope.resolveClip(op.target);
829
- // Deleting a group deletes the parent, not the picture: its children stay
830
- // where they are and stop inheriting (D4). Leaving them with a `parentId`
831
- // nothing answers is what the validator calls a dangling parent.
832
- const wasChild = scope.clips
833
- .filter((c) => c.parentId === clip.id)
834
- .map((c) => c.id);
835
- const remaining = isGroupClip(clip)
836
- ? ungroup(scope.clips, clip.id)
837
- : scope.clips;
838
- const out = scope.clipOut(clip);
839
- scope.clips = remaining.filter((c) => c.id !== clip.id);
840
- state.selectedClipIds = state.selectedClipIds.filter((id) => id !== clip.id);
841
- scope.touch(clip.id, ...wasChild);
842
- return { ok: true, deleted: out };
843
- }
844
- case "duplicate_clip": {
845
- 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
- };
856
- scope.clips.push(copy);
857
- state.selectedClipIds = [copy.id];
858
- scope.touch(copy.id);
859
- return { ok: true, clip: scope.clipOut(copy) };
860
- }
861
- case "set_clip_params": {
862
- let clip = scope.resolveClip(op.target);
863
- const patch = { ...op.patch };
864
- rejectUnknownClipParams(patch);
865
- // Timing belongs to move_clip and trim_clip, but a caller sending it here
866
- // means one edit either way — so apply it through the same code rather
867
- // than dropping it or making them call twice.
868
- clip = scope.applyTrim(clip, {
869
- durationMs: patch.durationMs,
870
- inPointMs: patch.inPointMs,
871
- outPointMs: patch.outPointMs
872
- });
873
- clip = scope.applyMove(clip, {
874
- startMs: patch.startMs,
875
- trackId: patch.trackId
876
- });
877
- if (patch.fontSizePx !== undefined) {
878
- // Shorthand for the one text field callers reach for by name.
879
- const style = patch.textStyle ?? clip.textStyle;
880
- if (!style) {
881
- throw new Error(`Clip "${clip.name}" carries no text to size; fontSizePx applies to a text clip's textStyle.`);
882
- }
883
- patch.textStyle = { ...style, fontSizePx: patch.fontSizePx };
884
- }
885
- if (patch.name !== undefined)
886
- clip.name = patch.name;
887
- if (patch.opacity !== undefined)
888
- clip.opacity = patch.opacity;
889
- if (patch.transform !== undefined) {
890
- clip.transform = mergeClipTransform(clip.transform, patch.transform);
891
- }
892
- if (patch.speedMultiplier !== undefined) {
893
- clip.speedMultiplier = patch.speedMultiplier;
894
- }
895
- if (patch.volumeDb !== undefined)
896
- clip.volumeDb = patch.volumeDb;
897
- if (patch.fadeInMs !== undefined)
898
- clip.fadeInMs = patch.fadeInMs;
899
- if (patch.fadeOutMs !== undefined)
900
- clip.fadeOutMs = patch.fadeOutMs;
901
- if (patch.fadeInShape !== undefined)
902
- clip.fadeInShape = patch.fadeInShape;
903
- if (patch.fadeOutShape !== undefined) {
904
- clip.fadeOutShape = patch.fadeOutShape;
905
- }
906
- if (patch.blendMode !== undefined) {
907
- clip.blendMode = patch.blendMode;
908
- }
909
- if (patch.borderRadius !== undefined)
910
- clip.borderRadius = patch.borderRadius;
911
- if (patch.crop !== undefined) {
912
- // Null is how a caller puts the whole source back; leaving the field
913
- // with all-zero insets would store a crop that means nothing.
914
- if (patch.crop === null) {
915
- delete clip.crop;
916
- }
917
- else {
918
- if (!isCropUsable(patch.crop)) {
919
- throw new Error(`Crop on clip "${clip.name}" keeps no picture: left + right and ` +
920
- "top + bottom must each stay below 1.");
921
- }
922
- clip.crop = patch.crop;
923
- }
924
- }
925
- if (patch.hidden !== undefined)
926
- clip.hidden = patch.hidden;
927
- if (patch.muted !== undefined)
928
- clip.muted = patch.muted;
929
- if (patch.locked !== undefined)
930
- clip.locked = patch.locked;
931
- if (patch.textStyle !== undefined)
932
- clip.textStyle = patch.textStyle;
933
- if (patch.shapeStyle !== undefined)
934
- clip.shapeStyle = patch.shapeStyle;
935
- if (patch.captionStyle !== undefined) {
936
- // The style rides on the clip's caption, so a clip with no words to
937
- // draw has nowhere to put it. Say so rather than storing a look nothing
938
- // renders.
939
- if (!clip.caption) {
940
- throw new Error(`Clip "${clip.name}" carries no caption to style.`);
941
- }
942
- clip.caption = { ...clip.caption, style: patch.captionStyle };
943
- }
944
- scope.touch(clip.id);
945
- return { ok: true, clip: scope.clipOut(clip) };
1386
+ if (patch.opacity !== undefined) {
1387
+ clip.opacity = patch.opacity;
946
1388
  }
947
- case "set_parent": {
948
- const clip = scope.resolveClip(op.target);
949
- scope.touch(clip.id);
950
- if (op.parentId === null) {
951
- delete clip.parentId;
952
- return { ok: true, clip: scope.clipOut(clip) };
953
- }
954
- const parent = scope.resolveClip(op.parentId);
955
- if (parent.mediaType !== "group") {
956
- 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")}`);
957
- }
958
- // A cycle renders unparented and warns, so refusing it here is the only
959
- // place it can still be fixed.
960
- let cursor = parent;
961
- while (cursor) {
962
- if (cursor.id === clip.id) {
963
- throw new Error(`"${parent.name}" is inside "${clip.name}" — parenting them would make a cycle.`);
964
- }
965
- const next = cursor.parentId;
966
- cursor = next ? scope.clips.find((c) => c.id === next) : undefined;
967
- }
968
- clip.parentId = parent.id;
969
- return { ok: true, clip: scope.clipOut(clip) };
1389
+ if (patch.transform !== undefined) {
1390
+ clip.transform = mergeClipTransform(clip.transform, patch.transform);
970
1391
  }
971
- case "set_transition": {
972
- const clip = scope.resolveClip(op.target);
973
- if (op.transition === null) {
974
- delete clip.transitionIn;
975
- }
976
- else {
977
- clip.transitionIn = buildTransition(op.transition);
978
- }
979
- scope.touch(clip.id);
980
- return { ok: true, clip: scope.clipOut(clip) };
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);
1399
+ }
1400
+ clip = scope.resolveClip(clip.id);
981
1401
  }
982
- case "apply_transition_at_cut": {
983
- const planned = planTransitionAtCut(scope.clips, op);
984
- if (!planned.ok)
985
- throw new Error(planned.error);
986
- const applied = applyTransitionAtCutCandidate(scope.clips, planned.candidate);
987
- if (!applied.ok)
988
- throw new Error(applied.error);
989
- scope.clips = applied.clips;
990
- scope.touch(planned.candidate.outgoingClipId, planned.candidate.incomingClipId);
991
- return {
992
- ok: true,
993
- candidate: planned.candidate,
994
- operation: planned.candidate.operation,
995
- description: applied.description
996
- };
1402
+ if (patch.volumeDb !== undefined) {
1403
+ clip.volumeDb = patch.volumeDb;
997
1404
  }
998
- case "set_mask": {
999
- const clip = scope.resolveClip(op.target);
1000
- if (op.mask === null) {
1001
- delete clip.mask;
1002
- }
1003
- else {
1004
- clip.mask = buildMask(op.mask, scope.ctx.parseSvgPath);
1005
- }
1006
- scope.touch(clip.id);
1007
- return { ok: true, clip: scope.clipOut(clip) };
1405
+ if (patch.fadeInMs !== undefined) {
1406
+ clip.fadeInMs = patch.fadeInMs;
1008
1407
  }
1009
- case "set_matte": {
1010
- const clip = scope.resolveClip(op.target);
1011
- scope.touch(clip.id);
1012
- if (op.matte === null) {
1013
- delete clip.matte;
1014
- return { ok: true, clip: scope.clipOut(clip) };
1015
- }
1016
- const source = scope.resolveClip(op.matte.source);
1017
- if (source.id === clip.id) {
1018
- throw new Error(`"${clip.name}" cannot be its own matte source — name another clip.`);
1019
- }
1020
- const matteOut = {
1021
- sourceClipId: source.id,
1022
- mode: op.matte.mode
1023
- };
1024
- if (op.matte.invert !== undefined)
1025
- matteOut.invert = op.matte.invert;
1026
- clip.matte = matteOut;
1027
- return { ok: true, clip: scope.clipOut(clip) };
1408
+ if (patch.fadeOutMs !== undefined) {
1409
+ clip.fadeOutMs = patch.fadeOutMs;
1028
1410
  }
1029
- case "set_generated_matte": {
1030
- const clip = scope.resolveClip(op.target);
1031
- scope.touch(clip.id);
1032
- if (op.clear === true) {
1033
- delete clip.generatedMatte;
1034
- return { ok: true, clip: scope.clipOut(clip), generatedMatte: null };
1035
- }
1036
- if (!clip.generatedMatte) {
1037
- throw new Error(`"${clip.name}" carries no generated matte. Run isolate_subject on ` +
1038
- "it first; this op only adjusts one that exists.");
1039
- }
1040
- if (op.selectVersionAssetId !== undefined) {
1041
- clip.generatedMatte = selectGeneratedMatteVersion(clip, op.selectVersionAssetId).generatedMatte;
1042
- }
1043
- // The knobs are the user's, so an absent field leaves the stored value
1044
- // alone rather than resetting it to a default the caller did not name.
1045
- const matte = clip.generatedMatte;
1046
- if (op.invert !== undefined)
1047
- matte.invert = op.invert;
1048
- if (op.strength !== undefined) {
1049
- matte.strength = Math.min(1, Math.max(0, op.strength));
1050
- }
1051
- if (op.featherPx !== undefined) {
1052
- matte.featherPx = Math.max(0, op.featherPx);
1053
- }
1054
- return { ok: true, clip: scope.clipOut(clip), generatedMatte: matte };
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;
1055
1419
  }
1056
- case "set_time_remap": {
1057
- const clip = scope.resolveClip(op.target);
1058
- if (op.timeRemap === null) {
1059
- delete clip.timeRemap;
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;
1060
1428
  }
1061
1429
  else {
1062
- clip.timeRemap = buildTimeRemap(op.timeRemap);
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.");
1433
+ }
1434
+ clip.crop = patch.crop;
1063
1435
  }
1064
- scope.touch(clip.id);
1065
- return { ok: true, clip: scope.clipOut(clip) };
1066
1436
  }
1067
- case "set_effects": {
1068
- const clip = scope.resolveClip(op.target);
1069
- const list = op.effects.map(buildEffect);
1070
- if (list.length === 0) {
1071
- delete clip.effects;
1072
- }
1073
- else {
1074
- clip.effects = list;
1437
+ if (patch.hidden !== undefined) {
1438
+ clip.hidden = patch.hidden;
1439
+ }
1440
+ if (patch.muted !== undefined) {
1441
+ clip.muted = patch.muted;
1442
+ }
1443
+ if (patch.locked !== undefined) {
1444
+ clip.locked = patch.locked;
1445
+ }
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(", ")}.`);
1075
1454
  }
1076
- scope.touch(clip.id);
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;
1077
1479
  return { ok: true, clip: scope.clipOut(clip) };
1078
1480
  }
1079
- case "set_clip_binding": {
1080
- const clip = scope.resolveClip(op.target);
1081
- if (clip.sourceType !== "generated") {
1082
- 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
- }
1084
- if (op.prompt !== undefined)
1085
- clip.prompt = op.prompt;
1086
- if (op.negativePrompt !== undefined)
1087
- clip.negativePrompt = op.negativePrompt;
1088
- if (op.provider !== undefined)
1089
- clip.provider = op.provider;
1090
- if (op.model !== undefined)
1091
- clip.model = op.model;
1092
- if (op.voice !== undefined)
1093
- clip.voice = op.voice;
1094
- if (op.width !== undefined)
1095
- clip.width = op.width;
1096
- if (op.height !== undefined)
1097
- clip.height = op.height;
1098
- if (op.aspectRatio !== undefined)
1099
- clip.aspectRatio = op.aspectRatio;
1100
- if (op.resolution !== undefined)
1101
- clip.resolution = op.resolution;
1102
- if (op.strength !== undefined)
1103
- clip.strength = op.strength;
1104
- if (op.numInferenceSteps !== undefined) {
1105
- clip.numInferenceSteps = op.numInferenceSteps;
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);
1106
1542
  }
1107
- if (op.regenerate)
1108
- clip.status = "queued";
1109
- scope.touch(clip.id);
1110
- return { ok: true, clip: scope.clipOut(clip) };
1111
1543
  }
1112
- case "animate_clip": {
1113
- const clip = scope.resolveClip(op.target);
1114
- const built = [];
1115
- for (const input of op.animations) {
1116
- if (input.preset === CUSTOM_ANIMATION_PRESET_ID) {
1117
- // `{preset: "custom", custom: {curves}}` reads as naturally as the
1118
- // flat form, so lift it rather than refusing it.
1119
- built.push(await buildCustomAnimation(scope, clip, liftCustom(input)));
1120
- continue;
1121
- }
1122
- const preset = ANIMATION_PRESETS.find((p) => p.id === input.preset);
1123
- if (!preset) {
1124
- const ids = ANIMATION_PRESETS.map((p) => p.id).join(", ");
1125
- throw new Error(`Unknown animation preset "${input.preset}". Valid presets: ${ids}, ${CUSTOM_ANIMATION_PRESET_ID}.`);
1126
- }
1127
- if (!preset.roles.includes(input.role)) {
1128
- throw new Error(`Preset "${input.preset}" does not support role "${input.role}". Valid roles for "${input.preset}": ${preset.roles.join(", ")}.`);
1129
- }
1130
- if (input.preset === "typewriter" && clip.mediaType !== "text") {
1131
- throw new Error('Preset "typewriter" requires a text clip.');
1132
- }
1133
- const timing = input.preset === "typewriter"
1134
- ? typewriterTiming(clip.textStyle?.text ?? "", clip.durationMs - (input.delayMs ?? 0), input.durationMs, input.stagger)
1135
- : null;
1136
- built.push({
1137
- id: scope.ctx.newId("anim"),
1138
- role: input.role,
1139
- preset: input.preset,
1140
- durationMs: timing?.durationMs ?? input.durationMs ?? preset.defaultDurationMs,
1141
- delayMs: input.delayMs,
1142
- easing: input.easing,
1143
- params: input.params,
1144
- stagger: timing?.stagger ?? input.stagger,
1145
- caret: input.preset === "typewriter" ? input.caret : undefined
1146
- });
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.");
1147
1559
  }
1148
- clip.animations =
1149
- op.mode === "add" ? [...(clip.animations ?? []), ...built] : built;
1150
- scope.touch(clip.id);
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;
1151
1570
  return { ok: true, clip: scope.clipOut(clip) };
1152
1571
  }
1153
- case "set_baked_animation": {
1154
- const clip = scope.resolveClip(op.target);
1155
- const outcome = buildBakedAnimation(clip, op.animation, () => scope.ctx.newId("anim"));
1156
- clip.animations = outcome.animations;
1157
- scope.touch(clip.id);
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.`);
1575
+ }
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) {
1158
1691
  return {
1159
1692
  ok: true,
1160
1693
  clip: scope.clipOut(clip),
1161
- animationId: outcome.animationId,
1162
- keyframeCount: outcome.animation.custom?.curves[0]?.keyframes.length ?? 0,
1163
- replaced: outcome.replaced
1694
+ regenerationStarted: false,
1695
+ note: "The binding was saved, but this surface cannot run generation jobs. Regenerate the clip from the timeline editor."
1164
1696
  };
1165
1697
  }
1166
- case "clear_animations": {
1167
- const clip = scope.resolveClip(op.target);
1168
- clip.animations = op.role
1169
- ? (clip.animations ?? []).filter((a) => a.role !== op.role)
1170
- : [];
1171
- scope.touch(clip.id);
1172
- return { ok: true, clip: scope.clipOut(clip) };
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}.`);
1173
1705
  }
1174
- case "list_animation_presets": {
1175
- const presets = ANIMATION_PRESETS.map((p) => ({
1176
- id: p.id,
1177
- roles: p.roles,
1178
- defaultDurationMs: p.defaultDurationMs,
1179
- defaultEasing: p.defaultEasing,
1180
- params: p.params,
1181
- describe: p.describe
1182
- }));
1183
- return {
1184
- ok: true,
1185
- presets,
1186
- custom: CUSTOM_ANIMATION_CONTRACT,
1187
- properties: CUSTOM_ANIMATION_CONTRACT.properties
1188
- };
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
+ });
1189
1740
  }
1190
- case "select_clip": {
1191
- if (!op.target) {
1192
- state.selectedClipIds = [];
1193
- return { ok: true, selected: null };
1194
- }
1195
- const clip = scope.resolveClip(op.target);
1196
- state.selectedClipIds = [clip.id];
1197
- return { ok: true, selected: scope.clipOut(clip) };
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 };
1198
1788
  }
1199
- case "seek": {
1200
- state.playheadMs = Math.max(0, op.timeMs);
1201
- return { ok: true, playheadMs: state.playheadMs };
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.`);
1202
1802
  }
1203
- case "add_marker": {
1204
- if (op.timeMs < 0) {
1205
- throw new Error(`A marker cannot sit before zero; got ${op.timeMs}ms.`);
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;
1206
1839
  }
1207
1840
  const marker = {
1208
1841
  id: scope.ctx.newId("marker"),
1209
- timeMs: Math.round(op.timeMs),
1210
- label: op.label ?? ""
1842
+ timeMs,
1843
+ label: `${stem} ${index + 1}`
1211
1844
  };
1212
- if (op.color !== undefined)
1213
- marker.color = op.color;
1214
- if (op.note !== undefined)
1215
- marker.note = op.note;
1216
1845
  state.markers.push(marker);
1217
- return { ok: true, marker: { ...marker } };
1218
- }
1219
- case "delete_marker": {
1220
- const marker = scope.resolveMarker(op.target);
1221
- state.markers = state.markers.filter((m) => m.id !== marker.id);
1222
- return { ok: true, deleted: { ...marker } };
1223
- }
1224
- case "set_markers_from_beats": {
1225
- const grid = buildBeatGrid({
1226
- onsetsMs: op.onsets_ms,
1227
- bpm: op.bpm,
1228
- offsetMs: op.offset_ms,
1229
- count: op.count
1230
- });
1231
- const stem = (op.label ?? "Beat").trim() || "Beat";
1232
- const taken = new Set(state.markers.map((m) => m.timeMs));
1233
- const added = [];
1234
- const skipped = [];
1235
- for (const [index, timeMs] of grid.entries()) {
1236
- if (taken.has(timeMs)) {
1237
- skipped.push(timeMs);
1238
- continue;
1846
+ taken.add(timeMs);
1847
+ added.push(marker);
1848
+ }
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;
1239
1878
  }
1240
- const marker = {
1241
- id: scope.ctx.newId("marker"),
1242
- timeMs,
1243
- label: `${stem} ${index + 1}`
1244
- };
1245
- state.markers.push(marker);
1246
- taken.add(timeMs);
1247
- added.push(marker);
1879
+ visited.add(parentId);
1880
+ parentId = parentOf.get(parentId);
1248
1881
  }
1249
- return {
1250
- ok: true,
1251
- grid: {
1252
- count: grid.length,
1253
- firstMs: grid[0],
1254
- lastMs: grid[grid.length - 1]
1255
- },
1256
- added: added.map((m) => ({ ...m })),
1257
- skipped_times_ms: skipped,
1258
- markers: state.markers.length
1259
- };
1260
- }
1261
- case "snap_to_beats": {
1262
- const named = op.targets === undefined || op.targets === "all"
1882
+ if (followLinks && clip.linkId !== undefined) {
1883
+ if (seenLinks.has(clip.linkId)) {
1884
+ return false;
1885
+ }
1886
+ seenLinks.add(clip.linkId);
1887
+ }
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
1263
1899
  ? undefined
1264
- : op.targets;
1265
- const { clips: targeted, missing } = scope.resolveSnapTargets(named);
1266
- const offsetMs = op.offset_ms ?? 0;
1267
- // A tempo grid has to reach the last boundary being snapped, so its
1268
- // length comes from the targets rather than from the caller.
1269
- const reachMs = targeted.reduce((end, clip) => Math.max(end, clip.startMs + clip.durationMs), 0);
1270
- const grid = buildBeatGrid({
1271
- onsetsMs: op.onsets_ms,
1272
- bpm: op.bpm,
1273
- offsetMs: op.offset_ms,
1274
- count: op.bpm === undefined
1275
- ? undefined
1276
- : beatCountToCover(op.bpm, offsetMs, reachMs)
1277
- });
1278
- const options = {};
1279
- if (op.tolerance_ms !== undefined)
1280
- options.toleranceMs = op.tolerance_ms;
1281
- if (op.mode !== undefined)
1282
- options.mode = op.mode;
1283
- if (op.action !== undefined)
1284
- options.action = op.action;
1285
- const result = snapClipsToGrid(targeted.map((clip) => ({
1286
- id: clip.id,
1287
- startMs: clip.startMs,
1288
- durationMs: clip.durationMs
1289
- })), grid, options);
1290
- const byId = new Map(targeted.map((clip) => [clip.id, clip]));
1291
- const reported = result.clips.map((entry) => {
1292
- const clip = byId.get(entry.clipId);
1293
- if (entry.snapped && clip) {
1294
- // Through the same ops the caller would use: a group carries its
1295
- // children (D4) and a trim carries the source points, neither of
1296
- // which a raw startMs/durationMs write does.
1297
- try {
1298
- if (entry.after.durationMs === entry.before.durationMs) {
1299
- scope.applyMove(clip, { startMs: entry.after.startMs });
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);
1300
1935
  }
1301
- 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 });
1936
+ const tailDelta = entry.after.endMs - entry.before.endMs;
1937
+ if (tailDelta !== 0) {
1938
+ scope.applyTrim(trimmed, {
1939
+ durationMs: trimmed.durationMs + tailDelta
1940
+ });
1307
1941
  }
1308
1942
  }
1309
- catch (error) {
1310
- return {
1311
- ...entry,
1312
- snapped: false,
1313
- after: entry.before,
1314
- delta: { startMs: 0, endMs: 0 },
1315
- reason: error instanceof Error ? error.message : String(error),
1316
- clipName: clip.name
1317
- };
1318
- }
1319
1943
  }
1320
- return { ...entry, clipName: clip?.name ?? null };
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
+ };
1953
+ }
1954
+ }
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}"`
1321
1968
  });
1322
- // A name nothing matched is a skip like any other: the caller has to see
1323
- // it in the same list, not infer it from a shorter one.
1324
- for (const target of missing) {
1325
- reported.push({
1326
- clipId: target,
1327
- clipName: null,
1328
- snapped: false,
1329
- before: { startMs: 0, endMs: 0, durationMs: 0 },
1330
- after: { startMs: 0, endMs: 0, durationMs: 0 },
1331
- delta: { startMs: 0, endMs: 0 },
1332
- reason: `no clip matches "${target}"`
1333
- });
1969
+ }
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);
1334
2012
  }
1335
- return {
1336
- ok: true,
1337
- grid: {
1338
- count: grid.length,
1339
- firstMs: grid[0],
1340
- lastMs: grid[grid.length - 1]
1341
- },
1342
- toleranceMs: result.toleranceMs,
1343
- mode: result.mode,
1344
- action: result.action,
1345
- snapped: result.snapped,
1346
- skipped: result.skipped + missing.length,
1347
- clips: reported
1348
- };
1349
2013
  }
1350
- case "insert_composition": {
1351
- const loader = scope.ctx.loadComposition;
1352
- if (!loader) {
1353
- throw new Error("This surface has no composition library, so insert_composition cannot resolve a template.");
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) {
2189
+ return { ok: true, clip: scope.clipOut(clip) };
2190
+ }
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
1354
2233
  }
1355
- const composition = await loader.get(op.composition_id);
1356
- if (!composition) {
1357
- const available = await loader.listIds();
1358
- throw new Error(`No composition with id "${op.composition_id}". ` +
1359
- (available.length > 0
1360
- ? `Available: ${available.join(", ")}.`
1361
- : "This install has none — save one with save_composition."));
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");
1362
2261
  }
1363
- const minted = instantiateComposition(composition, {
1364
- startMs: op.startMs,
1365
- params: op.params,
1366
- newId: () => scope.ctx.newId("clip")
1367
- });
1368
- // Template track ids are names, not document ids. Two clips overlapping
1369
- // on one track auto-dissolve into each other, so each template track
1370
- // becomes a track of its own — created front-most first, because the
1371
- // lowest track index draws on top (I9).
1372
- const templateTracks = [];
1373
- for (const child of composition.children) {
1374
- if (!templateTracks.includes(child.trackId)) {
1375
- templateTracks.push(child.trackId);
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}`);
1376
2266
  }
1377
- }
1378
- const mapped = new Map();
1379
- for (const name of [...templateTracks].reverse()) {
1380
- const existing = scope.tracks.find((t) => t.type === "overlay" && t.name === name);
1381
- mapped.set(name, (existing ?? scope.addTrack("overlay", name)).id);
1382
- }
1383
- // The group draws nothing, but it still occupies its track's timeline,
1384
- // and a group sharing a track with one of its children reads as an
1385
- // overlap. It gets a track named after the composition instead.
1386
- const groupTrack = op.trackId
1387
- ? scope.resolveTrack(op.trackId)
1388
- : (scope.tracks.find((t) => t.type === "overlay" && t.name === composition.name) ?? scope.addTrack("overlay", composition.name));
1389
- const [group, ...children] = minted;
1390
- group.trackId = groupTrack.id;
1391
- for (const [index, child] of children.entries()) {
1392
- child.trackId =
1393
- mapped.get(composition.children[index].trackId) ?? groupTrack.id;
1394
- }
1395
- scope.clips.push(group, ...children);
1396
- state.selectedClipIds = [group.id];
1397
- scope.touch(group.id, ...children.map((c) => c.id));
1398
- return {
1399
- ok: true,
1400
- compositionId: composition.id,
1401
- clip: scope.clipOut(group),
1402
- children: children.map((child) => scope.clipOut(child)),
1403
- params: group.compositionParams ?? {}
1404
- };
2267
+ return { ...zone, assetId: asset.id };
2268
+ }));
1405
2269
  }
1406
- case "list_takes": {
1407
- const clip = scope.resolveClip(op.target);
1408
- const versions = clip.versions ?? [];
1409
- const activeId = activeTakeIdOf(clip);
1410
- return {
1411
- ok: true,
1412
- takes: versions.map((v) => ({
1413
- id: v.id,
1414
- label: v.label,
1415
- source: v.source,
1416
- provider: v.provider,
1417
- model: v.model,
1418
- createdAt: v.createdAt,
1419
- costCredits: v.costCredits,
1420
- durationMs: v.durationMs,
1421
- status: v.status,
1422
- favorite: v.favorite,
1423
- active: v.id === activeId
1424
- })),
1425
- activeTakeId: activeId ?? null
1426
- };
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")}`);
1427
2281
  }
1428
- case "select_take": {
1429
- const clip = scope.resolveClip(op.target);
1430
- if (clip.mediaType === "model3d") {
1431
- throw new Error(`Clip "${clip.name}" is a 3D clip — its version history includes ` +
1432
- "bake renders that must not replace the glTF source. Take " +
1433
- "selection is not available for model3d clips yet.");
1434
- }
1435
- const version = (clip.versions ?? []).find((v) => v.id === op.takeId);
1436
- if (!version) {
1437
- throw new Error(`No take "${op.takeId}" on "${clip.name}". ${scope.validUnits((clip.versions ?? []).map((v) => ({
1438
- id: v.id,
1439
- name: v.label ?? v.id
1440
- })), "take")}`);
1441
- }
1442
- if (version.status !== "success") {
1443
- throw new Error(`Take "${op.takeId}" on "${clip.name}" did not finish successfully ` +
1444
- `(status: ${version.status}) — only a successful take can be selected.`);
1445
- }
1446
- const next = selectTake(clip, op.takeId);
1447
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1448
- scope.touch(clip.id);
1449
- return { ok: true, clip: scope.clipOut(next) };
1450
- }
1451
- case "rename_take": {
1452
- const clip = scope.resolveClip(op.target);
1453
- if (!(clip.versions ?? []).some((v) => v.id === op.takeId)) {
1454
- throw new Error(`No take "${op.takeId}" on "${clip.name}". ${scope.validUnits((clip.versions ?? []).map((v) => ({
1455
- id: v.id,
1456
- name: v.label ?? v.id
1457
- })), "take")}`);
1458
- }
1459
- const next = renameTakeOnClip(clip, op.takeId, op.label);
1460
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1461
- scope.touch(clip.id);
1462
- return { ok: true, clip: scope.clipOut(next) };
1463
- }
1464
- case "delete_take": {
1465
- const clip = scope.resolveClip(op.target);
1466
- const { clip: next, error } = deleteTakeOnClip(clip, op.takeId);
1467
- if (error) {
1468
- throw new Error(error);
1469
- }
1470
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1471
- scope.touch(clip.id);
1472
- return { ok: true, clip: scope.clipOut(next) };
1473
- }
1474
- // Subject/object tracks (P0 AI Video, Phase 2). The async provider call
1475
- // that fills a track's samples is the `track_object` capability, not an
1476
- // op — these four are the structural/synchronous surface over it.
1477
- case "list_tracks": {
1478
- const clipId = op.target ? scope.resolveClip(op.target).id : undefined;
1479
- const tracks = scope.mediaTracks.filter((t) => clipId === undefined || t.clipId === clipId);
1480
- return {
1481
- ok: true,
1482
- tracks: tracks.map((t) => ({
1483
- id: t.id,
1484
- clipId: t.clipId,
1485
- name: t.name,
1486
- kind: t.kind,
1487
- status: t.status,
1488
- sourceStartMs: t.sourceStartMs,
1489
- sourceEndMs: t.sourceEndMs,
1490
- sampleCount: t.samples.length,
1491
- confidence: t.confidence
1492
- }))
1493
- };
2282
+ if (track.status !== "ready") {
2283
+ throw new Error(`Track "${track.name}" is ${track.status}; Smart Reframe can only follow a ready track.`);
1494
2284
  }
1495
- case "delete_track_object": {
1496
- const track = scope.mediaTracks.find((t) => t.id === op.trackId);
1497
- if (!track) {
1498
- throw new Error(`No track "${op.trackId}". ${scope.validUnits(scope.mediaTracks.map((t) => ({ id: t.id, name: t.name })), "track")}`);
1499
- }
1500
- scope.mediaTracks = scope.mediaTracks.filter((t) => t.id !== op.trackId);
1501
- const unboundClipIds = [];
1502
- scope.clips = scope.clips.map((c) => {
1503
- if (c.trackBinding?.trackId !== op.trackId)
1504
- return c;
1505
- unboundClipIds.push(c.id);
1506
- const { trackBinding: _dropped, ...rest } = c;
1507
- return rest;
1508
- });
1509
- scope.touch(...unboundClipIds);
1510
- return { ok: true, deleted: { id: track.id, name: track.name } };
2285
+ if (!mediaTrackCanDriveReframe(track) || isMediaTrackStale(track, clip)) {
2286
+ throw new Error(`Track "${track.name}" has no current analysis for clip "${clip.name}".`);
1511
2287
  }
1512
- case "bind_to_track": {
1513
- const clip = scope.resolveClip(op.target);
1514
- const track = scope.mediaTracks.find((t) => t.id === op.trackId);
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");
1515
2331
  if (!track) {
1516
- throw new Error(`No track "${op.trackId}". ${scope.validUnits(scope.mediaTracks.map((t) => ({ id: t.id, name: t.name })), "track")}`);
1517
- }
1518
- if (op.mode !== "position" && op.mode !== "position_scale") {
1519
- throw new Error(`bind_to_track mode "${op.mode}" is not implemented yet — only ` +
1520
- `"position" and "position_scale" affect rendering in this build. ` +
1521
- "The field accepts the other modes so a document can name the " +
1522
- "intent without a schema migration later, but binding to one " +
1523
- "today would be a no-op, so the call is refused instead.");
2332
+ throw new Error(`Track "${trackId}" does not belong to clip "${clip.name}". ${scope.validUnits(scope.mediaTracks.filter((t) => t.clipId === clip.id), "track")}`);
1524
2333
  }
1525
- const binding = { trackId: op.trackId, mode: op.mode };
1526
- if (op.offset !== undefined)
1527
- binding.offset = op.offset;
1528
- if (op.scale !== undefined)
1529
- binding.scale = op.scale;
1530
- if (op.rotationOffset !== undefined) {
1531
- binding.rotationOffset = op.rotationOffset;
2334
+ if (track.status !== "ready") {
2335
+ throw new Error(`Track "${track.name}" is ${track.status}; a format adaptation can only follow a ready track.`);
1532
2336
  }
1533
- if (op.smoothing !== undefined)
1534
- binding.smoothing = op.smoothing;
1535
- const next = { ...clip, trackBinding: binding };
1536
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1537
- scope.touch(clip.id);
1538
- return { ok: true, clip: scope.clipOut(next) };
1539
- }
1540
- case "unbind_track": {
1541
- const clip = scope.resolveClip(op.target);
1542
- if (!clip.trackBinding) {
1543
- return { ok: true, clip: scope.clipOut(clip) };
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;
2353
+ }
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.");
2378
+ }
2379
+ for (const clip of clips) {
2380
+ if (!clip.animations?.length) {
2381
+ throw new Error(`Clip "${clip.name}" has no animations to stagger.`);
1544
2382
  }
1545
- const { trackBinding: _dropped, ...next } = clip;
1546
- scope.clips = scope.clips.map((c) => (c.id === clip.id ? next : c));
1547
- scope.touch(clip.id);
1548
- return { ok: true, clip: scope.clipOut(next) };
1549
2383
  }
1550
- default: {
1551
- const unknown = op;
1552
- throw new Error(`Unknown timeline op "${unknown.op}".`);
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);
1553
2440
  }
2441
+ Object.assign(scope.state, outcome.state);
2442
+ scope.touch(...outcome.changedClipIds);
2443
+ return outcome.result;
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}".`);
1554
2450
  }
2451
+ const handler = OP_HANDLERS[op.op];
2452
+ return handler(scope, op);
1555
2453
  }
1556
2454
  /** Deep copy of the document, so a failed op leaves the caller's state alone. */
1557
2455
  function cloneState(state) {
1558
2456
  return {
2457
+ ...state,
2458
+ tempo: state.tempo,
2459
+ setup: state.setup ? structuredClone(state.setup) : state.setup,
1559
2460
  fps: state.fps,
1560
2461
  width: state.width,
1561
2462
  height: state.height,
1562
2463
  tracks: state.tracks.map((t) => structuredClone(t)),
1563
2464
  clips: state.clips.map((c) => structuredClone(c)),
1564
2465
  markers: state.markers.map((m) => structuredClone(m)),
2466
+ storyboardMaterializations: state.storyboardMaterializations?.map((entry) => structuredClone(entry)),
1565
2467
  mediaTracks: (state.mediaTracks ?? []).map((t) => structuredClone(t)),
1566
2468
  playheadMs: state.playheadMs,
1567
2469
  selectedClipIds: [...state.selectedClipIds]
@@ -1592,4 +2494,135 @@ export async function applyTimelineOp(state, op, ctx) {
1592
2494
  };
1593
2495
  }
1594
2496
  }
2497
+ function serializeTracks(state) {
2498
+ const clipCount = new Map();
2499
+ for (const clip of state.clips) {
2500
+ clipCount.set(clip.trackId, (clipCount.get(clip.trackId) ?? 0) + 1);
2501
+ }
2502
+ return state.tracks.map((track) => serializeTrack(state, track, clipCount.get(track.id) ?? 0));
2503
+ }
2504
+ function runTrackOp(scope, op) {
2505
+ const state = scope.state;
2506
+ switch (op.op) {
2507
+ case "add_track": {
2508
+ const track = scope.addTrack(op.type, op.name);
2509
+ return { ok: true, track: scope.trackOut(track) };
2510
+ }
2511
+ case "move_track": {
2512
+ const { target, toIndex, before, after } = resolveMoveTrackArgs(op);
2513
+ const track = scope.resolveTrack(target);
2514
+ const destination = {};
2515
+ if (toIndex !== undefined) {
2516
+ destination.toIndex = toIndex;
2517
+ }
2518
+ if (before !== undefined) {
2519
+ destination.beforeId = scope.resolveTrack(before).id;
2520
+ }
2521
+ if (after !== undefined) {
2522
+ destination.afterId = scope.resolveTrack(after).id;
2523
+ }
2524
+ const orderedIds = moveTrackOrder(scope.tracks, track.id, destination);
2525
+ const byId = new Map(scope.tracks.map((t) => [t.id, t]));
2526
+ // The array order is what `get_state` prints, so keep it and the indices
2527
+ // saying the same thing.
2528
+ scope.tracks.length = 0;
2529
+ orderedIds.forEach((id, i) => {
2530
+ const moved = byId.get(id);
2531
+ if (!moved) {
2532
+ throw new Error(`Track "${id}" no longer exists.`);
2533
+ }
2534
+ moved.index = i;
2535
+ scope.tracks.push(moved);
2536
+ });
2537
+ return {
2538
+ ok: true,
2539
+ track: scope.trackOut(track),
2540
+ tracks: serializeTracks(scope.state)
2541
+ };
2542
+ }
2543
+ case "delete_track": {
2544
+ const { target, deleteClips } = resolveDeleteTrackArgs(op);
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);
2549
+ const onIt = scope.clips.filter((c) => c.trackId === track.id);
2550
+ if (deleteClips) {
2551
+ scope.assertWritable(onIt);
2552
+ }
2553
+ if (onIt.length > 0 && !deleteClips) {
2554
+ throw new Error(`Track "${track.name}" still holds ${onIt.length} clip(s): ` +
2555
+ `${onIt.map((c) => c.id).join(", ")}. Move them first, or pass ` +
2556
+ "deleteClips: true to delete them with the track.");
2557
+ }
2558
+ const removedClipIds = onIt.map((c) => c.id);
2559
+ const removed = new Set(removedClipIds);
2560
+ const kept = scope.clips.filter((c) => c.trackId !== track.id);
2561
+ scope.clips.length = 0;
2562
+ scope.clips.push(...kept);
2563
+ // A parent that went with the track would leave its children pointing at
2564
+ // a clip that no longer exists, which the validator reads as a broken
2565
+ // document rather than a deletion.
2566
+ for (const clip of scope.clips) {
2567
+ if (clip.parentId && removed.has(clip.parentId)) {
2568
+ delete clip.parentId;
2569
+ scope.touch(clip.id);
2570
+ }
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
+ }
2594
+ scope.touch(...removedClipIds);
2595
+ state.selectedClipIds = state.selectedClipIds.filter((id) => !removed.has(id));
2596
+ const remaining = scope.tracks.filter((t) => t.id !== track.id);
2597
+ scope.tracks.length = 0;
2598
+ // Index is z-order, so the stack has to close over the gap.
2599
+ remaining.forEach((t, i) => {
2600
+ t.index = i;
2601
+ scope.tracks.push(t);
2602
+ });
2603
+ return {
2604
+ ok: true,
2605
+ deleted: { id: track.id, name: track.name, type: track.type },
2606
+ deletedClipIds: removedClipIds,
2607
+ tracks: serializeTracks(scope.state)
2608
+ };
2609
+ }
2610
+ }
2611
+ }
2612
+ /** Synchronous document edits for hosts whose editor actions are synchronous. */
2613
+ export function applyTimelineTrackOp(state, op, ctx) {
2614
+ const scope = new OpScope(cloneState(state), ctx);
2615
+ try {
2616
+ const result = runTrackOp(scope, op);
2617
+ return { state: scope.state, result, changedClipIds: [...scope.changed] };
2618
+ }
2619
+ catch (error) {
2620
+ return {
2621
+ state,
2622
+ result: {},
2623
+ changedClipIds: [],
2624
+ error: error instanceof Error ? error.message : String(error)
2625
+ };
2626
+ }
2627
+ }
1595
2628
  //# sourceMappingURL=apply.js.map