rig-review 0.21.0 → 0.23.0

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.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/rig-c/review/main/assets/banner.svg" alt="@rig-c/review" width="100%" />
3
+ </p>
4
+
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/@rig-c/review"><img src="https://img.shields.io/npm/v/@rig-c/review.svg?style=flat-square&color=FF6B4A" alt="version"/></a>
7
+ <a href="https://www.npmjs.com/package/@rig-c/review"><img src="https://img.shields.io/npm/dm/@rig-c/review.svg?style=flat-square&color=EC4899" alt="downloads"/></a>
8
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-38BDF8.svg?style=flat-square" alt="MIT"/></a>
9
+ </p>
10
+
1
11
  # review
2
12
 
3
13
  A reusable local workspace for a person to inspect an agent's rig output, compare source references, and export feedback ready to become an issue. The person receives a package or opens an existing output folder; the agent does not build a new viewer for each rig.
package/docs/PANELS.md CHANGED
@@ -227,7 +227,7 @@ serving use per-port origins and keep them separate.
227
227
 
228
228
  ## Inspect animation keys
229
229
 
230
- Animate keeps its timeline in a panel of its own beside the other blocks, with Timeline, Curves and Bone tree views of the build currently on stage. Bone value tracks of `motion.animations_from` are editable: an edit is a pending op, previewed on the stage, and **Apply · Rebuild** builds it through the installed producer into scratch. Other tracks say why they are read-only, and compare mode is read-only (`ANIMATION_COMPARE_READ_ONLY`). The timeline preserves every stored bone/slot track and key time; click a key to seek, or scrub the transport to move its playhead. Bone selection filters its direct tracks. Tree, Parts and stage selections stay synchronized; enable **Bone points** to pick a bone on stage. Selecting a bone highlights all directly attached Parts rows without inventing a selected slot.
230
+ Animate keeps its timeline in a panel of its own beside the other blocks, with Timeline, Curves and Bone tree views of the build currently on stage. Bone value tracks of `motion.animations_from` are editable: an edit is a pending op, previewed on the stage, and **Apply · Rebuild** builds it through the installed producer into scratch; in a comparison session, switching to **Animate** edits and rebuilds only the picked side (**Editing Build A / Build B** via `/api/compare/a/rebuild` or `/api/compare/b/rebuild`) while keeping the other side's pose, pending ops, applied record and files untouched. Other tracks say why they are read-only. The timeline preserves every stored bone/slot track and key time; click a key to seek, Shift-click to add or remove editable keys from a multi-key selection, or box-drag across empty lane area to select editable keys across tracks (read-only tracks are skipped and named in the status bar, with zero browser text selection and an unshaded selection frame behind the keys). Dragging any selected key retimes the whole selection by the same delta as one undo step (`ANIMATION_KEY_ORDER`, `ANIMATION_KEY_TIME_INVALID` and `ANIMATION_OPS_TOO_MANY` refuse by name without writing), and **Delete** removes the selection as one undo step (`ANIMATION_TRACK_MIN_KEYS` refuses when fewer than two keys would remain on a track). Scrub the ruler or click an empty editable lane to move the playhead. Bone selection filters its direct tracks. Tree, Parts and stage selections stay synchronized; enable **Bone points** to pick or pose a bone on stage. Selecting a bone highlights all directly attached Parts rows without inventing a selected slot. With **Bone points** on, **Pose: Rotate** and **Pose: Move** (`Alt` during drag switches for that gesture) let you drag a bone handle on stage to set its `rotate` or `translate` key at the playhead—or insert and set a key at an unkeyed playhead as one undo step—inverting the parent bone's world matrix so a translated bone tracks the cursor whether its parent is rotated or not. When multiple bones share a stage point, the currently selected bone sits on top, followed by editable bones in clip track order above unkeyed or read-only bones, and clicking an overlapping point without dragging cycles through the overlapping editable bones. A bone without a matching source track (`ANIMATION_BONE_NO_TRACK`), driven by a physics/IK/transform constraint (`ANIMATION_BONE_CONSTRAINED`), or on a read-only track (`ANIMATION_TRACK_READ_ONLY`) refuses by name.
231
231
 
232
232
  Curves show the compiled skeleton’s exact linear, stepped or cubic Bézier segments and stored handles. On an editable bone value track, **Segment** picks the outgoing key, **Mode** switches between linear, stepped and cubic Bézier, and dragging the two handles on the plot edits the segment’s `[cx1, cy1, cx2, cy2]` (`set_key_curve` / `set_key_ease` ops, coalesced on the same key and previewed live on the stage before **Apply · Rebuild**). The separately labeled **Runtime evaluation** cursor/readout uses Play’s ten-piece Float32 interpolation, which can differ from the cubic. Its local value includes setup rotation/translation and scale multiplication, in stored timeline order, before constraints and previews. Rotation is unwrapped local degrees. **Inspect time** accepts exact seconds; frame labels require the existing explicit clock. Nothing is written into the package. See [animation inspection](ANIMATION_INSPECTION.md) for the numeric validation and reproduction commands.
233
233
 
