From 74faa4b2a42c60c77d1550e7288bf3333c15e25d Mon Sep 17 00:00:00 2001 From: Vance Ingalls Date: Fri, 3 Jul 2026 20:44:27 -0700 Subject: [PATCH 01/25] fix(sdk): moveElement survives GSAP animation per-axis via runtime delta translate (#1875) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(sdk): moveElement survives GSAP animation per-axis via runtime delta translate A committed moveElement wrote data-x/data-y but nothing rendered them: hosts shimmed CSS translate, which GSAP folds into the cached transform at first parse and then discards on the animated axis at every seek — dragging an animated element kept only the un-animated axis. Spike-proven on GSAP 3.15: a translate set AFTER GSAP's first parse is never read, folded, or cleared across seeks and composes natively with the animated transform. So: - moveElement captures the pre-edit baseline once (data-hf-edit-base-x/y) - the runtime (new core runtime/positionEdits.ts, applied at timeline bind — after GSAP parse) renders translate = (data-x − base), a pure delta that composes with GSAP tweens, tl.set positions, and CSS alike - applyDraft now drives the drag preview through the same translate channel (the --hf-studio-dx/dy vars had no consumer outside authored Studio bridges), and commitPreview mirrors the committed move onto the live element so it holds without an srcdoc reload Acceptance: packages/engine/scripts/test-runtime-position-edits-browser.ts (real Chrome + GSAP + runtime IIFE, no Studio shell) — X-animated, Y-animated, and static elements hold both edited axes across the full seek range. New subpath export @hyperframes/core/runtime/position-edits. Known limitation (documented): a tween created lazily at runtime that first-parses a marked element after apply folds the edit. Co-Authored-By: Claude Fable 5 * fix(sdk): harden position-edit rendering and the drag draft channel Fixes six issues from adversarial review of the moveElement stack: - Runtime: apply position edits at init as well as at timeline bind, so committed moves render in compositions with no usable GSAP timeline (CSS/WAAPI-animated or fully static) — previously the apply was unreachable outside the boundDuration > 0 bind branch and the edit silently vanished from reloads and renders. - Runtime: guard bind-path re-apply against post-fold double-apply — if the previously written translate was consumed externally (a lazily created tween folding it into GSAP's cached transform), skip instead of re-setting it on top ({force} escape hatch for editor commits). - Adapter: stop writing the --hf-studio-dx/dy custom properties during drags — compositions with the documented var-consuming drag-bridge CSS moved by twice the pointer delta (var transform + new inline translate). The inline translate is now the only draft channel; deltas accumulate in adapter fields. Docs updated to match. - Adapter: switching applyDraft to a new id reverts the abandoned element's draft translate instead of leaving it displaced with no op. - Adapter: cancelPreview restores the raw inline translate (removing it when there was none), so a stylesheet-authored translate is never promoted to a permanent inline style. - Adapter: commitPreview reverts the draft and clears state when dispatch throws, instead of leaving the element shifted by an uncommitted draft. Cleanups: reuse readCurrentTranslate from the core module (was a verbatim copy), drop the dead __hfApplyPositionEdits window hook. Browser acceptance test now also covers the GSAP-free composition path. Co-Authored-By: Claude Fable 5 * fix(core): prime GSAP transform cache before position-edit apply; add fold-loss telemetry Addresses PR #1875 review feedback (Rames, Miga): - Prime the element's GSAP transform parse (gsap.getProperty) before the first translate apply — positioned tl.set()s and tweens that first RENDER after the apply now reuse the cache instead of folding the edit. This closes the lazy-first-parse fold-loss for any page where GSAP is loaded at apply time; the residual limitation is GSAP itself loading after the apply. Proven by the extended browser acceptance test. - Emit position_edit_fold_skipped analytics at the fold-guard skip site so the residual degradation is observable instead of silent. - Browser acceptance test: add a both-axis-animated element (the shape that originated the per-axis loss) and a positioned tl.set() element, asserted across the full seek range. - Simplify the num() null guard (review nit). Co-Authored-By: Claude Fable 5 --------- Co-authored-by: Claude Fable 5 --- docs/sdk/guides/canvas-integration.mdx | 2 +- docs/sdk/reference/adapters.mdx | 6 +- packages/core/package.json | 10 + packages/core/src/runtime/analytics.ts | 3 +- packages/core/src/runtime/init.ts | 13 + .../core/src/runtime/positionEdits.test.ts | 150 ++++++++++ packages/core/src/runtime/positionEdits.ts | 167 +++++++++++ packages/core/tsconfig.json | 6 +- .../test-runtime-position-edits-browser.ts | 271 ++++++++++++++++++ packages/sdk/src/adapters/iframe.test.ts | 146 ++++++++-- packages/sdk/src/adapters/iframe.ts | 160 +++++++++-- packages/sdk/src/engine/mutate.test.ts | 27 ++ packages/sdk/src/engine/mutate.ts | 32 ++- 13 files changed, 929 insertions(+), 64 deletions(-) create mode 100644 packages/core/src/runtime/positionEdits.test.ts create mode 100644 packages/core/src/runtime/positionEdits.ts create mode 100644 packages/engine/scripts/test-runtime-position-edits-browser.ts diff --git a/docs/sdk/guides/canvas-integration.mdx b/docs/sdk/guides/canvas-integration.mdx index a60a912cdf..feea098842 100644 --- a/docs/sdk/guides/canvas-integration.mdx +++ b/docs/sdk/guides/canvas-integration.mdx @@ -86,7 +86,7 @@ iframeDoc.addEventListener("click", (e) => { The draft loop keeps the model clean during a drag. The SDK is **not** in the 60fps path — you call `preview.applyDraft` on every `pointermove` and `preview.commitPreview` once on `pointerup`. The model sees exactly one `moveElement` op per drag, rather than hundreds. -`applyDraft` writes CSS custom properties (`--hf-studio-dx`, `--hf-studio-dy`) directly onto the target element inside the iframe. The composition's CSS uses these vars to translate the element visually. Nothing in the SDK model changes. +`applyDraft` sets the element's CSS `translate` directly inside the iframe — the pre-drag value composed with the accumulated delta — so the drag is visible in any composition without composition-side CSS, and works on GSAP-animated elements (a `translate` set after GSAP's first parse composes with the animated transform instead of being overwritten). Nothing in the SDK model changes. `cancelPreview` restores the pre-drag translate; `commitPreview` derives one `moveElement` op and mirrors the committed position onto the live element. ```typescript let dragging = false; diff --git a/docs/sdk/reference/adapters.mdx b/docs/sdk/reference/adapters.mdx index 8a8666dc8c..87e149e71c 100644 --- a/docs/sdk/reference/adapters.mdx +++ b/docs/sdk/reference/adapters.mdx @@ -100,15 +100,15 @@ interface PreviewAdapter { - Applies draft CSS markers to the preview element at 60fps during a drag. Writes CSS custom properties (`--hf-studio-dx`, `--hf-studio-dy`) onto the element so the composition's CSS can visually translate it without touching the model. The **SDK is not called here** — this is a direct write to the preview surface by your pointer-move handler. + Visually translates the preview element at 60fps during a drag: sets the element's CSS `translate` to its pre-drag value composed with the accumulated delta. Works on GSAP-animated elements (a `translate` set after GSAP's first parse composes with the animated transform). The **SDK is not called here** — this is a direct write to the preview surface by your pointer-move handler. Switching `id` mid-drag reverts the previous element's draft first. - Called once on pointer-up. Reads the accumulated draft markers, derives a `moveElement` op from them, dispatches it into the SDK, emits a patch event, and clears the markers. This is the only moment the SDK becomes aware of a drag. + Called once on pointer-up. Reads the accumulated draft delta, derives a `moveElement` op from it, dispatches it into the SDK, emits a patch event, and mirrors the committed position onto the live element (so it holds without a reload). This is the only moment the SDK becomes aware of a drag. If dispatch throws, the draft translate is reverted and the error propagates. - Reverts the draft CSS markers without dispatching any op. The model is never changed. Call this on `Escape` keydown or when a drag is aborted. + Restores the element's pre-drag `translate` without dispatching any op. The model is never changed. Call this on `Escape` keydown or when a drag is aborted. diff --git a/packages/core/package.json b/packages/core/package.json index ca06a8d686..2c541d3d48 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -95,6 +95,12 @@ "import": "./src/runtime/clipTree.ts", "types": "./src/runtime/clipTree.ts" }, + "./runtime/position-edits": { + "bun": "./src/runtime/positionEdits.ts", + "node": "./dist/runtime/positionEdits.js", + "import": "./src/runtime/positionEdits.ts", + "types": "./src/runtime/positionEdits.ts" + }, "./runtime/lottie-readiness": { "bun": "./src/lottieReadiness.ts", "node": "./dist/lottieReadiness.js", @@ -269,6 +275,10 @@ "import": "./dist/runtime/clipTree.js", "types": "./dist/runtime/clipTree.d.ts" }, + "./runtime/position-edits": { + "import": "./dist/runtime/positionEdits.js", + "types": "./dist/runtime/positionEdits.d.ts" + }, "./runtime/lottie-readiness": { "import": "./dist/lottieReadiness.js", "types": "./dist/lottieReadiness.d.ts" diff --git a/packages/core/src/runtime/analytics.ts b/packages/core/src/runtime/analytics.ts index 119aa2aeef..795c20e1f5 100644 --- a/packages/core/src/runtime/analytics.ts +++ b/packages/core/src/runtime/analytics.ts @@ -12,7 +12,8 @@ export type RuntimeAnalyticsEvent = | "composition_paused" | "composition_seeked" | "composition_ended" - | "element_picked"; + | "element_picked" + | "position_edit_fold_skipped"; export type RuntimeAnalyticsProperties = Record; diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts index 2db41d2265..74cb5453b8 100644 --- a/packages/core/src/runtime/init.ts +++ b/packages/core/src/runtime/init.ts @@ -28,6 +28,7 @@ import { createRuntimeStartTimeResolver } from "./startResolver"; import { createClipTree } from "./clipTree"; import { loadExternalCompositions, loadInlineTemplateCompositions } from "./compositionLoader"; import { applyCaptionOverrides } from "./captionOverrides"; +import { applyPositionEdits } from "./positionEdits"; import { createColorGradingRuntime, type RuntimeColorGradingApi } from "./colorGrading"; import { TransportClock } from "./clock"; import { WebAudioTransport } from "./webAudioTransport"; @@ -72,6 +73,12 @@ function resolveExportRenderFps(): ExportRenderFpsResolution { export function initSandboxRuntimeModular(): void { const state = createRuntimeState(); + // SDK moveElement edits must render even when no usable GSAP timeline ever + // binds (CSS/WAAPI-animated or fully static compositions) — apply at init. + // This runs at DOMContentLoaded, after inline composition scripts have + // parsed their tweens, so GSAP (when present) won't fold the translate. + // Re-applied on every timeline bind for the rebind/soft-reload paths. + applyPositionEdits(document); const exportRenderFps = resolveExportRenderFps(); state.canonicalFps = exportRenderFps.fps ?? state.canonicalFps; if (window.__HF_EXPORT_RENDER_SEEK_CONFIG) { @@ -1198,6 +1205,12 @@ export function initSandboxRuntimeModular(): void { // during initial rebind (timing race on first load / soft reload). const applyFn = (window as Record).__hfStudioManualEditsApply; if (typeof applyFn === "function") applyFn(); + + // SDK moveElement edits (data-hf-edit-base-x/y markers) render as a + // CSS translate delta. Must run after the timeline is bound so GSAP has + // already parsed the elements — a translate present at first parse gets + // folded into the cached transform and lost per-axis on seek. + applyPositionEdits(document); } if (resolution.diagnostics) { postRuntimeMessage({ diff --git a/packages/core/src/runtime/positionEdits.test.ts b/packages/core/src/runtime/positionEdits.test.ts new file mode 100644 index 0000000000..d7eae7343c --- /dev/null +++ b/packages/core/src/runtime/positionEdits.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, it } from "vitest"; +import { + EDIT_BASE_X_ATTR, + EDIT_BASE_Y_ATTR, + EDIT_ORIGINAL_TRANSLATE_ATTR, + applyPositionEditToElement, + applyPositionEdits, + composeTranslate, +} from "./positionEdits"; + +function makeElement(attrs: Record, style = ""): HTMLElement { + const el = document.createElement("div"); + for (const [name, value] of Object.entries(attrs)) el.setAttribute(name, value); + if (style) el.setAttribute("style", style); + document.body.appendChild(el); + return el; +} + +describe("composeTranslate", () => { + it("returns the delta alone when there is no original", () => { + expect(composeTranslate("", "10px", "20px")).toBe("10px 20px"); + expect(composeTranslate("none", "10px", "20px")).toBe("10px 20px"); + }); + + it("adds px values numerically", () => { + expect(composeTranslate("5px 6px", "10px", "20px")).toBe("15px 26px"); + expect(composeTranslate("-5.5px 6px", "10px", "-20px")).toBe("4.5px -14px"); + }); + + it("treats a single-part original as x-only", () => { + expect(composeTranslate("5px", "10px", "20px")).toBe("15px 20px"); + }); + + it("falls back to calc() for non-px units and preserves z", () => { + expect(composeTranslate("10% 6px", "10px", "20px")).toBe("calc(10% + 10px) 26px"); + expect(composeTranslate("1px 2px 3px", "10px", "20px")).toBe("11px 22px 3px"); + }); +}); + +describe("applyPositionEdits", () => { + it("ignores unmarked elements", () => { + const el = makeElement({ "data-x": "100", "data-y": "50" }); + expect(applyPositionEdits(document)).toBe(0); + expect(el.style.getPropertyValue("translate")).toBe(""); + el.remove(); + }); + + it("applies the delta between data-x/y and the captured baseline", () => { + const el = makeElement({ + "data-x": "150", + "data-y": "-30", + [EDIT_BASE_X_ATTR]: "100", + [EDIT_BASE_Y_ATTR]: "20", + }); + expect(applyPositionEdits(document)).toBe(1); + expect(el.style.getPropertyValue("translate")).toBe("50px -50px"); + expect(el.getAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR)).toBe(""); + el.remove(); + }); + + it("treats missing data-x/y or baseline attributes as 0", () => { + const el = makeElement({ "data-x": "40", [EDIT_BASE_X_ATTR]: "0" }); + applyPositionEdits(document); + expect(el.style.getPropertyValue("translate")).toBe("40px 0px"); + el.remove(); + }); + + it("composes with a pre-existing inline translate and stays idempotent", () => { + const el = makeElement( + { "data-x": "10", "data-y": "20", [EDIT_BASE_X_ATTR]: "0", [EDIT_BASE_Y_ATTR]: "0" }, + "translate: 5px 6px", + ); + applyPositionEdits(document); + expect(el.style.getPropertyValue("translate")).toBe("15px 26px"); + expect(el.getAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR)).toBe("5px 6px"); + // Second application must not compound. + applyPositionEdits(document); + expect(el.style.getPropertyValue("translate")).toBe("15px 26px"); + el.remove(); + }); + + it("recomputes from the same baseline after data-x changes", () => { + const el = makeElement({ + "data-x": "10", + "data-y": "0", + [EDIT_BASE_X_ATTR]: "0", + [EDIT_BASE_Y_ATTR]: "0", + }); + applyPositionEdits(document); + expect(el.style.getPropertyValue("translate")).toBe("10px 0px"); + el.setAttribute("data-x", "70"); + applyPositionEdits(document); + expect(el.style.getPropertyValue("translate")).toBe("70px 0px"); + el.remove(); + }); + + it("never re-captures the original translate once set", () => { + const el = makeElement({ + "data-x": "10", + "data-y": "0", + [EDIT_BASE_X_ATTR]: "0", + [EDIT_BASE_Y_ATTR]: "0", + [EDIT_ORIGINAL_TRANSLATE_ATTR]: "3px 4px", + }); + applyPositionEdits(document); + expect(el.style.getPropertyValue("translate")).toBe("13px 4px"); + el.remove(); + }); + + it("counts and applies multiple marked elements", () => { + const a = makeElement({ "data-x": "1", [EDIT_BASE_X_ATTR]: "0" }); + const b = makeElement({ "data-y": "2", [EDIT_BASE_Y_ATTR]: "0" }); + expect(applyPositionEdits(document)).toBe(2); + a.remove(); + b.remove(); + }); + + it("skips re-apply when the written translate was consumed externally (GSAP fold)", () => { + const el = makeElement({ + "data-x": "10", + "data-y": "20", + [EDIT_BASE_X_ATTR]: "0", + [EDIT_BASE_Y_ATTR]: "0", + }); + applyPositionEdits(document); + expect(el.style.getPropertyValue("translate")).toBe("10px 20px"); + // GSAP folding the translate into its cached transform writes "none". + el.style.setProperty("translate", "none"); + applyPositionEdits(document); + // Re-setting would double the offset on non-animated axes — must skip. + expect(el.style.getPropertyValue("translate")).toBe("none"); + el.remove(); + }); + + it("force re-applies over a clobbered translate (editor commit path)", () => { + const el = makeElement({ + "data-x": "10", + "data-y": "20", + [EDIT_BASE_X_ATTR]: "0", + [EDIT_BASE_Y_ATTR]: "0", + }); + applyPositionEditToElement(el); + // A drag draft overwrites the translate; the commit must recompute. + el.style.setProperty("translate", "999px 999px"); + el.setAttribute("data-x", "30"); + applyPositionEditToElement(el, { force: true }); + expect(el.style.getPropertyValue("translate")).toBe("30px 20px"); + el.remove(); + }); +}); diff --git a/packages/core/src/runtime/positionEdits.ts b/packages/core/src/runtime/positionEdits.ts new file mode 100644 index 0000000000..0fabec7635 --- /dev/null +++ b/packages/core/src/runtime/positionEdits.ts @@ -0,0 +1,167 @@ +// fallow-ignore-file code-duplication +// (splitTopLevelWhitespace intentionally mirrors the studio-side copies in +// manualEditsDom.ts / manualEditsRenderScript.ts — this module ships inside +// the self-contained runtime bundle and cannot import studio code.) +/** + * Editor position edits (SDK `moveElement`) applied at render time. + * + * The SDK's `moveElement` writes `data-x` / `data-y` plus a captured baseline + * (`data-hf-edit-base-x` / `data-hf-edit-base-y` — the values before the first + * edit). The runtime renders the edit as the DELTA between the two, via the + * independent CSS `translate` longhand, so it composes additively with any + * position the composition itself produces (GSAP tweens, `tl.set`, CSS). + * + * Why `translate` and why after timeline bind: GSAP folds a `translate` that + * is present when it FIRST parses an element into its cached transform (and + * an absolute tween then discards it on the animated axis — the per-axis loss + * bug). A `translate` set AFTER that parse is never read, cleared, or baked + * by GSAP 3.x on subsequent seeks, so a single application at bind time holds + * for the whole timeline. Before the first apply, the element's transform + * parse is primed (gsap.getProperty) so tweens and positioned set()s that + * first RENDER later reuse the cache instead of folding the edit. Known + * limitation: if GSAP itself loads only after the apply ran, a later tween's + * first parse still folds the edit (the fold guard then skips re-apply and + * emits position_edit_fold_skipped instead of double-applying). + */ + +import { emitAnalyticsEvent } from "./analytics"; + +export const EDIT_BASE_X_ATTR = "data-hf-edit-base-x"; +export const EDIT_BASE_Y_ATTR = "data-hf-edit-base-y"; +export const EDIT_ORIGINAL_TRANSLATE_ATTR = "data-hf-edit-original-translate"; + +const num = (value: string | null): number => { + const n = parseFloat(value ?? ""); + return Number.isFinite(n) ? n : 0; +}; + +/** Split "10px 20px" / "calc(1px + 2px) 3px" on top-level whitespace only. */ +const splitTopLevelWhitespace = (value: string): string[] => { + const parts: string[] = []; + let depth = 0; + let current = ""; + for (const char of value.trim()) { + if (char === "(") depth += 1; + if (char === ")") depth = Math.max(0, depth - 1); + if (/\s/.test(char) && depth === 0) { + if (current) parts.push(current); + current = ""; + } else { + current += char; + } + } + if (current) parts.push(current); + return parts; +}; + +const PX_VALUE = /^-?(?:\d+(?:\.\d+)?|\.\d+)px$/; + +/** Sum two lengths — numerically when both are plain px, via calc() otherwise. */ +const addLengths = (a: string, b: string): string => { + if (PX_VALUE.test(a) && PX_VALUE.test(b)) return `${parseFloat(a) + parseFloat(b)}px`; + return `calc(${a} + ${b})`; +}; + +/** Compose the edit delta with the element's pre-edit translate value. */ +export const composeTranslate = (original: string, x: string, y: string): string => { + if (!original || original === "none") return `${x} ${y}`; + const [ox, oy, oz] = splitTopLevelWhitespace(original); + if (ox === undefined) return `${x} ${y}`; + if (oy === undefined) return `${addLengths(ox, x)} ${y}`; + const z = oz === undefined ? "" : ` ${oz}`; + return `${addLengths(ox, x)} ${addLengths(oy, y)}${z}`; +}; + +/** + * Force GSAP (when present) to parse and cache the element's transform BEFORE + * the edit translate is written. GSAP folds a CSS `translate` it sees at an + * element's first parse into its cached transform (losing it per-axis on + * absolute tweens); once the cache exists, later tweens and positioned set()s + * reuse it and never read the translate again. gsap.getProperty parses + * without mutating the element. Best-effort — absent or failing GSAP is fine. + */ +const primeGsapTransformCache = (el: HTMLElement): void => { + try { + const view = el.ownerDocument.defaultView as + | (Window & { gsap?: { getProperty?: (t: Element, p: string) => unknown } }) + | null; + view?.gsap?.getProperty?.(el, "x"); + } catch { + // parse priming is an optimization, never a requirement + } +}; + +/** The element's effective translate: inline if set, computed otherwise ("" = none). */ +export const readCurrentTranslate = (el: HTMLElement): string => { + const inline = el.style.getPropertyValue("translate").trim(); + if (inline) return inline === "none" ? "" : inline; + try { + const view = el.ownerDocument.defaultView; + const computed = view ? view.getComputedStyle(el).getPropertyValue("translate").trim() : ""; + return computed === "none" ? "" : computed; + } catch { + return ""; + } +}; + +/** + * The translate value this module last wrote per element. When a re-apply + * (timeline rebind) finds the element's inline translate no longer matching, + * something else consumed it — in practice GSAP folding it into the cached + * transform when a lazily-created tween first-parsed the element. Re-setting + * it then would DOUBLE the offset on every axis the tween doesn't animate, so + * the non-forced path skips instead (degrading to the documented fold-loss). + */ +const lastAppliedTranslate = new WeakMap(); + +/** + * Apply one element's position edit. Idempotent — the pre-edit translate is + * captured exactly once (into EDIT_ORIGINAL_TRANSLATE_ATTR, empty string + * meaning "none") on first application, and every application recomputes from + * that baseline. + * + * `force` re-applies even when the previously written translate was clobbered + * externally — used by editor commits, where the current inline translate is + * the draft-composed one and must be overwritten. + */ +export function applyPositionEditToElement(el: HTMLElement, opts?: { force?: boolean }): void { + const previous = lastAppliedTranslate.get(el); + if ( + !opts?.force && + previous !== undefined && + el.style.getPropertyValue("translate") !== previous + ) { + // Observable signal for the documented degradation — without it, a + // fold-loss surfaces to users only as "my edit didn't stick". + emitAnalyticsEvent("position_edit_fold_skipped", { + hfId: el.getAttribute("data-hf-id"), + }); + return; + } + const dx = num(el.getAttribute("data-x")) - num(el.getAttribute(EDIT_BASE_X_ATTR)); + const dy = num(el.getAttribute("data-y")) - num(el.getAttribute(EDIT_BASE_Y_ATTR)); + if (!el.hasAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR)) { + el.setAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR, readCurrentTranslate(el)); + } + if (previous === undefined) primeGsapTransformCache(el); + const original = el.getAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR) ?? ""; + const value = composeTranslate(original, `${dx}px`, `${dy}px`); + el.style.setProperty("translate", value); + lastAppliedTranslate.set(el, el.style.getPropertyValue("translate")); +} + +/** + * Apply all pending position edits in the document. Returns the number of + * elements updated. + */ +export function applyPositionEdits(doc: Document): number { + const marked = doc.querySelectorAll(`[${EDIT_BASE_X_ATTR}], [${EDIT_BASE_Y_ATTR}]`); + let applied = 0; + for (let i = 0; i < marked.length; i++) { + const el = marked[i]; + if (!(el instanceof HTMLElement)) continue; + applyPositionEditToElement(el); + applied += 1; + } + return applied; +} diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json index e400fc1acc..bf6eb101e7 100644 --- a/packages/core/tsconfig.json +++ b/packages/core/tsconfig.json @@ -13,7 +13,11 @@ "outDir": "./dist", "rootDir": "./src" }, - "files": ["src/runtime/clipTree.ts", "src/runtime/mediaVolumeEnvelope.ts"], + "files": [ + "src/runtime/clipTree.ts", + "src/runtime/mediaVolumeEnvelope.ts", + "src/runtime/positionEdits.ts" + ], "include": ["src/**/*"], "exclude": [ "node_modules", diff --git a/packages/engine/scripts/test-runtime-position-edits-browser.ts b/packages/engine/scripts/test-runtime-position-edits-browser.ts new file mode 100644 index 0000000000..048d5243ef --- /dev/null +++ b/packages/engine/scripts/test-runtime-position-edits-browser.ts @@ -0,0 +1,271 @@ +// fallow-ignore-file unused-file code-duplication complexity +/** + * Browser acceptance test: SDK moveElement edits survive GSAP animation + * per-axis (the AI Studio embedded-editor per-axis loss bug). + * + * Launches headless Chrome with real GSAP + the real runtime IIFE, loads a + * fixture whose elements carry committed moveElement state (data-x/data-y + + * data-hf-edit-base-x/y), seeks the timeline across its range, and asserts + * the rendered position reflects the edit on BOTH axes at every sample: + * - an X-animated element keeps its edited offset while X animates + * - a Y-animated element keeps its edited offset while Y animates + * - a static element keeps both + * + * Runs in the plain embedded runtime — no Studio shell, no manual-edits + * render script — matching what third-party SDK consumers load. + * + * Requires: puppeteer + gsap (monorepo deps, dynamically resolved; skips + * with a notice when unavailable). + * Run: cd packages/engine && npx tsx scripts/test-runtime-position-edits-browser.ts + */ + +import { createRequire } from "node:module"; +import { readFileSync } from "node:fs"; +import { resolve as resolvePath, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { buildHyperframesRuntimeScript } from "../../core/src/inline-scripts/hyperframesRuntime.engine"; + +const thisDir = dirname(fileURLToPath(import.meta.url)); + +function assert(condition: unknown, message: string): void { + if (!condition) { + throw new Error(`FAIL: ${message}`); + } +} + +function loadGsapSource(): string | null { + const req = createRequire(import.meta.url); + // gsap is a dep of studio / player / sdk-playground, hoisted in the + // workspace store — resolve through whichever package has it. + for (const pkg of ["studio", "player", "sdk-playground"]) { + try { + const path = req.resolve("gsap/dist/gsap.min.js", { + paths: [resolvePath(thisDir, `../../${pkg}`)], + }); + return readFileSync(path, "utf8"); + } catch { + // try the next package + } + } + return null; +} + +interface Sample { + t: number; + ax: { x: number; y: number }; + ay: { x: number; y: number }; + axy: { x: number; y: number }; + ts: { x: number; y: number }; + st: { x: number; y: number }; +} + +async function main(): Promise { + let puppeteer; + try { + puppeteer = (await import("puppeteer")).default; + } catch { + console.log( + JSON.stringify({ + event: "runtime_position_edits_browser_test_skipped", + reason: "puppeteer not available", + }), + ); + return; + } + + const gsapSource = loadGsapSource(); + if (gsapSource === null) { + console.log( + JSON.stringify({ + event: "runtime_position_edits_browser_test_skipped", + reason: "gsap not available", + }), + ); + return; + } + + const runtimeSource = buildHyperframesRuntimeScript({ minify: false }); + assert( + runtimeSource !== null, + "buildHyperframesRuntimeScript returned null — entry.ts not found", + ); + + // Committed moveElement state: every element moved by (50, -70). data-x/y + // hold the post-edit values; data-hf-edit-base-x/y hold the pre-edit ones + // (absent → "0"), exactly as handleMoveElement serializes them. + const html = ` + +
+
+
+
+
+
+
+ + + +`; + + const browser = await puppeteer.launch({ + headless: true, + args: ["--no-sandbox", "--disable-setuid-sandbox"], + }); + + try { + const page = await browser.newPage(); + await page.setContent(html, { waitUntil: "networkidle0", timeout: 10000 }); + + // The runtime applies position edits after it binds the timeline — wait + // for the translate to land on a marked element. String form: tsx/esbuild + // injects a __name helper into serialized closures that the page lacks. + await page.waitForFunction( + `(function () { + var el = document.getElementById("ax"); + return el !== null && getComputedStyle(el).translate !== "none"; + })()`, + { timeout: 10000 }, + ); + + const sampleScript = `(function (time) { + if (window.__player && typeof window.__player.renderSeek === "function") { + window.__player.renderSeek(time); + } else if (window.__hf && typeof window.__hf.seek === "function") { + window.__hf.seek(time); + } else { + throw new Error("no runtime seek surface (__player.renderSeek / __hf.seek)"); + } + function read(id) { + var el = document.getElementById(id); + if (!el) throw new Error("missing #" + id); + var cs = getComputedStyle(el); + var m = new DOMMatrix(cs.transform === "none" ? "" : cs.transform); + var parts = cs.translate === "none" ? [] : cs.translate.split(" "); + var tx = parts.length > 0 ? parseFloat(parts[0]) : 0; + var ty = parts.length > 1 ? parseFloat(parts[1]) : 0; + return { x: m.m41 + tx, y: m.m42 + ty }; + } + return { + t: time, + ax: read("ax"), + ay: read("ay"), + axy: read("axy"), + ts: read("ts"), + st: read("st"), + }; + })`; + + const samples: Sample[] = []; + for (const t of [0, 1, 2.5, 4]) { + const sample = (await page.evaluate(`(${sampleScript})(${t})`)) as Sample; + samples.push(sample); + } + + const close = (actual: number, expected: number): boolean => Math.abs(actual - expected) <= 0.5; + + for (const s of samples) { + // X-animated: x = animation (100·t) + edit (50); y = edit (−70). + assert( + close(s.ax.x, 100 * s.t + 50), + `t=${s.t}: X-animated element x should be ${100 * s.t + 50}, got ${s.ax.x}`, + ); + assert(close(s.ax.y, -70), `t=${s.t}: X-animated element y should keep -70, got ${s.ax.y}`); + // Y-animated: y = animation (75·t) + edit (−70); x = edit (50). + assert(close(s.ay.x, 50), `t=${s.t}: Y-animated element x should keep 50, got ${s.ay.x}`); + assert( + close(s.ay.y, 75 * s.t - 70), + `t=${s.t}: Y-animated element y should be ${75 * s.t - 70}, got ${s.ay.y}`, + ); + // Both-axis-animated: both axes = animation + edit (the shape that + // originated the per-axis loss bug). + assert( + close(s.axy.x, 100 * s.t + 50), + `t=${s.t}: XY-animated element x should be ${100 * s.t + 50}, got ${s.axy.x}`, + ); + assert( + close(s.axy.y, 75 * s.t - 70), + `t=${s.t}: XY-animated element y should be ${75 * s.t - 70}, got ${s.axy.y}`, + ); + // tl.set at t=1.0: before it fires, position = edit only; after, set + edit. + const setX = s.t >= 1.0 ? 200 : 0; + const setY = s.t >= 1.0 ? 100 : 0; + assert( + close(s.ts.x, setX + 50), + `t=${s.t}: tl.set element x should be ${setX + 50}, got ${s.ts.x}`, + ); + assert( + close(s.ts.y, setY - 70), + `t=${s.t}: tl.set element y should be ${setY - 70}, got ${s.ts.y}`, + ); + // Static: both axes hold the edit. + assert(close(s.st.x, 50), `t=${s.t}: static element x should be 50, got ${s.st.x}`); + assert(close(s.st.y, -70), `t=${s.t}: static element y should be -70, got ${s.st.y}`); + } + + // GSAP-free composition: no window.gsap, no timelines — the edit must + // still render (applied at runtime init, not only at timeline bind). + const gsapFreeHtml = ` + +
+
+
+ +`; + + const page2 = await browser.newPage(); + await page2.setContent(gsapFreeHtml, { waitUntil: "networkidle0", timeout: 10000 }); + await page2.waitForFunction( + `(function () { + var el = document.getElementById("st"); + return el !== null && getComputedStyle(el).translate !== "none"; + })()`, + { timeout: 10000 }, + ); + const gsapFree = (await page2.evaluate( + `(function () { + var cs = getComputedStyle(document.getElementById("st")); + return { translate: cs.translate }; + })()`, + )) as { translate: string }; + assert( + gsapFree.translate === "50px -70px", + `GSAP-free composition should render the edit as translate 50px -70px, got ${gsapFree.translate}`, + ); + + console.log( + JSON.stringify({ + event: "runtime_position_edits_browser_test_passed", + samples, + gsapFree, + }), + ); + } finally { + await browser.close(); + } +} + +main().catch((err) => { + console.error(err.message); + process.exit(1); +}); diff --git a/packages/sdk/src/adapters/iframe.test.ts b/packages/sdk/src/adapters/iframe.test.ts index e274800ae5..2d7c1afb7a 100644 --- a/packages/sdk/src/adapters/iframe.test.ts +++ b/packages/sdk/src/adapters/iframe.test.ts @@ -218,12 +218,12 @@ interface FakeStyle { } interface FakeDomEl { - "data-hf-id": string; - "data-x": string | null; - "data-y": string | null; + _attrs: Record; style: FakeStyle; isConnected: boolean; getAttribute(name: string): string | null; + setAttribute(name: string, value: string): void; + hasAttribute(name: string): boolean; querySelector(sel: string): FakeDomEl | null; } @@ -240,17 +240,21 @@ function fakeDomEl(id: string, dataX: string | null, dataY: string | null): Fake delete this._props[name]; }, }; + const attrs: Record = { "data-hf-id": id }; + if (dataX !== null) attrs["data-x"] = dataX; + if (dataY !== null) attrs["data-y"] = dataY; const el: FakeDomEl = { - "data-hf-id": id, - "data-x": dataX, - "data-y": dataY, + _attrs: attrs, style, isConnected: true, getAttribute(name) { - if (name === "data-x") return this["data-x"]; - if (name === "data-y") return this["data-y"]; - if (name === "data-hf-id") return this["data-hf-id"]; - return null; + return this._attrs[name] ?? null; + }, + setAttribute(name, value) { + this._attrs[name] = value; + }, + hasAttribute(name) { + return name in this._attrs; }, querySelector(_sel: string) { return null; @@ -316,6 +320,55 @@ describe("IframePreviewAdapter draft / commit / cancel", () => { }); }); + it("commitPreview mirrors the move onto the live element and applies the translate", () => { + const el = fakeDomEl("hf-abc", "100", "200"); + const adapter = createIframePreviewAdapter(fakeIframe(el), vi.fn()); + + adapter.applyDraft("hf-abc", { dx: 30, dy: -20 }); + adapter.commitPreview(); + + expect(el.getAttribute("data-x")).toBe("130"); + expect(el.getAttribute("data-y")).toBe("180"); + // Baseline captured from the pre-drag values. + expect(el.getAttribute("data-hf-edit-base-x")).toBe("100"); + expect(el.getAttribute("data-hf-edit-base-y")).toBe("200"); + // Final translate = delta from the baseline, held without a reload. + expect(el.getAttribute("data-hf-edit-original-translate")).toBe(""); + expect(el.style.getPropertyValue("translate")).toBe("30px -20px"); + + // A second drag composes from the committed state and keeps the baseline. + adapter.applyDraft("hf-abc", { dx: 10, dy: 10 }); + expect(el.style.getPropertyValue("translate")).toBe("40px -10px"); + adapter.commitPreview(); + expect(el.getAttribute("data-x")).toBe("140"); + expect(el.getAttribute("data-hf-edit-base-x")).toBe("100"); + expect(el.style.getPropertyValue("translate")).toBe("40px -10px"); + }); + + it("applyDraft translates the element live and cancelPreview restores it", () => { + const el = fakeDomEl("hf-abc", "0", "0"); + el.style.setProperty("translate", "5px 6px"); + const adapter = createIframePreviewAdapter(fakeIframe(el), vi.fn()); + + adapter.applyDraft("hf-abc", { dx: 30, dy: -20 }); + expect(el.style.getPropertyValue("translate")).toBe("35px -14px"); + + adapter.cancelPreview(); + expect(el.style.getPropertyValue("translate")).toBe("5px 6px"); + expect(el.getAttribute("data-hf-edit-base-x")).toBeNull(); + }); + + it("cancelPreview removes a draft translate when there was none before", () => { + const el = fakeDomEl("hf-abc", "0", "0"); + const adapter = createIframePreviewAdapter(fakeIframe(el), vi.fn()); + + adapter.applyDraft("hf-abc", { dx: 30 }); + expect(el.style.getPropertyValue("translate")).toBe("30px 0px"); + + adapter.cancelPreview(); + expect(el.style.getPropertyValue("translate")).toBe(""); + }); + it("applyDraft reuses the cached element across repeated calls (no re-query)", () => { const el = fakeDomEl("hf-abc", "0", "0"); let queryCount = 0; @@ -344,30 +397,17 @@ describe("IframePreviewAdapter draft / commit / cancel", () => { adapter.commitPreview(); }); - it("cancelPreview clears draft vars without dispatching", () => { + it("cancelPreview reverts the draft translate without dispatching", () => { const dispatch = vi.fn(); const el = fakeDomEl("hf-abc", "100", "200"); const adapter = createIframePreviewAdapter(fakeIframe(el), dispatch); adapter.applyDraft("hf-abc", { dx: 30, dy: 20 }); + expect(el.style.getPropertyValue("translate")).toBe("30px 20px"); adapter.cancelPreview(); expect(dispatch).not.toHaveBeenCalled(); - // CSS vars cleared - expect(el.style.getPropertyValue("--hf-studio-dx")).toBe(""); - expect(el.style.getPropertyValue("--hf-studio-dy")).toBe(""); - }); - - it("commitPreview clears draft vars after dispatching", () => { - const dispatch = vi.fn(); - const el = fakeDomEl("hf-abc", "0", "0"); - const adapter = createIframePreviewAdapter(fakeIframe(el), dispatch); - - adapter.applyDraft("hf-abc", { dx: 10, dy: 5 }); - adapter.commitPreview(); - - expect(el.style.getPropertyValue("--hf-studio-dx")).toBe(""); - expect(el.style.getPropertyValue("--hf-studio-dy")).toBe(""); + expect(el.style.getPropertyValue("translate")).toBe(""); }); it("second commitPreview after first is a no-op (draft cleared)", () => { @@ -381,6 +421,60 @@ describe("IframePreviewAdapter draft / commit / cancel", () => { expect(dispatch).toHaveBeenCalledTimes(1); }); + + it("switching applyDraft to a new id reverts the abandoned element", () => { + const elA = fakeDomEl("hf-a", "0", "0"); + const elB = fakeDomEl("hf-b", "0", "0"); + const iframe = { + contentDocument: { + querySelector(sel: string) { + return sel.includes("hf-a") ? elA : elB; + }, + }, + } as unknown as HTMLIFrameElement; + const adapter = createIframePreviewAdapter(iframe, vi.fn()); + + adapter.applyDraft("hf-a", { dx: 80, dy: 0 }); + expect(elA.style.getPropertyValue("translate")).toBe("80px 0px"); + + adapter.applyDraft("hf-b", { dx: 10, dy: 10 }); + // The abandoned element is restored; the delta does not carry over. + expect(elA.style.getPropertyValue("translate")).toBe(""); + expect(elB.style.getPropertyValue("translate")).toBe("10px 10px"); + }); + + it("commitPreview reverts the draft translate when dispatch throws", () => { + const el = fakeDomEl("hf-abc", "0", "0"); + el.style.setProperty("translate", "5px 6px"); + const dispatch = vi.fn(() => { + throw new Error("element_not_found"); + }); + const adapter = createIframePreviewAdapter(fakeIframe(el), dispatch); + + adapter.applyDraft("hf-abc", { dx: 30, dy: 20 }); + expect(() => adapter.commitPreview()).toThrow("element_not_found"); + expect(el.style.getPropertyValue("translate")).toBe("5px 6px"); + expect(el.getAttribute("data-hf-edit-base-x")).toBeNull(); + }); + + it("cancelPreview does not promote a computed (stylesheet) translate to inline", () => { + const el = fakeDomEl("hf-abc", "0", "0"); + // Simulate a stylesheet-authored translate visible only via computed style. + (el as unknown as { ownerDocument: unknown }).ownerDocument = { + defaultView: { + getComputedStyle: () => ({ getPropertyValue: () => "-50% -50%" }), + }, + }; + const adapter = createIframePreviewAdapter(fakeIframe(el), vi.fn()); + + adapter.applyDraft("hf-abc", { dx: 30, dy: 20 }); + // Draft composes onto the computed baseline (calc for non-px units). + expect(el.style.getPropertyValue("translate")).toBe("calc(-50% + 30px) calc(-50% + 20px)"); + + adapter.cancelPreview(); + // Inline translate removed — the stylesheet value stays authoritative. + expect(el.style.getPropertyValue("translate")).toBe(""); + }); }); // ─── WS-G: alphaIsOpaque ────────────────────────────────────────────────────── diff --git a/packages/sdk/src/adapters/iframe.ts b/packages/sdk/src/adapters/iframe.ts index e45c7acd90..9143e17461 100644 --- a/packages/sdk/src/adapters/iframe.ts +++ b/packages/sdk/src/adapters/iframe.ts @@ -28,14 +28,17 @@ * here — gated on a perf spike. */ +import { + EDIT_BASE_X_ATTR, + EDIT_BASE_Y_ATTR, + EDIT_ORIGINAL_TRANSLATE_ATTR, + applyPositionEditToElement, + composeTranslate, + readCurrentTranslate, +} from "@hyperframes/core/runtime/position-edits"; import type { PreviewAdapter, ElementAtPointResult, DraftProps } from "./types.js"; import type { EditOp } from "../types.js"; -// ─── CSS var names written onto elements during drag ───────────────────────── - -const VAR_DX = "--hf-studio-dx"; -const VAR_DY = "--hf-studio-dy"; - // ─── Pure resolver (testable without a browser) ─────────────────────────────── /** @@ -492,6 +495,21 @@ class IframePreviewAdapter implements PreviewAdapter { /** Tracked id and element for the in-progress drag. */ private _draftId: string | null = null; private _draftEl: HTMLElement | null = null; + /** Accumulated drag deltas from applyDraft calls. */ + private _draftDx = 0; + private _draftDy = 0; + /** + * The element's effective `translate` when the drag started (inline value, + * or computed when no inline one was set; "" = none). Drafts compose onto + * this. + */ + private _draftPrevTranslate: string | null = null; + /** + * The element's raw INLINE `translate` when the drag started ("" = not + * inline). Reverts restore exactly this, so a stylesheet-authored translate + * is never promoted to a permanent inline style. + */ + private _draftPrevInlineTranslate: string | null = null; constructor(iframe: HTMLIFrameElement, dispatch?: (op: EditOp) => void) { this.iframe = iframe; @@ -543,73 +561,159 @@ class IframePreviewAdapter implements PreviewAdapter { } /** - * Write draft CSS custom properties (`--hf-studio-dx`, `--hf-studio-dy`) onto - * the target element inside the iframe at 60fps. The composition's CSS uses - * these vars to visually translate the element without touching the model. + * Visually translate the target element inside the iframe at 60fps without + * touching the model: sets the element's `translate` to its pre-drag value + * composed with the accumulated delta. `translate` set after GSAP's first + * parse is untouched by seeks, so this renders correctly on animated + * elements too. (The `--hf-studio-dx/dy` custom properties are no longer + * written — compositions with the authored Studio drag-bridge CSS would + * move by twice the delta if both channels applied.) * - * Calling applyDraft with a new id replaces the tracked element (does not - * cancel the prior draft — call cancelPreview first if switching targets). + * Calling applyDraft with a new id switches the tracked element, reverting + * the previous element's draft translate first. * * width/height in DraftProps are not yet wired (resize → setStyle, future op). */ applyDraft(id: string, props: DraftProps): void { + const el = this._resolveDraftElement(id); + if (!el) return; + + if (props.dx !== undefined) this._draftDx = props.dx; + if (props.dy !== undefined) this._draftDy = props.dy; + + el.style.setProperty( + "translate", + composeTranslate(this._draftPrevTranslate ?? "", `${this._draftDx}px`, `${this._draftDy}px`), + ); + } + + /** + * Resolve and track the drag target. Reuses the tracked element across the + * 60fps drag; only re-queries when the id changes or the cached node + * detached (e.g. an iframe reload mid-drag). Switching to a different + * element reverts the previous one's draft first, then captures the new + * element's pre-drag translate. + */ + private _resolveDraftElement(id: string): HTMLElement | null { const doc = this.iframe.contentDocument; - if (!doc) return; + if (!doc) return null; - // Reuse the tracked element across the 60fps drag; only re-query when the id - // changes or the cached node detached (e.g. an iframe reload mid-drag). const cached = id === this._draftId && this._draftEl?.isConnected ? this._draftEl : null; const el = cached ?? doc.querySelector( `[data-hf-id="${id.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"]`, ); - if (!el) return; + if (!el) return null; + if (el !== this._draftEl) { + // Abandoning a prior target mid-drag must not leave it displaced. + this._revertDraftTranslate(); + this._draftDx = 0; + this._draftDy = 0; + this._draftPrevTranslate = readCurrentTranslate(el); + const inline = el.style.getPropertyValue("translate").trim(); + this._draftPrevInlineTranslate = inline === "none" ? "" : inline; + } this._draftId = id; this._draftEl = el; - - if (props.dx !== undefined) el.style.setProperty(VAR_DX, String(props.dx)); - if (props.dy !== undefined) el.style.setProperty(VAR_DY, String(props.dy)); + return el; } /** * Read the accumulated draft deltas, derive a moveElement op, dispatch it, - * then clear the CSS vars and draft state. + * then clear the draft state. * - * No-ops when: + * No-ops (reverting any draft translate) when: * - No applyDraft was called (nothing to commit) * - No dispatch callback was provided at construction + * + * If dispatch throws (e.g. the model no longer has the element), the draft + * translate is reverted and the error propagates — the element is never + * left displaced by an uncommitted draft. */ commitPreview(): void { if (!this._draftId || !this._draftEl || !this._dispatch) { + this._revertDraftTranslate(); this._clearDraft(); return; } const el = this._draftEl; - const dx = parseFloat(el.style.getPropertyValue(VAR_DX) || "0") || 0; - const dy = parseFloat(el.style.getPropertyValue(VAR_DY) || "0") || 0; const dataX = el.getAttribute("data-x"); const dataY = el.getAttribute("data-y"); - const { x, y } = computeDraftPosition(dataX, dataY, dx, dy); + const { x, y } = computeDraftPosition(dataX, dataY, this._draftDx, this._draftDy); - this._dispatch({ type: "moveElement", target: this._draftId, x, y }); + try { + this._dispatch({ type: "moveElement", target: this._draftId, x, y }); + } catch (err) { + this._revertDraftTranslate(); + this._clearDraft(); + throw err; + } + this._mirrorCommittedMove(el, dataX, dataY, x, y); this._clearDraft(); } - /** Revert draft CSS vars without dispatching any op. */ + /** + * Mirror a committed move onto the live element so the position holds + * without a document reload — same attributes handleMoveElement writes + * into the model, rendered by the runtime's position-edit translate. + * + * The pre-edit translate is stamped from the value captured at drag start + * (the element's current inline translate is the draft-composed one, which + * must not be mistaken for the original), then the final translate is + * recomputed the same way the runtime does at bind time. + */ + private _mirrorCommittedMove( + el: HTMLElement, + dataX: string | null, + dataY: string | null, + x: number, + y: number, + ): void { + if (el.getAttribute(EDIT_BASE_X_ATTR) === null) { + el.setAttribute(EDIT_BASE_X_ATTR, dataX ?? "0"); + } + if (el.getAttribute(EDIT_BASE_Y_ATTR) === null) { + el.setAttribute(EDIT_BASE_Y_ATTR, dataY ?? "0"); + } + if (el.getAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR) === null) { + el.setAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR, this._draftPrevTranslate ?? ""); + } + el.setAttribute("data-x", String(x)); + el.setAttribute("data-y", String(y)); + applyPositionEditToElement(el, { force: true }); + } + + /** Revert the draft translate without dispatching any op. */ cancelPreview(): void { + this._revertDraftTranslate(); this._clearDraft(); } + /** + * Restore the element's pre-drag INLINE `translate` (removing it when there + * was none, so a stylesheet-authored translate is never promoted to inline). + * NOT called on a successful commit — the committed position-edit translate + * is recomputed onto the element by _mirrorCommittedMove. + */ + private _revertDraftTranslate(): void { + if (!this._draftEl || this._draftPrevInlineTranslate === null) return; + if (this._draftPrevInlineTranslate === "") { + this._draftEl.style.removeProperty("translate"); + } else { + this._draftEl.style.setProperty("translate", this._draftPrevInlineTranslate); + } + } + private _clearDraft(): void { - if (this._draftEl) { - this._draftEl.style.removeProperty(VAR_DX); - this._draftEl.style.removeProperty(VAR_DY); - } this._draftId = null; this._draftEl = null; + this._draftDx = 0; + this._draftDy = 0; + this._draftPrevTranslate = null; + this._draftPrevInlineTranslate = null; } // Selection ----------------------------------------------------------------- diff --git a/packages/sdk/src/engine/mutate.test.ts b/packages/sdk/src/engine/mutate.test.ts index 82fa26aa4f..1e814d5dab 100644 --- a/packages/sdk/src/engine/mutate.test.ts +++ b/packages/sdk/src/engine/mutate.test.ts @@ -974,6 +974,33 @@ describe("moveElement", () => { expect(el.getAttribute("data-x")).toBe("50"); expect(el.getAttribute("data-y")).toBe("75"); }); + + it("captures the pre-edit baseline on first move only", () => { + const parsed = fresh(); + const el = parsed.document.querySelector('[data-hf-id="hf-title"]') as Element; + el.setAttribute("data-x", "50"); + applyOp(parsed, { type: "moveElement", target: "hf-title", x: 100, y: 200 }); + // Baseline = the values before the first edit (absent data-y → "0"). + expect(el.getAttribute("data-hf-edit-base-x")).toBe("50"); + expect(el.getAttribute("data-hf-edit-base-y")).toBe("0"); + // A second move keeps the original baseline. + applyOp(parsed, { type: "moveElement", target: "hf-title", x: 300, y: 400 }); + expect(el.getAttribute("data-hf-edit-base-x")).toBe("50"); + expect(el.getAttribute("data-hf-edit-base-y")).toBe("0"); + expect(el.getAttribute("data-x")).toBe("300"); + expect(el.getAttribute("data-y")).toBe("400"); + }); + + it("inverse of the first move removes the baseline attributes", () => { + const parsed = fresh(); + const el = parsed.document.querySelector('[data-hf-id="hf-title"]') as Element; + const result = applyOp(parsed, { type: "moveElement", target: "hf-title", x: 100, y: 200 }); + applyPatchesToDocument(parsed, result.inverse); + expect(el.getAttribute("data-hf-edit-base-x")).toBeNull(); + expect(el.getAttribute("data-hf-edit-base-y")).toBeNull(); + expect(el.getAttribute("data-x")).toBeNull(); + expect(el.getAttribute("data-y")).toBeNull(); + }); }); // ─── validateOp (can()) ─────────────────────────────────────────────────────── diff --git a/packages/sdk/src/engine/mutate.ts b/packages/sdk/src/engine/mutate.ts index 6580506dd1..3f2c5c69f0 100644 --- a/packages/sdk/src/engine/mutate.ts +++ b/packages/sdk/src/engine/mutate.ts @@ -51,6 +51,7 @@ import { } from "./patches.js"; import { upsertCssRule } from "./cssWriter.js"; import { mintHfId, EXCLUDED_TAGS } from "@hyperframes/core/hf-ids"; +import { EDIT_BASE_X_ATTR, EDIT_BASE_Y_ATTR } from "@hyperframes/core/runtime/position-edits"; import { parseGsapScriptAcornForWrite } from "@hyperframes/core/gsap-parser-acorn"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import { @@ -342,11 +343,34 @@ function handleMoveElement( ): MutationResult { // HF elements are positioned via data-x / data-y (parsed by htmlParser.ts, // emitted by hyperframes generator). CSS left/top is not the convention. - const rx = handleSetAttribute(parsed, ids, "data-x", String(x)); - const ry = handleSetAttribute(parsed, ids, "data-y", String(y)); + // + // The pre-edit values are captured once per element into + // data-hf-edit-base-x/y. The runtime (core runtime/positionEdits.ts) renders + // the edit as translate(data-x − base, data-y − base), which composes with + // GSAP-animated transforms instead of being overwritten per-axis. + const parts: MutationResult[] = []; + for (const id of ids) { + const el = resolveScoped(parsed.document, id); + if (!el) continue; + if (el.getAttribute(EDIT_BASE_X_ATTR) === null) { + parts.push( + handleSetAttribute(parsed, [id], EDIT_BASE_X_ATTR, el.getAttribute("data-x") ?? "0"), + ); + } + if (el.getAttribute(EDIT_BASE_Y_ATTR) === null) { + parts.push( + handleSetAttribute(parsed, [id], EDIT_BASE_Y_ATTR, el.getAttribute("data-y") ?? "0"), + ); + } + } + parts.push(handleSetAttribute(parsed, ids, "data-x", String(x))); + parts.push(handleSetAttribute(parsed, ids, "data-y", String(y))); return { - forward: [...rx.forward, ...ry.forward], - inverse: [...ry.inverse, ...rx.inverse], + forward: parts.flatMap((p) => p.forward), + inverse: parts + .slice() + .reverse() + .flatMap((p) => p.inverse), }; } From fe821ff8bc9acbb840b4a42153db66790b9419a1 Mon Sep 17 00:00:00 2001 From: Vance Ingalls Date: Fri, 3 Jul 2026 21:45:23 -0700 Subject: [PATCH 02/25] feat(studio): add resolver-shadow attempt counter for soak-gate denominator (#1926) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(studio): add resolver-shadow attempt counter for soak-gate denominator Co-Authored-By: Claude Sonnet 5 * fix(studio): harden attempt-counter exception safety and tab-hide flush ordering PR review feedback (4 reviewers): recordAttempt() sat outside the try/catch in all three emit functions, so a throw inside it (e.g. setInterval/ addEventListener failing in a non-standard environment) would break the "never throws" contract. Also, the new visibilitychange listener races studioTelemetry.ts's own tab-hide handler — whichever fires first can beacon the queue before or after this module's rollup lands in it, silently dropping the attempt count for short sessions closed before the 5-minute timer fires. Fixes: move recordAttempt() inside each function's try block; export flushViaBeacon() from studioTelemetry.ts and call it explicitly after queuing the rollup, so delivery no longer depends on listener registration order; capture the visibilitychange handler by reference so __resetAttemptSchedulingForTests() actually removes it instead of leaking a duplicate on re-arm. Co-Authored-By: Claude Sonnet 5 --------- Co-authored-by: Claude Sonnet 5 --- .../src/utils/sdkResolverShadow.test.ts | 181 +++++++++++++++++- .../studio/src/utils/sdkResolverShadow.ts | 95 ++++++++- packages/studio/src/utils/studioTelemetry.ts | 47 +++-- 3 files changed, 301 insertions(+), 22 deletions(-) diff --git a/packages/studio/src/utils/sdkResolverShadow.test.ts b/packages/studio/src/utils/sdkResolverShadow.test.ts index 71ceaba2f0..6274ed6029 100644 --- a/packages/studio/src/utils/sdkResolverShadow.test.ts +++ b/packages/studio/src/utils/sdkResolverShadow.test.ts @@ -1,10 +1,14 @@ -import { describe, expect, it, vi, beforeEach } from "vitest"; +// @vitest-environment happy-dom +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; import { sdkResolverShadowCheck, runResolverShadow, recordResolverParity, recordAnimationResolverParity, evaluateSoakGate, + recordAttempt, + flushAttemptCounts, + __resetAttemptSchedulingForTests, type SdkResolverMismatch, } from "./sdkResolverShadow"; import type { PatchOperation } from "./sourcePatcher"; @@ -13,12 +17,15 @@ import { openComposition } from "@hyperframes/sdk"; // ─── Telemetry capture ──────────────────────────────────────────────────────── const trackedEvents: Array<{ event: string; props: Record }> = []; +const flushViaBeacon = vi.fn(); vi.mock("./studioTelemetry", () => ({ trackStudioEvent: (event: string, props: Record) => trackedEvents.push({ event, props }), + flushViaBeacon: () => flushViaBeacon(), })); beforeEach(() => { trackedEvents.length = 0; + flushViaBeacon.mockClear(); }); const lastShadow = () => trackedEvents.filter((e) => e.event === "sdk_resolver_shadow").at(-1)?.props; @@ -532,3 +539,175 @@ describe("H. inlined sub-composition leaf", () => { expect(mismatches.some((m) => m.kind === "element_not_found")).toBe(false); }); }); + +// ─── I. Attempt counter (denominator for the soak gate) ─────────────────────── + +describe("I. recordAttempt / flushAttemptCounts", () => { + beforeEach(() => { + // Drain any counts left over from a prior test so each test starts clean. + flushAttemptCounts(); + }); + + it("flushAttemptCounts returns null when nothing has been recorded", () => { + expect(flushAttemptCounts()).toBeNull(); + }); + + it("increments the counter for a given op label", () => { + recordAttempt("setTiming"); + expect(flushAttemptCounts()).toEqual({ setTiming: 1 }); + }); + + it("accumulates multiple calls with the same label", () => { + recordAttempt("setTiming"); + recordAttempt("setTiming"); + recordAttempt("setTiming"); + expect(flushAttemptCounts()).toEqual({ setTiming: 3 }); + }); + + it("tracks different labels independently", () => { + recordAttempt("setTiming"); + recordAttempt("addGsapTween"); + recordAttempt("setTiming"); + expect(flushAttemptCounts()).toEqual({ setTiming: 2, addGsapTween: 1 }); + }); + + it("resets to empty after a flush", () => { + recordAttempt("setTiming"); + flushAttemptCounts(); + expect(flushAttemptCounts()).toBeNull(); + }); +}); + +describe("I. attempt counting inside the three emit functions", () => { + beforeEach(() => { + flushAttemptCounts(); + }); + + it("runResolverShadow counts an attempt on the parity (silent) path", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(BASE_HTML); + runResolverShadow(session, "hf-box", [ + { type: "inline-style", property: "color", value: "blue" }, + ]); + expect(flushAttemptCounts()).toEqual({ "dom-edit": 1 }); + expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow")).toHaveLength(0); + }); + + it("runResolverShadow counts an attempt on the divergence (emits) path too", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(BASE_HTML); + runResolverShadow(session, "hf-missing", [ + { type: "inline-style", property: "color", value: "blue" }, + ]); + expect(flushAttemptCounts()).toEqual({ "dom-edit": 1 }); + expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow")).toHaveLength(1); + }); + + it("recordResolverParity counts an attempt on the parity (silent) path", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(BASE_HTML); + await recordResolverParity(session, "hf-box", "setTiming"); + expect(flushAttemptCounts()).toEqual({ setTiming: 1 }); + }); + + it("recordResolverParity counts an attempt on the divergence (emits) path too", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(BASE_HTML); + await recordResolverParity(session, "hf-missing", "setTiming"); + expect(flushAttemptCounts()).toEqual({ setTiming: 1 }); + }); + + it("recordAnimationResolverParity counts an attempt on the parity (silent) path", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(GSAP_HTML); + const realId = session.getElements().flatMap((e) => [...e.animationIds])[0] ?? ""; + expect(realId).not.toBe(""); // fixture has a tween on hf-box, see block G above + recordAnimationResolverParity(session, realId, "removeGsapTween"); + expect(flushAttemptCounts()).toEqual({ removeGsapTween: 1 }); + expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow")).toHaveLength(0); + }); + + it("recordAnimationResolverParity counts an attempt on the divergence (emits) path too", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(GSAP_HTML); + recordAnimationResolverParity(session, "no-such-anim", "setGsapTween"); + expect(flushAttemptCounts()).toEqual({ setGsapTween: 1 }); + expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow")).toHaveLength(1); + }); + + it("counts accumulate across multiple different chokepoints in one rollup", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(BASE_HTML); + await recordResolverParity(session, "hf-box", "setTiming"); + await recordResolverParity(session, "hf-box", "setTiming"); + recordAnimationResolverParity(session, "no-such-anim", "setGsapTween"); + expect(flushAttemptCounts()).toEqual({ setTiming: 2, setGsapTween: 1 }); + }); + + it("does not count an attempt when the flag is off", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = false; + const session = await openComposition(BASE_HTML); + runResolverShadow(session, "hf-box", [ + { type: "inline-style", property: "color", value: "blue" }, + ]); + await recordResolverParity(session, "hf-box", "setTiming"); + recordAnimationResolverParity(session, "no-such-anim", "setGsapTween"); + expect(flushAttemptCounts()).toBeNull(); + }); +}); + +describe("I. production rollup wiring", () => { + beforeEach(() => { + flushAttemptCounts(); + __resetAttemptSchedulingForTests(); + vi.useFakeTimers({ toFake: ["setTimeout", "setInterval", "clearInterval", "clearTimeout"] }); + }); + + afterEach(() => { + __resetAttemptSchedulingForTests(); + vi.useRealTimers(); + Object.defineProperty(document, "visibilityState", { value: "visible", configurable: true }); + }); + + it("does not emit a rollup event when nothing was recorded", () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + vi.advanceTimersByTime(5 * 60_000); + expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow_attempt")).toHaveLength(0); + }); + + it("emits a sdk_resolver_shadow_attempt rollup event every 5 minutes after the first attempt", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(BASE_HTML); + await recordResolverParity(session, "hf-box", "setTiming"); + vi.advanceTimersByTime(5 * 60_000); + const rollups = trackedEvents.filter((e) => e.event === "sdk_resolver_shadow_attempt"); + expect(rollups).toHaveLength(1); + expect(rollups[0].props.counts).toBe(JSON.stringify({ setTiming: 1 })); + }); + + it("flushes a rollup and forces a beacon delivery on visibilitychange -> hidden", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(BASE_HTML); + await recordResolverParity(session, "hf-box", "setTiming"); + Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true }); + document.dispatchEvent(new Event("visibilitychange")); + const rollups = trackedEvents.filter((e) => e.event === "sdk_resolver_shadow_attempt"); + expect(rollups).toHaveLength(1); + expect(rollups[0].props.counts).toBe(JSON.stringify({ setTiming: 1 })); + // Delivery must not depend on studioTelemetry's own visibilitychange listener + // winning a race — this module forces its own beacon flush. + expect(flushViaBeacon).toHaveBeenCalledTimes(1); + }); + + it("does not register a duplicate visibilitychange listener after a scheduling reset", async () => { + mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true; + const session = await openComposition(BASE_HTML); + await recordResolverParity(session, "hf-box", "setTiming"); + __resetAttemptSchedulingForTests(); + await recordResolverParity(session, "hf-box", "setTiming"); // re-arms scheduling, incl. listener + Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true }); + document.dispatchEvent(new Event("visibilitychange")); + // If the reset had leaked the old listener, this would fire twice. + expect(flushViaBeacon).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/studio/src/utils/sdkResolverShadow.ts b/packages/studio/src/utils/sdkResolverShadow.ts index 537a1e3b60..56c9724f77 100644 --- a/packages/studio/src/utils/sdkResolverShadow.ts +++ b/packages/studio/src/utils/sdkResolverShadow.ts @@ -19,7 +19,7 @@ import type { Composition, JsonPatchOp } from "@hyperframes/sdk"; import type { PatchOperation } from "./sourcePatcher"; import { STUDIO_SDK_RESOLVER_SHADOW_ENABLED } from "../components/editor/manualEditingAvailability"; import { patchOpsToSdkEditOps } from "./sdkOpMapping"; -import { trackStudioEvent } from "./studioTelemetry"; +import { trackStudioEvent, flushViaBeacon } from "./studioTelemetry"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -229,6 +229,96 @@ export function sdkResolverShadowCheck( } } +// ─── Attempt counter (denominator for the soak gate) ────────────────────────── +// +// The three emit functions below only fire a PostHog event on divergence — +// parity is silent, by design, to avoid firing on every edit. That leaves no +// way to compute a rate (divergences / attempts): we can count failures but +// never attempts. This counter tracks attempts in memory and rolls them up +// into ONE low-frequency event instead of firing per-attempt, which would +// recreate the exact chattiness problem the divergence-only design avoids. + +const attemptCounts: Record = {}; + +/** + * Record that the resolver-shadow tripwire ran for `opLabel`, regardless of + * outcome (parity or divergence). No flag check of its own — only ever called + * from inside the three emit functions below, after their own + * STUDIO_SDK_RESOLVER_SHADOW_ENABLED guard, so it's already flag-gated. + */ +export function recordAttempt(opLabel: string): void { + attemptCounts[opLabel] = (attemptCounts[opLabel] ?? 0) + 1; + ensureAttemptFlushScheduled(); +} + +/** + * Return the accumulated attempt counts since the last flush (or `null` if + * nothing has been recorded — no point emitting an empty rollup), and reset + * the counter to empty. + */ +export function flushAttemptCounts(): Record | null { + const keys = Object.keys(attemptCounts); + if (keys.length === 0) return null; + const snapshot: Record = {}; + for (const key of keys) { + snapshot[key] = attemptCounts[key]; + delete attemptCounts[key]; + } + return snapshot; +} + +const ATTEMPT_FLUSH_INTERVAL_MS = 5 * 60_000; +let attemptFlushTimer: ReturnType | null = null; +let attemptVisibilityHandler: (() => void) | null = null; + +function flushAndEmitAttempts(): void { + const counts = flushAttemptCounts(); + if (counts === null) return; + trackStudioEvent("sdk_resolver_shadow_attempt", { counts: JSON.stringify(counts) }); +} + +// Lazily starts the rollup timer + visibilitychange listener on the FIRST +// attempt in a session — mirrors studioTelemetry.ts's own lazy flushTimer +// start, so a session that never exercises the tripwire never runs a +// background timer. +function ensureAttemptFlushScheduled(): void { + if (!attemptFlushTimer) { + attemptFlushTimer = setInterval(flushAndEmitAttempts, ATTEMPT_FLUSH_INTERVAL_MS); + } + if (!attemptVisibilityHandler && typeof document !== "undefined") { + attemptVisibilityHandler = () => { + if (document.visibilityState !== "hidden") return; + flushAndEmitAttempts(); + // studioTelemetry.ts registers its own visibilitychange listener (on + // window, at module load) that drains its queue via sendBeacon. Listener + // execution order between that handler and this one (on document, + // registered lazily) is not something to rely on — whichever runs + // first could otherwise beacon-flush before or after this rollup lands + // in the queue. Forcing a beacon flush here makes delivery of this + // rollup event correct regardless of that order. + flushViaBeacon(); + }; + document.addEventListener("visibilitychange", attemptVisibilityHandler); + } +} + +/** + * Test-only: clears the lazy timer/listener singleton state so tests can + * verify the "starts on first attempt" behavior in isolation, without an + * earlier test's real-timer interval (or visibilitychange listener) silently + * surviving into a later test. Does NOT touch attemptCounts — only the + * scheduling state. Not part of the public module contract; only imported + * from sdkResolverShadow.test.ts. + */ +export function __resetAttemptSchedulingForTests(): void { + if (attemptFlushTimer) clearInterval(attemptFlushTimer); + attemptFlushTimer = null; + if (attemptVisibilityHandler && typeof document !== "undefined") { + document.removeEventListener("visibilitychange", attemptVisibilityHandler); + } + attemptVisibilityHandler = null; +} + // ─── Telemetry ──────────────────────────────────────────────────────────────── // Redact all user-content values before telemetry: style values and text both @@ -266,6 +356,7 @@ export function runResolverShadow( if (!STUDIO_SDK_RESOLVER_SHADOW_ENABLED) return; if (!hfId) return; try { + recordAttempt("dom-edit"); const mismatches = sdkResolverShadowCheck(session, hfId, ops, sourceContent); // Emit only on divergence — parity is silent, matching recordResolverParity // and recordAnimationResolverParity. Otherwise this fires a PostHog event on @@ -318,6 +409,7 @@ export async function recordResolverParity( if (!STUDIO_SDK_RESOLVER_SHADOW_ENABLED) return; if (!session || !hfId) return; try { + recordAttempt(opLabel); if (resolveSnapshot(session, hfId)) return; // resolves — parity, nothing to record // Capture BEFORE any await: this call is fire-and-forget (`void recordResolverParity(...)`) // and the caller runs its own session mutation synchronously right after this call @@ -380,6 +472,7 @@ export function recordAnimationResolverParity( if (!STUDIO_SDK_RESOLVER_SHADOW_ENABLED) return; if (!session || !animationId) return; try { + recordAttempt(opLabel); const elements = session.getElements(); const resolves = elements.some((el) => el.animationIds.includes(animationId)); if (resolves) return; // SDK locates the animation — parity diff --git a/packages/studio/src/utils/studioTelemetry.ts b/packages/studio/src/utils/studioTelemetry.ts index 49406bb078..d72b148209 100644 --- a/packages/studio/src/utils/studioTelemetry.ts +++ b/packages/studio/src/utils/studioTelemetry.ts @@ -90,27 +90,34 @@ async function flushEvents(): Promise { } } +// Synchronously drains the queue via sendBeacon — safe to call from any +// tab-hide handler regardless of listener registration order. Exported so +// other modules (e.g. sdkResolverShadow.ts) can force delivery of an event +// they just queued without racing this module's own visibilitychange +// listener below. +export function flushViaBeacon(): void { + if (flushTimer) { + clearInterval(flushTimer); + flushTimer = null; + } + if (queue.length === 0) return; + const batch = queue.map((e) => ({ + event: e.event, + properties: { ...e.properties, $ip: null }, + distinct_id: getDistinctId(), + timestamp: e.timestamp, + })); + queue = []; + const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch }); + try { + navigator.sendBeacon(`${POSTHOG_HOST}/batch/`, body); + } catch { + // best-effort + } +} + if (typeof window !== "undefined") { window.addEventListener("visibilitychange", () => { - if (document.visibilityState === "hidden") { - if (flushTimer) { - clearInterval(flushTimer); - flushTimer = null; - } - if (queue.length === 0) return; - const batch = queue.map((e) => ({ - event: e.event, - properties: { ...e.properties, $ip: null }, - distinct_id: getDistinctId(), - timestamp: e.timestamp, - })); - queue = []; - const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch }); - try { - navigator.sendBeacon(`${POSTHOG_HOST}/batch/`, body); - } catch { - // best-effort - } - } + if (document.visibilityState === "hidden") flushViaBeacon(); }); } From cf594403ef293b2f1c1c04e0927ddeae66286ff6 Mon Sep 17 00:00:00 2001 From: Vance Ingalls Date: Fri, 3 Jul 2026 21:47:20 -0700 Subject: [PATCH 03/25] chore: release v0.7.30 --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- docs/changelog.mdx | 18 ++++++++++++++++++ packages/aws-lambda/package.json | 2 +- packages/cli/package.json | 2 +- packages/core/package.json | 2 +- packages/engine/package.json | 2 +- packages/gcp-cloud-run/package.json | 2 +- packages/lint/package.json | 2 +- packages/parsers/package.json | 2 +- packages/player/package.json | 2 +- packages/producer/package.json | 2 +- packages/sdk/package.json | 2 +- packages/shader-transitions/package.json | 2 +- packages/studio-server/package.json | 2 +- packages/studio/package.json | 2 +- releases/v0.7.30.md | 17 +++++++++++++++++ 18 files changed, 51 insertions(+), 16 deletions(-) create mode 100644 releases/v0.7.30.md diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 76cbc26054..7cacd8e0d1 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "hyperframes", "description": "HyperFrames by HeyGen. Write HTML, render video. Compositions, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website-to-video capture for HyperFrames.", - "version": "0.7.29", + "version": "0.7.30", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 086c62772d..e657b62fcf 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "hyperframes", - "version": "0.7.29", + "version": "0.7.30", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website-to-video capture for HyperFrames.", "author": { "name": "HeyGen", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 5efdc215fb..3ce6a4c536 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -2,7 +2,7 @@ "$schema": "https://cursor.com/schemas/cursor-plugin/plugin.json", "name": "hyperframes", "displayName": "HyperFrames by HeyGen", - "version": "0.7.29", + "version": "0.7.30", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website-to-video capture for HyperFrames.", "author": { "name": "HeyGen", diff --git a/docs/changelog.mdx b/docs/changelog.mdx index 07d3a3ab07..3a551f5c64 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -8,6 +8,24 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio {/* New release entries are prepended by `bun run changelog:draft --write`. */} + +This release adds a low-volume attempt counter to the resolver-shadow tripwire, giving the SDK-cutover soak gate a real `divergences / attempts` denominator instead of a bare divergence count. It also fixes `moveElement` losing its offset when the target element is under a running GSAP animation. + +## Features + +- **Studio:** Add resolver-shadow attempt counter for soak-gate denominator ([fe821ff8b](https://github.com/heygen-com/hyperframes/commit/fe821ff8bc9acbb840b4a42153db66790b9419a1), [#1926](https://github.com/heygen-com/hyperframes/pull/1926)) + +## Fixes + +- **Sdk:** MoveElement survives GSAP animation per-axis via runtime delta translate ([74faa4b2a](https://github.com/heygen-com/hyperframes/commit/74faa4b2a42c60c77d1550e7288bf3333c15e25d), [#1875](https://github.com/heygen-com/hyperframes/pull/1875)) + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.7.29...v0.7.30). + + Date: Fri, 3 Jul 2026 22:56:43 -0700 Subject: [PATCH 04/25] =?UTF-8?q?feat(core,cli):=20media-use=20interop=20?= =?UTF-8?q?=E2=80=94=20shared=20index.md=20regen=20+=20description/entity?= =?UTF-8?q?=20on=20figma=20imports=20(#1927)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Post-release review of media-use ↔ figma coupling (spec §13.1): - figma asset imports now regenerate .media/index.md, the agent-readable inventory media-use maintains — format locked byte-identical via a cross-runner parity test against media-use's own index-gen.mjs - figma asset --description/--entity land in the manifest record, the index table, and ; component rasterize auto-describes with the node name. Named brand marks become visible to media-use's resolve --entity lookups. - spec §13.1 records the review verdict (loose coupling correct) and the follow-up queue (shared media-ledger module, global cache for figma assets, media-use version-keyed idempotency) Co-authored-by: Claude Fable 5 --- packages/cli/src/commands/figma/asset.test.ts | 52 +++++++++ packages/cli/src/commands/figma/asset.ts | 84 +++++++++++--- packages/cli/src/commands/figma/component.ts | 12 +- packages/core/src/figma/index.ts | 3 + packages/core/src/figma/manifest.ts | 42 +++++-- packages/core/src/figma/mediaIndex.test.ts | 107 ++++++++++++++++++ packages/core/src/figma/mediaIndex.ts | 89 +++++++++++++++ packages/core/src/figma/types.ts | 2 + skills-manifest.json | 4 +- skills/figma/SKILL.md | 4 +- skills/media-use/scripts/resolve.mjs | 18 ++- skills/media-use/scripts/resolve.test.mjs | 34 ++++++ 12 files changed, 418 insertions(+), 33 deletions(-) create mode 100644 packages/core/src/figma/mediaIndex.test.ts create mode 100644 packages/core/src/figma/mediaIndex.ts diff --git a/packages/cli/src/commands/figma/asset.test.ts b/packages/cli/src/commands/figma/asset.test.ts index 680866673d..c3e25a340b 100644 --- a/packages/cli/src/commands/figma/asset.test.ts +++ b/packages/cli/src/commands/figma/asset.test.ts @@ -101,4 +101,56 @@ describe("runAssetImport", () => { /node/i, ); }); + + it("records description + entity and regenerates .media/index.md", async () => { + const dir = scratch(); + const out = await runAssetImport( + "KEY:1-2", + { format: "png", description: "hero illustration", entity: "Acme hero" }, + deps(dir), + ); + expect(out.record.description).toBe("hero illustration"); + expect(out.record.entity).toBe("Acme hero"); + expect(out.snippet.html).toContain('alt="hero illustration"'); + const index = readFileSync(join(dir, ".media", "index.md"), "utf8"); + expect(index).toContain("hero illustration"); + expect(index).toContain(out.record.id); + }); + + it("applies --description/--entity on a reuse hit instead of dropping them", async () => { + const dir = scratch(); + const first = await runAssetImport("KEY:1-2", { format: "png" }, deps(dir)); + expect(first.record.description).toBeUndefined(); + const again = await runAssetImport( + "KEY:1-2", + { format: "png", description: "Acme logo", entity: "Acme logo" }, + deps(dir), + ); + expect(again.reused).toBe(true); + expect(again.record.description).toBe("Acme logo"); + expect(again.snippet.html).toContain('alt="Acme logo"'); + const index = readFileSync(join(dir, ".media", "index.md"), "utf8"); + expect(index).toContain("Acme logo"); + expect(index).not.toContain("image_002"); + }); + + it("reuses against ANY matching tuple, not just the oldest row", async () => { + const dir = scratch(); + await runAssetImport("KEY:1-2", { format: "svg" }, deps(dir)); // image_001 (svg) + const png = await runAssetImport("KEY:1-2", { format: "png" }, deps(dir)); // image_002 + expect(png.reused).toBe(false); + const pngAgain = await runAssetImport("KEY:1-2", { format: "png" }, deps(dir)); + expect(pngAgain.reused).toBe(true); + expect(pngAgain.record.id).toBe(png.record.id); + }); + + it("flattens whitespace in descriptions so index.md rows stay single-line", async () => { + const dir = scratch(); + const out = await runAssetImport( + "KEY:1-2", + { format: "png", description: "line one\nline two" }, + deps(dir), + ); + expect(out.record.description).toBe("line one line two"); + }); }); diff --git a/packages/cli/src/commands/figma/asset.ts b/packages/cli/src/commands/figma/asset.ts index 4508682494..79252c0305 100644 --- a/packages/cli/src/commands/figma/asset.ts +++ b/packages/cli/src/commands/figma/asset.ts @@ -9,12 +9,14 @@ import { appendRecord, buildAssetSnippet, createFigmaClient, - findByFigmaNode, + findAllByFigmaNode, freezeBytes, nextId, parseFigmaRef, + regenerateIndex, sanitizeSvg, typeDirPath, + updateRecord, type AssetSnippet, type FigmaAssetFormat, type FigmaClient, @@ -28,6 +30,10 @@ import { withFigmaErrors } from "./cliError.js"; export interface AssetImportOptions { format: FigmaAssetFormat; scale?: number; + /** human description — lands in the manifest + index.md + */ + description?: string; + /** media-use interop: entity name for `resolve --entity` cache hits */ + entity?: string; } export interface AssetImportDeps { @@ -55,21 +61,39 @@ export async function runAssetImport( ); const { version } = await deps.client.fileVersion(ref.fileKey); + const description = normalizeMeta(opts.description); + const entity = normalizeMeta(opts.entity); // Cache key per spec §5: fileKey:nodeId:format:scale:version → reuse. - // Unspecified scale is canonically 1 on both sides (figma's default), so - // `--scale 1` and no flag dedupe to the same record. Reuse also requires - // the frozen file to still exist — a deleted file falls through to - // re-import instead of returning a snippet that points at nothing. - const existing = findByFigmaNode(deps.projectDir, ref.fileKey, ref.nodeId); - if ( - existing && - existing.provenance.format === opts.format && - (existing.provenance.scale ?? 1) === (opts.scale ?? 1) && - existing.provenance.version === version && - existsSync(join(deps.projectDir, existing.path)) - ) { - return { record: existing, snippet: buildAssetSnippet(existing), reused: true }; + // Check EVERY row for the node (a node can legitimately have several + // format/scale/version tuples — the oldest-row shortcut minted duplicates + // forever once a second tuple existed). Unspecified scale is canonically 1 + // on both sides (figma's default). Reuse also requires the frozen file to + // still exist — a deleted file falls through to re-import. + const existing = findAllByFigmaNode(deps.projectDir, ref.fileKey, ref.nodeId).find( + (r) => + r.provenance.format === opts.format && + (r.provenance.scale ?? 1) === (opts.scale ?? 1) && + r.provenance.version === version && + existsSync(join(deps.projectDir, r.path)), + ); + if (existing) { + // Metadata supplied on a re-import still lands: upsert the row instead + // of silently discarding the flags. + let record = existing; + if ( + (description !== undefined && description !== existing.description) || + (entity !== undefined && entity !== existing.entity) + ) { + record = { + ...existing, + ...(description !== undefined && { description }), + ...(entity !== undefined && { entity }), + }; + updateRecord(deps.projectDir, record); + } + safeRegenerateIndex(deps.projectDir); + return { record, snippet: buildAssetSnippet(record), reused: true }; } const rendered = await deps.client.renderNode(ref, opts); @@ -92,6 +116,8 @@ export async function runAssetImport( type: "image", path: relative(deps.projectDir, destAbs), source: `figma:${ref.fileKey}/${ref.nodeId}`, + ...(description !== undefined && { description }), + ...(entity !== undefined && { entity }), provenance: { source: "figma", fileKey: ref.fileKey, @@ -102,9 +128,29 @@ export async function runAssetImport( }, }; appendRecord(deps.projectDir, record); + safeRegenerateIndex(deps.projectDir); return { record, snippet: buildAssetSnippet(record), reused: false }; } +/** index.md is a single table row per record — newlines/tabs in a + * description would corrupt the whole table. */ +function normalizeMeta(value: string | undefined): string | undefined { + if (value === undefined) return undefined; + const cleaned = value.replace(/\s+/g, " ").trim(); + return cleaned.length > 0 ? cleaned : undefined; +} + +/** Keep the agent-readable inventory in step with the manifest (media-use + * regenerates the same file after its writes). Best-effort: the import is + * already durable, so an index write failure must not fail the command. */ +function safeRegenerateIndex(projectDir: string): void { + try { + regenerateIndex(projectDir); + } catch (err) { + console.warn(`index.md regeneration failed: ${err instanceof Error ? err.message : err}`); + } +} + const FORMATS: readonly FigmaAssetFormat[] = ["png", "svg", "jpg", "pdf"]; function parseFormat(raw: string): FigmaAssetFormat { @@ -122,6 +168,14 @@ export default defineCommand({ }, format: { type: "string", description: "png | svg | jpg | pdf", default: "svg" }, scale: { type: "string", description: "export scale (e.g. 2)" }, + description: { + type: "string", + description: "what this asset is (index.md + ); e.g. the layer's purpose", + }, + entity: { + type: "string", + description: 'entity name for media-use cache lookups (e.g. "Acme logo")', + }, dir: { type: "string", description: "project directory", default: "." }, }, async run({ args }) { @@ -133,6 +187,8 @@ export default defineCommand({ { format: parseFormat(args.format), scale: args.scale !== undefined ? Number(args.scale) : undefined, + description: args.description, + entity: args.entity, }, { projectDir: args.dir, client, download: downloadRender }, ); diff --git a/packages/cli/src/commands/figma/component.ts b/packages/cli/src/commands/figma/component.ts index 5c6f6bf4e0..b80a2f9f0b 100644 --- a/packages/cli/src/commands/figma/component.ts +++ b/packages/cli/src/commands/figma/component.ts @@ -67,12 +67,14 @@ export async function runComponentImport( // The search key must match the EMITTED (html-escaped) node id, and // replaceAll covers the same node appearing twice in the tree. let html = mapped.html; + const frozenAssets: string[] = []; for (const req of mapped.rasterize) { const asset = await runAssetImport( `${ref.fileKey}:${req.nodeId}`, - { format: "svg" }, + { format: "svg", description: req.name }, { projectDir: deps.projectDir, client: deps.client, download: deps.download }, ); + frozenAssets.push(asset.record.path); // src is a URL — always forward slashes, even when relative() yields // windows separators. const srcRel = relative(componentDir, join(deps.projectDir, asset.record.path)).replaceAll( @@ -99,9 +101,11 @@ export async function runComponentImport( target: `compositions/components/${name}/${name}.html`, type: "hyperframes:snippet", }, - ...mapped.rasterize.map((r) => ({ - path: `${r.slug}.svg`, - target: `.media/images/${r.slug}.svg`, + // The paths the frozen files ACTUALLY landed at (image_NNN.svg), which + // is also what the emitted HTML references — not the slug names. + ...frozenAssets.map((p) => ({ + path: p.split("/").pop() ?? p, + target: p.replaceAll("\\", "/"), type: "hyperframes:asset", })), ], diff --git a/packages/core/src/figma/index.ts b/packages/core/src/figma/index.ts index 369687ab2c..9e9a0b552d 100644 --- a/packages/core/src/figma/index.ts +++ b/packages/core/src/figma/index.ts @@ -25,12 +25,15 @@ export { mediaDir, manifestPath, typeDirPath, + updateRecord, isFigmaManifestRecord, readManifest, appendRecord, + findAllByFigmaNode, findByFigmaNode, nextId, } from "./manifest"; +export { regenerateIndex } from "./mediaIndex"; export { buildAssetSnippet } from "./assetSnippet"; export { sanitizeSvg } from "./sanitizeSvg"; export { diff --git a/packages/core/src/figma/manifest.ts b/packages/core/src/figma/manifest.ts index 3bce171585..86f0e5dcdc 100644 --- a/packages/core/src/figma/manifest.ts +++ b/packages/core/src/figma/manifest.ts @@ -1,4 +1,4 @@ -import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"; +import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { readJsonlValues } from "./jsonl"; import type { FigmaManifestRecord } from "./types"; @@ -68,15 +68,41 @@ export function findByFigmaNode( fileKey: string, nodeId: string, ): FigmaManifestRecord | null { - for (const r of readManifest(projectDir)) { - if ( + return findAllByFigmaNode(projectDir, fileKey, nodeId)[0] ?? null; +} + +/** EVERY row for a node — reuse gates must check all (format, scale, version) + * tuples, not just the oldest, or a second tuple defeats idempotency forever. */ +export function findAllByFigmaNode( + projectDir: string, + fileKey: string, + nodeId: string, +): FigmaManifestRecord[] { + return readManifest(projectDir).filter( + (r) => r.provenance.source === "figma" && r.provenance.fileKey === fileKey && - r.provenance.nodeId === nodeId - ) - return r; - } - return null; + r.provenance.nodeId === nodeId, + ); +} + +/** Rewrite one row in place by id, preserving every other line (other + * writers' rows included) byte-for-byte. */ +export function updateRecord(projectDir: string, record: FigmaManifestRecord): void { + const p = manifestPath(projectDir); + const lines = readFileSync(p, "utf8").split(/\r?\n/); + const out = lines.map((line) => { + const trimmed = line.trim(); + if (trimmed.length === 0) return line; + try { + const parsed: unknown = JSON.parse(trimmed); + if (isFigmaManifestRecord(parsed) && parsed.id === record.id) return JSON.stringify(record); + } catch { + // non-JSON line — preserve untouched + } + return line; + }); + writeFileSync(p, out.join("\n")); } export function nextId(projectDir: string, type: FigmaManifestRecord["type"]): string { diff --git a/packages/core/src/figma/mediaIndex.test.ts b/packages/core/src/figma/mediaIndex.test.ts new file mode 100644 index 0000000000..b2d597f8ae --- /dev/null +++ b/packages/core/src/figma/mediaIndex.test.ts @@ -0,0 +1,107 @@ +// @vitest-environment node +import { describe, expect, it, afterEach } from "vitest"; +import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { execFileSync } from "node:child_process"; +import { generateIndexContent, indexPath, regenerateIndex } from "./mediaIndex"; +import { manifestPath } from "./manifest"; + +const dirs: string[] = []; +function project(): string { + const d = mkdtempSync(join(tmpdir(), "hf-media-index-")); + dirs.push(d); + mkdirSync(join(d, ".media"), { recursive: true }); + return d; +} +afterEach(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); +}); + +const MEDIA_USE_ROW = { + id: "bgm_001", + type: "bgm", + path: ".media/audio/bgm/bgm_001.mp3", + source: "search", + description: "upbeat tech launch", + duration: 25, + provenance: { provider: "heygen-audio", prompt: "upbeat tech launch" }, +}; +const IMAGE_ROW = { + id: "image_001", + type: "image", + path: ".media/images/image_001.jpg", + source: "search", + description: "gradient tech background", + width: 1920, + height: 1080, + provenance: { provider: "heygen-asset", prompt: "gradient tech background" }, +}; +const ICON_ROW = { + id: "icon_001", + type: "icon", + path: ".media/images/icon_001.svg", + source: "search", + description: "rocket", + transparent: true, + provenance: { provider: "heygen-asset", prompt: "rocket" }, +}; +const FIGMA_ROW = { + id: "image_002", + type: "image", + path: ".media/images/image_002.svg", + source: "figma:KEY/1:2", + description: "hero illustration", + entity: "Acme hero", + provenance: { source: "figma", fileKey: "KEY", nodeId: "1:2", version: "9", format: "svg" }, +}; +// media-use renders every JSON-parseable row, shape or no shape — selection +// parity matters as much as format parity. +const JUNK_ROW = { note: "not a media record" }; +const ALL_ROWS = [MEDIA_USE_ROW, IMAGE_ROW, ICON_ROW, FIGMA_ROW, JUNK_ROW]; + +describe("regenerateIndex", () => { + it("renders every writer's rows (media-use + figma) into one table", () => { + const p = project(); + for (const row of ALL_ROWS) appendFileSync(manifestPath(p), JSON.stringify(row) + "\n"); + regenerateIndex(p); + const index = readFileSync(indexPath(p), "utf8"); + expect(index).toContain("# .media · 5 assets"); + expect(index).toContain("25s"); + expect(index).toContain("1920×1080"); + expect(index).toContain("hero illustration"); + }); + + it("matches media-use's index-gen output byte-for-byte on the same rows", () => { + // Covers duration, width×height, icon+transparent, no-dims, and junk-row + // selection — the full set of branches both generators format. + const ours = generateIndexContent(ALL_ROWS as Record[]); + // Run the actual media-use generator on identical input. Resolve the + // script relative to THIS file (cwd varies per test runner) and hand it + // over as a file:// URL so the specifier is valid on windows too. + const genUrl = pathToFileURL( + join( + fileURLToPath(new URL(".", import.meta.url)), + "..", + "..", + "..", + "..", + "skills", + "media-use", + "scripts", + "lib", + "index-gen.mjs", + ), + ).href; + const script = ` + import { generateIndexContent } from ${JSON.stringify(genUrl)}; + const rows = ${JSON.stringify(ALL_ROWS)}; + process.stdout.write(generateIndexContent(rows)); + `; + const theirs = execFileSync("node", ["--input-type=module", "-e", script], { + encoding: "utf8", + }); + expect(ours).toBe(theirs); + }); +}); diff --git a/packages/core/src/figma/mediaIndex.ts b/packages/core/src/figma/mediaIndex.ts new file mode 100644 index 0000000000..8ec865b35a --- /dev/null +++ b/packages/core/src/figma/mediaIndex.ts @@ -0,0 +1,89 @@ +/** + * Regenerate .media/index.md — the agent-readable inventory table — after a + * figma import, exactly the way media-use does after a resolve. Both writers + * regenerate the SAME file from the full manifest (all writers' rows), so the + * output format AND row selection here must stay byte-identical with + * skills/media-use/scripts/lib/index-gen.mjs — including rendering every + * JSON-parseable row (no shape filtering), or the file would flip-flop + * depending on which writer ran last. + */ + +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { readJsonlValues } from "./jsonl"; +import { manifestPath, mediaDir } from "./manifest"; + +type IndexRow = Record; + +function isRow(value: unknown): value is IndexRow { + return typeof value === "object" && value !== null; +} + +export function indexPath(projectDir: string): string { + return join(mediaDir(projectDir), "index.md"); +} + +function pad(str: unknown, len: number): string { + return String(str ?? "").padEnd(len); +} + +function formatDur(r: IndexRow): string { + if (r.duration == null) return "—"; + return `${String(r.duration)}s`; +} + +function formatDims(r: IndexRow): string { + if (r.width && r.height) return `${String(r.width)}×${String(r.height)}`; + if (r.type === "icon" && r.transparent) return "svg"; + return "—"; +} + +function len(value: unknown): number { + return String(value ?? "").length; +} + +export function generateIndexContent(records: IndexRow[]): string { + const count = records.length; + const header = `# .media · ${count} asset${count === 1 ? "" : "s"}\n`; + if (count === 0) return header; + + const cols = { id: 4, type: 5, dur: 4, dims: 5, path: 5 }; + for (const r of records) { + cols.id = Math.max(cols.id, len(r.id)); + cols.type = Math.max(cols.type, len(r.type)); + cols.dur = Math.max(cols.dur, formatDur(r).length); + cols.dims = Math.max(cols.dims, formatDims(r).length); + cols.path = Math.max(cols.path, len(r.path)); + } + + const heading = + pad("id", cols.id + 2) + + pad("type", cols.type + 2) + + pad("dur", cols.dur + 2) + + pad("dims", cols.dims + 2) + + pad("path", cols.path + 2) + + "description"; + + const lines = [header, heading]; + for (const r of records) { + lines.push( + pad(r.id, cols.id + 2) + + pad(r.type, cols.type + 2) + + pad(formatDur(r), cols.dur + 2) + + pad(formatDims(r), cols.dims + 2) + + pad(r.path, cols.path + 2) + + String(r.description ?? ""), + ); + } + return lines.join("\n") + "\n"; +} + +/** Rebuild index.md from EVERY writer's manifest rows (media-use + figma). */ +export function regenerateIndex(projectDir: string): string { + const records = readJsonlValues(manifestPath(projectDir)).filter(isRow); + const content = generateIndexContent(records); + const p = indexPath(projectDir); + mkdirSync(dirname(p), { recursive: true }); + writeFileSync(p, content); + return content; +} diff --git a/packages/core/src/figma/types.ts b/packages/core/src/figma/types.ts index 769106235b..4cbc7b173e 100644 --- a/packages/core/src/figma/types.ts +++ b/packages/core/src/figma/types.ts @@ -20,6 +20,8 @@ export interface FigmaManifestRecord { path: string; source: string; description?: string; + /** media-use interop: lets `resolve --entity` find figma-imported assets */ + entity?: string; width?: number; height?: number; provenance: FigmaProvenance; diff --git a/skills-manifest.json b/skills-manifest.json index 7001b1b645..2b11428795 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -10,7 +10,7 @@ "files": 17 }, "figma": { - "hash": "c462519102acc265", + "hash": "0adc2a1e01767db7", "files": 1 }, "general-video": { @@ -50,7 +50,7 @@ "files": 10 }, "media-use": { - "hash": "fba6e0963e431b1e", + "hash": "75dda0086dda18ce", "files": 19 }, "motion-graphics": { diff --git a/skills/figma/SKILL.md b/skills/figma/SKILL.md index 6a2f153560..17e0f3985e 100644 --- a/skills/figma/SKILL.md +++ b/skills/figma/SKILL.md @@ -49,10 +49,10 @@ Parse the user's figma link with `parseFigmaRef` (URL, `fileKey:nodeId`, bare `f ## Assets (Phase 1 — CLI) ```bash -hyperframes figma asset '' [--format svg|png|jpg|pdf] [--scale 2] +hyperframes figma asset '' [--format svg|png|jpg|pdf] [--scale 2] [--description "..."] [--entity "..."] ``` -Renders over REST, sanitizes SVG, freezes under `.media/images/`, appends the manifest with provenance, prints an `` snippet. Idempotent per `fileKey:nodeId:format:scale:version`. Prefer SVG for vectors/logos (scalable, animatable), PNG `--scale 2` for raster fidelity. +Renders over REST, sanitizes SVG, freezes under `.media/images/`, appends the manifest with provenance, regenerates `.media/index.md` (the shared media-use inventory), prints an `` snippet. Idempotent per `fileKey:nodeId:format:scale:version`. Prefer SVG for vectors/logos (scalable, animatable), PNG `--scale 2` for raster fidelity. **Always pass `--description ""`** (it becomes the index row + ``); add `--entity ""` for named brand marks so media-use `resolve --entity` finds them later (entity hits match across image/icon). ## Tokens (Phase 2 — CLI) diff --git a/skills/media-use/scripts/resolve.mjs b/skills/media-use/scripts/resolve.mjs index 0de752cdd1..242b49406f 100644 --- a/skills/media-use/scripts/resolve.mjs +++ b/skills/media-use/scripts/resolve.mjs @@ -74,10 +74,16 @@ async function run() { return result(projectHit, "cached"); } - // 1b. entity match in project + // 1b. entity match in project. icon and image are interchangeable for + // entity hits — both live in images/, and figma-imported brand marks are + // always recorded as type image while agents ask for logos as type icon. if (entity) { const entityHit = findByEntity(projectDir, entity); - if (entityHit && entityHit.type === type && existsSync(join(projectDir, entityHit.path))) { + if ( + entityHit && + typesMatch(entityHit.type, type) && + existsSync(join(projectDir, entityHit.path)) + ) { return result(entityHit, "cached"); } } @@ -115,7 +121,7 @@ async function run() { if (entity) { const entityCacheHit = cacheGetByEntity(entity); - if (entityCacheHit && entityCacheHit.type === type) { + if (entityCacheHit && typesMatch(entityCacheHit.type, type)) { const id = nextId(projectDir, type); const ext = extname(entityCacheHit.cached_path); const localPath = `.media/${typeSubdir(type)}/${id}${ext}`; @@ -197,6 +203,12 @@ async function run() { return result(record, searchResult.source || "search"); } +function typesMatch(a, b) { + if (a === b) return true; + const visual = new Set(["icon", "image"]); + return visual.has(a) && visual.has(b); +} + function result(record, source) { if (args.json) { console.log(JSON.stringify({ ok: true, ...record, _source: source })); diff --git a/skills/media-use/scripts/resolve.test.mjs b/skills/media-use/scripts/resolve.test.mjs index 90462c0bea..60899fd926 100644 --- a/skills/media-use/scripts/resolve.test.mjs +++ b/skills/media-use/scripts/resolve.test.mjs @@ -68,6 +68,40 @@ test("project manifest hit skips providers", () => { cleanup(); }); +test("entity hit matches across icon/image (figma-imported brand marks)", () => { + setup(); + const record = makeRecord({ + id: "image_001", + type: "image", + path: ".media/images/image_001.svg", + description: "Acme logo", + entity: "Acme logo", + provenance: { source: "figma", fileKey: "KEY", nodeId: "1:2", version: "1", format: "svg" }, + }); + delete record.duration; + appendRecord(tmp, record); + const filePath = join(tmp, record.path); + mkdirSync(join(filePath, ".."), { recursive: true }); + writeFileSync(filePath, ""); + + const out = runResolve([ + "--type", + "icon", + "--intent", + "acme brand mark", + "--entity", + "Acme logo", + "--project", + tmp, + "--json", + ]); + const parsed = JSON.parse(out.trim()); + assert.equal(parsed.ok, true); + assert.equal(parsed.id, "image_001"); + assert.equal(parsed._source, "cached"); + cleanup(); +}); + // --- global cache hit --- test("global cache hit copies to project and registers", () => { From af5f3e5fabd4822766ef9c8662d6242d6c69fca9 Mon Sep 17 00:00:00 2001 From: Vance Ingalls Date: Fri, 3 Jul 2026 23:07:38 -0700 Subject: [PATCH 05/25] chore: release v0.7.31 --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- docs/changelog.mdx | 14 ++++++++++++++ packages/aws-lambda/package.json | 2 +- packages/cli/package.json | 2 +- packages/core/package.json | 2 +- packages/engine/package.json | 2 +- packages/gcp-cloud-run/package.json | 2 +- packages/lint/package.json | 2 +- packages/parsers/package.json | 2 +- packages/player/package.json | 2 +- packages/producer/package.json | 2 +- packages/sdk/package.json | 2 +- packages/shader-transitions/package.json | 2 +- packages/studio-server/package.json | 2 +- packages/studio/package.json | 2 +- releases/v0.7.31.md | 13 +++++++++++++ 18 files changed, 43 insertions(+), 16 deletions(-) create mode 100644 releases/v0.7.31.md diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 7cacd8e0d1..9f3d027ca5 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "hyperframes", "description": "HyperFrames by HeyGen. Write HTML, render video. Compositions, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website-to-video capture for HyperFrames.", - "version": "0.7.30", + "version": "0.7.31", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index e657b62fcf..59babf9f8e 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "hyperframes", - "version": "0.7.30", + "version": "0.7.31", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website-to-video capture for HyperFrames.", "author": { "name": "HeyGen", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 3ce6a4c536..314dc94a8a 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -2,7 +2,7 @@ "$schema": "https://cursor.com/schemas/cursor-plugin/plugin.json", "name": "hyperframes", "displayName": "HyperFrames by HeyGen", - "version": "0.7.30", + "version": "0.7.31", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website-to-video capture for HyperFrames.", "author": { "name": "HeyGen", diff --git a/docs/changelog.mdx b/docs/changelog.mdx index 3a551f5c64..12ab100cd1 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -8,6 +8,20 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio {/* New release entries are prepended by `bun run changelog:draft --write`. */} + +This release makes Figma imports first-class citizens of the shared media inventory: every `hyperframes figma asset` import now regenerates `.media/index.md` (byte-identical with media-use's format), carries `--description`/`--entity` metadata into the manifest, index, and alt text, and the reuse path correctly upserts metadata and dedupes against any prior format/scale/version tuple. media-use's entity lookups now match figma-imported brand marks across the icon/image boundary. + +## Features + +- **Core,cli:** Media-use interop — shared index.md regen + description/entity on figma imports ([3900caaaa](https://github.com/heygen-com/hyperframes/commit/3900caaaa94443efb01597dac26df1533f8add35), [#1927](https://github.com/heygen-com/hyperframes/pull/1927)) + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.7.30...v0.7.31). + + Date: Sat, 4 Jul 2026 14:08:08 -0700 Subject: [PATCH 06/25] fix(core): route window.__hyperframes to the scoped variant in sub-comps (#1931) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sub-composition scripts run inside a wrapper that passes the SCOPED __hyperframes (per-instance getVariables) as a bare script param, while `window` is a Proxy. That proxy intercepted only __timelines, so `window.__hyperframes` fell through to the HOST page's base __hyperframes — whose getVariables reads the host's variables, not this instance's. So the two documented spellings diverged: the bare `__hyperframes.getVariables()` param returned the correct per-instance values, but `window.__hyperframes.getVariables()` returned the wrong (host / empty) ones, silently rendering every reused instance with the first instance's content (or defaults). docs/concepts/variables.mdx already promises both forms "work in both top-level and sub-composition scripts ... each instance sees its own resolved values" — the runtime just didn't honor it. Reported directly (a user lost significant debugging time across three parametrized sub-comps before discovering the bare param was the only form that worked), and matches an earlier deferred finding that getVariables() returns {} for reused sub-comp instances. Fix: the scoped `window` proxy now returns the scoped __hyperframes for `prop === "__hyperframes"`, so window.__hyperframes.getVariables() and the bare param resolve identically to this composition's own variables. The scoped variant is Object.assign({}, base, { getVariables }), so all other __hyperframes members still pass through to the base unchanged. Test: two new executed-wrapper cases (new Function(...)(fakeWindow)) — window.__hyperframes.getVariables() now returns the per-comp variables instead of the TOP-LEVEL-LEAK host value, and a non-getVariables member (fitTextFontSize) still reaches the base. Full core suite (1092) passes. --- .../src/compiler/compositionScoping.test.ts | 53 +++++++++++++++++++ .../core/src/compiler/compositionScoping.ts | 10 ++++ 2 files changed, 63 insertions(+) diff --git a/packages/core/src/compiler/compositionScoping.test.ts b/packages/core/src/compiler/compositionScoping.test.ts index df3ce1d595..19c7b019d7 100644 --- a/packages/core/src/compiler/compositionScoping.test.ts +++ b/packages/core/src/compiler/compositionScoping.test.ts @@ -79,6 +79,59 @@ body { margin: 0; } expect(fakeWindow.__captured).toEqual({ title: "Pro", price: "$29" }); }); + it("routes the documented window.__hyperframes.getVariables() to the scoped variant too", () => { + // Regression: the docs (variables-and-media.md) show `window.__hyperframes. + // getVariables()`, but inside a sub-comp the scoped `window` proxy used to + // fall through to the HOST page's base __hyperframes, returning the wrong + // (or empty) variables — the bare `__hyperframes` param was the only form + // that worked. Both spellings must now resolve to this comp's variables. + const { document } = parseHTML(`
`); + const fakeWindow: Record = { + document, + __timelines: {}, + __hfVariablesByComp: { + "card-1": { title: "Pro", price: "$29" }, + "card-2": { title: "Enterprise", price: "Custom" }, + }, + __hyperframes: { + getVariables: () => ({ title: "TOP-LEVEL-LEAK" }), + fitTextFontSize: () => undefined, + }, + }; + const wrapped = wrapScopedCompositionScript( + `window.__captured = window.__hyperframes.getVariables();`, + "card-1", + ); + + new Function("window", wrapped)(fakeWindow); + + expect(fakeWindow.__captured).toEqual({ title: "Pro", price: "$29" }); + }); + + it("preserves non-getVariables members on window.__hyperframes (only getVariables is rescoped)", () => { + const { document } = parseHTML(`
`); + let fitCalled = false; + const fakeWindow: Record = { + document, + __timelines: {}, + __hfVariablesByComp: { "card-1": { title: "Pro" } }, + __hyperframes: { + getVariables: () => ({ title: "TOP-LEVEL-LEAK" }), + fitTextFontSize: () => { + fitCalled = true; + }, + }, + }; + const wrapped = wrapScopedCompositionScript( + `window.__hyperframes.fitTextFontSize();`, + "card-1", + ); + + new Function("window", wrapped)(fakeWindow); + + expect(fitCalled).toBe(true); + }); + it("scoped getVariables reads from the runtime composition id when it differs", () => { const { document } = parseHTML(`
`); const fakeWindow: Record = { diff --git a/packages/core/src/compiler/compositionScoping.ts b/packages/core/src/compiler/compositionScoping.ts index be49f149a0..4315d770a9 100644 --- a/packages/core/src/compiler/compositionScoping.ts +++ b/packages/core/src/compiler/compositionScoping.ts @@ -396,6 +396,16 @@ export function wrapScopedCompositionScript( ? new Proxy(window, { get: function(target, prop, receiver) { if (prop === "__timelines") return __hfGetTimelineRegistry(); + // Inside a sub-composition, __hyperframes is passed as a bare script + // param bound to the SCOPED variant (per-comp getVariables). But + // authors routinely write the documented window.__hyperframes. + // getVariables() form, which would otherwise fall through to the host + // page's base __hyperframes and return the WRONG (or empty) variables + // for this instance. Route it to the scoped variant too so both + // spellings resolve to this composition's own variables. + // (__hfScopedHyperframes is a hoisted var assigned below, before any + // sub-comp script -- the only code that reads this -- runs.) + if (prop === "__hyperframes") return __hfScopedHyperframes; return Reflect.get(target, prop, target); }, set: function(target, prop, value, receiver) { From 78069da1403669cb3f68a475da128d0b0ce14a97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sat, 4 Jul 2026 14:08:12 -0700 Subject: [PATCH 07/25] fix(cli): purge stale/partial browser installs instead of wedging retries (#1913) * fix(cli): purge stale/partial browser installs instead of wedging retries Two independent reports of the same failure: a `chrome-headless-shell` zip extraction gets interrupted (Windows AV lock, sleep/wake, ctrl-C) and leaves only the alphabetically-early files (ABOUT/LICENSE) in the target directory, no executable. Every subsequent `browser ensure` (or implicit re-download from `findBrowser`/`ensureBrowser`) sees the directory already exists and hands it straight to @puppeteer/browsers' install(), which throws "folder exists but the executable is missing" without re-extracting -- permanently wedging the machine until someone manually deletes the directory. `--force` didn't help because it was a phantom flag: `browser.ts` never declared it, so it silently did nothing (mentioned only in an error-message string). Root cause: `findFromCache()` already detects this exact case (dir exists, exe missing) and returns it as `staleHyperframesCachePath`, but `findBrowser()`/`ensureBrowser()` fed that straight into a re-download without ever deleting the stale directory first, so install() hit the same "exists" branch every time. Fix: - `findFromCache()` also returns `staleInstallPath` (InstalledBrowser's `.path` -- the actual install-folder root, not the missing executablePath) for the stale case. - Both `findBrowser()` and `ensureBrowser()` now purge that directory (`rmSync`, inside the existing `withInstallLock` mutex from #1866 so a purge can't race a concurrent installer) before retrying, so install() actually re-extracts instead of erroring. - Wired up a real `--force` flag on `hyperframes browser ensure`: it purges the whole HF-managed cache (reusing the already-tested `clearBrowser()`) and skips every cache/system shortcut, so it always gets a fresh download regardless of what's currently on disk -- matching what the existing (previously false) help text already claimed it did. Not fixed here (separate root cause, flagged for later): neither report's machine had a usable auto-detected system Chrome fallback on Windows -- `SYSTEM_CHROME_PATHS` only lists macOS/Linux paths, so `findFromSystem()` can never succeed on win32. Both reporters worked around this manually via HYPERFRAMES_BROWSER_PATH, which still works fine; adding real Windows system-Chrome detection is a distinct, larger change. Test: extended manager.test.ts's existing stale-cache-redownload test to include a populated stale install directory and assert it's gone before the mocked install() is called (was previously only asserting the redownload happened, not that the fix's purge step ran). Added a new test for `ensureBrowser({force: true})` purging the cache and bypassing a healthy cache/system-Chrome shortcut. Also fixed the shared fs mock's `rmSync` to actually simulate recursive deletion (drop nested tracked paths too), which the new tests need and the old ones never exercised. Full CLI suite (1222 tests) passes. * fix(cli): serialize force browser cache purge --- packages/cli/src/browser/manager.test.ts | 106 ++++++++++++++++++++--- packages/cli/src/browser/manager.ts | 83 +++++++++++++----- packages/cli/src/commands/browser.ts | 51 +++++++---- 3 files changed, 187 insertions(+), 53 deletions(-) diff --git a/packages/cli/src/browser/manager.test.ts b/packages/cli/src/browser/manager.test.ts index f19d1993bd..7f166efb9b 100644 --- a/packages/cli/src/browser/manager.test.ts +++ b/packages/cli/src/browser/manager.test.ts @@ -21,7 +21,7 @@ * `background-removal/manager.test.ts`) so we don't touch the real * `HOME` cache. */ -import { join } from "node:path"; +import { join, sep } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // Use `path.join` so the fake paths line up with whatever separator Node's @@ -30,7 +30,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // `/fake/home/...` literals would fail on Windows because the set lookup // would never match the `\\`-joined real paths. const FAKE_HOME = join("/", "fake", "home"); +const CACHE_ROOT = join(FAKE_HOME, ".cache", "hyperframes"); const HF_CACHE = join(FAKE_HOME, ".cache", "hyperframes", "chrome"); +const HF_LOCK = join(CACHE_ROOT, ".chrome.install.lock"); +const HF_RECLAIM_LOCK = join(CACHE_ROOT, ".chrome.install.reclaim.lock"); const PUPPETEER_CACHE = join(FAKE_HOME, ".cache", "puppeteer", "chrome-headless-shell"); const PUPPETEER_BINARY = join( PUPPETEER_CACHE, @@ -75,8 +78,15 @@ function installFsMocks({ existing, dirs }: FsMockOptions) { mtimes.set(p, Date.now()); }, rmSync: (p: string) => { - paths.delete(p); - mtimes.delete(p); + // Real rmSync({recursive:true}) removes the target AND everything under + // it; the mock's flat path Set has no real tree structure, so simulate + // that by also dropping any tracked path nested under `p`. + for (const existingPath of [...paths]) { + if (existingPath === p || existingPath.startsWith(p + sep)) { + paths.delete(existingPath); + mtimes.delete(existingPath); + } + } }, statSync: (p: string) => { if (!paths.has(p)) { @@ -97,9 +107,10 @@ function installFsMocks({ existing, dirs }: FsMockOptions) { function installPuppeteerBrowsersMock( opts: { - installedInHfCache?: Array<{ browser: string; executablePath: string }>; + installedInHfCache?: Array<{ browser: string; executablePath: string; path?: string }>; installedInHfCacheError?: Error; installResult?: { executablePath: string }; + installImpl?: () => Promise<{ executablePath: string }>; } = {}, ) { vi.doMock("@puppeteer/browsers", () => ({ @@ -108,7 +119,11 @@ function installPuppeteerBrowsersMock( getInstalledBrowsers: opts.installedInHfCacheError ? vi.fn().mockRejectedValue(opts.installedInHfCacheError) : vi.fn().mockResolvedValue(opts.installedInHfCache ?? []), - install: vi.fn().mockResolvedValue(opts.installResult ?? { executablePath: HF_BINARY }), + install: vi + .fn() + .mockImplementation( + opts.installImpl ?? (async () => opts.installResult ?? { executablePath: HF_BINARY }), + ), })); } @@ -169,9 +184,15 @@ describe("findBrowser — cache resolution", () => { "chrome-headless-shell-linux64", "redownloaded-chrome-headless-shell", ); - installFsMocks({ existing: new Set([HF_CACHE]) }); + const staleInstallDir = join(HF_CACHE, "chrome-headless-shell", "linux-131.0.6778.85"); + // The stale install DIR is present (extraction got partway through, e.g. an + // ABOUT/LICENSE-only extract) even though the exe itself is missing — + // exercises the purge-before-redownload fix, not just the redownload path. + const paths = installFsMocks({ existing: new Set([HF_CACHE, staleInstallDir]) }); installPuppeteerBrowsersMock({ - installedInHfCache: [{ browser: "chrome-headless-shell", executablePath: HF_BINARY }], + installedInHfCache: [ + { browser: "chrome-headless-shell", executablePath: HF_BINARY, path: staleInstallDir }, + ], installResult: { executablePath: redownloadedBinary }, }); const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); @@ -181,6 +202,67 @@ describe("findBrowser — cache resolution", () => { expect(result).toEqual({ executablePath: redownloadedBinary, source: "download" }); expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Cached binary missing")); + // The stale directory must be gone before @puppeteer/browsers' install() + // sees it — otherwise install() throws "folder exists but exe missing" + // instead of re-extracting (the exact bug both feedback reports hit). + expect(paths.has(staleInstallDir)).toBe(false); + }); + + it("ensureBrowser({force: true}) purges the whole cache before downloading, bypassing any cache/system shortcut", async () => { + const staleInstallDir = join(HF_CACHE, "chrome-headless-shell", "linux-131.0.6778.85"); + const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "force-downloaded"); + // A HEALTHY cached binary AND system Chrome are both present — force must + // ignore both shortcuts and always re-download, which is the whole point + // of the flag (the reported bug: --force did nothing, a stale dir kept + // winning over every retry). + const paths = installFsMocks({ + existing: new Set([HF_CACHE, HF_BINARY, staleInstallDir, SYSTEM_CHROME]), + }); + installPuppeteerBrowsersMock({ + installedInHfCache: [ + { browser: "chrome-headless-shell", executablePath: HF_BINARY, path: staleInstallDir }, + ], + installResult: { executablePath: downloadedBinary }, + }); + + const { ensureBrowser } = await import("./manager.js"); + const result = await ensureBrowser({ force: true }); + + expect(result).toEqual({ executablePath: downloadedBinary, source: "download" }); + // clearBrowser() wipes prior contents; withInstallLock uses a sibling lock + // outside CACHE_DIR, so assert the purge on what was actually INSIDE it, + // not the directory's own existence. + expect(paths.has(staleInstallDir)).toBe(false); + expect(paths.has(HF_BINARY)).toBe(false); + }); + + it("serializes concurrent force downloads so one purge cannot delete another installer's lock", async () => { + const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "force-downloaded"); + const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_CACHE, HF_BINARY]) }); + let activeInstalls = 0; + let maxActiveInstalls = 0; + installPuppeteerBrowsersMock({ + installedInHfCache: [{ browser: "chrome-headless-shell", executablePath: HF_BINARY }], + installImpl: async () => { + activeInstalls += 1; + maxActiveInstalls = Math.max(maxActiveInstalls, activeInstalls); + expect(paths.has(HF_LOCK)).toBe(true); + await new Promise((resolve) => setTimeout(resolve, 20)); + activeInstalls -= 1; + return { executablePath: downloadedBinary }; + }, + }); + + const { ensureBrowser } = await import("./manager.js"); + + await expect( + Promise.all([ensureBrowser({ force: true }), ensureBrowser({ force: true })]), + ).resolves.toEqual([ + { executablePath: downloadedBinary, source: "download" }, + { executablePath: downloadedBinary, source: "download" }, + ]); + expect(maxActiveInstalls).toBe(1); + expect(paths.has(HF_LOCK)).toBe(false); }); it("ensureBrowser does not leak the install lock directory after a successful download", async () => { @@ -191,7 +273,6 @@ describe("findBrowser — cache resolution", () => { // same extract target. mkdirSync as an atomic mutex closes that race; // this asserts the lock is actually released afterward (a leaked lock // would permanently wedge every future render on this machine). - const HF_LOCK = join(HF_CACHE, ".install.lock"); const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "downloaded"); // Cache dir exists but is empty (no manifest entries) — distinct from the // ENOTDIR "cache unreadable" case, which falls back to system instead. @@ -216,8 +297,7 @@ describe("findBrowser — cache resolution", () => { // withInstallLock directly with tiny real timeouts (it takes an // injectable timeoutMs/pollMs for exactly this) rather than mocking // Date.now()/setTimeout through the full ensureBrowser call graph. - const HF_LOCK = join(HF_CACHE, ".install.lock"); - const paths = installFsMocks({ existing: new Set([HF_CACHE, HF_LOCK]) }); + const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_LOCK]) }); const { withInstallLock } = await import("./manager.js"); const result = await withInstallLock(async () => "done", 10, 5); @@ -231,9 +311,7 @@ describe("findBrowser — cache resolution", () => { // the stale-lock deadline together, waiter A can reclaim the stale lock and // acquire a fresh one. Waiter B's old deadline is still expired, but it must // not delete A's fresh lock. - const HF_LOCK = join(HF_CACHE, ".install.lock"); - const RECLAIM_LOCK = join(HF_CACHE, ".install.reclaim.lock"); - const paths = installFsMocks({ existing: new Set([HF_CACHE, HF_LOCK]) }); + const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_LOCK]) }); const { withInstallLock } = await import("./manager.js"); const first = withInstallLock( @@ -248,7 +326,7 @@ describe("findBrowser — cache resolution", () => { await expect(Promise.all([first, second])).resolves.toEqual(["first", "second"]); expect(paths.has(HF_LOCK)).toBe(false); - expect(paths.has(RECLAIM_LOCK)).toBe(false); + expect(paths.has(HF_RECLAIM_LOCK)).toBe(false); }); it("warns and falls through when the hyperframes cache cannot be read", async () => { diff --git a/packages/cli/src/browser/manager.ts b/packages/cli/src/browser/manager.ts index a7c6ea14fc..a2a345eb4e 100644 --- a/packages/cli/src/browser/manager.ts +++ b/packages/cli/src/browser/manager.ts @@ -21,6 +21,7 @@ async function loadPuppeteerBrowsers(): Promise { } const CHROME_VERSION = "131.0.6778.85"; +const CACHE_ROOT_DIR = join(homedir(), ".cache", "hyperframes"); const CACHE_DIR = join(homedir(), ".cache", "hyperframes", "chrome"); // Puppeteer's managed cache — where `@puppeteer/browsers install // chrome-headless-shell` (and `puppeteer install`) drop binaries. The engine's @@ -39,8 +40,8 @@ const PUPPETEER_CACHE_DIR = join(homedir(), ".cache", "puppeteer", "chrome-headl // // mkdirSync is atomic (EEXIST if another process already holds it), so it // doubles as a zero-dependency cross-process mutex — no lockfile library needed. -const INSTALL_LOCK_DIR = join(CACHE_DIR, ".install.lock"); -const INSTALL_RECLAIM_LOCK_DIR = join(CACHE_DIR, ".install.reclaim.lock"); +const INSTALL_LOCK_DIR = join(CACHE_ROOT_DIR, ".chrome.install.lock"); +const INSTALL_RECLAIM_LOCK_DIR = join(CACHE_ROOT_DIR, ".chrome.install.reclaim.lock"); const INSTALL_LOCK_TIMEOUT_MS = 120_000; // generous: a real download+extract can take a while const INSTALL_LOCK_POLL_MS = 200; @@ -88,7 +89,9 @@ export async function withInstallLock( pollMs = INSTALL_LOCK_POLL_MS, ): Promise { // recursive:false below needs the parent to already exist (unlike `mkdir -p`). - if (!existsSync(CACHE_DIR)) mkdirSync(CACHE_DIR, { recursive: true }); + // Keep lock dirs outside CACHE_DIR so force-clearing the Chrome cache cannot + // delete another installer's in-flight lock. + if (!existsSync(CACHE_ROOT_DIR)) mkdirSync(CACHE_ROOT_DIR, { recursive: true }); let deadline = Date.now() + timeoutMs; for (;;) { if (existsSync(INSTALL_RECLAIM_LOCK_DIR)) { @@ -127,11 +130,31 @@ export interface BrowserResult { export interface EnsureBrowserOptions { onProgress?: (downloadedBytes: number, totalBytes: number) => void; + // Purge any cached HF-managed download before resolving, so a stale or + // partially-extracted install can't make the retry look like a no-op. + force?: boolean; } interface CacheLookupResult { result?: BrowserResult; staleHyperframesCachePath?: string; + // Root install-folder path for the stale entry (InstalledBrowser#path), NOT + // the missing executablePath above — this is what actually needs deleting. + staleInstallPath?: string; +} + +/** + * Remove one browser version's install directory (not the whole CACHE_DIR). + * @puppeteer/browsers' install() treats an existing-but-incomplete directory + * as already installed and throws "folder exists but executable is missing" + * rather than re-extracting — so an extraction interrupted by a Windows AV + * lock, a sleep/wake cycle, or ctrl-C (left with only alphabetically-early + * files like ABOUT/LICENSE, no exe) wedges every subsequent ensure/render + * with the same error until someone manually deletes the directory. Purging + * it first makes the retry actually retry. + */ +function purgeStaleInstall(installPath: string): void { + rmSync(installPath, { recursive: true, force: true }); } // --- Internal helpers ------------------------------------------------------- @@ -215,7 +238,7 @@ async function findFromCache(): Promise { return { result: { executablePath: match.executablePath, source: "cache" } }; } if (match) { - return { staleHyperframesCachePath: match.executablePath }; + return { staleHyperframesCachePath: match.executablePath, staleInstallPath: match.path }; } } @@ -371,7 +394,10 @@ export async function findBrowser(): Promise { `[browser] Cached binary missing at ${fromCache.staleHyperframesCachePath} — re-downloading...`, ); try { - return await withInstallLock(() => downloadBrowser()); + return await withInstallLock(async () => { + if (fromCache.staleInstallPath) purgeStaleInstall(fromCache.staleInstallPath); + return downloadBrowser(); + }); } catch (err) { const cause = normalizeErrorMessage(err); throw new Error( @@ -445,27 +471,44 @@ export async function ensureBrowser(options?: EnsureBrowserOptions): Promise downloadBrowser(options)); - } + if (!options?.force) { + const fromCache = await findFromCache(); + if (fromCache.result) return fromCache.result; + if (fromCache.staleHyperframesCachePath) { + console.warn( + `[browser] Cached binary missing at ${fromCache.staleHyperframesCachePath} — re-downloading...`, + ); + return withInstallLock(async () => { + if (fromCache.staleInstallPath) purgeStaleInstall(fromCache.staleInstallPath); + return downloadBrowser(options); + }); + } - const fromSystem = findFromSystem(); - if (fromSystem) { - warnSystemFallbackOnce(fromSystem.executablePath); - return fromSystem; + const fromSystem = findFromSystem(); + if (fromSystem) { + warnSystemFallbackOnce(fromSystem.executablePath); + return fromSystem; + } } return withInstallLock(async () => { + if (options?.force) { + // `--force` means "always get a fresh managed download" — purging the + // whole HF-managed cache after acquiring the install lock keeps two + // concurrent force retries from deleting each other's in-flight lock or + // partially extracted install. + clearBrowser(); + } + // Re-check after acquiring the lock: a concurrent invocation may have // finished installing while we were waiting, in which case reuse its - // result instead of downloading and extracting a second time. - const afterLock = await findFromCache(); - if (afterLock.result) return afterLock.result; + // result instead of downloading and extracting a second time. Skipped + // under --force, which already purged and always wants a fresh download. + if (!options?.force) { + const afterLock = await findFromCache(); + if (afterLock.result) return afterLock.result; + if (afterLock.staleInstallPath) purgeStaleInstall(afterLock.staleInstallPath); + } return downloadBrowser(options); }); } diff --git a/packages/cli/src/commands/browser.ts b/packages/cli/src/commands/browser.ts index 20e9ea6c95..d9391cc108 100644 --- a/packages/cli/src/commands/browser.ts +++ b/packages/cli/src/commands/browser.ts @@ -5,6 +5,7 @@ import { c } from "../ui/colors.js"; export const examples: Example[] = [ ["Find or download Chrome for rendering", "hyperframes browser ensure"], + ["Purge a stale/partial download and re-download", "hyperframes browser ensure --force"], ["Print the Chrome executable path", "hyperframes browser path"], ["Remove cached Chrome download", "hyperframes browser clear"], ]; @@ -19,11 +20,11 @@ import { } from "../browser/manager.js"; import { trackBrowserInstall, trackCommandFailure } from "../telemetry/events.js"; -async function runEnsure(): Promise { +async function runEnsure(options?: { force?: boolean }): Promise { clack.intro(c.bold("hyperframes browser ensure")); - // ARM64 Linux: Chrome headless shell is not available. - // Try to find system Chromium first, then attempt auto-install via apt. + // ARM64 Linux: Chrome headless shell is not available (apt-get/system-only + // install flow, no download cache to force a purge of) — --force is a no-op here. if (isLinuxArm()) { const s = clack.spinner(); s.start("Linux ARM64 detected — looking for system Chromium..."); @@ -61,26 +62,31 @@ async function runEnsure(): Promise { } const s = clack.spinner(); - s.start("Looking for an existing browser..."); + if (!options?.force) { + s.start("Looking for an existing browser..."); - const existing = await findBrowser(); - if (existing) { - s.stop(c.success("Browser found")); - console.log(); - console.log(` ${c.dim("Source:")} ${c.bold(existing.source)}`); - console.log(` ${c.dim("Path:")} ${c.bold(existing.executablePath)}`); - console.log(); - clack.outro(c.success("Ready to render.")); - return; + const existing = await findBrowser(); + if (existing) { + s.stop(c.success("Browser found")); + console.log(); + console.log(` ${c.dim("Source:")} ${c.bold(existing.source)}`); + console.log(` ${c.dim("Path:")} ${c.bold(existing.executablePath)}`); + console.log(); + clack.outro(c.success("Ready to render.")); + return; + } + + s.stop("No browser found — downloading"); + } else { + s.start("Purging cached download and re-downloading..."); } - s.stop("No browser found — downloading"); - const downloadSpinner = clack.spinner(); downloadSpinner.start(`Downloading Chrome Headless Shell ${c.dim("v" + CHROME_VERSION)}...`); let lastPct = -1; const result = await ensureBrowser({ + force: options?.force, onProgress: (downloaded, total) => { if (total <= 0) return; const pct = Math.floor((downloaded / total) * 100); @@ -141,6 +147,12 @@ export default defineCommand({ "ensure = find or download Chrome, path = print executable path, clear = remove cached download", required: false, }, + force: { + type: "boolean", + description: + "ensure only: purge any cached download (including a stale/partial one) and re-download from scratch", + default: false, + }, }, async run({ args }) { const subcommand = args.subcommand; @@ -157,16 +169,17 @@ ${c.bold("SUBCOMMANDS:")} ${c.accent("clear")} ${c.dim("Remove cached Chrome download")} ${c.bold("EXAMPLES:")} - ${c.accent("npx hyperframes browser ensure")} ${c.dim("Download Chrome if needed")} - ${c.accent("npx hyperframes browser path")} ${c.dim("Print path for scripts")} - ${c.accent("npx hyperframes browser clear")} ${c.dim("Remove cached browser")} + ${c.accent("npx hyperframes browser ensure")} ${c.dim("Download Chrome if needed")} + ${c.accent("npx hyperframes browser ensure --force")} ${c.dim("Purge a stale/partial download and re-download")} + ${c.accent("npx hyperframes browser path")} ${c.dim("Print path for scripts")} + ${c.accent("npx hyperframes browser clear")} ${c.dim("Remove cached browser")} `); return; } switch (subcommand) { case "ensure": - return runEnsure(); + return runEnsure({ force: args.force }); case "path": return runPath(); case "clear": From 8a3227f5482320907edcb47972c3d7f6e25c6d62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sat, 4 Jul 2026 14:08:15 -0700 Subject: [PATCH 08/25] fix(engine): write the audio mix filter graph to a file, not the command line (#1890) * fix(engine): write the audio mix filter graph to a file, not the command line mixAudioTracks built the ffmpeg -filter_complex argument as one inline string scaling linearly with track count. Reported in the wild at 146 timed audio clips: the resulting command line exceeded the OS length limit and spawn failed with ENAMETOOLONG, dropping audio entirely until the user manually consolidated clips to reduce the count. FFmpeg supports -filter_complex_script specifically for this - the same filter graph read from a file instead of inlined as an argument. The -i pairs for each track still scale with count but stay short and fixed-size each, so the one component that actually grew unbounded (the filter string) no longer sits on the command line at all. The temp file is cleaned up immediately after ffmpeg exits, matching the existing sibling temp-file convention in audioVolumeEnvelope.ts. Verified end-to-end against a real ffmpeg binary (not just mocked): a two-track mix produced correct output audio with no leftover temp files. * fix(engine): create audio filter scripts safely --- .../engine/src/services/audioMixer.test.ts | 130 +++++++++++++----- packages/engine/src/services/audioMixer.ts | 40 ++++-- 2 files changed, 126 insertions(+), 44 deletions(-) diff --git a/packages/engine/src/services/audioMixer.test.ts b/packages/engine/src/services/audioMixer.test.ts index 6f6eb4756a..0533688807 100644 --- a/packages/engine/src/services/audioMixer.test.ts +++ b/packages/engine/src/services/audioMixer.test.ts @@ -3,14 +3,29 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; -const { runFfmpegMock } = vi.hoisted(() => ({ - runFfmpegMock: vi.fn(async () => ({ - success: true, - durationMs: 1, - stderr: "", - exitCode: 0, - })), -})); +// The mix filter graph is written to a temp file and passed via +// -filter_complex_script (not inlined via -filter_complex) so the command +// line doesn't scale with track count — production code deletes that file +// the moment the (real) ffmpeg process exits. The mock captures each call's +// filter content synchronously, while the file still exists, into an +// index-aligned side array (rather than re-reading it from disk after +// processCompositionAudio resolves, by which point it's already gone). +const { runFfmpegMock, capturedFilterScripts } = vi.hoisted(() => { + const capturedFilterScripts: string[] = []; + return { + capturedFilterScripts, + runFfmpegMock: vi.fn(async (args: string[]) => { + const idx = args.indexOf("-filter_complex_script"); + if (idx >= 0) { + const { readFileSync } = await import("node:fs"); + capturedFilterScripts.push(readFileSync(args[idx + 1], "utf8")); + } else { + capturedFilterScripts.push(""); + } + return { success: true, durationMs: 1, stderr: "", exitCode: 0 }; + }), + }; +}); vi.mock("../utils/runFfmpeg.js", () => ({ runFfmpeg: runFfmpegMock, @@ -23,6 +38,7 @@ describe("processCompositionAudio", () => { afterEach(() => { runFfmpegMock.mockClear(); + capturedFilterScripts.length = 0; for (const dir of tempDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); } @@ -57,9 +73,7 @@ describe("processCompositionAudio", () => { expect(result.success).toBe(true); expect(runFfmpegMock).toHaveBeenCalledTimes(2); - const mixArgs = runFfmpegMock.mock.calls[1]?.[0]; - const filterIndex = mixArgs.indexOf("-filter_complex"); - const filter = mixArgs[filterIndex + 1]; + const filter = capturedFilterScripts[1]; expect(filter).toContain("volume=0"); expect(filter).toContain("[mixed]volume=1[out]"); @@ -119,8 +133,7 @@ describe("processCompositionAudio", () => { // 3 prepare calls (one per track via Promise.all) precede the mix call, // so the mix is at index 3, not index 1. expect(runFfmpegMock).toHaveBeenCalledTimes(4); - const mixArgs = runFfmpegMock.mock.calls[3]?.[0]; - const filter = mixArgs[mixArgs.indexOf("-filter_complex") + 1]; + const filter = capturedFilterScripts[3]; expect(filter).toContain("amix=inputs=3"); expect(filter).not.toContain("normalize="); @@ -161,9 +174,7 @@ describe("processCompositionAudio", () => { expect(result.success).toBe(true); - const mixArgs = runFfmpegMock.mock.calls[1]?.[0]; - const filterIndex = mixArgs.indexOf("-filter_complex"); - const filter = mixArgs[filterIndex + 1]; + const filter = capturedFilterScripts[1]; expect(filter).toContain("volume="); expect(filter).toContain(":eval=frame"); @@ -211,9 +222,7 @@ describe("processCompositionAudio", () => { expect(result.success).toBe(true); - const mixArgs = runFfmpegMock.mock.calls[1]?.[0]; - const filterIndex = mixArgs.indexOf("-filter_complex"); - const filter = mixArgs[filterIndex + 1]; + const filter = capturedFilterScripts[1]; // One nested `if(lt(...))` is emitted per segment; cap it well under the // FFmpeg evaluator's nesting limit (MAX_VOLUME_SEGMENTS = 32). @@ -235,20 +244,24 @@ describe("processCompositionAudio", () => { // Simulate an ffmpeg build that rejects the automation expression: the // first mix attempt fails, the static-volume retry succeeds. (prepare = - // call 0, automated mix = call 1, fallback mix = call 2.) + // call 0, automated mix = call 1, fallback mix = call 2.) These two + // one-time overrides bypass the default mock's capturedFilterScripts + // push, so they push an empty placeholder themselves to keep the array + // index-aligned with call order for the fallback mix's assertion below. runFfmpegMock - .mockImplementationOnce(async () => ({ - success: true, - durationMs: 1, - stderr: "", - exitCode: 0, - })) - .mockImplementationOnce(async () => ({ - success: false, - durationMs: 1, - stderr: "Error initializing filters", - exitCode: 234, - })); + .mockImplementationOnce(async () => { + capturedFilterScripts.push(""); + return { success: true, durationMs: 1, stderr: "", exitCode: 0 }; + }) + .mockImplementationOnce(async () => { + capturedFilterScripts.push(""); + return { + success: false, + durationMs: 1, + stderr: "Error initializing filters", + exitCode: 234, + }; + }); const result = await processCompositionAudio( [ @@ -280,12 +293,61 @@ describe("processCompositionAudio", () => { expect(result.error).toMatch(/base volume/i); // The fallback mix omits the automation expression (base volume only). - const fallbackArgs = runFfmpegMock.mock.calls[2]?.[0]; - const fallbackFilter = fallbackArgs[fallbackArgs.indexOf("-filter_complex") + 1]; + const fallbackFilter = capturedFilterScripts[2]; expect(fallbackFilter).not.toContain(":eval=frame"); expect(fallbackFilter).toContain("volume=0.8"); }); + it("keeps the ffmpeg command line short with a large track count (regression for spawn ENAMETOOLONG)", async () => { + const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-base-")); + const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-")); + tempDirs.push(baseDir, workDir); + + // Reported in the wild at 146 timed audio clips: the old inline + // -filter_complex string scaled with track count and blew past the OS + // command-line length limit. 150 tracks reproduces the same shape. + const trackCount = 150; + const elements = Array.from({ length: trackCount }, (_, i) => { + const filename = `clip-${i}.wav`; + writeFileSync(join(baseDir, filename), "stub"); + return { + id: `clip-${i}`, + src: filename, + start: i * 0.1, + end: i * 0.1 + 0.5, + mediaStart: 0, + layer: i, + volume: 1, + type: "audio" as const, + }; + }); + + const result = await processCompositionAudio( + elements, + baseDir, + workDir, + join(baseDir, "out.m4a"), + trackCount * 0.1 + 0.5, + ); + + expect(result.success).toBe(true); + expect(result.tracksProcessed).toBe(trackCount); + + const mixArgs = runFfmpegMock.mock.calls.at(-1)?.[0] as string[]; + expect(mixArgs).toContain("-filter_complex_script"); + expect(mixArgs).not.toContain("-filter_complex"); + + // The only things that scale with track count are the -i pairs (short, + // fixed-size each) and the filter SCRIPT FILE's content (off the command + // line entirely) — not the args array's own total character length. + const argsLength = mixArgs.join(" ").length; + expect(argsLength).toBeLessThan(20_000); + + const filter = capturedFilterScripts.at(-1); + expect(filter).toContain(`amix=inputs=${trackCount}`); + expect((filter?.match(/atrim=/g) ?? []).length).toBe(trackCount); + }); + it("prepares percent-encoded non-Latin audio srcs from decoded filesystem paths", async () => { const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-base-")); const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-")); diff --git a/packages/engine/src/services/audioMixer.ts b/packages/engine/src/services/audioMixer.ts index b47d6171cb..eb3ad47c55 100644 --- a/packages/engine/src/services/audioMixer.ts +++ b/packages/engine/src/services/audioMixer.ts @@ -4,7 +4,7 @@ * Processes and mixes audio tracks using FFmpeg. */ -import { existsSync, mkdirSync, rmSync } from "fs"; +import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, rmSync, writeFileSync } from "fs"; import { isAbsolute, join, dirname } from "path"; import { parseHTML } from "linkedom"; import { extractAudioMetadata } from "../utils/ffprobe.js"; @@ -384,11 +384,9 @@ async function mixAudioTracks( const outputDir = dirname(outputPath); if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true }); - const buildArgs = (ignoreAutomation: boolean): string[] => { - const inputs: string[] = []; + const buildFilterComplex = (ignoreAutomation: boolean): string => { const filterParts: string[] = []; tracks.forEach((track, i) => { - inputs.push("-i", track.srcPath); const delayMs = Math.round(track.start * 1000); const trimDuration = track.end - track.start; const volumeFilter = buildVolumeExpression(track, ignoreAutomation); @@ -403,12 +401,31 @@ async function mixAudioTracks( // gain by track count so per-track volumes authored in data-volume are preserved. const compensatedGain = masterOutputGain * tracks.length; const postMixGainFilter = `[mixed]volume=${formatFilterNumber(compensatedGain)}[out]`; - const fullFilter = [...filterParts, mixFilter, postMixGainFilter].join(";"); + return [...filterParts, mixFilter, postMixGainFilter].join(";"); + }; - return [ + // A large track count (100+) makes the inline `-filter_complex ` + // argument scale linearly with track count until it exceeds the OS + // command-line length limit — spawn ENAMETOOLONG, seen in practice at 146 + // tracks — even though every individual filter segment is short. FFmpeg's + // own `-filter_complex_script ` reads the same graph from disk + // instead, sidestepping the argv limit for the one component of this + // command line that actually grows with the composition. + const runMix = (ignoreAutomation: boolean) => { + const inputs: string[] = []; + tracks.forEach((track) => inputs.push("-i", track.srcPath)); + const scriptDir = mkdtempSync(join(outputDir, ".filter-complex-")); + const scriptPath = join(scriptDir, "graph.txt"); + const fd = openSync(scriptPath, "wx", 0o600); + try { + writeFileSync(fd, buildFilterComplex(ignoreAutomation)); + } finally { + closeSync(fd); + } + const args = [ ...inputs, - "-filter_complex", - fullFilter, + "-filter_complex_script", + scriptPath, "-map", "[out]", "-acodec", @@ -420,9 +437,12 @@ async function mixAudioTracks( "-y", outputPath, ]; + return runFfmpeg(args, { signal, timeout: ffmpegProcessTimeout }).finally(() => + rmSync(scriptDir, { recursive: true, force: true }), + ); }; - let result = await runFfmpeg(buildArgs(false), { signal, timeout: ffmpegProcessTimeout }); + let result = await runMix(false); // Defense in depth: volume automation is folded into an FFmpeg `volume` // expression whose evaluator limits are build-dependent (see @@ -432,7 +452,7 @@ async function mixAudioTracks( let degradedAutomation = false; const hasAutomation = tracks.some((track) => (track.volumeKeyframes?.length ?? 0) > 0); if (!result.success && !signal?.aborted && hasAutomation) { - const retry = await runFfmpeg(buildArgs(true), { signal, timeout: ffmpegProcessTimeout }); + const retry = await runMix(true); if (retry.success) { result = retry; degradedAutomation = true; From 8bc1e5d603bd828511bdc6dddaa96a64ea7a43d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sat, 4 Jul 2026 14:08:18 -0700 Subject: [PATCH 09/25] fix(video-workflows): pad the frame's own duration to match the transition tail (#1889) * fix(video-workflows): pad the frame's own duration to match the transition tail transitions.mjs extends the index.html WRAPPER's data-duration to cover an outgoing transition's tail, but the frame's own internal composition file kept its shorter, content-only data-duration (authored per frame-worker.md's "duration is fixed upstream" instruction). The render engine clip-gates a sub-composition's visible content at its own declared duration, so content vanished abruptly at content-end instead of fading through the wrapper's extended fade-out tween. A user root-caused and verified this themselves: padding the frame's own duration to match the wrapper fixed it, project-wide, across every non-final frame. transitions.mjs already computes the correct padded duration for the wrapper - it now writes the same value into the matching frame's own file at inject time. Extracted to a shared lib/pad-frame-duration.mjs (mirroring the existing lib/transition-registry.mjs convention) since transitions.mjs's own top-level CLI dispatch runs on import, making it untestable directly. Duplicated identically across pr-to-video, faceless-explainer, and product-launch-video, whose transitions.mjs copies are otherwise byte-identical (confirmed via diff) - one root cause, one fix, applied everywhere it lives. * fix(skills): avoid duration helper file race --- skills-manifest.json | 12 +-- .../scripts/lib/pad-frame-duration.mjs | 36 +++++++++ .../scripts/transitions.mjs | 7 ++ .../scripts/lib/pad-frame-duration.mjs | 36 +++++++++ skills/pr-to-video/scripts/transitions.mjs | 7 ++ .../scripts/lib/pad-frame-duration.mjs | 36 +++++++++ .../scripts/lib/pad-frame-duration.test.mjs | 76 +++++++++++++++++++ .../scripts/transitions.mjs | 7 ++ 8 files changed, 211 insertions(+), 6 deletions(-) create mode 100644 skills/faceless-explainer/scripts/lib/pad-frame-duration.mjs create mode 100644 skills/pr-to-video/scripts/lib/pad-frame-duration.mjs create mode 100644 skills/product-launch-video/scripts/lib/pad-frame-duration.mjs create mode 100644 skills/product-launch-video/scripts/lib/pad-frame-duration.test.mjs diff --git a/skills-manifest.json b/skills-manifest.json index 2b11428795..5d48f0d0f2 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -6,8 +6,8 @@ "files": 144 }, "faceless-explainer": { - "hash": "844c54a06fd16d3c", - "files": 17 + "hash": "6dac80491c3db278", + "files": 18 }, "figma": { "hash": "0adc2a1e01767db7", @@ -62,12 +62,12 @@ "files": 132 }, "pr-to-video": { - "hash": "132b44ddda774fef", - "files": 21 + "hash": "d40ba25aa5af30e1", + "files": 22 }, "product-launch-video": { - "hash": "32cab842cc7a6b76", - "files": 18 + "hash": "b1895d518ec04da5", + "files": 20 }, "remotion-to-hyperframes": { "hash": "9d959b31fa0fc9d0", diff --git a/skills/faceless-explainer/scripts/lib/pad-frame-duration.mjs b/skills/faceless-explainer/scripts/lib/pad-frame-duration.mjs new file mode 100644 index 0000000000..91471151fc --- /dev/null +++ b/skills/faceless-explainer/scripts/lib/pad-frame-duration.mjs @@ -0,0 +1,36 @@ +// pad-frame-duration.mjs — keeps a frame's own #root/clip data-duration in +// sync with the padded index.html wrapper duration transitions.mjs computes. +// +// The frame's OWN internal file declares its #root/clip data-duration to the +// STORYBOARD's content-only length (frame-worker.md: duration is "fixed +// upstream"). When an outgoing transition pads the index.html WRAPPER's +// data-duration to cover the transition tail, the frame's own internal +// duration is left short — the render engine clip-gates the sub-composition's +// visible content at that shorter value, so content vanishes abruptly at +// content-end instead of fading gracefully through the wrapper's extended +// fade-out tween. Pad the frame's own file to match so both durations agree. + +import { readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; + +export function padFrameInternalDuration(hyperframesDir, frameSrc, frameId, newDuration) { + const framePath = resolve(hyperframesDir, frameSrc); + let html; + try { + html = readFileSync(framePath, "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return; + throw err; + } + const tagRe = /<[a-z][\w:-]*\s[^<>]*?>/gi; + let m; + while ((m = tagRe.exec(html)) !== null) { + const tag = m[0]; + if (!tag.includes(`data-composition-id="${frameId}"`)) continue; + if (!/data-duration="[\d.]+"/.test(tag)) continue; + const newTag = tag.replace(/data-duration="[\d.]+"/, `data-duration="${newDuration}"`); + if (newTag === tag) return; + writeFileSync(framePath, html.slice(0, m.index) + newTag + html.slice(m.index + tag.length)); + return; + } +} diff --git a/skills/faceless-explainer/scripts/transitions.mjs b/skills/faceless-explainer/scripts/transitions.mjs index d30a9fae82..22ad13ff8d 100644 --- a/skills/faceless-explainer/scripts/transitions.mjs +++ b/skills/faceless-explainer/scripts/transitions.mjs @@ -28,6 +28,7 @@ import { join, resolve } from "node:path"; import { parseStoryboard } from "./lib/storyboard.mjs"; import { parseFormat } from "./lib/dimensions.mjs"; import { loadTransitionRegistry, transitionsByName } from "./lib/transition-registry.mjs"; +import { padFrameInternalDuration } from "./lib/pad-frame-duration.mjs"; const flag = (argv, name, def) => { const i = argv.indexOf(`--${name}`); @@ -183,6 +184,12 @@ function runInject(argv) { const dur = resolveDur(spec, rec, reg); const T = r3(incoming.start); // cut = incoming start (frames tile) outgoing.duration = r3(outgoing.duration + dur); // extend outgoing only + padFrameInternalDuration( + hyperframesDir, + order[i - 1].frame.src, + outgoing.id, + outgoing.duration, + ); gsapLines.push( ...buildGsap(rec, outgoing.id, incoming.id, dur, T, spec.direction, CW, CH, die), ); diff --git a/skills/pr-to-video/scripts/lib/pad-frame-duration.mjs b/skills/pr-to-video/scripts/lib/pad-frame-duration.mjs new file mode 100644 index 0000000000..91471151fc --- /dev/null +++ b/skills/pr-to-video/scripts/lib/pad-frame-duration.mjs @@ -0,0 +1,36 @@ +// pad-frame-duration.mjs — keeps a frame's own #root/clip data-duration in +// sync with the padded index.html wrapper duration transitions.mjs computes. +// +// The frame's OWN internal file declares its #root/clip data-duration to the +// STORYBOARD's content-only length (frame-worker.md: duration is "fixed +// upstream"). When an outgoing transition pads the index.html WRAPPER's +// data-duration to cover the transition tail, the frame's own internal +// duration is left short — the render engine clip-gates the sub-composition's +// visible content at that shorter value, so content vanishes abruptly at +// content-end instead of fading gracefully through the wrapper's extended +// fade-out tween. Pad the frame's own file to match so both durations agree. + +import { readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; + +export function padFrameInternalDuration(hyperframesDir, frameSrc, frameId, newDuration) { + const framePath = resolve(hyperframesDir, frameSrc); + let html; + try { + html = readFileSync(framePath, "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return; + throw err; + } + const tagRe = /<[a-z][\w:-]*\s[^<>]*?>/gi; + let m; + while ((m = tagRe.exec(html)) !== null) { + const tag = m[0]; + if (!tag.includes(`data-composition-id="${frameId}"`)) continue; + if (!/data-duration="[\d.]+"/.test(tag)) continue; + const newTag = tag.replace(/data-duration="[\d.]+"/, `data-duration="${newDuration}"`); + if (newTag === tag) return; + writeFileSync(framePath, html.slice(0, m.index) + newTag + html.slice(m.index + tag.length)); + return; + } +} diff --git a/skills/pr-to-video/scripts/transitions.mjs b/skills/pr-to-video/scripts/transitions.mjs index d30a9fae82..22ad13ff8d 100644 --- a/skills/pr-to-video/scripts/transitions.mjs +++ b/skills/pr-to-video/scripts/transitions.mjs @@ -28,6 +28,7 @@ import { join, resolve } from "node:path"; import { parseStoryboard } from "./lib/storyboard.mjs"; import { parseFormat } from "./lib/dimensions.mjs"; import { loadTransitionRegistry, transitionsByName } from "./lib/transition-registry.mjs"; +import { padFrameInternalDuration } from "./lib/pad-frame-duration.mjs"; const flag = (argv, name, def) => { const i = argv.indexOf(`--${name}`); @@ -183,6 +184,12 @@ function runInject(argv) { const dur = resolveDur(spec, rec, reg); const T = r3(incoming.start); // cut = incoming start (frames tile) outgoing.duration = r3(outgoing.duration + dur); // extend outgoing only + padFrameInternalDuration( + hyperframesDir, + order[i - 1].frame.src, + outgoing.id, + outgoing.duration, + ); gsapLines.push( ...buildGsap(rec, outgoing.id, incoming.id, dur, T, spec.direction, CW, CH, die), ); diff --git a/skills/product-launch-video/scripts/lib/pad-frame-duration.mjs b/skills/product-launch-video/scripts/lib/pad-frame-duration.mjs new file mode 100644 index 0000000000..91471151fc --- /dev/null +++ b/skills/product-launch-video/scripts/lib/pad-frame-duration.mjs @@ -0,0 +1,36 @@ +// pad-frame-duration.mjs — keeps a frame's own #root/clip data-duration in +// sync with the padded index.html wrapper duration transitions.mjs computes. +// +// The frame's OWN internal file declares its #root/clip data-duration to the +// STORYBOARD's content-only length (frame-worker.md: duration is "fixed +// upstream"). When an outgoing transition pads the index.html WRAPPER's +// data-duration to cover the transition tail, the frame's own internal +// duration is left short — the render engine clip-gates the sub-composition's +// visible content at that shorter value, so content vanishes abruptly at +// content-end instead of fading gracefully through the wrapper's extended +// fade-out tween. Pad the frame's own file to match so both durations agree. + +import { readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; + +export function padFrameInternalDuration(hyperframesDir, frameSrc, frameId, newDuration) { + const framePath = resolve(hyperframesDir, frameSrc); + let html; + try { + html = readFileSync(framePath, "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return; + throw err; + } + const tagRe = /<[a-z][\w:-]*\s[^<>]*?>/gi; + let m; + while ((m = tagRe.exec(html)) !== null) { + const tag = m[0]; + if (!tag.includes(`data-composition-id="${frameId}"`)) continue; + if (!/data-duration="[\d.]+"/.test(tag)) continue; + const newTag = tag.replace(/data-duration="[\d.]+"/, `data-duration="${newDuration}"`); + if (newTag === tag) return; + writeFileSync(framePath, html.slice(0, m.index) + newTag + html.slice(m.index + tag.length)); + return; + } +} diff --git a/skills/product-launch-video/scripts/lib/pad-frame-duration.test.mjs b/skills/product-launch-video/scripts/lib/pad-frame-duration.test.mjs new file mode 100644 index 0000000000..5bb395c2b9 --- /dev/null +++ b/skills/product-launch-video/scripts/lib/pad-frame-duration.test.mjs @@ -0,0 +1,76 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { padFrameInternalDuration } from "./pad-frame-duration.mjs"; + +// Regression: an outgoing transition pads the index.html WRAPPER's +// data-duration to cover the transition tail, but the frame's own internal +// file kept its shorter content-only duration, so the render engine +// clip-gated the sub-composition's visible content at the shorter value — +// content vanished abruptly instead of fading through the wrapper's +// extended fade-out tween. A user diagnosed and verified this fix +// themselves: pad the frame's own #root/clip data-duration to match. +test("padFrameInternalDuration pads the matching frame's own data-duration", () => { + const dir = mkdtempSync(join(tmpdir(), "transitions-pad-")); + const framesDir = join(dir, "compositions", "frames"); + mkdirSync(framesDir, { recursive: true }); + const frameSrc = "compositions/frames/scene-1.html"; + const framePath = join(dir, frameSrc); + writeFileSync( + framePath, + ``, + ); + + try { + padFrameInternalDuration(dir, frameSrc, "scene-1", 4.7); + const updated = readFileSync(framePath, "utf8"); + assert.match(updated, /data-duration="4\.7"/); + assert.doesNotMatch(updated, /data-duration="4\.2"/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("padFrameInternalDuration only touches the tag matching the given frame id", () => { + const dir = mkdtempSync(join(tmpdir(), "transitions-pad-scope-")); + const framesDir = join(dir, "compositions", "frames"); + mkdirSync(framesDir, { recursive: true }); + const frameSrc = "compositions/frames/scene-2.html"; + const framePath = join(dir, frameSrc); + const original = ``; + writeFileSync(framePath, original); + + try { + padFrameInternalDuration(dir, frameSrc, "scene-2", 3.5); + const updated = readFileSync(framePath, "utf8"); + assert.match(updated, /data-composition-id="scene-2" data-duration="3\.5"/); + assert.match(updated, /data-composition-id="unrelated-child" data-duration="1\.0"/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("padFrameInternalDuration is a no-op when the frame file does not exist", () => { + const dir = mkdtempSync(join(tmpdir(), "transitions-pad-missing-")); + try { + assert.doesNotThrow(() => + padFrameInternalDuration(dir, "compositions/frames/missing.html", "missing", 5), + ); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/skills/product-launch-video/scripts/transitions.mjs b/skills/product-launch-video/scripts/transitions.mjs index 00b1246aae..66b3b60aae 100644 --- a/skills/product-launch-video/scripts/transitions.mjs +++ b/skills/product-launch-video/scripts/transitions.mjs @@ -28,6 +28,7 @@ import { join, resolve } from "node:path"; import { parseStoryboard } from "./lib/storyboard.mjs"; import { parseFormat } from "./lib/dimensions.mjs"; import { loadTransitionRegistry, transitionsByName } from "./lib/transition-registry.mjs"; +import { padFrameInternalDuration } from "./lib/pad-frame-duration.mjs"; const flag = (argv, name, def) => { const i = argv.indexOf(`--${name}`); @@ -183,6 +184,12 @@ function runInject(argv) { const dur = resolveDur(spec, rec, reg); const T = r3(incoming.start); // cut = incoming start (frames tile) outgoing.duration = r3(outgoing.duration + dur); // extend outgoing only + padFrameInternalDuration( + hyperframesDir, + order[i - 1].frame.src, + outgoing.id, + outgoing.duration, + ); gsapLines.push( ...buildGsap(rec, outgoing.id, incoming.id, dur, T, spec.direction, CW, CH, die), ); From 0338be97fdc548fd4a179561810c0c9320b61388 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sat, 4 Jul 2026 14:08:22 -0700 Subject: [PATCH 10/25] fix(cli): validate navigation timeout honors --timeout, hints on CDN scripts (#1929) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `validate` navigated the page with a hardcoded 10s timeout that ignored the --timeout option. A composition that loads GSAP (or any library) from a CDN