@@ -259,7 +259,7 @@ Rig pixels are the whole figure's frame, which is the crop frame the model's sta
259
259
  - **Inputs.** The producer handoff (`docs/REVIEW_PACKAGE.md`, *Producer handoff*): `open --config` (and `--parts`), else the review.json `producer` block, else `config.json`, then `rig/config.json` inside the opened folder, then `../config.json` beside an opened `out/`. The parts directory defaults to `out/` beside the config and holds `parts.json`, `parts/` and the inspected `rig/`. The editor bar shows, before any Apply, how the config was found (declared, discovered, or discovered outside the opened folder), its path and SHA-256, and the baseline. Without a handoff the bar shows `MODELING_INPUT_UNAVAILABLE: config.json — looked at …` and Apply refuses `MODELING_HANDOFF_MISSING`, naming `--config`. The request carries only `{part, regions, configHash}`; the server reads the config, replaces `meshes.<part>.contour.regions` with the designated regions (every other field as written) and runs `rig-parts remesh --rig <out>/rig --config <config> --parts <out> --part <part> --mesh mesh.json --out revision`, then `rigc build --profile rig-play --pack` with the revision's own `--page-edges` / `--pack-shape`, both with the scratch directory as working directory. A region row with equal semi-axes and no clip is sent as the config's circle, any other as the 32-sample polygon. An untouched editor starts from the config's own circle regions and contour numbers.
260
260
  - **Baseline.** Once per session, when the handoff and the producer both resolve, review runs `rig-parts rig --config <config> --parts <parts> --out <state>/baseline/<key>/baseline` and compares every file it writes (rig.json, motion.json, mesh_report.json, sets.json, images/*) with the inspected rig directory: `baseline: reproduced — rig.json <hash> = inspected <hash>`, or `baseline: not reproduced — <first differing path> · <what Apply can still do here>`. The key is the package hash, the handoff record and the producer versions (no clock), so a reopen reuses the result. Ops that rebuild the whole rig refuse `EDIT_BASELINE_MISMATCH <path>` unless the baseline reproduced; `remesh` keeps its own `REMESH_BASELINE_MISMATCH`. A build the config does not reproduce — a hand repair — is not open to every Apply (#148): retune carries a **mesh** repair over but holds every image, so a repair that redrew an image refuses every physics and idle edit (`RETUNE_REQUEST_HELD: images/<part>.png`); remesh from a config entry refuses the repaired parts and re-fits the others; a mesh edit is held to the inspected mesh, not the config; and remesh, its mesh edit and retune all refuse an inspected `rig.json` (or `mesh_report.json`, `motion.json`) that is not the writer's text (`…_INPUT_WRITTEN` — re-serialise it as rig writes it, JSON with one space of indent and a closing newline, in a copy). The baseline line and `EDIT_BASELINE_MISMATCH` name which of these hold here, and a producer refusal review can explain carries `review: …` after the producer's own line (docs/REVIEW_PACKAGE.md, *Baseline reach*). Once it reproduces, `rig-parts check` runs on the baseline output in the background (into `<state>/baseline/<key>/inspected-check/`, with Apply's default `--page-edges free --pack-shape polygon`) and its summary is stored beside the baseline record as `inspected-check.json`; that is the physics readout's BEFORE for the inspected build, and a reopen reads it instead of re-running.
261
261
  - **Scratch.** `<state>/rebuild/<package source hash>/<designation hash>/` under `RIG_REVIEW_STATE_DIR` (refused, by its canonical location, inside the package, its build root or the handoff root), named from the package, the config bytes, the part, the entry and both tool versions — no clock. The same designation again reuses its build and says so; a new one replaces the previous scratch build on the stage (the earlier applied records' builds are kept beside the scratch root for undo, at most eight per package). The inspected package's files are only read.
262
- - **Watching.** The producer's lines stream into the editor bar (the latest line and a short log); a refusal shows the producer's first named line verbatim (for example `FAIL REMESH_REQUEST_HELD: …`) and the stage is unchanged. On success the compiled scratch build (served read-only under `/rebuild/<id>/`, its model and pages hashed) replaces the drawn rig in place with the same camera, animation, time and part set; playback resumes with physics when it was running. **Reset** returns the stage to the inspected build. **Undo last Apply** (the *Applied records* list at the top of the Inspector, its depth in the label) returns the stage to the previous applied build, or to the inspected build when none is left; a predecessor whose build was evicted re-runs its recorded step and must come back byte for byte, else `UNDO_PREDECESSOR_CHANGED: <what>` (docs/REVIEW_PACKAGE.md, *Undo across Applies*). A change to the handoff config ends the session's undo stack (reopen): Undo is then refused `FRONT_INSTANCE_EXPIRED`. The Cuts and Cloth blocks mark a pending op applied only while the record on the stage holds it, so after an undo they show the predecessor's ops as applied, and none on the inspected build. The mark shows what the build on the stage carries, not every op applied so far: while a cloth build is on the stage, the Cuts block marks nothing.
262
+ - **Watching.** The producer's lines stream into the editor bar (the latest line and a short log); a refusal shows the producer's first named line verbatim (for example `FAIL REMESH_REQUEST_HELD: …`) and the stage is unchanged. On success the compiled scratch build (served read-only under `/rebuild/<id>/`, its model and pages hashed) replaces the drawn rig in place with the same camera, animation, time and part set; playback resumes with physics when it was running. **Reset** returns the stage to the inspected build. **Undo last Apply** (the *Applied records* list at the top of the Inspector, its depth in the label) returns the stage to the previous applied build, or to the inspected build when none is left; a predecessor whose build was evicted re-runs its recorded step and must come back byte for byte, else `UNDO_PREDECESSOR_CHANGED: <what>` (docs/REVIEW_PACKAGE.md, *Undo across Applies*). A change to the handoff config ends the session's undo stack (reopen): Undo is then refused `FRONT_INSTANCE_EXPIRED`. The Cuts and Cloth blocks mark a pending op applied only while the record on the stage holds it, so after an undo they show the predecessor's ops as applied, and none on the inspected build. The mark shows what the build on the stage carries, not every op applied so far: while a cloth build is on the stage, the Cuts block marks nothing. Whenever the stage holds an applied edit from another panel or job kind, each panel shows a plain-words statement beside its Apply button before the click (`This rebuild starts from the handoff and drops: …`), and after a second panel applies, the superseded panel stops reading as applied while keeping its in-panel edits for re-Apply.
263
263
  - **Record.** The last applied state (`rig-review-applied/1`: part, regions, for a Landmarks Apply also `bust` — the entry as sent, with `regions` its two derived circles — config hash, entry SHA-256, producer and compiler versions, the producer's line and the scratch model's SHA-256) stays in the inspection draft, and feedback added while that build is on the stage carries it as `context.applied`. The review's `reviewedSource` still names the inspected build.
264
264
  - **Config patch.** The same loop takes any config edit as data: `POST /api/rebuild {patch}` with a `rig-review-config-patch/1` document (JSON Pointer ops over the handoff config, refused `EDIT_PATCH_STALE` when made against other config bytes) rebuilds the whole rig (`rig`) or one part (`remesh`) into scratch, compiles it and runs `rig-parts check` on it; the page's `window.rigReviewEditor.applyPatch(patch)` streams, reloads and resets like Apply, and the draft and `context.applied` carry `rig-review-applied/2` (the patch, its hash, the producer's line, check's summary and the diff of every document the producer writes, per file, with the images by hash). Schema and refusals: `docs/REVIEW_PACKAGE.md`, *Config patch and Apply*.
265
265
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -402,10 +402,115 @@ export interface TrackClassification {
402
402
  reason: string | null;
403
403
  }
404
404
 
405
+ export interface BoneConstraintInfo {
406
+ name: string;
407
+ kind: 'physics' | 'ik' | 'transform' | 'path' | 'slider';
408
+ }
409
+
405
410
  function isRecord(v: unknown): v is Record<string, unknown> {
406
411
  return typeof v === 'object' && v !== null && !Array.isArray(v);
407
412
  }
408
413
 
414
+ /**
415
+ * Inspect a compiled `rigc-compiled/3` model document to determine whether `boneName`
416
+ * is driven by a constraint (`physics`, `ik`, `transform`, `path`, or `slider`).
417
+ */
418
+ export function findBoneConstraint(
419
+ modelDocument: unknown,
420
+ boneName: string,
421
+ ): BoneConstraintInfo | null {
422
+ if (!isRecord(modelDocument) || !boneName) return null;
423
+ const animations = Array.isArray(modelDocument.animations) ? modelDocument.animations : [];
424
+ const checkConstraint = (
425
+ raw: unknown,
426
+ fallbackKind?: BoneConstraintInfo['kind'],
427
+ ): BoneConstraintInfo | null => {
428
+ if (!isRecord(raw) || typeof raw.name !== 'string') return null;
429
+ const rec = isRecord(raw.record) ? raw.record : raw;
430
+ const kind = (
431
+ typeof raw.kind === 'string'
432
+ ? raw.kind
433
+ : typeof raw.type === 'string'
434
+ ? raw.type
435
+ : typeof rec.kind === 'string'
436
+ ? rec.kind
437
+ : typeof rec.type === 'string'
438
+ ? rec.type
439
+ : fallbackKind
440
+ ) as BoneConstraintInfo['kind'] | undefined;
441
+ if (!kind) return null;
442
+ const boneField =
443
+ typeof rec.bone === 'string'
444
+ ? rec.bone
445
+ : typeof raw.bone === 'string'
446
+ ? raw.bone
447
+ : undefined;
448
+ const bonesField = Array.isArray(rec.bones)
449
+ ? rec.bones
450
+ : Array.isArray(raw.bones)
451
+ ? raw.bones
452
+ : undefined;
453
+ if (kind === 'physics' && boneField === boneName) {
454
+ return { name: raw.name, kind: 'physics' };
455
+ }
456
+ if (
457
+ (kind === 'ik' || kind === 'transform' || kind === 'path') &&
458
+ (boneField === boneName || (bonesField !== undefined && bonesField.includes(boneName)))
459
+ ) {
460
+ return { name: raw.name, kind };
461
+ }
462
+ if (kind === 'slider') {
463
+ if (boneField === boneName || (bonesField !== undefined && bonesField.includes(boneName))) {
464
+ return { name: raw.name, kind: 'slider' };
465
+ }
466
+ if (
467
+ isRecord(rec.timelines) &&
468
+ Array.isArray(rec.timelines.bones) &&
469
+ rec.timelines.bones.some((b) => isRecord(b) && b.name === boneName)
470
+ ) {
471
+ return { name: raw.name, kind: 'slider' };
472
+ }
473
+ const animName =
474
+ typeof rec.animation === 'string'
475
+ ? rec.animation
476
+ : typeof raw.animation === 'string'
477
+ ? raw.animation
478
+ : undefined;
479
+ if (animName) {
480
+ const sliderAnim = animations.find(
481
+ (a) => isRecord(a) && a.name === animName && Array.isArray(a.bones),
482
+ ) as { bones?: unknown[] } | undefined;
483
+ if (sliderAnim?.bones?.some((b) => isRecord(b) && b.name === boneName)) {
484
+ return { name: raw.name, kind: 'slider' };
485
+ }
486
+ }
487
+ }
488
+ return null;
489
+ };
490
+ if (Array.isArray(modelDocument.constraints)) {
491
+ for (const raw of modelDocument.constraints) {
492
+ const hit = checkConstraint(raw);
493
+ if (hit) return hit;
494
+ }
495
+ }
496
+ for (const [field, kind] of [
497
+ ['physics', 'physics'],
498
+ ['ik', 'ik'],
499
+ ['transform', 'transform'],
500
+ ['path', 'path'],
501
+ ['sliders', 'slider'],
502
+ ] as const) {
503
+ const list = modelDocument[field];
504
+ if (Array.isArray(list)) {
505
+ for (const raw of list) {
506
+ const hit = checkConstraint(raw, kind);
507
+ if (hit) return hit;
508
+ }
509
+ }
510
+ }
511
+ return null;
512
+ }
513
+
409
514
  /**
410
515
  * Evaluate whether an animation in a package may be edited through `animations_from`.
411
516
  */
@@ -1048,24 +1153,30 @@ export function applyAnimationOp(
1048
1153
  const channels = classification.channels;
1049
1154
  const keysPath = ['animations', op.animation, 'tracks', op.track, 'keys'] as const;
1050
1155
 
1156
+ const trackLabel = `animation "${op.animation}" track ${op.track} ("${classification.target}.${classification.property}")`;
1157
+
1051
1158
  if (op.op === 'set_key_time') {
1052
1159
  if (!Number.isInteger(op.key) || op.key < 0 || op.key >= keys.length) {
1053
- throw new Error(`ANIMATION_KEY_OUT_OF_RANGE: key index ${op.key} out of [0, ${keys.length - 1}]`);
1160
+ throw new Error(
1161
+ `ANIMATION_KEY_OUT_OF_RANGE: ${trackLabel} key index ${op.key} out of [0, ${keys.length - 1}]`,
1162
+ );
1054
1163
  }
1055
1164
  if (typeof op.time !== 'number' || !Number.isFinite(op.time) || op.time < 0) {
1056
- throw new Error(`ANIMATION_KEY_TIME_INVALID: key time must be a finite number >= 0, got ${String(op.time)}`);
1165
+ throw new Error(
1166
+ `ANIMATION_KEY_TIME_INVALID: ${trackLabel} key ${op.key} time must be a finite number >= 0, got ${String(op.time)}`,
1167
+ );
1057
1168
  }
1058
1169
  const nextTime = cleanMotionNumber(op.time);
1059
1170
  const prevKey = op.key > 0 ? keys[op.key - 1] : undefined;
1060
1171
  const nextKey = op.key + 1 < keys.length ? keys[op.key + 1] : undefined;
1061
1172
  if (prevKey && nextTime <= prevKey.t) {
1062
1173
  throw new Error(
1063
- `ANIMATION_KEY_ORDER: key ${op.key} time ${nextTime} must be > previous key ${op.key - 1} time ${prevKey.t}`,
1174
+ `ANIMATION_KEY_ORDER: ${trackLabel} key ${op.key} time ${nextTime} must be > previous key ${op.key - 1} time ${prevKey.t}`,
1064
1175
  );
1065
1176
  }
1066
1177
  if (nextKey && nextTime >= nextKey.t) {
1067
1178
  throw new Error(
1068
- `ANIMATION_KEY_ORDER: key ${op.key} time ${nextTime} must be < next key ${op.key + 1} time ${nextKey.t}`,
1179
+ `ANIMATION_KEY_ORDER: ${trackLabel} key ${op.key} time ${nextTime} must be < next key ${op.key + 1} time ${nextKey.t}`,
1069
1180
  );
1070
1181
  }
1071
1182
 
@@ -1347,10 +1458,14 @@ export function applyAnimationOp(
1347
1458
 
1348
1459
  if (op.op === 'delete_key') {
1349
1460
  if (!Number.isInteger(op.key) || op.key < 0 || op.key >= keys.length) {
1350
- throw new Error(`ANIMATION_KEY_OUT_OF_RANGE: key index ${op.key} out of [0, ${keys.length - 1}]`);
1461
+ throw new Error(
1462
+ `ANIMATION_KEY_OUT_OF_RANGE: ${trackLabel} key index ${op.key} out of [0, ${keys.length - 1}]`,
1463
+ );
1351
1464
  }
1352
1465
  if (keys.length <= 1) {
1353
- throw new Error('ANIMATION_TRACK_MIN_KEYS: cannot delete the only key on a track');
1466
+ throw new Error(
1467
+ `ANIMATION_TRACK_MIN_KEYS: ${trackLabel} cannot delete key ${op.key}; cannot delete the only key on a track (has ${keys.length})`,
1468
+ );
1354
1469
  }
1355
1470
 
1356
1471
  const keysArray = resolveArrayNode(text, keysPath);
@@ -1663,7 +1778,15 @@ export class AnimationOpBuilder {
1663
1778
  readonly baseText: string;
1664
1779
  readonly fallbackEasings?: Readonly<Record<string, EasingTuple>>;
1665
1780
  private currentText: string;
1666
- private readonly history: Array<{ op: AnimationSourceOp; textBefore: string }> = [];
1781
+ private readonly history: Array<{
1782
+ op: AnimationSourceOp;
1783
+ textBefore: string;
1784
+ undoGroupId?: number;
1785
+ explicitGroup?: boolean;
1786
+ }> = [];
1787
+ private nextUndoGroupId = 1;
1788
+ private activeUndoGroupId: number | undefined = undefined;
1789
+ private explicitGroupDepth = 0;
1667
1790
 
1668
1791
  constructor(baseText: string, fallbackEasings?: Readonly<Record<string, EasingTuple>>) {
1669
1792
  this.baseText = baseText;
@@ -1683,10 +1806,120 @@ export class AnimationOpBuilder {
1683
1806
  return this.currentText !== this.baseText;
1684
1807
  }
1685
1808
 
1809
+ beginUndoGroup(): number {
1810
+ return this.nextUndoGroupId++;
1811
+ }
1812
+
1813
+ withUndoGroup<T>(groupId: number, fn: () => T): T {
1814
+ const prev = this.activeUndoGroupId;
1815
+ this.activeUndoGroupId = groupId;
1816
+ this.explicitGroupDepth++;
1817
+ try {
1818
+ return fn();
1819
+ } finally {
1820
+ this.explicitGroupDepth--;
1821
+ this.activeUndoGroupId = prev;
1822
+ }
1823
+ }
1824
+
1825
+ private withInternalUndoGroup<T>(groupId: number, fn: () => T): T {
1826
+ const prev = this.activeUndoGroupId;
1827
+ this.activeUndoGroupId = groupId;
1828
+ try {
1829
+ return fn();
1830
+ } finally {
1831
+ this.activeUndoGroupId = prev;
1832
+ }
1833
+ }
1834
+
1835
+ unwindUndoGroup(groupId: number): void {
1836
+ let earliestTextBefore: string | undefined;
1837
+ while (
1838
+ this.history.length > 0 &&
1839
+ this.history.at(-1)!.undoGroupId === groupId
1840
+ ) {
1841
+ earliestTextBefore = this.history.pop()!.textBefore;
1842
+ }
1843
+ if (earliestTextBefore !== undefined) {
1844
+ this.currentText = earliestTextBefore;
1845
+ }
1846
+ }
1847
+
1686
1848
  apply(op: AnimationSourceOp): AppliedAnimationOpsResult {
1687
1849
  const last = this.history.at(-1);
1850
+
1851
+ // Coalesce a set_key_value into a trailing insert_key on the same (animation, track)
1852
+ // only within the same explicit undo group (e.g. stage bone drag on an unkeyed frame).
1853
+ if (
1854
+ last !== undefined &&
1855
+ this.activeUndoGroupId !== undefined &&
1856
+ last.undoGroupId === this.activeUndoGroupId &&
1857
+ last.op.op === 'insert_key' &&
1858
+ op.op === 'set_key_value' &&
1859
+ last.op.animation === op.animation &&
1860
+ last.op.track === op.track
1861
+ ) {
1862
+ const { classification, keys } = resolveEditableTrack(
1863
+ this.currentText,
1864
+ op.animation,
1865
+ op.track,
1866
+ );
1867
+ const targetKey = keys[op.key];
1868
+ if (targetKey && targetKey.t === cleanMotionNumber(last.op.time)) {
1869
+ const channels = classification.channels;
1870
+ const nextValues = [...last.op.value];
1871
+ if (op.channel !== undefined) {
1872
+ if (
1873
+ !Number.isInteger(op.channel) ||
1874
+ op.channel < 0 ||
1875
+ op.channel >= channels ||
1876
+ typeof op.value !== 'number' ||
1877
+ !Number.isFinite(op.value)
1878
+ ) {
1879
+ throw new Error(
1880
+ `ANIMATION_VALUE_INVALID: expected finite number for channel ${String(op.channel)}`,
1881
+ );
1882
+ }
1883
+ nextValues[op.channel] = cleanMotionNumber(op.value);
1884
+ } else if (
1885
+ Array.isArray(op.value) &&
1886
+ op.value.length === channels &&
1887
+ op.value.every((n) => typeof n === 'number' && Number.isFinite(n))
1888
+ ) {
1889
+ for (let c = 0; c < channels; c++) {
1890
+ nextValues[c] = cleanMotionNumber(op.value[c]!);
1891
+ }
1892
+ } else {
1893
+ throw new Error(
1894
+ `ANIMATION_VALUE_INVALID: expected array of ${channels} finite number(s)`,
1895
+ );
1896
+ }
1897
+ const replayFrom = last.textBefore;
1898
+ const coalescedInsert: AnimationSourceOp = {
1899
+ ...last.op,
1900
+ value: nextValues,
1901
+ };
1902
+ const res = applyAnimationOp(
1903
+ replayFrom,
1904
+ coalescedInsert,
1905
+ this.baseText,
1906
+ this.fallbackEasings,
1907
+ );
1908
+ this.history.pop();
1909
+ this.history.push({
1910
+ op: coalescedInsert,
1911
+ textBefore: replayFrom,
1912
+ undoGroupId: this.activeUndoGroupId,
1913
+ explicitGroup: this.explicitGroupDepth > 0,
1914
+ });
1915
+ this.currentText = res.text;
1916
+ return res;
1917
+ }
1918
+ }
1919
+
1688
1920
  const sameKeyTarget =
1689
1921
  last !== undefined &&
1922
+ last.undoGroupId === this.activeUndoGroupId &&
1690
1923
  last.op.animation === op.animation &&
1691
1924
  last.op.track === op.track &&
1692
1925
  'key' in last.op &&
@@ -1707,44 +1940,44 @@ export class AnimationOpBuilder {
1707
1940
  : op;
1708
1941
  const res = applyAnimationOp(replayFrom, coalescedOp, this.baseText, this.fallbackEasings);
1709
1942
  this.history.pop();
1710
- if (res.text === this.baseText) {
1711
- this.history.length = 0;
1712
- this.currentText = this.baseText;
1713
- return { text: this.baseText, changedSpans: [] };
1714
- }
1715
1943
  if (res.text === replayFrom) {
1716
1944
  this.currentText = replayFrom;
1717
1945
  return { text: replayFrom, changedSpans: [] };
1718
1946
  }
1719
- this.history.push({ op: coalescedOp, textBefore: replayFrom });
1947
+ this.history.push({
1948
+ op: coalescedOp,
1949
+ textBefore: replayFrom,
1950
+ undoGroupId: this.activeUndoGroupId,
1951
+ explicitGroup: this.explicitGroupDepth > 0,
1952
+ });
1720
1953
  this.currentText = res.text;
1721
1954
  return res;
1722
1955
  }
1723
1956
 
1724
1957
  const res = applyAnimationOp(this.currentText, op, this.baseText, this.fallbackEasings);
1725
- if (res.text === this.baseText) {
1726
- this.history.length = 0;
1727
- this.currentText = this.baseText;
1728
- return { text: this.baseText, changedSpans: [] };
1729
- }
1730
1958
  if (res.text === this.currentText) {
1731
1959
  return { text: this.currentText, changedSpans: [] };
1732
1960
  }
1733
1961
  if (this.history.length >= MAX_ANIMATION_OPS) {
1734
1962
  throw new Error(
1735
- `ANIMATION_OPS_TOO_MANY: pending operations cannot exceed MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
1963
+ `ANIMATION_OPS_TOO_MANY: animation "${op.animation}" track ${op.track} operation "${op.op}" exceeds MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
1736
1964
  );
1737
1965
  }
1738
- this.history.push({ op, textBefore: this.currentText });
1966
+ this.history.push({
1967
+ op,
1968
+ textBefore: this.currentText,
1969
+ undoGroupId: this.activeUndoGroupId,
1970
+ explicitGroup: this.explicitGroupDepth > 0,
1971
+ });
1739
1972
  this.currentText = res.text;
1740
1973
  return res;
1741
1974
  }
1742
1975
 
1743
1976
  /**
1744
1977
  * Move a selection of `(track, key)` pairs in `animation` by `deltaTime` seconds
1745
- * atomically. When `deltaTime > 0`, keys on the same track are moved from right to left
1746
- * so an earlier key does not collide with its not-yet-moved right neighbor; when
1747
- * `deltaTime < 0`, from left to right. Refuses with `ANIMATION_OPS_TOO_MANY` (restoring
1978
+ * atomically as a single undo group. When `deltaTime > 0`, keys on the same track are moved
1979
+ * from right to left so an earlier key does not collide with its not-yet-moved right neighbor;
1980
+ * when `deltaTime < 0`, from left to right. Refuses with `ANIMATION_OPS_TOO_MANY` (restoring
1748
1981
  * the builder's prior state) if the move would exceed `MAX_ANIMATION_OPS`.
1749
1982
  */
1750
1983
  moveSelection(
@@ -1753,7 +1986,7 @@ export class AnimationOpBuilder {
1753
1986
  deltaTime: number,
1754
1987
  ): AppliedAnimationOpsResult {
1755
1988
  if (!Number.isFinite(deltaTime)) {
1756
- throw new Error(`ANIMATION_KEY_TIME_INVALID: deltaTime must be finite, got ${String(deltaTime)}`);
1989
+ throw new Error(`ANIMATION_KEY_TIME_INVALID: animation "${animation}" deltaTime must be finite, got ${String(deltaTime)}`);
1757
1990
  }
1758
1991
  if (selections.length === 0 || deltaTime === 0) {
1759
1992
  return { text: this.currentText, changedSpans: [] };
@@ -1770,7 +2003,7 @@ export class AnimationOpBuilder {
1770
2003
  const totalSelected = [...byTrack.values()].reduce((acc, a) => acc + a.length, 0);
1771
2004
  if (totalSelected > MAX_ANIMATION_OPS) {
1772
2005
  throw new Error(
1773
- `ANIMATION_OPS_TOO_MANY: selection move of ${totalSelected} keys exceeds MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
2006
+ `ANIMATION_OPS_TOO_MANY: animation "${animation}" selection move of ${totalSelected} keys exceeds MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
1774
2007
  );
1775
2008
  }
1776
2009
  const savedText = this.currentText;
@@ -1780,52 +2013,164 @@ export class AnimationOpBuilder {
1780
2013
  const sortedTracks = [...byTrack.keys()].sort((a, b) => a - b);
1781
2014
  const targetTimes = new Map<string, number>();
1782
2015
  for (const track of sortedTracks) {
1783
- const { keys } = resolveEditableTrack(this.currentText, animation, track);
2016
+ const { classification, keys } = resolveEditableTrack(this.currentText, animation, track);
1784
2017
  for (const key of byTrack.get(track)!) {
1785
2018
  const k = keys[key];
1786
2019
  if (!k) {
1787
- throw new Error(`ANIMATION_KEY_OUT_OF_RANGE: key index ${key} out of [0, ${keys.length - 1}]`);
2020
+ throw new Error(
2021
+ `ANIMATION_KEY_OUT_OF_RANGE: animation "${animation}" track ${track} ("${classification.target}.${classification.property}") key index ${key} out of [0, ${keys.length - 1}]`,
2022
+ );
1788
2023
  }
1789
2024
  targetTimes.set(`${track}:${key}`, cleanMotionNumber(k.t + deltaTime));
1790
2025
  }
1791
2026
  }
1792
2027
 
1793
- // Coalesce with a trailing batch of set_key_time ops on the same selection
2028
+ // Coalesce with a trailing batch of set_key_time ops on the exact same selection and undo context
2029
+ const last = this.history.at(-1);
1794
2030
  let suffixStart = this.history.length;
1795
- while (suffixStart > 0) {
1796
- const prev = this.history[suffixStart - 1]!.op;
1797
- if (
1798
- prev.op === 'set_key_time' &&
1799
- prev.animation === animation &&
1800
- targetTimes.has(`${prev.track}:${prev.key}`)
2031
+ let existingGroupId: number | undefined;
2032
+ const canTryCoalesce =
2033
+ last !== undefined &&
2034
+ last.undoGroupId !== undefined &&
2035
+ (this.activeUndoGroupId !== undefined
2036
+ ? last.undoGroupId === this.activeUndoGroupId
2037
+ : !last.explicitGroup);
2038
+ if (canTryCoalesce) {
2039
+ const candidateGroupId = last.undoGroupId!;
2040
+ const matchedTargets = new Set<string>();
2041
+ let candidateStart = this.history.length;
2042
+ let validBatch = true;
2043
+ while (
2044
+ candidateStart > 0 &&
2045
+ this.history[candidateStart - 1]!.undoGroupId === candidateGroupId
1801
2046
  ) {
1802
- suffixStart--;
1803
- } else {
1804
- break;
2047
+ const prev = this.history[candidateStart - 1]!.op;
2048
+ const targetKey = `${prev.track}:${'key' in prev ? prev.key : -1}`;
2049
+ if (
2050
+ prev.op === 'set_key_time' &&
2051
+ prev.animation === animation &&
2052
+ targetTimes.has(targetKey) &&
2053
+ !matchedTargets.has(targetKey)
2054
+ ) {
2055
+ matchedTargets.add(targetKey);
2056
+ candidateStart--;
2057
+ } else {
2058
+ validBatch = false;
2059
+ break;
2060
+ }
2061
+ }
2062
+ if (validBatch && matchedTargets.size === targetTimes.size) {
2063
+ suffixStart = candidateStart;
2064
+ existingGroupId = candidateGroupId;
1805
2065
  }
1806
2066
  }
1807
2067
  if (suffixStart < this.history.length) {
1808
2068
  this.currentText = this.history[suffixStart]!.textBefore;
1809
2069
  this.history.length = suffixStart;
1810
2070
  }
2071
+ if (this.history.length + totalSelected > MAX_ANIMATION_OPS) {
2072
+ throw new Error(
2073
+ `ANIMATION_OPS_TOO_MANY: animation "${animation}" selection move of ${totalSelected} keys with ${this.history.length} pending op(s) exceeds MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
2074
+ );
2075
+ }
1811
2076
 
1812
- for (const track of sortedTracks) {
1813
- const { keys } = resolveEditableTrack(this.currentText, animation, track);
1814
- const keyIndices = [...byTrack.get(track)!].sort((a, b) => {
1815
- const shiftA = targetTimes.get(`${track}:${a}`)! - keys[a]!.t;
1816
- return shiftA >= 0 ? b - a : a - b;
1817
- });
1818
- for (const key of keyIndices) {
1819
- const res = this.apply({
1820
- op: 'set_key_time',
1821
- animation,
1822
- track,
1823
- key,
1824
- time: targetTimes.get(`${track}:${key}`)!,
2077
+ const groupId = this.activeUndoGroupId ?? existingGroupId ?? this.beginUndoGroup();
2078
+ this.withInternalUndoGroup(groupId, () => {
2079
+ for (const track of sortedTracks) {
2080
+ const { keys } = resolveEditableTrack(this.currentText, animation, track);
2081
+ const keyIndices = [...byTrack.get(track)!].sort((a, b) => {
2082
+ const shiftA = targetTimes.get(`${track}:${a}`)! - keys[a]!.t;
2083
+ return shiftA >= 0 ? b - a : a - b;
1825
2084
  });
1826
- changedSpans.push(...res.changedSpans);
2085
+ for (const key of keyIndices) {
2086
+ const res = this.apply({
2087
+ op: 'set_key_time',
2088
+ animation,
2089
+ track,
2090
+ key,
2091
+ time: targetTimes.get(`${track}:${key}`)!,
2092
+ });
2093
+ changedSpans.push(...res.changedSpans);
2094
+ }
2095
+ }
2096
+ });
2097
+ return { text: this.currentText, changedSpans };
2098
+ } catch (err) {
2099
+ this.currentText = savedText;
2100
+ this.history.length = 0;
2101
+ this.history.push(...savedHistory);
2102
+ throw err;
2103
+ }
2104
+ }
2105
+
2106
+ /**
2107
+ * Delete a selection of `(track, key)` pairs in `animation` atomically as a single undo group.
2108
+ * Keys on the same track are deleted in descending index order so earlier indices remain stable.
2109
+ * Refuses with `ANIMATION_TRACK_MIN_KEYS` if any track would be left with `< 1` key, and
2110
+ * `ANIMATION_OPS_TOO_MANY` if the total pending ops would exceed `MAX_ANIMATION_OPS`.
2111
+ */
2112
+ deleteSelection(
2113
+ animation: string,
2114
+ selections: ReadonlyArray<{ track: number; key: number }>,
2115
+ ): AppliedAnimationOpsResult {
2116
+ if (selections.length === 0) {
2117
+ return { text: this.currentText, changedSpans: [] };
2118
+ }
2119
+ const byTrack = new Map<number, number[]>();
2120
+ for (const sel of selections) {
2121
+ let arr = byTrack.get(sel.track);
2122
+ if (!arr) {
2123
+ arr = [];
2124
+ byTrack.set(sel.track, arr);
2125
+ }
2126
+ if (!arr.includes(sel.key)) arr.push(sel.key);
2127
+ }
2128
+ const sortedTracks = [...byTrack.keys()].sort((a, b) => a - b);
2129
+ let totalSelected = 0;
2130
+ for (const track of sortedTracks) {
2131
+ const { classification, keys } = resolveEditableTrack(this.currentText, animation, track);
2132
+ const trackLabel = `animation "${animation}" track ${track} ("${classification.target}.${classification.property}")`;
2133
+ const keyIndices = [...byTrack.get(track)!].sort((a, b) => b - a);
2134
+ for (const k of keyIndices) {
2135
+ if (!Number.isInteger(k) || k < 0 || k >= keys.length) {
2136
+ throw new Error(
2137
+ `ANIMATION_KEY_OUT_OF_RANGE: ${trackLabel} key index ${k} out of [0, ${keys.length - 1}]`,
2138
+ );
1827
2139
  }
1828
2140
  }
2141
+ if (keys.length - keyIndices.length < 1) {
2142
+ throw new Error(
2143
+ `ANIMATION_TRACK_MIN_KEYS: ${trackLabel} cannot delete ${keyIndices.length} of ${keys.length} key(s); cannot delete the only key on a track`,
2144
+ );
2145
+ }
2146
+ byTrack.set(track, keyIndices);
2147
+ totalSelected += keyIndices.length;
2148
+ }
2149
+ if (this.history.length + totalSelected > MAX_ANIMATION_OPS) {
2150
+ throw new Error(
2151
+ `ANIMATION_OPS_TOO_MANY: animation "${animation}" selection delete of ${totalSelected} keys with ${this.history.length} pending op(s) exceeds MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
2152
+ );
2153
+ }
2154
+
2155
+ const savedText = this.currentText;
2156
+ const savedHistory = this.history.map((h) => ({ ...h }));
2157
+ const changedSpans: { start: number; end: number }[] = [];
2158
+ try {
2159
+ const groupId = this.activeUndoGroupId ?? this.beginUndoGroup();
2160
+ this.withInternalUndoGroup(groupId, () => {
2161
+ for (const track of sortedTracks) {
2162
+ const keyIndices = byTrack.get(track)!;
2163
+ for (const key of keyIndices) {
2164
+ const res = this.apply({
2165
+ op: 'delete_key',
2166
+ animation,
2167
+ track,
2168
+ key,
2169
+ });
2170
+ changedSpans.push(...res.changedSpans);
2171
+ }
2172
+ }
2173
+ });
1829
2174
  return { text: this.currentText, changedSpans };
1830
2175
  } catch (err) {
1831
2176
  this.currentText = savedText;
@@ -1838,7 +2183,16 @@ export class AnimationOpBuilder {
1838
2183
  undo(): boolean {
1839
2184
  const last = this.history.pop();
1840
2185
  if (!last) return false;
1841
- this.currentText = last.textBefore;
2186
+ let earliestTextBefore = last.textBefore;
2187
+ if (last.undoGroupId !== undefined) {
2188
+ while (
2189
+ this.history.length > 0 &&
2190
+ this.history.at(-1)!.undoGroupId === last.undoGroupId
2191
+ ) {
2192
+ earliestTextBefore = this.history.pop()!.textBefore;
2193
+ }
2194
+ }
2195
+ this.currentText = earliestTextBefore;
1842
2196
  return true;
1843
2197
  }
1844
2198