From c8c5214a4136e75aedaf12890f5e8479f695e39d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sat, 21 Nov 2026 07:51:06 +0000 Subject: [PATCH 001/367] fix(core): look up SVG selector aliases by namespace before matching their values (#8354) * test(core): a predicate reads only aliases in its own namespace * fix(core): look up SVG selector aliases by namespace before matching their values * refactor(core): index each SVG alias by attribute in its own function * chore(core): regenerate the inlined alias module and the catalog font mirror index * test(core): re-record the page goldens for the new inlined alias module * refactor(core): pick a predicate's alias index in one place * chore(core): regenerate the inlined alias module and page goldens --- .../__goldens__/pageBuild.preview.html | 1539 +++++++++-------- .../__goldens__/pageBuild.render.html | 1539 +++++++++-------- .../src/compiler/svgIdNamespacing.test.ts | 26 + .../core/src/compiler/svgSelectorAliases.ts | 56 +- .../generated/svg-selector-aliases-inline.ts | 2 +- scripts/catalog-fetch-mirror/index.json | 30 +- 6 files changed, 1646 insertions(+), 1546 deletions(-) diff --git a/packages/core/src/compiler/__goldens__/pageBuild.preview.html b/packages/core/src/compiler/__goldens__/pageBuild.preview.html index ceece89be5..9392a4f5e1 100644 --- a/packages/core/src/compiler/__goldens__/pageBuild.preview.html +++ b/packages/core/src/compiler/__goldens__/pageBuild.preview.html @@ -125,170 +125,170 @@ window.__timelines.main = gsap.timeline({ paused: true });`; + delete document.body.dataset.main; + delete document.body.dataset.other; + const kills: string[] = []; + const timeline = (key: string) => ({ kill: () => kills.push(key), clear: () => {} }); + win.gsap = { timeline: () => ({}), set: () => {} }; + win.__timelines = { main: timeline("main"), other: timeline("other") }; + win.__hfForceTimelineRebind = () => {}; + const seeks: number[] = []; + let now = 4; + let playing = false; + win.__player = { + seek: (t: number) => seeks.push((now = t)), + getTime: () => now, + isPlaying: () => playing, + play: () => {}, + playFor: (t: number) => ((playing = true), (now = t)), + }; + const append = document.body.appendChild.bind(document.body); + document.body.appendChild = (node: T): T => { + for (const [, key] of (node.textContent ?? "").matchAll(/__timelines\["(\w+)"\]/g)) + (win.__timelines as Record)[key!] = timeline(key!); + const added = append(node); + if (node.nodeName === "SCRIPT") new Function(node.textContent ?? "")(); + return added; + }; + return { seeks, kills }; + } + + const plugin = () => document.head.querySelector("script[src]")!; + const newer = async (key: string) => + expect(await softReload(params({ script: run(key, "newer") }))).toEqual({ result: "applied" }); + const STEPS: Record unknown> = { + play: () => (win.__player as { playFor(t: number): void }).playFor(5), + two: () => void softReload(params({ script: run("other", "newer", true), time: 3 })), + patch: () => + expect( + patchTweens({ + patches: [{ selector: "#a", change: { kind: "set", props: { x: 300 } } }], + seek: true, + }), + ).toEqual({ patched: false }), + scrub: () => { + for (const t of [3, 4]) (win.__player as { seek(t: number): void }).seek(t); + }, + same: () => newer("main"), + other: () => newer("other"), + attr: () => restoreAttributesOrRerun({ scopes: restoreA(2), scripted: false, time: 4 }), + edit: () => document.getElementById("a")!.style.setProperty("color", "red"), + ok: () => { + win.MotionPathPlugin = {}; + plugin().onload!(new Event("load")); + }, + fail: () => plugin().onerror!(new Event("error")), + }; + + async function play(steps: Step[]): Promise { + const { seeks } = page(); + const older = softReload( + params({ script: run("main", "older", true), time: 2, restore: restoreA(1) }), + ); + for (const step of steps) { + await STEPS[step](); + await Promise.resolve(); + } + const { dataset } = document.body; + return { + answer: (await older).result, + main: dataset.main, + other: dataset.other, + left: document.getElementById("a")!.style.left, + color: document.getElementById("a")!.style.color, + at: seeks.at(-1) ?? NaN, + }; + } + + it("starts a fresh plugin load for the next re-run after one failed", async () => { + page(); + const motion = params({ script: run("main", "older", true) }); + const first = softReload(motion); + plugin().onerror!(new Event("error")); + expect(await first).toEqual({ result: "cannot-soft-reload" }); + const second = softReload(motion); + expect(document.head.querySelectorAll("script[src]")).toHaveLength(2); + win.MotionPathPlugin = {}; + document.head.querySelectorAll("script[src]")[1]!.onload!(new Event("load")); + expect(await second).toEqual({ result: "applied" }); + }); + + // fails without the fix: rows "ok", "same,ok", "same,fail", "other,ok", "other,fail", "attr,ok", "play,ok", + // "two,ok" and "patch,ok". + it.each<[string, Step[], Partial]>([ + ["ok", ["ok"], { answer: "applied", main: "older", left: "1px", at: 4 }], + ["scrub,ok", ["scrub", "ok"], { answer: "applied", main: "older", at: 4 }], + ["ok,scrub", ["ok", "scrub"], { answer: "applied", main: "older", at: 4 }], + ["same,ok", ["same", "ok"], { answer: "superseded", main: "newer", left: "1px" }], + ["same,fail", ["same", "fail"], { answer: "superseded", main: "newer" }], + ["ok,same", ["ok", "same"], { answer: "applied", main: "newer" }], + ["fail,same", ["fail", "same"], { answer: "cannot-soft-reload", main: "newer" }], + ["other,ok", ["other", "ok"], { answer: "applied", main: "older", other: "newer" }], + [ + "other,fail", + ["other", "fail"], + { answer: "cannot-soft-reload", main: undefined, other: "newer", left: "1px" }, + ], + ["ok,other", ["ok", "other"], { answer: "applied", main: "older", other: "newer" }], + ["attr,ok", ["attr", "ok"], { answer: "applied", main: "older", left: "2px" }], + ["ok,attr", ["ok", "attr"], { answer: "applied", main: "older", left: "2px" }], + ["edit,ok", ["edit", "ok"], { answer: "applied", main: "older", color: "red" }], + ["ok,edit", ["ok", "edit"], { answer: "applied", main: "older", color: "red" }], + ["play,ok", ["play", "ok"], { answer: "applied", main: "older", at: 5 }], + ["two,ok", ["two", "ok"], { answer: "applied", main: "older", other: "newer", at: 4 }], + ["patch,ok", ["patch", "ok"], { answer: "applied", main: "older" }], + ])("%s", async (_name, steps, expected) => { + expect(await play(steps)).toMatchObject(expected); + }); +}); + const restoreOf = (key: string, attributes: Array<[string, string]>) => ({ file: null, elements: [{ key, attributes }], @@ -164,6 +341,78 @@ describe("soft-reload of an undo", () => { }); }); +// fails without the fix: the frame refused an element GSAP parsed, and Studio's later re-run raced newer edits. +describe("restore-attributes with a re-run", () => { + const MARKUP = `
`; + const RERUN = { script: SCRIPT, sets: [], authored: [], timing: [] }; + const request = (rerun?: object) => ({ + scopes: [ + restoreOf("hf:h1", [ + ["id", "a"], + ["data-hf-id", "h1"], + ["style", "left: 0px"], + ]), + ], + scripted: true, + time: 1.5, + ...(rerun && { rerun }), + }); + const parsedEl = () => Object.assign(document.getElementById("a")!, { _gsap: {} }); + + it("re-runs the script in the same request when GSAP has parsed a restored element", async () => { + const seeks = preview(MARKUP); + const el = parsedEl(); + const seen: Array = []; + win.__hfForceTimelineRebind = () => seen.push(el.getAttribute("style")); + const params = parseRestoreAttributesRerun(request(RERUN))!; + expect(await restoreAttributesOrRerun(params)).toEqual({ applied: true, reran: true }); + expect(seen).toEqual([expect.stringContaining("left: 0px")]); + expect(killed).toHaveBeenCalledOnce(); + expect(seeks).toContain(1.5); + }); + + it("refuses and changes nothing when GSAP has parsed a restored element and no re-run came", async () => { + preview(MARKUP); + const el = parsedEl(); + expect(await restoreAttributesOrRerun(parseRestoreAttributesRerun(request())!)).toEqual({ + applied: false, + reran: false, + }); + expect(el.getAttribute("style")).toBe("left: 90px"); + expect(killed).not.toHaveBeenCalled(); + }); + + it("sets the attributes without re-running when GSAP has parsed none of them", async () => { + preview(MARKUP); + const params = parseRestoreAttributesRerun(request(RERUN))!; + expect(await restoreAttributesOrRerun(params)).toEqual({ applied: true, reran: false }); + expect(document.getElementById("a")!.getAttribute("style")).toBe("left: 0px"); + expect(killed).not.toHaveBeenCalled(); + }); + + it("is refused by an older frame's parser, so Studio reloads as before", () => { + expect(parseRestoreAttributes(request(RERUN))).toBeNull(); + }); + + // fails without the fix: an unrelated style over the re-run's limit refused a restore that needed no re-run. + it.each([ + ["an empty script", { ...RERUN, script: "" }], + ["a field soft-reload does not take", { ...RERUN, restore: [] }], + ["an authored style over its limit", { ...RERUN, authored: [["#big", "x".repeat(16_385)]] }], + ["no object", "rerun"], + ])("drops a re-run with %s and keeps the restore", (_name, rerun) => { + expect(parseRestoreAttributesRerun({ ...request(), rerun })).toEqual(request()); + }); + + it("sets the attributes in place when the re-run it carried was dropped and none is needed", async () => { + preview(MARKUP); + const big = { ...RERUN, authored: [["#big", "x".repeat(16_385)]] }; + const params = parseRestoreAttributesRerun(request(big))!; + expect(await restoreAttributesOrRerun(params)).toEqual({ applied: true, reran: false }); + expect(document.getElementById("a")!.getAttribute("style")).toBe("left: 0px"); + }); +}); + describe("soft-reload of a timing edit", () => { const MARKUP = `
`; diff --git a/packages/core/src/runtime/editing/softReload.ts b/packages/core/src/runtime/editing/softReload.ts index 0b5131bce0..b297a9504c 100644 --- a/packages/core/src/runtime/editing/softReload.ts +++ b/packages/core/src/runtime/editing/softReload.ts @@ -7,8 +7,11 @@ import { escapeCssString } from "../editingElement"; import { applyAuthoredTiming } from "../../studioPreviewMark"; import { applyRestorePlan, + parseRestoreAttributes, parseRestoreScopes, planRestore, + restoreInPlace, + type RestoreAttributesParams, type RestorePlan, type RestoreScope, } from "./restoreAttributes"; @@ -30,8 +33,10 @@ export type SoftReloadWindow = Window & { __hfForceTimelineRebind?: () => void; __hfSuppressSceneMutations?: (fn: () => T) => T; __hfStudioManualEditsApply?: () => void; - // Set while a MotionPathPlugin script is fetched, so overlapping reloads queue no second one. - __hfMotionPathPluginLoading?: boolean; + // Everyone waiting on the one MotionPathPlugin script being fetched; absent when none is. + __hfMotionPathWaiters?: [ready: () => void, failed: () => void][]; + __hfSwapsWaiting?: number; + __hfTimelineGenerations?: Map; gsap?: { version?: string; registerPlugin?: (...plugins: unknown[]) => unknown; @@ -45,7 +50,8 @@ export type StandaloneSet = { selector: string; props: string[] }; // "applied": ran, or runs once the MotionPath plugin loads. "verify-failed": ran, its timeline keys // read empty for now, the live state is right. "cannot-soft-reload": only a full reload fixes it. -export type SoftReloadResult = "applied" | "verify-failed" | "cannot-soft-reload"; +// "superseded": a newer soft reload replaced one of its timelines while it waited, so it changed nothing. +export type SoftReloadResult = "applied" | "verify-failed" | "cannot-soft-reload" | "superseded"; export interface SoftReloadInput { script: string; @@ -392,32 +398,18 @@ function whenMotionPathLoaded( ready: () => void, failed: () => void, ): void { - // A load already in flight is the one to wait for; a second plugin script re-flashes the frame. - if (win.__hfMotionPathPluginLoading) { - const started = Date.now(); - const poll = win.setInterval(() => { - if (win.MotionPathPlugin) { - win.clearInterval(poll); - ready(); - } else if (!win.__hfMotionPathPluginLoading || Date.now() - started > 10000) { - win.clearInterval(poll); - failed(); - } - }, 50); - return; - } - win.__hfMotionPathPluginLoading = true; + if (win.__hfMotionPathWaiters) return void win.__hfMotionPathWaiters.push([ready, failed]); + const waiters: [() => void, () => void][] = [[ready, failed]]; + win.__hfMotionPathWaiters = waiters; + const settle = (loaded: boolean) => { + win.__hfMotionPathWaiters = undefined; + for (const [onReady, onFailed] of waiters) (loaded ? onReady : onFailed)(); + }; const pluginScript = doc.createElement("script"); pluginScript.src = previewMotionPathUrl(doc, win.gsap?.version); - pluginScript.onload = () => { - win.__hfMotionPathPluginLoading = false; - ready(); - }; + pluginScript.onload = () => settle(Boolean(win.MotionPathPlugin)); // Running the script without the plugin would leave a motionPath tween that cannot play. - pluginScript.onerror = () => { - win.__hfMotionPathPluginLoading = false; - failed(); - }; + pluginScript.onerror = () => settle(false); doc.head.appendChild(pluginScript); } @@ -459,6 +451,39 @@ function readAuthoredStyles( // Re-runs the script in place of the live one registering the same `__timelines` keys, tearing down // only those timelines. A promise only while it waits for the MotionPath plugin. +export function swapWaiting(win: SoftReloadWindow = window as SoftReloadWindow): boolean { + return (win.__hfSwapsWaiting ?? 0) > 0; +} + +/** Loads and registers MotionPathPlugin ahead of the first re-run that needs it, as Studio does same-origin. */ +export function preloadMotionPath( + win: SoftReloadWindow = window as SoftReloadWindow, + doc: Document = document, +): void { + if (win.MotionPathPlugin || win.__hfMotionPathWaiters || !win.gsap) return; + const register = () => win.MotionPathPlugin && win.gsap?.registerPlugin?.(win.MotionPathPlugin); + whenMotionPathLoaded(win, doc, register, () => {}); +} + +function runScript(win: SoftReloadWindow, doc: Document, script: string): boolean { + if (win.MotionPathPlugin && win.gsap?.registerPlugin) + win.gsap.registerPlugin(win.MotionPathPlugin); + const s = doc.createElement("script"); + s.textContent = `(function(){${script}\n})();`; + const before = doc.body.querySelectorAll("*").length + 1; + doc.body.appendChild(s); + // A script that builds DOM builds it again on every run; only a full load starts from the file. + // Not seen: text-only writes, nodes put in the head or a shadow root, and nodes added later. + return doc.body.querySelectorAll("*").length > before; +} + +function startRun(win: SoftReloadWindow, keys: string[]) { + const generations = (win.__hfTimelineGenerations ??= new Map()); + const numbered = keys.map((key) => [key, (generations.get(key) ?? 0) + 1] as const); + for (const [key, n] of numbered) generations.set(key, n); + return () => numbered.every(([key, n]) => generations.get(key) === n); +} + export function softReloadFrame( win: SoftReloadWindow, doc: Document, @@ -476,41 +501,50 @@ export function softReloadFrame( if (!authored) return "cannot-soft-reload"; const timing = input.timing ? planSavedTiming(doc, ownFile, input.timing) : []; if (timing === null) return "cannot-soft-reload"; - - let deferred: ((result: SoftReloadResult) => void) | null = null; - let pending: Promise | null = null; - let builtDom = false; - - const executeScript = () => { - if (win.MotionPathPlugin && win.gsap?.registerPlugin) - win.gsap.registerPlugin(win.MotionPathPlugin); - const s = doc.createElement("script"); - s.textContent = `(function(){${script}\n})();`; - const before = doc.body.querySelectorAll("*").length + 1; - doc.body.appendChild(s); - // A script that builds DOM builds it again on every run; only a full load starts from the file. - // Not seen: text-only writes, nodes put in the head or a shadow root, and nodes added later. - builtDom = doc.body.querySelectorAll("*").length > before; - finalizeSoftReload(win, currentTime); - deferred?.(builtDom ? "cannot-soft-reload" : "applied"); + // The file's own state lands now, in the order requests arrive; only the timeline swap may wait. + if ( + !runSuppressed(win, () => { + if (input.restorePlan) applyRestorePlan(input.restorePlan); + applyTimingPlan(timing); + }) + ) + return "cannot-soft-reload"; + const current = startRun(win, targetKeys); + const swap = (time: number): boolean => { + let builtDom = false; + const ran = runSuppressed(win, () => { + killTimelines(win, targetKeys); + resetTargetStyles(win, targets, authored); + forgetLiveSets(targets); + for (const stale of staleScripts) stale.remove(); + builtDom = runScript(win, doc, script); + finalizeSoftReload(win, time); + }); + return ran && !builtDom; }; - const doReload = () => { - if (input.restorePlan) applyRestorePlan(input.restorePlan); - applyTimingPlan(timing); - killTimelines(win, targetKeys); - resetTargetStyles(win, targets, authored); - forgetLiveSets(targets); - for (const stale of staleScripts) stale.remove(); - const needsMotionPath = /motionPath\s*[:{]/.test(script); - if (!needsMotionPath || win.MotionPathPlugin || !win.gsap) return executeScript(); - pending = new Promise((resolve) => (deferred = resolve)); - whenMotionPathLoaded(win, doc, executeScript, () => deferred?.("cannot-soft-reload")); - }; - - if (!runSuppressed(win, doReload) || builtDom) return "cannot-soft-reload"; - if (pending) return pending; - return verifyTimelinesPopulated(win, targetKeys) ? "applied" : "verify-failed"; + const needsMotionPath = /motionPath\s*[:{]/.test(script); + if (!needsMotionPath || win.MotionPathPlugin || !win.gsap) { + if (!swap(currentTime)) return "cannot-soft-reload"; + return verifyTimelinesPopulated(win, targetKeys) ? "applied" : "verify-failed"; + } + win.__hfSwapsWaiting = (win.__hfSwapsWaiting ?? 0) + 1; + return new Promise((settle) => { + const end = (result: SoftReloadResult) => { + win.__hfSwapsWaiting = (win.__hfSwapsWaiting ?? 1) - 1; + settle(result); + }; + whenMotionPathLoaded( + win, + doc, + () => { + if (!current()) return end("superseded"); + const time = win.__player?.getTime?.() ?? currentTime; + end(swap(time) ? "applied" : "cannot-soft-reload"); + }, + () => end(current() ? "cannot-soft-reload" : "superseded"), + ); + }); } export const MAX_SOFT_RELOAD_SCRIPT = 1_000_000; @@ -535,6 +569,8 @@ export type SoftReloadParams = { restore: RestoreScope[]; }; +export type SoftReloadRerun = Omit; + const isRecord = (value: unknown): value is Record => Object.prototype.toString.call(value) === "[object Object]"; @@ -618,3 +654,38 @@ export async function softReload(params: SoftReloadParams): Promise<{ result: So }); return { result }; } + +/** `restore-attributes` with the re-run it may need; any other key still refuses the whole request. */ +export function parseRestoreAttributesRerun(params: unknown): RestoreAttributesParams | null { + if (!isRecord(params) || !("rerun" in params)) return parseRestoreAttributes(params); + const { rerun, ...rest } = params; + const restore = parseRestoreAttributes(rest); + if (!restore) return null; + const run = parsedRerun(rerun, restore); + return run ? { ...restore, rerun: run } : restore; +} + +function parsedRerun(rerun: unknown, restore: RestoreAttributesParams): SoftReloadRerun | null { + if (!isRecord(rerun) || Object.keys(rerun).sort().join() !== "authored,script,sets,timing") + return null; + const run = parseSoftReload({ ...rerun, time: restore.time, restore: restore.scopes }); + return run && { script: run.script, sets: run.sets, authored: run.authored, timing: run.timing }; +} + +/** An element GSAP has parsed is restored by re-running the script, in the same request that sent it. */ +export async function restoreAttributesOrRerun( + params: RestoreAttributesParams, +): Promise<{ applied: boolean; reran: boolean }> { + const outcome = restoreInPlace(params); + if (outcome !== "gsap-parsed" || !params.rerun) + return { applied: outcome === "applied", reran: false }; + const { result } = await softReload({ + ...params.rerun, + time: params.time, + restore: params.scopes, + }); + return { + applied: result !== "cannot-soft-reload", + reran: result === "applied" || result === "verify-failed", + }; +} diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index 8558294e52..ade904285d 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -560,15 +560,17 @@ describe("installEditingAgent", () => { id: 1, ok: false, }); - expect(document.querySelector("script")?.textContent).toBe(script); + expect(document.body.querySelector("script")?.textContent).toBe(script); // The sent script registers on a local, so the frame reads its timeline empty for now. expect(await ask(port, { v: 1, id: 2, kind: "soft-reload", params })).toMatchObject({ id: 2, ok: true, result: { result: "verify-failed" }, }); - expect(document.querySelector("script")?.textContent).toBe(`(function(){${script}\n})();`); - for (const key of ["gsap", "__timelines", "__hfForceTimelineRebind"]) delete frame[key]; + expect(document.body.querySelector("script")?.textContent).toBe(`(function(){${script}\n})();`); + for (const key of ["gsap", "__timelines", "__hfForceTimelineRebind", "__hfMotionPathWaiters"]) + delete frame[key]; + document.head.querySelector("script[src]")?.remove(); }); it("holds and swaps scenes through the port, and refuses a hold carrying anything extra", async () => { diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts index 91276acb48..dcbbc25fbe 100644 --- a/packages/core/src/runtime/editingAgent.ts +++ b/packages/core/src/runtime/editingAgent.ts @@ -32,7 +32,6 @@ import { elementGeometry } from "./editingGeometry"; import { pointerTargetsAt } from "./editingTargets"; import { layersOf } from "./editingLayers"; import { drawDrafts } from "./editingDraft"; -import { restoreAttributes } from "./editing/restoreAttributes"; import { stopWatchingGeometry, watchGeometry } from "./editing/watchGeometry"; import { maxZIndex } from "./editing/maxZIndex"; import { gestureStart } from "./editingGestureStart"; @@ -42,7 +41,7 @@ import { cropLift } from "./editing/cropLift"; import { stackingFamily } from "./editingLayers"; import { gsapSet } from "./editing/gsapSet"; import { patchTweens } from "./editing/patchTween"; -import { softReload } from "./editing/softReload"; +import { preloadMotionPath, restoreAttributesOrRerun, softReload } from "./editing/softReload"; import { holdScenes, markScenesStale, swapScenes } from "./editing/scenes"; import { liveRetime } from "./editing/liveRetime"; import { previewAssetsUnloaded } from "../lottieReadiness"; @@ -212,7 +211,7 @@ const HANDLERS: Handlers = { return { errors, truncated: from + errors.length < seen.length }; }, "watch-keys": ({ combos }, port) => watchKeys(port, combos), - "restore-attributes": (params) => restoreAttributes(params), + "restore-attributes": restoreAttributesOrRerun, "caption-words": captionWords, "caption-transform": captionTransform, "color-grading-status": colorGradingStatus, @@ -294,6 +293,7 @@ export function installEditingAgent(parent: Window = window.parent): { dispose: const port = channel.port1; ports.add(port); serve(port); + preloadMotionPath(); try { // "*" as every runtime post does (bridge.ts): the frame is not told its parent's origin. parent.postMessage( diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index 0352fd1b78..b014d7e222 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -9,7 +9,7 @@ * otherwise takes straight off the frame's window, which an opaque-origin * preview does not allow. */ -import { parseRestoreAttributes, type RestoreAttributesParams } from "./editing/restoreAttributes"; +import type { RestoreAttributesParams } from "./editing/restoreAttributes"; import { geometryEvent, parseWatchGeometry, @@ -32,6 +32,7 @@ import type { EditingLayer, EditingStackingSibling } from "./editingLayers"; import { parseGsapSet, type GsapSetParams } from "./editing/gsapSet"; import { parsePatchTweens, type PatchTweensParams } from "./editing/patchTween"; import { + parseRestoreAttributesRerun, parseSoftReload, type SoftReloadParams, type SoftReloadResult, @@ -332,7 +333,10 @@ export interface EditingRequests { /** The frame cancels these combos outside the elements that own keys, and forwards them and their * keyups to this port; an empty list stops. */ "watch-keys": { params: { combos: string[] }; result: { watching: number } }; - "restore-attributes": { params: RestoreAttributesParams; result: { applied: boolean } }; + "restore-attributes": { + params: RestoreAttributesParams; + result: { applied: boolean; reran?: boolean }; + }; /** Boxes of the words of visible caption groups; a group written as plain text is split into word spans. */ "caption-words": { params: CaptionWordsParams; result: { boxes: CaptionWordBox[] } }; "caption-transform": { params: CaptionTransformParams; result: { words: CaptionWordState[] } }; @@ -573,7 +577,7 @@ const PARAM_PARSERS: { "console-errors": (params) => hasKeys(params, "from") && isOffset(params.from) ? { from: params.from } : null, "watch-keys": comboList, - "restore-attributes": parseRestoreAttributes, + "restore-attributes": parseRestoreAttributesRerun, "caption-words": captionWordsParams, "caption-transform": captionTransformParams, "color-grading-status": parseColorGradingStatusParams, diff --git a/packages/studio/src/hooks/gsapMutationClient.ts b/packages/studio/src/hooks/gsapMutationClient.ts index ea12b89cfd..edaaa32a67 100644 --- a/packages/studio/src/hooks/gsapMutationClient.ts +++ b/packages/studio/src/hooks/gsapMutationClient.ts @@ -1,4 +1,4 @@ -import { studioWriteHeaders } from "../utils/studioFileVersion"; +import { studioFileRevision, studioWriteHeaders } from "../utils/studioFileVersion"; import { studioApiFetch } from "../utils/studioApiFetch"; import { heldFileWordsOf, withStatus } from "../utils/studioSaveDiagnostics"; @@ -62,6 +62,7 @@ export type GsapMutationStatus = { /** Atomic whole-file ownership pair returned by the mutation endpoint. */ before?: string; after?: string; + revision?: number; }; function isRecord(value: unknown): value is Record { @@ -118,8 +119,11 @@ async function postOwnedGsapMutation( fallback: string, ): Promise { let response: Response; + let revision: number; try { - response = await requestGsapMutation(projectId, route, filePath, body); + const pending = requestGsapMutation(projectId, route, filePath, body); + revision = studioFileRevision(); + response = await pending; } catch (error) { throw new GsapPreviewConvergenceError(`${fallback}: mutation outcome unknown`, { cause: error, @@ -132,7 +136,7 @@ async function postOwnedGsapMutation( held ?? withStatus(readMutationError(payload, fallback), response), ); } - return readMutationStatus(payload); + return { ...readMutationStatus(payload), revision }; } export function postGsapMutation( diff --git a/packages/studio/src/hooks/gsapRuntimePatch.ts b/packages/studio/src/hooks/gsapRuntimePatch.ts index b2436492ff..806f931b39 100644 --- a/packages/studio/src/hooks/gsapRuntimePatch.ts +++ b/packages/studio/src/hooks/gsapRuntimePatch.ts @@ -10,6 +10,7 @@ import { type PatchTarget, type RuntimeTweenChange, } from "@hyperframes/core/runtime/patch-tween"; +import { swapWaiting, type SoftReloadWindow } from "@hyperframes/core/runtime/soft-reload"; export type { RuntimeTweenChange, SetPatchProps } from "@hyperframes/core/runtime/patch-tween"; @@ -42,6 +43,7 @@ export function patchRuntimeTweenInPlace( ): boolean { if (!iframe) return false; try { + if (iframe.contentWindow && swapWaiting(iframe.contentWindow as SoftReloadWindow)) return false; const target = reachablePreview(iframe); if (change.kind !== "global-set") return patchTween(target, selector, change, compositionId, deferSeek); diff --git a/packages/studio/src/hooks/gsapScriptCommitTypes.ts b/packages/studio/src/hooks/gsapScriptCommitTypes.ts index 755e9d83e1..a941cc94fc 100644 --- a/packages/studio/src/hooks/gsapScriptCommitTypes.ts +++ b/packages/studio/src/hooks/gsapScriptCommitTypes.ts @@ -23,6 +23,7 @@ export interface MutationResult { before?: string; after?: string; scriptText?: string; + revision?: number; } export interface CommitMutationOptions { diff --git a/packages/studio/src/hooks/sealedTweenPatch.ts b/packages/studio/src/hooks/sealedTweenPatch.ts index a813240cac..9bf2af9c64 100644 --- a/packages/studio/src/hooks/sealedTweenPatch.ts +++ b/packages/studio/src/hooks/sealedTweenPatch.ts @@ -1,5 +1,5 @@ import type { RuntimeTweenChange } from "./gsapRuntimePatch"; -import { previewRequest } from "../player/lib/previewChannel"; +import { sendPreviewWrite, type PreviewTicket } from "../utils/sealedPreviewLedger"; const definedChannels = (props: T): T => Object.fromEntries(Object.entries(props).filter(([, v]) => v !== undefined)) as T; @@ -22,15 +22,18 @@ const wirePatch = ({ selector, change }: { selector: string; change: RuntimeTwee const sealedGroupPatched = new WeakMap>(); -/** A sealed preview patches its own tweens; a refusal, or no answer, reloads it once after the group's last write. */ +/** A sealed preview patches its own tweens; a refusal or no answer runs `fallback` after the group's last write. */ export function patchSealedPreview( - iframe: HTMLIFrameElement, + ticket: PreviewTicket, patches: ReadonlyArray<{ selector: string; change: RuntimeTweenChange }>, lastWrite: boolean, - reloadPreview: () => void, + fallback: () => void, ): void { const request = { patches: patches.map(wirePatch), seek: lastWrite }; - const patched = previewRequest(iframe, "patch-tweens", request).then((r) => r?.patched === true); + const { iframe } = ticket; + const patched = sendPreviewWrite(ticket, "patch-tweens", request).then( + (r) => typeof r === "object" && r?.patched === true, + ); const earlier = sealedGroupPatched.get(iframe) ?? Promise.resolve(true); const group = Promise.all([earlier, patched]).then(([a, b]) => a && b); if (!lastWrite) { @@ -39,6 +42,6 @@ export function patchSealedPreview( } sealedGroupPatched.delete(iframe); void group.then((all) => { - if (!all) reloadPreview(); + if (!all) fallback(); }); } diff --git a/packages/studio/src/hooks/timelineTimingSync.sealed.test.ts b/packages/studio/src/hooks/timelineTimingSync.sealed.test.ts index 919b03ba95..1a886728b6 100644 --- a/packages/studio/src/hooks/timelineTimingSync.sealed.test.ts +++ b/packages/studio/src/hooks/timelineTimingSync.sealed.test.ts @@ -2,10 +2,13 @@ import { expect, it, vi } from "vitest"; const { previewRequest } = vi.hoisted(() => ({ previewRequest: vi.fn() })); +const PREVIEW_LOAD = vi.hoisted(() => ({})); vi.mock("../player/lib/previewChannel", async (importOriginal) => ({ ...(await importOriginal()), previewFrameOpaque: () => true, + previewEditingClient: () => PREVIEW_LOAD, previewRequest, + previewAnswer: previewRequest, })); import { finishTimelineTimingFallback } from "./timelineTimingSync"; diff --git a/packages/studio/src/hooks/timelineTimingSync.ts b/packages/studio/src/hooks/timelineTimingSync.ts index 04e3b72e7f..d1afc052bf 100644 --- a/packages/studio/src/hooks/timelineTimingSync.ts +++ b/packages/studio/src/hooks/timelineTimingSync.ts @@ -150,6 +150,7 @@ async function syncTimingEditPreview( previousHtml: outcome.before, timingEdit: true, nestedFiles, + version: outcome.revision, }); if (result === "cannot-soft-reload") reloadPreview(); } diff --git a/packages/studio/src/hooks/useEditHistoryActions.ts b/packages/studio/src/hooks/useEditHistoryActions.ts index 5c34ae3f57..38807de832 100644 --- a/packages/studio/src/hooks/useEditHistoryActions.ts +++ b/packages/studio/src/hooks/useEditHistoryActions.ts @@ -20,6 +20,7 @@ interface HistoryResult { undoes?: string; /** Per-file restored/previous content, used to soft-apply the preview. */ files?: RestoreFiles; + revision?: number; } interface HistoryFileCallbacks { readFile: (path: string) => Promise; @@ -130,7 +131,7 @@ export function useEditHistoryActions({ serverSteppedShown && predictedShown ? fromShown(result.files, predicted!.files) : result.files; - const restore = { paths: result.paths, files }; + const restore = { paths: result.paths, files, revision: result.revision }; onAfterUndoRedo?.(restore); if (activeCompPath && result.paths?.includes(activeCompPath)) { forceReloadSdkSession?.(); diff --git a/packages/studio/src/hooks/useGsapScriptCommits.sealed.test.ts b/packages/studio/src/hooks/useGsapScriptCommits.sealed.test.ts index eabc8f1dcd..2db083348b 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.sealed.test.ts +++ b/packages/studio/src/hooks/useGsapScriptCommits.sealed.test.ts @@ -5,11 +5,16 @@ const { previewRequest, patchRuntimeTweenInPlace } = vi.hoisted(() => ({ previewRequest: vi.fn(), patchRuntimeTweenInPlace: vi.fn(), })); -vi.mock("../player/lib/previewChannel", async (importOriginal) => ({ - ...(await importOriginal()), - previewFrameOpaque: () => true, - previewRequest, -})); +vi.mock("../player/lib/previewChannel", async (importOriginal) => { + const original = await importOriginal(); + const { admittedAnswer } = await import("../../tests/previewAnswerMock"); + return { + ...original, + previewFrameOpaque: () => true, + previewRequest, + previewAnswer: admittedAnswer(previewRequest, original.PREVIEW_STALE), + }; +}); vi.mock("./gsapRuntimePatch", () => ({ patchRuntimeTweenInPlace })); import { applyPreviewSync } from "./useGsapScriptCommits"; @@ -39,13 +44,18 @@ it("sends a sealed preview's value edits to the frame in one request, without em vi.fn(), ); - expect(previewRequest).toHaveBeenCalledExactlyOnceWith(iframe, "patch-tweens", { - patches: [ - { selector: "#a", change: { kind: "set", props: { x: 10 } } }, - { selector: "#b", change: { kind: "global-set", props: { rotation: 45 } } }, - ], - seek: true, - }); + expect(previewRequest).toHaveBeenCalledExactlyOnceWith( + iframe, + "patch-tweens", + { + patches: [ + { selector: "#a", change: { kind: "set", props: { x: 10 } } }, + { selector: "#b", change: { kind: "global-set", props: { rotation: 45 } } }, + ], + seek: true, + }, + undefined, + ); const sent = previewRequest.mock.calls[0]?.[2] as { patches: Array<{ change: { props: object } }>; }; @@ -105,3 +115,35 @@ it("leaves the render to the group's last write", () => { expect(previewRequest.mock.calls[0]?.[2]).toMatchObject({ seek: false }); }); + +// fails without the fix: a refused sealed patch remounted the whole preview instead of re-running the script. +it("re-runs the saved script in place when the frame refuses a patch of a soft-reloadable edit", async () => { + const saved = { + ok: true, + scriptText: `window.__timelines["main"] = gsap.timeline().set("#a", { x: 10 });`, + before: "
", + after: "
", + }; + previewRequest.mockImplementation(async (_iframe, kind) => + kind === "patch-tweens" ? { patched: false } : { result: "applied" }, + ); + const reloadPreview = vi.fn(); + applyPreviewSync( + iframe, + saved, + { + label: "drag", + softReload: true, + instantPatch: { selector: "#a", change: { kind: "set", props: { x: 10 } } }, + }, + reloadPreview, + ); + + await vi.waitFor(() => + expect(previewRequest.mock.calls.map(([, kind]) => kind)).toEqual([ + "patch-tweens", + "soft-reload", + ]), + ); + expect(reloadPreview).not.toHaveBeenCalled(); +}); diff --git a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx index a7da353013..b29f37dd7e 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx +++ b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx @@ -70,12 +70,14 @@ function expectSoftReloadedWith( onAsyncFailure: unknown, authoredHtml: string | undefined, previousHtml?: string, + version?: unknown, ) { expect(applySoftReload).toHaveBeenCalledWith(FAKE_IFRAME, "SCRIPT", { onAsyncFailure, currentTimeOverride: 0, authoredHtml, previousHtml, + version, }); } @@ -712,7 +714,8 @@ describe("runCommit — instantPatch wiring", () => { ); }); - expectSoftReloadedWith(deps.reloadPreview, "AFTER", "BEFORE"); + // The save's own revision, taken when its request went out. + expectSoftReloadedWith(deps.reloadPreview, "AFTER", "BEFORE", expect.any(Number)); expect(deps.reloadPreview).not.toHaveBeenCalled(); }); @@ -907,7 +910,8 @@ describe("runCommit — instantPatch wiring", () => { }); expect(fetch).toHaveBeenCalledTimes(1); - expectSoftReloadedWith(deps.reloadPreview, "AFTER", "BEFORE"); + // The save's own revision, taken when its request went out. + expectSoftReloadedWith(deps.reloadPreview, "AFTER", "BEFORE", expect.any(Number)); expect(deps.reloadPreview).not.toHaveBeenCalled(); expect(deps.onCacheInvalidate).toHaveBeenCalledTimes(1); }); @@ -922,7 +926,8 @@ describe("runCommit — instantPatch wiring", () => { }); expect(patchRuntimeTweenInPlace).not.toHaveBeenCalled(); - expectSoftReloadedWith(deps.reloadPreview, "AFTER", "BEFORE"); + // The save's own revision, taken when its request went out. + expectSoftReloadedWith(deps.reloadPreview, "AFTER", "BEFORE", expect.any(Number)); expect(deps.reloadPreview).not.toHaveBeenCalled(); }); diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.ts index 16952e9603..50cc299241 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.ts +++ b/packages/studio/src/hooks/useGsapScriptCommits.ts @@ -28,6 +28,12 @@ import { patchRuntimeTweenInPlace } from "./gsapRuntimePatch"; import { lastTweenPatch } from "@hyperframes/core/runtime/patch-tween"; import { previewFrameOpaque } from "../player/lib/previewChannel"; import { patchSealedPreview } from "./sealedTweenPatch"; +import { + newestPreviewWrite, + takePreviewTicket, + ticketNeedsRecovery, + type PreviewWrite, +} from "../utils/sealedPreviewLedger"; import { createKeyedSerializer } from "./serializeByKey"; import { GsapMutationHttpError, @@ -51,6 +57,7 @@ import { useSafeGsapCommitMutation, } from "./useSafeGsapCommitMutation"; import { requestGsapMutation } from "./gsapMutationClient"; +import { studioFileRevision } from "../utils/studioFileVersion"; import { whileScriptWrites } from "../player/previewReloading"; async function mutateGsapScript( @@ -59,11 +66,13 @@ async function mutateGsapScript( sourceFile: string, body: unknown, ): Promise { - const res = await requestGsapMutation(projectId, route, sourceFile, body); + const pending = requestGsapMutation(projectId, route, sourceFile, body); + const revision = studioFileRevision(); + const res = await pending; if (!res.ok) throw new GsapMutationHttpError(res.status, await readJsonResponseBody(res)); const result = (await res.json()) as MutationResult; if (!result.ok) throw new Error(`Failed to update GSAP in ${sourceFile}`); - return result; + return { ...result, revision }; } type ShowToast = (message: string, tone?: "error" | "info") => void; @@ -214,14 +223,13 @@ function syncCommittedGsapMutation({ * - `"applied"` → success (or deferred to async plugin load; `onAsyncFailure` * covers the CDN-error escalation). */ +type ShownFiles = Pick & Partial; + function softReloadOrEscalate( iframe: HTMLIFrameElement | null, - scriptText: string, + { scriptText, authoredHtml, previousHtml, nestedFiles, timingEdit, version }: ShownFiles, reloadPreview: () => void, origin: "preview_sync" | "sdk_refresh", - authoredHtml?: string, - nestedFiles?: Map | null, - previousHtml?: string, ): void { // Seek the rebuilt timeline to the studio's own authoritative scrub position, // not the iframe's raw `__player.getTime()` — see the comment in @@ -233,6 +241,8 @@ function softReloadOrEscalate( authoredHtml, previousHtml, nestedFiles, + timingEdit, + version, }); if (result === "applied") return; trackStudioEvent("gsap_soft_reload_outcome", { @@ -262,8 +272,20 @@ export function applyPreviewSync( const patches = instantPatchesFor(options); const writtenWithoutPatch = patches.length === 0; let needsFallback = options.previewFallbackLatch?.pending === true || writtenWithoutPatch; + const write: ShownFiles = { + scriptText: result.scriptText ?? "", + authoredHtml: result.after ?? undefined, + previousHtml: result.before, + nestedFiles, + version: result.revision, + }; + const show = (shown: ShownFiles | null) => { + if (!options.softReload || !shown?.scriptText) return reloadPreview(); + softReloadOrEscalate(iframe, shown, reloadPreview, "preview_sync"); + }; + const fallback = () => show(write); if (patches.length > 0) { - if (!patchInstantly(iframe, patches, options, reloadPreview)) needsFallback = true; + if (!patchInstantly(iframe, patches, options, write, show)) needsFallback = true; // Patched in place: no reload unless an earlier deferred batch left one member unpatched. if (!needsFallback) return; } @@ -274,37 +296,36 @@ export function applyPreviewSync( } if (options.deferPreviewSync && !needsFallback) return; if (options.previewFallbackLatch) options.previewFallbackLatch.pending = false; - if (options.softReload && result.scriptText) { - // A soft-reloadable edit escalates to a full iframe remount ONLY on the - // PERMANENT "cannot-soft-reload" result (the preview is genuinely stale/ - // broken). The TRANSIENT "verify-failed" does NOT escalate — the value is - // already correct on screen, and a remount re-flashes the WebGL context AND - // re-inlines subcomps (reverting their keyframes). The async MotionPath-plugin - // load failure escalates separately via `onAsyncFailure`. - softReloadOrEscalate( - iframe, - result.scriptText, - reloadPreview, - "preview_sync", - result.after ?? undefined, - nestedFiles, - result.before, - ); - } else { - reloadPreview(); - } + // A soft-reloadable edit escalates to a full remount only on "cannot-soft-reload"; "verify-failed" is + // transient (the value is already on screen), and a remount re-flashes WebGL and reverts subcomp keyframes. + fallback(); } -/** A sealed preview patches itself (and reloads on its own if it must); a reachable one is patched here. */ +/** A sealed preview patches itself; its late refusal re-runs the newest saved script unless a re-run covers it. */ function patchInstantly( iframe: HTMLIFrameElement | null, patches: NonNullable, options: CommitMutationOptions, - reloadPreview: () => void, + write: ShownFiles, + show: (shown: ShownFiles | null) => void, ): boolean { if (!iframe || !previewFrameOpaque(iframe)) return patchReachablePreview(iframe, patches, options.deferPreviewSync === true); - patchSealedPreview(iframe, patches, !options.deferPreviewSync, reloadPreview); + const { authoredHtml, previousHtml } = write; + const snapshot = + authoredHtml !== undefined && previousHtml !== undefined + ? { ...write, authoredHtml, previousHtml } + : null; + const ticket = takePreviewTicket(iframe, { + scriptText: write.scriptText, + snapshot, + attributes: false, + timing: false, + version: write.version, + }); + patchSealedPreview(ticket, patches, !options.deferPreviewSync, () => { + if (ticketNeedsRecovery(ticket)) show(newestPreviewWrite(ticket)); + }); return true; } @@ -506,7 +527,8 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra // plugin-CDN load error genuinely breaks the iframe → full reload. Per U4, a // synchronous "verify-failed" (transient empty __timelines) does NOT escalate, // but a "cannot-soft-reload" (structural failure) does. - softReloadOrEscalate(previewIframeRef.current, script, reloadPreview, "sdk_refresh", after); + const shown = { scriptText: script, authoredHtml: after }; + softReloadOrEscalate(previewIframeRef.current, shown, reloadPreview, "sdk_refresh"); } else { reloadPreview(); } diff --git a/packages/studio/src/hooks/usePersistentEditHistory.test.ts b/packages/studio/src/hooks/usePersistentEditHistory.test.ts index ec2c898679..47e8c52dc4 100644 --- a/packages/studio/src/hooks/usePersistentEditHistory.test.ts +++ b/packages/studio/src/hooks/usePersistentEditHistory.test.ts @@ -83,6 +83,7 @@ it("an edit Studio saved is undone and redone by the project's history, with the undoes: expect.any(String), paths: ["index.html"], files: { "index.html": { previous: "B", restored: "A" } }, + revision: expect.any(Number), }); expect(file()).toBe("A"); diff --git a/packages/studio/src/hooks/usePersistentEditHistory.ts b/packages/studio/src/hooks/usePersistentEditHistory.ts index 6e367b6fc5..9a6a66bed8 100644 --- a/packages/studio/src/hooks/usePersistentEditHistory.ts +++ b/packages/studio/src/hooks/usePersistentEditHistory.ts @@ -1,6 +1,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { HistoryListItem, HistoryResult } from "@hyperframes/studio-server"; -import { studioFileContentVersion, studioWriteHeaders } from "../utils/studioFileVersion"; +import { + studioFileContentVersion, + studioFileRevision, + studioWriteHeaders, +} from "../utils/studioFileVersion"; import type { RestoreFiles } from "../utils/gsapUndoRestore"; import { studioApiFetch } from "../utils/studioApiFetch"; import { @@ -29,6 +33,7 @@ interface ApplyResult { paths?: string[]; undoes?: string; files?: RestoreFiles; + revision?: number; } interface NextStep { @@ -312,11 +317,13 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistory own.overtake(); const attempt = async (target: string | null): Promise => { const previous = await readAll(paths, callbacks.readFile); - const posted = await post( + const pending = post( historyUrl(projectId, target ? "/undo" : "/step"), target ? { entryId: target } : { direction: direction === "undo" ? "back" : "forward" }, studioWriteHeaders(), ); + const revision = studioFileRevision(); + const posted = await pending; heldClaimRef.current = null; void refresh(); if (!posted.ok && posted.status === APP_KEEPS_NO_HISTORY) @@ -332,6 +339,7 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistory const changed = reply.entry.files.map((file) => file.path); return { ok: true, + revision, label: reply.entry.label, undoes: reply.entry.undoes, paths: changed, diff --git a/packages/studio/src/hooks/usePreviewPersistence.ts b/packages/studio/src/hooks/usePreviewPersistence.ts index 5aa0259065..f2eb0bcf06 100644 --- a/packages/studio/src/hooks/usePreviewPersistence.ts +++ b/packages/studio/src/hooks/usePreviewPersistence.ts @@ -40,6 +40,7 @@ import { interface HistoryPreviewRestore { paths?: string[]; files?: RestoreFiles; + revision?: number; } // ── Types ── @@ -259,6 +260,7 @@ export function usePreviewPersistence({ usePlayerStore.getState().currentTime, reloadPreview, nestedFiles, + restore.revision, ); if (strategy === "full") return; // A soft restore patched the reverted attributes onto the live preview, but the diff --git a/packages/studio/src/player/hooks/useShadowPreviewReload.ts b/packages/studio/src/player/hooks/useShadowPreviewReload.ts index 96bee6e1fb..392084238e 100644 --- a/packages/studio/src/player/hooks/useShadowPreviewReload.ts +++ b/packages/studio/src/player/hooks/useShadowPreviewReload.ts @@ -24,6 +24,7 @@ import type { IframeWindow, PlaybackAdapter } from "../lib/playbackTypes"; import { setPreviewReloading } from "../previewReloading"; import { previewFrameOpaque, previewSeekPainted } from "../lib/previewChannel"; import { studioFileRevision } from "../../utils/studioFileVersion"; +import { previewLoadShows } from "../../utils/sealedPreviewLedger"; import { announcePreviewPromoted } from "../sceneSwap"; import { afterStudioPendingEdits, isStudioEditSaving } from "../../utils/studioPendingEdits"; import { usePlayerStore } from "../store/playerStore"; @@ -314,6 +315,7 @@ export function useShadowPreviewReload({ attachIframeShortcutListeners(); applyPreviewAudioState(); setPreviewSlots((prev) => planShadowPromotion(prev, gen)); + previewLoadShows(shadow, revisionAtRequestRef.current); if (liveTime != null) handOverPlaybackRef.current(liveTime, playing); if (held) releaseAfterPaint(shadow, held.release); announcePreviewPromoted({ retired, live: shadow }); diff --git a/packages/studio/src/player/lib/previewChannel.test.ts b/packages/studio/src/player/lib/previewChannel.test.ts index 2374b07e5b..932f614b65 100644 --- a/packages/studio/src/player/lib/previewChannel.test.ts +++ b/packages/studio/src/player/lib/previewChannel.test.ts @@ -3,9 +3,12 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { AGENT_PROBE_MS, + PREVIEW_REJECTED, + previewAnswer, previewClipManifest, previewEditingClient, previewFrameOpaque, + previewRequest, previewSeekPainted, setFrameLoopStart, } from "./previewChannel"; @@ -130,6 +133,23 @@ describe("previewEditingClient", () => { expect(Date.now() - again).toBeLessThan(100); }); + it("keeps a frame's error answer apart from no answer; previewRequest answers null for both", async () => { + const frame: Record = {}; + const iframe = detachedFakeIframe(frame); + const answerWithError = (port: MessagePort) => + queueMicrotask(() => { + port.onmessage = (event: MessageEvent<{ id: number; kind: string }>) => { + if (event.data.kind === "runtime-snapshot") return; + const error = { code: "invalid-params", message: "timing value too long" }; + port.postMessage({ v: 1, id: event.data.id, ok: false, error }); + }; + }); + closers.push(serveEditingRequests(frame, () => null, answerWithError)); + expect(await previewAnswer(iframe, "wait-for-seek", {})).toBe(PREVIEW_REJECTED); + expect(await previewRequest(iframe, "wait-for-seek", {})).toBeNull(); + expect(await previewAnswer(iframe, "runtime-snapshot", {}, 50)).toBeNull(); + }); + it("returns the runtime's manifest only when its reply has the manifest's shape", async () => { const manifest = { clips: [], durationInFrames: 30, scenes: [] }; let reply: unknown = { clipManifest: manifest }; diff --git a/packages/studio/src/player/lib/previewChannel.ts b/packages/studio/src/player/lib/previewChannel.ts index 2936f9ed15..0d9c9152cf 100644 --- a/packages/studio/src/player/lib/previewChannel.ts +++ b/packages/studio/src/player/lib/previewChannel.ts @@ -1,6 +1,7 @@ // Runtime-state reads over a preview frame's editing port; an opaque frame's window is out of reach. import { createEditingPortClient, + EditingPortError, type EditingParams, type EditingPortClient, type EditingRequestKind, @@ -84,16 +85,35 @@ async function agentConnected(client: EditingPortClient): Promise { return connected; } -/** Null when no port comes within AGENT_PROBE_MS (a runtime without the editing agent), or on error. */ +export const PREVIEW_REJECTED = Symbol("preview-rejected"); +export const PREVIEW_STALE = Symbol("preview-stale"); + +/** previewRequest's reply, keeping an error answer (PREVIEW_REJECTED) apart from no reply (null: no port, timeout). */ +export async function previewAnswer( + iframe: HTMLIFrameElement, + kind: K, + params: EditingParams, + timeoutMs?: number, + admit?: () => boolean, +): Promise | typeof PREVIEW_REJECTED | typeof PREVIEW_STALE | null> { + const client = previewEditingClient(iframe); + if (!(await agentConnected(client))) return null; + if (admit && !admit()) return PREVIEW_STALE; + return client.request(kind, params, { timeoutMs }).catch((err: unknown) => { + const noReply = + err instanceof EditingPortError && (err.code === "timeout" || err.code === "disposed"); + return noReply ? null : PREVIEW_REJECTED; + }); +} + export async function previewRequest( iframe: HTMLIFrameElement, kind: K, params: EditingParams, timeoutMs?: number, ): Promise | null> { - const client = previewEditingClient(iframe); - if (!(await agentConnected(client))) return null; - return client.request(kind, params, { timeoutMs }).catch(() => null); + const answer = await previewAnswer(iframe, kind, params, timeoutMs); + return answer === PREVIEW_REJECTED || answer === PREVIEW_STALE ? null : answer; } export async function previewSeekPainted(iframe: HTMLIFrameElement, timeoutMs?: number) { diff --git a/packages/studio/src/utils/gsapLiveRetime.sealed.test.ts b/packages/studio/src/utils/gsapLiveRetime.sealed.test.ts index acddde15f2..a05b4897b5 100644 --- a/packages/studio/src/utils/gsapLiveRetime.sealed.test.ts +++ b/packages/studio/src/utils/gsapLiveRetime.sealed.test.ts @@ -2,13 +2,19 @@ import { beforeEach, expect, it, vi } from "vitest"; const { previewRequest } = vi.hoisted(() => ({ previewRequest: vi.fn() })); -vi.mock("../player/lib/previewChannel", async (importOriginal) => ({ - ...(await importOriginal()), - previewFrameOpaque: () => true, - previewRequest, -})); +vi.mock("../player/lib/previewChannel", async (importOriginal) => { + const original = await importOriginal(); + const { admittedAnswer } = await import("../../tests/previewAnswerMock"); + return { + ...original, + previewFrameOpaque: () => true, + previewRequest, + previewAnswer: admittedAnswer(previewRequest, original.PREVIEW_STALE), + }; +}); import { moveLiveTweens } from "./gsapLiveRetime"; +import { SAVED_STATE_DEADLINE_MS } from "./sealedPreviewLedger"; const iframe = document.createElement("iframe"); const script = (start: number) => @@ -31,23 +37,28 @@ it("sends a sealed preview the move planned from the saved file before and after expect(await moveLiveTweens(iframe, script(1.5), 2, reload, files)).toBe(true); - expect(previewRequest).toHaveBeenCalledExactlyOnceWith(iframe, "live-retime", { - key: "t", - after: script(1.5), - tweens: [ - { - selector: "#a", - start: 1.5, - duration: 1, - wasStart: 0.5, - wasDuration: 1, - moved: true, - source: 0, - }, - ], - time: 2, - timing: [[expect.any(String), [["data-start", "1.5"]]]], - }); + expect(previewRequest).toHaveBeenCalledExactlyOnceWith( + iframe, + "live-retime", + { + key: "t", + after: script(1.5), + tweens: [ + { + selector: "#a", + start: 1.5, + duration: 1, + wasStart: 0.5, + wasDuration: 1, + moved: true, + source: 0, + }, + ], + time: 2, + timing: [[expect.any(String), [["data-start", "1.5"]]]], + }, + SAVED_STATE_DEADLINE_MS, + ); expect(reload).not.toHaveBeenCalled(); }); diff --git a/packages/studio/src/utils/gsapLiveRetime.ts b/packages/studio/src/utils/gsapLiveRetime.ts index 63121c4ae1..f030125ff5 100644 --- a/packages/studio/src/utils/gsapLiveRetime.ts +++ b/packages/studio/src/utils/gsapLiveRetime.ts @@ -7,13 +7,24 @@ import { type TweenTiming, } from "@hyperframes/core/runtime/live-retime"; import { + applySoftReload, applySoftReloadFinalization, findGsapScriptElements, scriptsRegistering, timelineKeys, } from "./gsapSoftReload"; -import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel"; +import { PREVIEW_REJECTED, PREVIEW_STALE, previewFrameOpaque } from "../player/lib/previewChannel"; +import { usePlayerStore } from "../player/store/playerStore"; import { savedTiming } from "./authoredSource"; +import { + SAVED_STATE_DEADLINE_MS, + newestPreviewWrite, + sendPreviewWrite, + takePreviewTicket, + ticketNeedsRecovery, + type PreviewTicket, + type PreviewWrite, +} from "./sealedPreviewLedger"; /** * How a saved script differs from the live one: `retime` when only tween starts and lengths moved @@ -124,8 +135,8 @@ function sealedRetimeResult(reply: unknown): LiveRetimeResult { return RETIME_RESULTS.has(result) ? (result as LiveRetimeResult) : "failed"; } -/** The edited file as saved before and after the edit. */ -type SavedFiles = { before?: string; after?: string }; +/** The edited file as saved before and after, and the revision its save went out at. */ +type SavedFiles = { before?: string; after?: string; revision?: number }; /** A `retime` plan from the file as saved before the edit; null when no single script there owns the timeline. */ function planFromSavedFile( @@ -141,6 +152,17 @@ function planFromSavedFile( return plan.kind === "retime" ? plan : null; } +function rerunNewest( + iframe: HTMLIFrameElement, + { scriptText, ...write }: PreviewWrite, + reloadPreview: () => void, +): void { + // At the playhead now, not when the retime was sent: a scrub since then must not be undone. + const currentTimeOverride = usePlayerStore.getState().currentTime; + const options = { ...write, currentTimeOverride, onAsyncFailure: reloadPreview }; + if (applySoftReload(iframe, scriptText, options) === "cannot-soft-reload") reloadPreview(); +} + // Planned from the saved files alone; the frame checks its timeline matches the plan before moving anything. async function moveSealedLiveTweens( iframe: HTMLIFrameElement, @@ -153,16 +175,49 @@ async function moveSealedLiveTweens( const plan = planFromSavedFile(scriptText, files.before); if (!plan) return false; const { key: planKey, after, tweens } = plan; - const reply = await previewRequest(iframe, "live-retime", { + const snapshot = { + scriptText, + authoredHtml: files.after, + previousHtml: files.before, + timingEdit: true, + version: files.revision, + }; + const ticket = takePreviewTicket(iframe, { + scriptText, + snapshot, + attributes: false, + timing: true, + }); + const params = { key: planKey, after, tweens, time: currentTime, timing: savedTiming(files.after), - }); - const result = sealedRetimeResult(reply); - if (result === "unchanged") return false; - if (result === "failed") reloadPreview(); + }; + const answer = await sendPreviewWrite(ticket, "live-retime", params, SAVED_STATE_DEADLINE_MS); + // Stale: the frame shows a newer file, which recovers in place like a refusal. + const result = + answer === PREVIEW_STALE + ? "unchanged" + : sealedRetimeResult(answer === PREVIEW_REJECTED ? null : answer); + if (result === "moved" || !ticketNeedsRecovery(ticket)) return true; + return recoverRetime(iframe, ticket, result === "failed", files.after, reloadPreview); +} + +/** False when the caller's own re-run of this saved file is the recovery. */ +function recoverRetime( + iframe: HTMLIFrameElement, + ticket: PreviewTicket, + failed: boolean, + savedAfter: string, + reloadPreview: () => void, +): boolean { + const newest = newestPreviewWrite(ticket); + if (failed || !newest) reloadPreview(); + // A newer saved file is the one to re-run: the caller would re-run this older script. + else if (newest.authoredHtml !== savedAfter) rerunNewest(iframe, newest, reloadPreview); + else return false; return true; } diff --git a/packages/studio/src/utils/gsapSoftReload.sealed.test.ts b/packages/studio/src/utils/gsapSoftReload.sealed.test.ts index d369ee467d..80a4edbd22 100644 --- a/packages/studio/src/utils/gsapSoftReload.sealed.test.ts +++ b/packages/studio/src/utils/gsapSoftReload.sealed.test.ts @@ -2,10 +2,13 @@ import { beforeEach, expect, it, vi } from "vitest"; const { previewRequest } = vi.hoisted(() => ({ previewRequest: vi.fn() })); +const PREVIEW_LOAD = vi.hoisted(() => ({})); vi.mock("../player/lib/previewChannel", async (importOriginal) => ({ ...(await importOriginal()), previewFrameOpaque: () => true, + previewEditingClient: () => PREVIEW_LOAD, previewRequest, + previewAnswer: previewRequest, })); import { applySoftReload } from "./gsapSoftReload"; diff --git a/packages/studio/src/utils/gsapSoftReload.test.ts b/packages/studio/src/utils/gsapSoftReload.test.ts index 9628dabace..b21d3768bd 100644 --- a/packages/studio/src/utils/gsapSoftReload.test.ts +++ b/packages/studio/src/utils/gsapSoftReload.test.ts @@ -316,7 +316,7 @@ window.__timelines["root"] = tl;`; await Promise.resolve(); expect(onAsyncFailure).toHaveBeenCalledTimes(1); expect(contentWindow.__hfForceTimelineRebind).not.toHaveBeenCalled(); - expect(contentWindow.__hfMotionPathPluginLoading).toBe(false); + expect(contentWindow.__hfMotionPathWaiters).toBeUndefined(); }); it("loads a missing soft-reload plugin from the iframe mirror and reports its failure", async () => { @@ -338,7 +338,7 @@ window.__timelines["root"] = tl;`; await Promise.resolve(); expect(onAsyncFailure).toHaveBeenCalledTimes(1); expect(contentWindow.__hfForceTimelineRebind).not.toHaveBeenCalled(); - expect(contentWindow.__hfMotionPathPluginLoading).toBe(false); + expect(contentWindow.__hfMotionPathWaiters).toBeUndefined(); expect(head.querySelectorAll("script")).toHaveLength(1); }); @@ -471,7 +471,7 @@ function buildBootstrapIframe(overrides: Record = {}) { const contentWindow = { gsap: { registerPlugin } as Record | undefined, MotionPathPlugin: undefined as unknown, - __hfMotionPathPluginLoading: undefined as boolean | undefined, + __hfMotionPathWaiters: undefined as unknown[] | undefined, ...overrides, }; const contentDocument = { @@ -572,7 +572,7 @@ describe("ensureMotionPathPluginLoaded", () => { "http://localhost:8080/vendor/npm/gsap@3.14.2/dist/MotionPathPlugin.min.js", ); appendedScripts[0]!.onerror?.(new Event("error")); - expect(contentWindow.__hfMotionPathPluginLoading).toBe(false); + expect(contentWindow.__hfMotionPathWaiters).toBeUndefined(); expect(registerPlugin).not.toHaveBeenCalled(); expect(appendedScripts).toHaveLength(1); }); @@ -601,13 +601,13 @@ describe("ensureMotionPathPluginLoaded", () => { ensureMotionPathPluginLoaded(iframe); expect(appendedScripts).toHaveLength(1); expect(appendedScripts[0]!.src).toContain("MotionPathPlugin"); - expect(contentWindow.__hfMotionPathPluginLoading).toBe(true); + expect(contentWindow.__hfMotionPathWaiters).toBeDefined(); // Simulate the CDN load completing; the plugin is now present. contentWindow.MotionPathPlugin = {}; appendedScripts[0]!.onload?.(new Event("load")); expect(registerPlugin).toHaveBeenCalledWith(contentWindow.MotionPathPlugin); - expect(contentWindow.__hfMotionPathPluginLoading).toBe(false); + expect(contentWindow.__hfMotionPathWaiters).toBeUndefined(); }); it("is idempotent: a second call while loading does not append a second script", () => { @@ -631,7 +631,7 @@ describe("ensureMotionPathPluginLoaded", () => { const { iframe, contentWindow, appendedScripts } = buildBootstrapIframe(); ensureMotionPathPluginLoaded(iframe); appendedScripts[0]!.onerror?.(new Event("error")); - expect(contentWindow.__hfMotionPathPluginLoading).toBe(false); + expect(contentWindow.__hfMotionPathWaiters).toBeUndefined(); // A subsequent call can retry (plugin still absent, flag cleared). ensureMotionPathPluginLoaded(iframe); expect(appendedScripts).toHaveLength(2); diff --git a/packages/studio/src/utils/gsapSoftReload.ts b/packages/studio/src/utils/gsapSoftReload.ts index e4edc04338..456052a723 100644 --- a/packages/studio/src/utils/gsapSoftReload.ts +++ b/packages/studio/src/utils/gsapSoftReload.ts @@ -5,7 +5,7 @@ import { compositionFile, finalizeSoftReload, findGsapScriptElements, - previewMotionPathUrl, + preloadMotionPath, restoreAuthoredStyle, scriptsRegistering, softReloadFrame, @@ -16,7 +16,13 @@ import { import { authoredStyles, findAuthoredElement, savedTiming } from "./authoredSource"; import { fileDocs, standaloneSets } from "./softReloadTargets"; import type { EditingParams } from "@hyperframes/core/runtime/editing-port"; -import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel"; +import { PREVIEW_REJECTED, PREVIEW_STALE, previewFrameOpaque } from "../player/lib/previewChannel"; +import { + SAVED_STATE_DEADLINE_MS, + sendPreviewWrite, + takePreviewTicket, + ticketNeedsRecovery, +} from "./sealedPreviewLedger"; export { findGsapScriptElements, @@ -65,27 +71,7 @@ export function ensureMotionPathPluginLoaded(iframe: HTMLIFrameElement | null): window.addEventListener("message", retry); return; } - // A load is already in flight for this iframe — don't queue a second script. - if (win.__hfMotionPathPluginLoading) return; - - try { - win.__hfMotionPathPluginLoading = true; - const pluginScript = doc.createElement("script"); - pluginScript.src = previewMotionPathUrl(doc, win.gsap?.version); - const finalize = () => { - win.__hfMotionPathPluginLoading = false; - try { - if (win.MotionPathPlugin && win.gsap?.registerPlugin) { - win.gsap.registerPlugin(win.MotionPathPlugin); - } - } catch {} - }; - pluginScript.onload = finalize; - pluginScript.onerror = finalize; - doc.head.appendChild(pluginScript); - } catch { - win.__hfMotionPathPluginLoading = false; - } + preloadMotionPath(win, doc); } /** @@ -112,6 +98,8 @@ export interface SoftReloadOptions { previousHtml?: string; /** A timing edit, whose saved timing a sealed preview takes along: no commit could patch it live. */ timingEdit?: boolean; + /** The Studio file revision `authoredHtml`'s save went out at. */ + version?: number; /** Other composition files a reset element is written in, by path; null when one could not be read. */ nestedFiles?: Map | null; restore?: EditingParams<"soft-reload">["restore"]; @@ -179,7 +167,12 @@ const outgoingScripts = (doc: ParentNode, scriptText: string): string[] => (script) => script.textContent ?? "", ); -const SOFT_RELOAD_RESULTS = new Set(["applied", "verify-failed", "cannot-soft-reload"]); +const SOFT_RELOAD_RESULTS = new Set([ + "applied", + "verify-failed", + "cannot-soft-reload", + "superseded", +]); /** The frame's reply is data: anything but exactly `{ result }` with a known result counts as a refusal. */ function sealedSoftReloadResult(reply: unknown): SoftReloadResult { @@ -190,6 +183,24 @@ function sealedSoftReloadResult(reply: unknown): SoftReloadResult { return result as SoftReloadResult; } +/** What a sealed frame needs to re-run `scriptText`, from the saved files alone. */ +export function sealedRerun( + scriptText: string, + { + authoredHtml, + previousHtml, + timingEdit, + }: { authoredHtml: string; previousHtml: string; timingEdit?: boolean }, +): Omit, "time" | "restore"> { + const previous = new DOMParser().parseFromString(previousHtml, "text/html"); + return { + script: scriptText, + sets: standaloneSets(outgoingScripts(previous, scriptText)), + authored: authoredStyles(authoredHtml), + timing: timingEdit ? savedTiming(authoredHtml) : [], + }; +} + // Everything sent comes from the files Studio saved, never from the frame; the reply only says whether it applied. function softReloadSealed( iframe: HTMLIFrameElement, @@ -201,22 +212,33 @@ function softReloadSealed( onAsyncFailure, onShownInPlace, timingEdit, + nestedFiles, + version, restore = [], }: SoftReloadOptions, ): SoftReloadResult { if (authoredHtml === undefined || previousHtml === undefined || currentTimeOverride === undefined) return "cannot-soft-reload"; - const previous = new DOMParser().parseFromString(previousHtml, "text/html"); - void previewRequest(iframe, "soft-reload", { - script: scriptText, - time: currentTimeOverride, - sets: standaloneSets(outgoingScripts(previous, scriptText)), - authored: authoredStyles(authoredHtml), - timing: timingEdit ? savedTiming(authoredHtml) : [], - restore, - }).then((reply) => { - if (sealedSoftReloadResult(reply) === "cannot-soft-reload") onAsyncFailure?.(); - else onShownInPlace?.(); + const rerun = sealedRerun(scriptText, { authoredHtml, previousHtml, timingEdit }); + const ticket = takePreviewTicket(iframe, { + scriptText, + snapshot: { scriptText, authoredHtml, previousHtml, nestedFiles, timingEdit, version }, + attributes: restore.length > 0, + timing: timingEdit === true, + rerun: true, + }); + const savedState = ticket.sent.attributes || ticket.sent.timing; + const deadline = savedState ? SAVED_STATE_DEADLINE_MS : undefined; + const params = { ...rerun, time: currentTimeOverride, restore }; + void sendPreviewWrite(ticket, "soft-reload", params, deadline).then((answer) => { + // No answer, a refusal, a rejection and a stale write all leave the change unproven on screen. + const result = + answer === PREVIEW_REJECTED || answer === PREVIEW_STALE + ? "cannot-soft-reload" + : sealedSoftReloadResult(answer); + if (!ticketNeedsRecovery(ticket)) return; + if (result === "cannot-soft-reload") onAsyncFailure?.(); + else if (result !== "superseded") onShownInPlace?.(); }); return "applied"; } @@ -248,7 +270,7 @@ export function applySoftReload( }); if (typeof result === "string") return result; void result.then((settled) => { - if (settled !== "applied") options.onAsyncFailure?.(); + if (settled !== "applied" && settled !== "superseded") options.onAsyncFailure?.(); }); return "applied"; } diff --git a/packages/studio/src/utils/gsapSoftReloadWait.browser.test.ts b/packages/studio/src/utils/gsapSoftReloadWait.browser.test.ts new file mode 100644 index 0000000000..9f67c8d9bb --- /dev/null +++ b/packages/studio/src/utils/gsapSoftReloadWait.browser.test.ts @@ -0,0 +1,464 @@ +// Real Chrome: a preview Studio cannot script (a sandboxed frame), or a same-origin one, running the real runtime, +// with the MotionPath plugin request held so a re-run has to wait for it. +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import type { Browser, Page } from "puppeteer-core"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils"; +import { + buildStudioBundle, + openPreview as openSharedPreview, + type Preview, + type Studio, +} from "../../tests/sealedPreviewHarness"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); +const require = createRequire(import.meta.url); +const STUDIO_MARK = ''; +const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"]; +let browser: Browser; +let studioBundle: string; + +beforeAll(async () => { + browser = await launchTestChrome(); + studioBundle = await buildStudioBundle(); +}); + +afterAll(() => closeTestChrome(browser)); + +const C_ATTRIBUTES = (left: number) => [ + ["id", "c"], + ["data-hf-id", "c"], + ["class", "clip box"], + ["data-start", "0"], + ["data-duration", "4"], + ["data-track-index", "3"], + ["style", `left: ${left}px; top: 500px`], +]; +const restoreC = (left: number) => [ + { file: null, elements: [{ key: "hf:c", attributes: C_ATTRIBUTES(left) }] }, +]; + +/** A timeline script for `key`: "main" moves #target to `x`, "other" moves #b. */ +function timeline(key: "main" | "other", name: string, x: number, motion = false): string { + const target = key === "main" ? "#target" : "#b"; + return `(function () { + window.__timelines = window.__timelines || {}; + var tl = gsap.timeline({ paused: true }); + tl.to("${target}", { x: ${x}, duration: 4, ease: "none" }, 0); + window.__timelines["${key}"] = tl; + window.__ran = Object.assign(window.__ran || {}, { ${key}: "${name}" }); + })();${motion ? "\n// motionPath: held until the plugin loads" : ""}`; +} + +/** A Studio preview page with two timelines, "main" and "other", GSAP and the runtime inline. */ +function previewHtml(): string { + const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8"); + const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); + const box = (id: string, track: number, style: string) => + `
`; + return `${STUDIO_MARK} + + +
+ ${box("target", 1, "left: 100px; top: 100px")}${box("b", 2, "left: 600px; top: 100px")} +
+
+ + `; +} + +const openPreview = (mode: string) => openSharedPreview(browser, studioBundle, previewHtml(), mode); + +/** Studio's re-run of `script` at `time`: its answer now, or with `late`, "reload" if Studio falls back later. */ +function rerun(page: Page, script: string, time: number, restore: unknown[] = [], late = false) { + return page.evaluate( + (text, at, scopes, waitLate) => + new Promise((resolve) => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const iframe = document.querySelector("iframe")!; + const html = ``; + const result = studio.applySoftReload(iframe, text, { + currentTimeOverride: at, + authoredHtml: html, + previousHtml: html, + restore: scopes as never, + onAsyncFailure: () => resolve("reload"), + }); + if (result !== "applied" || !waitLate) resolve(result); + }), + script, + time, + restore, + late, + ); +} + +/** Waits until every answer the frame owes Studio has reached it. */ +async function settled({ page, frame }: Preview, sealed: boolean) { + await frame.waitForFunction( + () => !(window as { __hfMotionPathWaiters?: unknown }).__hfMotionPathWaiters, + ); + // The swap's seek renders on the frame's next animation frame; a step after it must come after that render. + await frame.evaluate( + () => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))), + ); + if (sealed) + await page.evaluate(async () => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + await studio.previewRequest(document.querySelector("iframe")!, "runtime-snapshot", {}); + }); +} + +type Step = + | "drag" + | "scrub" + | "play" + | "late" + | "same" + | "other" + | "two" + | "patch" + | "attr" + | "edit" + | "move" + | "ok" + | "fail"; + +/** Restores #c's left as Studio does: through the frame when sealed, by writing the same-origin DOM otherwise. */ +function restoreLeftOfC(preview: Preview, sealed: boolean, left: number) { + if (!sealed) + return preview.frame.evaluate( + (l) => document.getElementById("c")!.setAttribute("style", `left: ${l}px; top: 500px`), + left, + ); + return preview.page.evaluate( + (scopes) => + (window as unknown as { hfStudio: Studio }).hfStudio.previewRequest( + document.querySelector("iframe")!, + "restore-attributes", + { scopes: scopes as never, scripted: true, time: 4 }, + ), + restoreC(left), + ); +} + +const styleTarget = (preview: Preview, name: string, value: string) => + preview.frame.evaluate( + (n, v) => document.getElementById("target")!.style.setProperty(n, v), + name, + value, + ); + +const STEPS: Record Promise> = { + // Playback runs past 1 s during the wait, then pauses: the swap leaves the playhead on that frame. + play: async (p) => { + const control = (action: string) => + p.page.evaluate((a) => { + const msg = { source: "hf-parent", type: "control", action: a }; + document.querySelector("iframe")!.contentWindow!.postMessage(msg, "*"); + }, action); + await control("play"); + await expect.poll(p.time).toBeGreaterThan(1); + await control("pause"); + await p.frame.waitForFunction( + () => !(window as unknown as { __player: { isPlaying(): boolean } }).__player.isPlaying(), + ); + // A playback tick already scheduled can still land after the pause; read the frame it leaves. + await p.frame.evaluate( + () => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))), + ); + pausedAt = Math.round((await p.time()) * 100) / 100; + }, + // Studio's editing port gives a request 5 s (editingPort.ts); the plugin stays held past that. + late: () => new Promise((done) => setTimeout(done, 5_500)), + // A drag's live preview is a gsap.set on the element per frame; each call moves it 10 px further. + drag: (p) => + p.frame.evaluate(() => { + const w = window as unknown as { + gsap: { set(t: Element, v: object): void }; + __drag?: number; + }; + w.__drag = (w.__drag ?? 140) + 10; + w.gsap.set(document.getElementById("target")!, { x: w.__drag }); + }), + // A second run that waits too: it counts only once the frame holds both swaps. + two: async (p) => { + void rerun(p.page, timeline("other", "newer", 200, true), 3); + await p.frame.waitForFunction( + () => ((window as unknown as { __hfSwapsWaiting?: number }).__hfSwapsWaiting ?? 0) >= 2, + ); + }, + patch: async (p, sealed) => { + const patched = await p.page.evaluate(async (isSealed) => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const iframe = document.querySelector("iframe")!; + const change = { kind: "set" as const, props: { x: 300 } }; + if (!isSealed) return studio.patchRuntimeTweenInPlace(iframe, "#target", change); + const reply = await studio.previewRequest(iframe, "patch-tweens", { + patches: [{ selector: "#target", change }], + seek: true, + }); + return reply?.patched === true; + }, sealed); + expect(patched).toBe(false); + }, + scrub: async (p) => { + for (const t of [3, 4]) await p.seek(t); + }, + same: (p) => rerun(p.page, timeline("main", "newer", 200), 4), + other: (p) => rerun(p.page, timeline("other", "newer", 200), 4), + attr: (p, sealed) => restoreLeftOfC(p, sealed, 2), + edit: (p) => styleTarget(p, "color", "red"), + move: (p) => styleTarget(p, "transform", "translateX(300px)"), + ok: async (p, sealed) => { + await p.release(200); + await settled(p, sealed); + }, + fail: async (p, sealed) => { + await p.release(404); + await settled(p, sealed); + }, +}; + +let pausedAt: number | undefined; + +/** Plays `steps` against an older "main" re-run waiting for the plugin, sent at 2 s with the player at 4 s. */ +async function play(mode: string, steps: Step[]) { + const sealed = mode === "sealed"; + pausedAt = undefined; + const preview = await openPreview(mode); + const { page, frame, held, seek, time } = preview; + await seek(4); + if (!sealed) await restoreLeftOfC(preview, sealed, 1); + const older = rerun( + page, + timeline("main", "older", 60, true), + 2, + sealed ? restoreC(1) : [], + true, + ); + await expect.poll(() => held.length).toBeGreaterThan(0); + for (const step of steps) await STEPS[step](preview, sealed); + const answer = await Promise.race([older, Promise.resolve("kept")]); + const state = await frame.evaluate(() => { + const target = document.getElementById("target")!; + return { + ran: (window as unknown as { __ran: Record }).__ran, + left: document.getElementById("c")!.style.left, + color: target.style.color, + x: Math.round(new DOMMatrix(getComputedStyle(target).transform).m41), + }; + }); + const at = Math.round((await time()) * 100) / 100; + const outcome = { + answer, + ...state, + at, + ...(pausedAt === undefined ? {} : { moved: Math.abs(at - pausedAt) > 1 / 30, pausedAt }), + }; + await page.close(); + return outcome; +} + +// fails without the fix (core as at 5822316a): scrub,ok ends at 2; same,ok and same,fail lose the newer edit +// or reload; other,fail reloads with main's timeline killed; attr,ok puts the older left back. +const ROWS: [string, Step[], Record][] = [ + ["ok", ["ok"], { answer: "kept", ran: { main: "older", other: "file" }, at: 4, x: 60 }], + ["scrub,ok", ["scrub", "ok"], { answer: "kept", ran: { main: "older" }, at: 4, x: 60 }], + ["ok,scrub", ["ok", "scrub"], { answer: "kept", ran: { main: "older" }, at: 4, x: 60 }], + ["same,ok", ["same", "ok"], { answer: "kept", ran: { main: "newer" }, x: 200 }], + ["same,fail", ["same", "fail"], { answer: "kept", ran: { main: "newer" }, x: 200 }], + ["ok,same", ["ok", "same"], { answer: "kept", ran: { main: "newer" }, x: 200 }], + ["fail,same", ["fail", "same"], { answer: "reload", ran: { main: "newer" } }], + ["other,ok", ["other", "ok"], { answer: "kept", ran: { main: "older", other: "newer" } }], + [ + "other,fail", + ["other", "fail"], + { answer: "reload", ran: { main: "file", other: "newer" }, x: 120 }, + ], + ["ok,other", ["ok", "other"], { answer: "kept", ran: { main: "older", other: "newer" } }], + ["attr,ok", ["attr", "ok"], { answer: "kept", left: "2px" }], + ["ok,attr", ["ok", "attr"], { answer: "kept", left: "2px" }], + ["edit,ok", ["edit", "ok"], { answer: "kept", color: "red", x: 60 }], + ["ok,edit", ["ok", "edit"], { answer: "kept", color: "red", x: 60 }], + ["move,ok", ["move", "ok"], { answer: "kept", x: 60 }], + ["ok,move", ["ok", "move"], { answer: "kept", x: 300 }], + ["play,ok", ["play", "ok"], { answer: "kept", moved: false }], + ["same,late,ok", ["same", "late", "ok"], { answer: "kept", ran: { main: "newer" } }], + ["two,ok", ["two", "ok"], { answer: "kept", ran: { main: "older", other: "newer" }, at: 4 }], + ["drag,ok,drag", ["drag", "ok", "drag"], { answer: "kept", ran: { main: "older" }, x: 160 }], + ["patch,ok", ["patch", "ok"], { answer: "kept", ran: { main: "older" }, x: 60 }], +]; + +describe.each(MODES)("a re-run waiting for the MotionPath plugin, %s", (mode) => { + it.each(ROWS)("%s", async (name, steps, expected) => { + const outcome = await play(mode, steps); + console.info(`[soft-wait] ${mode} ${name} ${JSON.stringify(outcome)}`); + expect(outcome).toMatchObject(expected); + }); +}); + +// Parity: a same-origin preview gets the plugin on load (NLEContext), and a sealed one when Studio connects. +it.each(MODES)( + "the first motion-path re-run after load finds the plugin loaded (%s)", + async (mode) => { + const { page, frame, release } = await openPreview(mode); + await release(200); + await page.evaluate(async () => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const iframe = document.querySelector("iframe")!; + studio.ensureMotionPathPluginLoaded(iframe); + await studio.previewRequest(iframe, "runtime-snapshot", {}); + }); + await frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 }); + expect(await rerun(page, timeline("main", "older", 60, true), 1)).toBe("applied"); + await page.close(); + }, +); + +// fails without the fix: all but "still recovers an older script refusal after an unrelated successful patch", +// which guards the coverage rule against dropping a refusal no re-run carries. +describe("late answers held in transit, sealed", () => { + const hold = (page: Page, on: boolean) => + page.evaluate((h) => ((window as unknown as { __hold: boolean }).__hold = h), on); + const heldCount = (page: Page) => + page.evaluate(() => (window as unknown as { __held: unknown[] }).__held.length); + /** Delivers the held replies in order; `results` overrides the result of the one at that index. */ + const deliver = (page: Page, results: Record = {}) => + page.evaluate( + (overrides) => { + const w = window as unknown as { __hold: boolean; __held: Array<(r?: unknown) => void> }; + w.__hold = false; + w.__held.splice(0).forEach((send, i) => send(overrides[i])); + }, + results as Record, + ); + const ran = (p: Preview) => + p.frame.evaluate(() => (window as unknown as { __ran: Record }).__ran.main); + /** A sealed commit of `script` whose value edit Studio patches in place; resolves "reload" on a full reload. */ + const commit = (page: Page, script: string, x: number) => + page.evaluate( + (text, value) => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const html = ``; + const result = { ok: true, scriptText: text, before: html, after: html }; + const instantPatch = { + selector: "#target", + change: { kind: "set" as const, props: { x: value } }, + }; + const options = { label: "drag", softReload: true, instantPatch }; + studio.applyPreviewSync(document.querySelector("iframe"), result, options, () => { + (window as unknown as { __reloads?: number }).__reloads = 1; + }); + }, + script, + x, + ); + const undoLeftOfC = (page: Page, left: number) => + page.evaluate( + (l, script) => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const c = (at: number) => + `
`; + const file = (at: number) => + `
${c(at)}
`; + const files = { "index.html": { previous: file(0), restored: file(l) } }; + const reload = () => ((window as unknown as { __reloads?: number }).__reloads = 1); + return studio.applyUndoRestoreToPreview( + document.querySelector("iframe"), + null, + files, + 2, + reload, + ); + }, + left, + timeline("main", "file", 120), + ); + const reloads = (page: Page) => + page.evaluate(() => (window as unknown as { __reloads?: number }).__reloads ?? 0); + + it("drops an older explicit refusal that arrives after a newer run painted", async () => { + const p = await openPreview("sealed"); + // A page closed under a still-waiting run rejects its evaluate. + const older = rerun(p.page, timeline("main", "older", 60, true), 2, [], true).catch( + () => "closed", + ); + await expect.poll(() => p.held.length).toBeGreaterThan(0); + await hold(p.page, true); + await p.release(404); + await expect.poll(() => heldCount(p.page)).toBe(1); + await rerun(p.page, timeline("main", "newer", 200), 2); + await expect.poll(() => ran(p)).toBe("newer"); + await deliver(p.page); + await settled(p, true); + expect(await Promise.race([older, Promise.resolve("kept")])).toBe("kept"); + await p.page.close(); + }); + + it("re-runs the newest script when a patch refusal held across the swap arrives late", async () => { + const p = await openPreview("sealed"); + void rerun(p.page, timeline("main", "older", 60, true), 2, [], true).catch(() => {}); + await expect.poll(() => p.held.length).toBeGreaterThan(0); + await hold(p.page, true); + await commit(p.page, timeline("main", "p1", 10), 10); + await expect.poll(() => heldCount(p.page)).toBe(1); + await p.release(200); + await expect.poll(() => ran(p)).toBe("older"); + await commit(p.page, timeline("main", "p2", 20), 20); + await expect.poll(() => heldCount(p.page)).toBe(3); + await deliver(p.page, { 0: { patched: false }, 2: { patched: true } }); + await expect.poll(() => ran(p)).toBe("p2"); + await settled(p, true); + expect(await ran(p)).toBe("p2"); + await p.page.close(); + }); + + it("still recovers an older script refusal after an unrelated successful patch", async () => { + const p = await openPreview("sealed"); + const older = rerun(p.page, timeline("main", "older", 60, true), 2, [], true); + await expect.poll(() => p.held.length).toBeGreaterThan(0); + await hold(p.page, true); + await p.release(404); + await expect.poll(() => heldCount(p.page)).toBe(1); + await commit(p.page, timeline("main", "file", 120), 30); + await expect.poll(() => heldCount(p.page)).toBe(2); + await deliver(p.page, { 1: { patched: true } }); + expect(await older).toBe("reload"); + await p.page.close(); + }); + + it("still recovers an older run that times out after an attribute-only undo", async () => { + const p = await openPreview("sealed"); + const older = rerun(p.page, timeline("main", "older", 60, true), 2, [], true); + await expect.poll(() => p.held.length).toBeGreaterThan(0); + expect(await undoLeftOfC(p.page, 5)).toBe("soft"); + await expect + .poll(() => p.frame.evaluate(() => document.getElementById("c")!.style.left)) + .toBe("5px"); + await hold(p.page, true); + await p.release(404); + // Studio's editing port gives a request 5 s (editingPort.ts); the refusal stays held past that. + expect(await older).toBe("reload"); + await p.page.close(); + }); + + it("does not reload a new preview load for a restore its old load never answered", async () => { + const p = await openPreview("sealed"); + await hold(p.page, true); + expect(await undoLeftOfC(p.page, 5)).toBe("soft"); + await p.page.evaluate( + () => + new Promise((loaded) => { + const iframe = document.querySelector("iframe")!; + iframe.addEventListener("load", () => setTimeout(loaded, 0), { once: true }); + iframe.srcdoc = iframe.srcdoc + " "; + }), + ); + await deliver(p.page); + expect(await reloads(p.page)).toBe(0); + await p.page.close(); + }); +}); diff --git a/packages/studio/src/utils/gsapUndoRestore.browser.test.ts b/packages/studio/src/utils/gsapUndoRestore.browser.test.ts index de2b53eab4..b23e73f410 100644 --- a/packages/studio/src/utils/gsapUndoRestore.browser.test.ts +++ b/packages/studio/src/utils/gsapUndoRestore.browser.test.ts @@ -4,9 +4,14 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import type { Browser } from "puppeteer-core"; -import { build, type Plugin } from "esbuild"; +import { build } from "esbuild"; import { afterAll, beforeAll, expect, it, vi } from "vitest"; -import { closeTestChrome, launchTestChrome, showWithRuntime } from "../../tests/chromeTestUtils"; +import { + closeTestChrome, + emptyNodeBuiltins, + launchTestChrome, + showWithRuntime, +} from "../../tests/chromeTestUtils"; import { writeFixture } from "../../tests/e2e/edit-accuracy/grid.mjs"; const CROP = "inset(0px 40px 0px 0px)"; @@ -16,16 +21,6 @@ let browser: Browser; let undoBundle: string; let softReloadBundle: string; -// recast imports these, and its code that uses them is dropped from the bundle. A new -// built-in fails the build instead of turning into an empty module the way Vite makes it. -const emptyNodeBuiltins: Plugin = { - name: "empty-node-builtins", - setup(build) { - build.onResolve({ filter: /^(node:)?(fs|os)$/ }, ({ path }) => ({ path, namespace: "empty" })); - build.onLoad({ filter: /.*/, namespace: "empty" }, () => ({ contents: "module.exports = {}" })); - }, -}; - async function bundle(file: string, name: string): Promise { const out = await build({ entryPoints: [fileURLToPath(new URL(file, import.meta.url))], diff --git a/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts b/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts index 46aee486a5..085cce54c7 100644 --- a/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts +++ b/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts @@ -3,11 +3,22 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const channel = vi.hoisted(() => ({ request: vi.fn() })); -vi.mock("../player/lib/previewChannel", () => ({ - previewFrameOpaque: () => true, - previewRequest: channel.request, -})); +const PREVIEW_LOAD = vi.hoisted(() => ({})); +vi.mock("../player/lib/previewChannel", async () => { + const { admittedAnswer } = await import("../../tests/previewAnswerMock"); + const PREVIEW_STALE = Symbol("preview-stale"); + return { + previewFrameOpaque: () => true, + previewEditingClient: () => PREVIEW_LOAD, + previewRequest: channel.request, + previewAnswer: admittedAnswer(channel.request, PREVIEW_STALE), + PREVIEW_REJECTED: Symbol("preview-rejected"), + PREVIEW_STALE, + }; +}); import { applyUndoRestoreToPreview } from "./gsapUndoRestore"; +import { applySoftReload } from "./gsapSoftReload"; +import { SAVED_STATE_DEADLINE_MS } from "./sealedPreviewLedger"; import { onPreviewRestoredInPlace } from "../player/sceneSwap"; const page = (body: string) => `${body}`; @@ -30,32 +41,44 @@ const BOX_AT_0 = { }; const settled = () => new Promise((resolve) => setTimeout(resolve, 0)); +// A reload tells the frame its scenes are stale; that request is the reload's, not the restore's. +const sentToFrame = () => + channel.request.mock.calls + .map(([, request, params]) => [request, params] as const) + .filter(([request]) => request !== "mark-scenes-stale"); -beforeEach(() => channel.request.mockReset()); +beforeEach(() => { + channel.request.mockReset(); +}); describe("undo on a sealed preview", () => { it("sends the restored attributes to the frame instead of reloading", async () => { channel.request.mockResolvedValue({ applied: true }); const { reload, strategy, iframe } = undo(box(90), box(0)); expect(strategy).toBe("soft"); - expect(channel.request).toHaveBeenCalledWith(iframe, "restore-attributes", { - scopes: [ - { - file: null, - elements: [ - { - key: "hf:box", - attributes: [ - ["data-hf-id", "box"], - ["style", "left: 0px"], - ], - }, - ], - }, - ], - scripted: false, - time: 2, - }); + expect(channel.request).toHaveBeenCalledWith( + iframe, + "restore-attributes", + { + scopes: [ + { + file: null, + elements: [ + { + key: "hf:box", + attributes: [ + ["data-hf-id", "box"], + ["style", "left: 0px"], + ], + }, + ], + }, + ], + scripted: false, + time: 2, + }, + SAVED_STATE_DEADLINE_MS, + ); await settled(); expect(reload).not.toHaveBeenCalled(); }); @@ -90,11 +113,79 @@ describe("undo on a sealed preview", () => { iframe, "soft-reload", expect.objectContaining({ script: expect.stringContaining("{ x: 2 }"), time: 2, restore }), + restore.length > 0 ? SAVED_STATE_DEADLINE_MS : undefined, ); await settled(); expect(reload).not.toHaveBeenCalled(); }); + // fails without the fix: the frame refused an element GSAP has parsed, and the undo reloaded the preview. + it("carries the script re-run in the restore request when the file keeps a script", async () => { + channel.request.mockResolvedValue({ applied: true }); + const { reload, strategy, iframe } = undo( + box(90) + script("{ x: 1 }"), + box(0) + script("{ x: 1 }"), + ); + expect(strategy).toBe("soft"); + expect(channel.request).toHaveBeenCalledExactlyOnceWith( + iframe, + "restore-attributes", + { + scopes: [{ file: null, elements: [BOX_AT_0] }], + scripted: true, + time: 2, + rerun: { + script: expect.stringContaining("{ x: 1 }"), + sets: [], + authored: expect.any(Array), + timing: [], + }, + }, + SAVED_STATE_DEADLINE_MS, + ); + await settled(); + expect(reload).not.toHaveBeenCalled(); + }); + + it("sends no re-run when the files have no script", () => { + channel.request.mockResolvedValue({ applied: true }); + undo(box(90), box(0)); + expect(channel.request.mock.calls[0]![2]).not.toHaveProperty("rerun"); + }); + + // fails without the fix: a late refusal re-ran the undo's older script over an edit sent meanwhile. + it("leaves an edit sent while the restore waits, and the playhead it was sent at", async () => { + let answer: (reply: unknown) => void = () => {}; + channel.request.mockImplementation((_frame, request) => + request === "restore-attributes" + ? new Promise((resolve) => (answer = resolve)) + : Promise.resolve({ result: "applied" }), + ); + const { reload, iframe } = undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 1 }")); + const edit = page(box(0) + script("{ x: 9 }")); + applySoftReload(iframe, 'gsap.timeline().to("#t", { x: 9 });', { + currentTimeOverride: 3, + authoredHtml: edit, + previousHtml: page(box(0) + script("{ x: 1 }")), + }); + answer({ applied: false }); + await settled(); + expect(sentToFrame().map(([request, params]) => [request, params.time])).toEqual([ + ["restore-attributes", 2], + ["soft-reload", 3], + ]); + expect(reload).toHaveBeenCalledOnce(); + }); + + // fails without the fix: a reply lost to a new preview load re-ran the undo into that load. + it("sends nothing more after a reply a new preview load lost", async () => { + channel.request.mockResolvedValue(null); + const { reload } = undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 1 }")); + await settled(); + expect(sentToFrame().map(([request]) => request)).toEqual(["restore-attributes"]); + expect(reload).toHaveBeenCalledOnce(); + }); + it.each([ ["the attributes it restored", { applied: true }, box(90), box(0)], [ @@ -116,6 +207,33 @@ describe("undo on a sealed preview", () => { expect(reload).not.toHaveBeenCalled(); }); + // fails without the fix: a request that timed out reloaded over a newer run already shown. + it.each([ + ["no newer run was sent for its timeline", false, 1], + ["a newer run on its timeline was sent", true, 0], + ])("reloads a timed-out re-run only when %s", async (_name, newer, reloads) => { + const late: Array<(reply: unknown) => void> = []; + channel.request.mockImplementation(() => new Promise((resolve) => late.push(resolve))); + const iframe = document.createElement("iframe"); + const reload = vi.fn(); + const run = (x: number, onAsyncFailure?: () => void) => + applySoftReload( + iframe, + `window.__timelines["main"] = gsap.timeline().to("#t", { x: ${x} });`, + { + currentTimeOverride: 1, + authoredHtml: page(box(0)), + previousHtml: page(box(0)), + onAsyncFailure, + }, + ); + run(1, reload); + if (newer) run(2); + late[0]!(null); + await settled(); + expect(reload).toHaveBeenCalledTimes(reloads); + }); + it("reloads when the frame cannot re-run the changed script", async () => { channel.request.mockResolvedValue({ result: "cannot-soft-reload" }); const { reload, iframe } = undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 2 }")); diff --git a/packages/studio/src/utils/gsapUndoRestore.ts b/packages/studio/src/utils/gsapUndoRestore.ts index a5ca321f92..008fb330c5 100644 --- a/packages/studio/src/utils/gsapUndoRestore.ts +++ b/packages/studio/src/utils/gsapUndoRestore.ts @@ -9,15 +9,16 @@ import { findGsapScriptElements, readNestedFiles, repaintDroppedTweenStyle, + sealedRerun, timelineKeys, } from "./gsapSoftReload"; +import { restoredSnapshot, sendSealedRestore, type SealedRestore } from "./sealedRestoreSend"; import { ensureHfIds, isCompositionTemplate } from "@hyperframes/parsers/hf-ids"; import { templateContent } from "@hyperframes/parsers/sub-composition-validity"; import { findAuthoredElement, parseSavedSource } from "./authoredSource"; import { STUDIO_EDIT_ATTRS } from "../components/editor/manualEditsSeekReapply"; import { announcePreviewRestoredInPlace, markScenesStale } from "../player/sceneSwap"; -import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel"; -import type { EditingParams } from "@hyperframes/core/runtime/editing-port"; +import { previewFrameOpaque } from "../player/lib/previewChannel"; import { STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR } from "../components/editor/manualEditsTypes"; import { countStudioPreviewChange, @@ -370,8 +371,6 @@ function repaintWhileReloading(win: PreviewWindow, doc: Document, restored?: str ); } -type SealedRestore = Omit, "time">; - const restoredAttributes = (el: Element): [string, string][] => el.getAttributeNames().map((name) => [name, el.getAttribute(name) ?? ""]); @@ -409,7 +408,17 @@ function sealedRestore(activeDocPath: string, files: RestoreFiles): SealedRestor return restore; } -/** Sends the restore to a sealed preview; a refusal, or no answer, reloads it. */ +function withRerun( + restore: SealedRestore, + active: UndoRestoreFile | undefined, + script: string | null, +): SealedRestore { + if (!restore.scripted || !active || !script) return restore; + const files = { authoredHtml: active.restored, previousHtml: active.previous }; + return { ...restore, rerun: sealedRerun(script, files) }; +} + +/** Sends the restore to a sealed preview, with the script re-run an element GSAP parsed needs; a refusal reloads. */ function applySealedRestore( iframe: HTMLIFrameElement, activeDocPath: string, @@ -417,6 +426,7 @@ function applySealedRestore( currentTime: number, reloadPreview: () => void, onShownInPlace?: () => void, + version?: number, ): "soft" | "full" { const restore = sealedRestore(activeDocPath, files); const active = files[activeDocPath]; @@ -431,31 +441,25 @@ function applySealedRestore( authoredHtml: active.restored, previousHtml: active.previous, restore: restore.scopes, + version, }); if (rerun === "applied") return "soft"; } else if (restore?.scopes.length) { - sendSealedRestore(iframe, restore, currentTime, reloadPreview, onShownInPlace); + const sent = withRerun(restore, active, script); + const snapshot = restoredSnapshot(sent, active, version); + sendSealedRestore( + iframe, + { sent, snapshot, version }, + currentTime, + reloadPreview, + onShownInPlace, + ); return "soft"; } reloadPreview(); return "full"; } -function sendSealedRestore( - iframe: HTMLIFrameElement, - restore: SealedRestore, - currentTime: number, - reloadPreview: () => void, - onShownInPlace?: () => void, -): void { - void previewRequest(iframe, "restore-attributes", { ...restore, time: currentTime }).then( - (reply) => { - if (!reply?.applied) reloadPreview(); - else onShownInPlace?.(); - }, - ); -} - /** * Soft-apply an undo/redo restore to the live preview WITHOUT a full iframe * remount (which blanks the frame black and re-flashes the WebGL context). Eligible @@ -491,6 +495,7 @@ export function applyUndoRestoreToPreview( currentTime: number, reload: () => void, nestedFiles?: Map | null, + version?: number, ): "soft" | "full" { // The master view carries a NULL activeCompPath but the root iframe shows // index.html — the codebase-wide convention (`activeCompPath || "index.html"`). @@ -503,8 +508,14 @@ export function applyUndoRestoreToPreview( reload(); }; if (iframe && files && previewFrameOpaque(iframe)) - return applySealedRestore(iframe, activeDocPath, files, currentTime, reloadPreview, () => - announcePreviewRestoredInPlace(iframe), + return applySealedRestore( + iframe, + activeDocPath, + files, + currentTime, + reloadPreview, + () => announcePreviewRestoredInPlace(iframe), + version, ); const doc = iframe?.contentDocument; const win = iframe?.contentWindow as PreviewWindow | null; diff --git a/packages/studio/src/utils/sealedPreviewLedger.test.ts b/packages/studio/src/utils/sealedPreviewLedger.test.ts new file mode 100644 index 0000000000..391ba05f89 --- /dev/null +++ b/packages/studio/src/utils/sealedPreviewLedger.test.ts @@ -0,0 +1,232 @@ +// @vitest-environment happy-dom +// fails without the fix: all but "still recovers an older script run after an unrelated successful patch" and +// "does not let a re-run sent while a patch's write was in flight cover the patch", which guard the coverage rule. +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const channel = vi.hoisted(() => ({ + request: vi.fn(), + load: { id: 1 }, +})); +vi.mock("../player/lib/previewChannel", async (importOriginal) => { + const original = await importOriginal(); + const { admittedAnswer } = await import("../../tests/previewAnswerMock"); + return { + ...original, + previewFrameOpaque: () => true, + previewRequest: channel.request, + previewAnswer: admittedAnswer(channel.request, original.PREVIEW_STALE), + previewEditingClient: () => channel.load, + }; +}); +import { applySoftReload } from "./gsapSoftReload"; +import { applyUndoRestoreToPreview } from "./gsapUndoRestore"; +import { applyPreviewSync } from "../hooks/useGsapScriptCommits"; +import { moveLiveTweens } from "./gsapLiveRetime"; +import { markStudioWriteToken } from "./studioFileVersion"; +import { previewLoadShows } from "./sealedPreviewLedger"; + +const iframe = document.createElement("iframe"); +const page = (body: string) => `${body}`; +const script = (x: number) => `window.__timelines["main"] = gsap.timeline().to("#a", { x: ${x} });`; +const settled = () => new Promise((resolve) => setTimeout(resolve, 0)); + +/** Every request waits until the test answers it, in any order. */ +let held: Array<{ kind: string; params: unknown; answer: (reply: unknown) => void }> = []; +beforeEach(() => { + held = []; + channel.load = { id: Math.random() }; + channel.request.mockReset(); + channel.request.mockImplementation( + (_iframe: unknown, kind: string, params: unknown) => + new Promise((answer) => held.push({ kind, params, answer })), + ); +}); + +function rerun(x: number, onAsyncFailure = vi.fn()) { + applySoftReload(iframe, script(x), { + currentTimeOverride: 1, + authoredHtml: page(``), + previousHtml: page(""), + onAsyncFailure, + }); + return onAsyncFailure; +} + +function patch(x: number, reloadPreview = vi.fn()) { + markStudioWriteToken(`w${x}`); + const text = script(x); + const result = { + ok: true, + scriptText: text, + before: page(""), + after: page(``), + }; + const instantPatch = { selector: "#a", change: { kind: "set" as const, props: { x } } }; + applyPreviewSync( + iframe, + result, + { label: "drag", softReload: true, instantPatch }, + reloadPreview, + ); + return reloadPreview; +} + +const reruns = () => + held + .filter(({ kind }) => kind === "soft-reload") + .map(({ params }) => (params as { script: string }).script); + +it("drops an older explicit refusal once a newer re-run of its timeline was sent", async () => { + const older = rerun(1); + rerun(2); + held[0]!.answer({ result: "cannot-soft-reload" }); + await settled(); + expect(older).not.toHaveBeenCalled(); +}); + +it("re-runs the newest saved script when a patch refusal held while a newer patch lands arrives", async () => { + patch(10); + patch(20); + held[1]!.answer({ patched: true }); + held[0]!.answer({ patched: false }); + await settled(); + expect(reruns()).toEqual([script(20)]); +}); + +it("still recovers an older script run after an unrelated successful patch of its timeline", async () => { + const older = rerun(1); + patch(30); + held[1]!.answer({ patched: true }); + held[0]!.answer({ result: "cannot-soft-reload" }); + await settled(); + expect(older).toHaveBeenCalledOnce(); +}); + +it("still recovers an older script run that times out after an attribute-only undo of its timeline", async () => { + const older = rerun(1); + const files = { + "index.html": { + previous: page( + `
t
`, + ), + restored: page( + `
t
`, + ), + }, + }; + applyUndoRestoreToPreview(iframe, null, files, 2, vi.fn()); + held.find(({ kind }) => kind === "restore-attributes")!.answer({ applied: true, reran: false }); + held[0]!.answer(null); + await settled(); + expect(older).toHaveBeenCalledOnce(); +}); + +it("does not let a re-run sent while a patch's write was in flight cover the patch", async () => { + markStudioWriteToken("in-flight"); + rerun(1); + patch(40); + held[1]!.answer({ patched: false }); + await settled(); + expect(reruns()).toEqual([script(1), script(40)]); +}); + +it("ignores a restore answered after the next load: the new load shows the saved file", async () => { + const reload = vi.fn(); + const files = { + "index.html": { + previous: page(`
t
`), + restored: page(`
t
`), + }, + }; + applyUndoRestoreToPreview(iframe, null, files, 2, reload); + channel.load = { id: Math.random() }; + held[0]!.answer(null); + await settled(); + expect(reload).not.toHaveBeenCalled(); +}); + +// fails without the fix: the recovery re-ran the retime's script without its saved clip timing. +it("re-runs a refused patch's recovery with the timing of a live retime saved after it", async () => { + const retimed = (d: number) => + `window.__timelines["main"] = gsap.timeline().to("#a", { x: 10, duration: ${d} }, 0);`; + const file = (start: number, d: number) => + page(`
`); + markStudioWriteToken("patch"); + const patched = { ok: true, scriptText: retimed(1), before: file(0, 1), after: file(0, 1) }; + const instantPatch = { selector: "#a", change: { kind: "set" as const, props: { x: 10 } } }; + applyPreviewSync(iframe, patched, { label: "drag", softReload: true, instantPatch }, vi.fn()); + markStudioWriteToken("retime"); + void moveLiveTweens(iframe, retimed(2), 1, vi.fn(), { before: file(0, 1), after: file(1, 2) }); + await settled(); + expect(held.map(({ kind }) => kind)).toEqual(["patch-tweens", "live-retime"]); + held[0]!.answer({ patched: false }); + await settled(); + const rerun = held.find(({ kind }) => kind === "soft-reload")!.params as { timing: unknown[] }; + expect(rerun.timing).toContainEqual(["hf:a", [["data-start", "1"]]]); +}); + +// fails without the fix: the older retime went out and put its file's clip timing over the newer file's. +describe("an older live retime whose preview sync goes out after a newer file's", () => { + const retimed = (d: number) => + `window.__timelines["main"] = gsap.timeline().to("#a", { x: 10, duration: ${d} }, 0);`; + const file = (start: number, d: number, b = 0) => + page( + `
` + + ``, + ); + const kinds = () => held.map(({ kind }) => kind); + + it("is not sent, and re-runs the newer file in place", async () => { + const reload = vi.fn(); + applySoftReload(iframe, retimed(3), { + currentTimeOverride: 1, + authoredHtml: file(1, 3), + previousHtml: file(1, 2), + version: 5, + }); + await settled(); + await moveLiveTweens(iframe, retimed(2), 1, reload, { + before: file(0, 1), + after: file(1, 2), + revision: 4, + }); + await settled(); + expect(kinds()).toEqual(["soft-reload", "soft-reload"]); + const recovery = held[1]!.params as { script: string; timing: unknown[] }; + expect(recovery.script).toBe(retimed(3)); + expect(recovery.timing).toContainEqual(["hf:a", [["data-start", "1"]]]); + expect(reload).not.toHaveBeenCalled(); + }); + + it("is not sent after a newer undo of another clip, and re-runs the undone file in place", async () => { + const reload = vi.fn(); + const undo = { "index.html": { previous: file(1, 2, 0), restored: file(1, 2, 1) } }; + applyUndoRestoreToPreview(iframe, null, undo, 1, vi.fn(), undefined, 5); + await settled(); + await moveLiveTweens(iframe, retimed(2), 1, reload, { + before: file(0, 1), + after: file(1, 2), + revision: 4, + }); + await settled(); + expect(kinds()).toEqual(["restore-attributes", "soft-reload"]); + const recovery = held[1]!.params as { timing: unknown[] }; + expect(recovery.timing).toContainEqual(["hf:b", [["data-start", "1"]]]); + expect(recovery.timing).toContainEqual(["hf:a", [["data-start", "1"]]]); + expect(reload).not.toHaveBeenCalled(); + }); + + it("is not sent to a new load showing a newer saved file, and reloads it", async () => { + channel.load = { id: Math.random() }; + previewLoadShows(iframe, 5); + const reload = vi.fn(); + await moveLiveTweens(iframe, retimed(2), 1, reload, { + before: file(0, 1), + after: file(1, 2), + revision: 4, + }); + await settled(); + expect(kinds()).toEqual([]); + expect(reload).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/studio/src/utils/sealedPreviewLedger.ts b/packages/studio/src/utils/sealedPreviewLedger.ts new file mode 100644 index 0000000000..7f84742b26 --- /dev/null +++ b/packages/studio/src/utils/sealedPreviewLedger.ts @@ -0,0 +1,182 @@ +// Which late answers from a sealed preview may still act: one record per preview load. +import type { + EditingParams, + EditingPortClient, + EditingRequestKind, +} from "@hyperframes/core/runtime/editing-port"; +import { + previewAnswer, + previewEditingClient, + previewFrameOpaque, +} from "../player/lib/previewChannel"; +import { studioFileRevision } from "./studioFileVersion"; +import { timelineKeys } from "@hyperframes/core/runtime/soft-reload"; + +/** A complete saved file state a re-run can show: the script, both files it was read from, and its timing. */ +export interface PreviewWrite { + scriptText: string; + authoredHtml: string; + previousHtml: string; + nestedFiles?: Map | null; + timingEdit?: boolean; + version?: number; +} + +/** How long a write carrying restored attributes or clip timing waits for the frame before it recovers. */ +export const SAVED_STATE_DEADLINE_MS = 30_000; + +export interface PreviewSend { + scriptText: string; + snapshot: PreviewWrite | null; + /** Restored attributes: no other write sends them again, so nothing covers them. */ + attributes: boolean; + /** Clip timing: covered only by a newer re-run that carried the saved timing too. */ + timing: boolean; + /** A script re-run: it owns its timelines from its send. */ + rerun?: boolean; + version?: number; +} + +export interface PreviewTicket { + readonly iframe: HTMLIFrameElement; + readonly load: EditingPortClient; + readonly keys: readonly string[]; + readonly seq: number; + /** The Studio file version its write produced: a re-run read at a lower one lacks it. */ + readonly version: number; + readonly sent: PreviewSend; +} + +type Owner = { seq: number; version: number }; + +interface Ledger { + seq: number; + reruns: Map; + /** Kept apart: a later script-only re-run leaves the timing an earlier one applied in place. */ + timedReruns: Map; + writes: Map; + newestVersion: number; + /** The newest saved file version sent to this load. */ + sentVersion: number; +} + +const ledgers = new WeakMap(); + +function ledgerOf(load: EditingPortClient): Ledger { + let ledger = ledgers.get(load); + if (!ledger) + ledgers.set( + load, + (ledger = { + seq: 0, + reruns: new Map(), + timedReruns: new Map(), + writes: new Map(), + newestVersion: 0, + sentVersion: 0, + }), + ); + return ledger; +} + +export function takePreviewTicket(iframe: HTMLIFrameElement, sent: PreviewSend): PreviewTicket { + const load = previewEditingClient(iframe); + const ledger = ledgerOf(load); + const ticket = { + iframe, + load, + keys: timelineKeys(sent.scriptText), + seq: ++ledger.seq, + version: sent.snapshot?.version ?? sent.version ?? studioFileRevision(), + sent, + }; + ledger.newestVersion = Math.max(ledger.newestVersion, ticket.version); + if (sent.snapshot) { + const write = { seq: ticket.seq, version: ticket.version, write: sent.snapshot }; + for (const key of ticket.keys) { + const kept = ledger.writes.get(key); + if (!kept || newer(write, kept)) ledger.writes.set(key, write); + } + } + return ticket; +} + +/** A later saved file wins; of one file's writes, the later sent. */ +function newer(a: { seq: number; version: number }, b: { seq: number; version: number }) { + return a.version > b.version || (a.version === b.version && a.seq > b.seq); +} + +/** A re-run owns its timelines from its send: it applies, or it fails and recovers to the newest file itself. */ +export function confirmPreviewRerun(ticket: PreviewTicket): void { + const { reruns, timedReruns } = ledgerOf(ticket.load); + const owner = { seq: ticket.seq, version: ticket.version }; + for (const owners of ticket.sent.timing ? [reruns, timedReruns] : [reruns]) + for (const key of ticket.keys) { + const current = owners.get(key); + if (!current || newer(owner, current)) owners.set(key, owner); + } +} + +/** Every sealed write's one send: once the frame can take it, a write older than a file already sent there is not. */ +export function sendPreviewWrite( + ticket: PreviewTicket, + kind: K, + params: EditingParams, + timeoutMs?: number, +) { + return previewAnswer(ticket.iframe, kind, params, timeoutMs, () => { + const ledger = ledgerOf(ticket.load); + if (ticket.version < ledger.sentVersion) return false; + ledger.sentVersion = ticket.version; + if (ticket.sent.rerun) confirmPreviewRerun(ticket); + return true; + }); +} + +/** The load now in `iframe` shows the saved file at `revision`: an older write is not sent to it. */ +export function previewLoadShows(iframe: HTMLIFrameElement, revision: number): void { + if (!previewFrameOpaque(iframe)) return; + const ledger = ledgerOf(previewEditingClient(iframe)); + ledger.sentVersion = Math.max(ledger.sentVersion, revision); + ledger.newestVersion = Math.max(ledger.newestVersion, revision); +} + +/** An answer from a load that has since been replaced must not touch its replacement. */ +export function ticketLoadLive(ticket: PreviewTicket): boolean { + return previewEditingClient(ticket.iframe) === ticket.load; +} + +/** A later re-run read at this version or newer carries everything this write changed. */ +function ticketCovered(ticket: PreviewTicket): boolean { + const { reruns, timedReruns } = ledgerOf(ticket.load); + const owners = ticket.sent.timing ? timedReruns : reruns; + return ( + !ticket.sent.attributes && + ticket.keys.length > 0 && + ticket.keys.every((key) => { + const owner = owners.get(key); + if (!owner) return false; + return ( + owner.version > ticket.version || + (owner.seq > ticket.seq && owner.version >= ticket.version) + ); + }) + ); +} + +/** The newest saved state for the ticket's timelines, with timing; null when a newer file was sent without one. */ +export function newestPreviewWrite(ticket: PreviewTicket): PreviewWrite | null { + const { writes, newestVersion } = ledgerOf(ticket.load); + let newest = { seq: ticket.seq, version: ticket.version, write: ticket.sent.snapshot }; + for (const key of ticket.keys) { + const sent = writes.get(key); + if (sent && newer(sent, newest)) newest = sent; + } + if (!newest.write || newest.version < newestVersion) return null; + return { ...newest.write, version: newest.version, timingEdit: true }; +} + +/** A late failure acts only for the live load and only when no later re-run carries its change. */ +export function ticketNeedsRecovery(ticket: PreviewTicket): boolean { + return ticketLoadLive(ticket) && !ticketCovered(ticket); +} diff --git a/packages/studio/src/utils/sealedPreviewOrdering.browser.test.ts b/packages/studio/src/utils/sealedPreviewOrdering.browser.test.ts new file mode 100644 index 0000000000..0048c25a24 --- /dev/null +++ b/packages/studio/src/utils/sealedPreviewOrdering.browser.test.ts @@ -0,0 +1,368 @@ +// Real Chrome, sealed preview: Studio's saves (script re-runs, tween patches, retimes, undos) reach the frame or are +// refused, their replies arrive in any order, and the frame may reload. Once every reply has settled, the preview +// must equal a fresh load of the saved file, with a full reload only after a refusal nothing can recover in place. +// The reviewer's sequences and the pinned seeds; sealedPreviewOrderingGenerated.browser.test.ts runs fresh seeds. +import type { Browser } from "puppeteer-core"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils"; +import { playOrdering, type Step } from "../../tests/sealedOrderingFixture"; +import { buildStudioBundle } from "../../tests/sealedPreviewHarness"; + +vi.setConfig({ testTimeout: 120_000, hookTimeout: 60_000 }); +let browser: Browser; +let studioBundle: string; + +beforeAll(async () => { + browser = await launchTestChrome(); + studioBundle = await buildStudioBundle(); +}); +afterAll(() => closeTestChrome(browser)); +const play = (steps: Step[], seed = 1, two = false) => + playOrdering(browser, studioBundle, steps, seed, two); + +// The reviewer's sequences: the first and third are red without the fix; the second guards its class. +type Fixed = [string, Step[], { seed?: number; two?: boolean; reloads?: number }?]; +const SEEDS: Fixed[] = [ + [ + "an undo of a script and a title the frame refuses, held past a newer script-only run", + [ + { save: "undoBoth", fate: "frame" }, + { save: "run", fate: "frame" }, + { answer: "newest" }, + { answer: "oldest" }, + ], + ], + [ + // A guard, not the reviewer's sequence: his retime went through live-retime, which this harness does not + // send (sealedPreviewLedger.test.ts reproduces it); seed 28 reproduces the lost data-start here. + "a refused patch, then a refused retime re-run, then the patch's refusal", + [ + { save: "patch", fate: "refused" }, + { save: "retime", fate: "refused" }, + { answer: "patch-tweens" }, + ], + ], + [ + "a refused patch, then a static undo, then the patch's refusal", + [ + { save: "patch", fate: "refused" }, + { save: "undoLabel", fate: "frame" }, + { answer: "any" }, + { answer: "patch-tweens" }, + ], + ], + // The reviewer's round-8 probes, as written. + [ + "a refused patch, a live retime whose refusal is pending and a static undo, then the patch's refusal", + [ + { save: "patch", fate: "refused" }, + { save: "liveRetime", fate: "refused" }, + { save: "undoLabel", fate: "frame" }, + { answer: "patch-tweens" }, + ], + ], + [ + "a refused live retime, then a script-only run, then the retime's refusal", + [ + { save: "liveRetime", fate: "refused" }, + { save: "run", fate: "frame" }, + { answer: "newest" }, + { answer: "live-retime" }, + ], + ], + [ + "a refused live retime at 2 s, a newer run, a scrub to 4 s, then the retime's refusal", + [ + { save: "liveRetime", fate: "refused" }, + { save: "run", fate: "frame" }, + { answer: "newest" }, + { scrub: 4 }, + { answer: "live-retime" }, + ], + ], + [ + "a retime the port rejects before applying, answered after a newer script-only run painted", + [ + { save: "retime", fate: "rejected" }, + { save: "run", fate: "frame" }, + { answer: "newest" }, + { answer: "soft-reload" }, + ], + ], + // The reviewer's round-9 probes, as written. + [ + "two scripts: a refused patch, then an undo of data-start applied, then the patch's refusal", + [ + { save: "patch", fate: "refused" }, + { save: "undoStart", fate: "frame" }, + { answer: "oldest" }, + { answer: "patch-tweens" }, + ], + { two: true }, + ], + [ + "an undo of a script and a title the frame refuses, and a newer run, both answered after the undo's deadline", + [ + { save: "undoBoth", fate: "frame" }, + { save: "run", fate: "frame" }, + { pastDeadline: true }, + { answer: "oldest" }, + { answer: "oldest" }, + ], + ], + // A guard: Studio's reload loads the newer file again when a save lands during it (useShadowPreviewReload.ts). + [ + "a run saved while the reload from a refused title undo is in flight", + [{ save: "undoTitle", fate: "frame" }, { answer: "oldest" }, { save: "run", fate: "frame" }], + ], + // The reviewer's round-10 probe and its control: a script-only run must not drop the timing a newer retime + // already applied, so the older retime's refusal recovers without a reload. + [ + "a held retime refusal, a newer retime applied, a script-only run applied, then the refusal", + [ + { save: "retime", fate: "refused" }, + { save: "retime", fate: "frame" }, + { answer: "newest" }, + { save: "run", fate: "frame" }, + { answer: "newest" }, + { answer: "soft-reload" }, + ], + { reloads: 0 }, + ], + [ + "a held retime refusal, a newer retime applied, then the refusal", + [ + { save: "retime", fate: "refused" }, + { save: "retime", fate: "frame" }, + { answer: "newest" }, + { answer: "soft-reload" }, + ], + { reloads: 0 }, + ], + // Found in review: a newer save's preview sync going out before an older timing sync's. + [ + "a live retime and a newer run whose responses come back newest first, the retime refused", + [{ reversed: ["liveRetime", "run"] }, { answer: "newest" }], + ], + // The reviewer's round-11 probes: an older timing write's sync goes out after a newer undo of an unanimated + // clip's data-start, and the frame applies it; the clip must keep the undo's timing. + [ + "an applied older live retime after a newer data-start undo of another clip", + [{ reversed: ["liveRetime", "undoStart"] }, { answer: "any" }, { answer: "any" }], + ], + [ + "an applied older retime re-run after a newer data-start undo of another clip", + [{ reversed: ["retime", "undoStart"] }, { answer: "any" }, { answer: "any" }], + ], + // The reviewer's round-12 probes: the same, with the frame loading the newer saved file between the two syncs. + [ + "an applied older live retime after a newer data-start undo and a load of the newer file", + [{ reversed: ["liveRetime", "undoStart"], reload: true }, { answer: "any" }, { answer: "any" }], + ], + [ + "an applied older retime re-run after a newer data-start undo and a load of the newer file", + [{ reversed: ["retime", "undoStart"], reload: true }, { answer: "any" }, { answer: "any" }], + ], + // The round-10 generator's seeds that found reversed save responses, kept as it generated them: 52 an older + // script left on screen, 148 a newer patch's value lost. + ...( + [ + [ + 52, + [ + { save: "undoTitle", fate: "frame" }, + { reloadFrame: true }, + { save: "run", fate: "frame" }, + { save: "retime", fate: "frame" }, + { save: "retime", fate: "frame" }, + { answer: "any" }, + { scrub: 1 }, + { reversed: ["liveRetime", "run"] }, + ], + ], + [ + 148, + [ + { reloadFrame: true }, + { save: "run", fate: "frame" }, + { reversed: ["liveRetime", "undoLabel"] }, + { save: "run", fate: "rejected" }, + { save: "run", fate: "frame" }, + { reversed: ["liveRetime", "run"] }, + { save: "run", fate: "refused" }, + { reversed: ["liveRetime", "patch"] }, + ], + ], + ] as Array<[number, Step[]]> + ).map(([seed, steps]): Fixed => [`round-10 seed ${seed}`, steps, { seed, two: seed % 2 === 1 }]), + // The round-9 generator's seeds that found a class without the fix, kept as it generated them: 312 and 320 a + // write of saved state never answered, then covered by a script-only run; 2101, 3037 and 3657 a two-script + // file's newer timing undo overwritten. + ...( + [ + [ + 312, + [ + { answer: "any" }, + { scrub: 4 }, + { reloadFrame: true }, + { answer: "any" }, + { reloadFrame: true }, + { save: "liveRetime", fate: "never" }, + { scrub: 4 }, + { save: "run", fate: "frame" }, + ], + ], + [ + 320, + [ + { answer: "any" }, + { answer: "any" }, + { save: "run", fate: "frame" }, + { pastDeadline: true }, + { save: "undoBoth", fate: "never" }, + { save: "patch", fate: "refused" }, + { save: "liveRetime", fate: "frame" }, + { answer: "any" }, + ], + ], + [ + 2101, + [ + { save: "liveRetime", fate: "frame" }, + { save: "liveRetime", fate: "refused" }, + { answer: "any" }, + { save: "retime", fate: "frame" }, + { save: "liveRetime", fate: "refused" }, + { scrub: 3 }, + { save: "patch", fate: "frame" }, + { save: "undoStart", fate: "frame" }, + ], + ], + [ + 3037, + [ + { save: "undoTitle", fate: "never" }, + { save: "undoTitle", fate: "never" }, + { answer: "any" }, + { save: "undoLabel", fate: "frame" }, + { answer: "any" }, + { scrub: 3 }, + { save: "patch", fate: "refused" }, + { save: "undoStart", fate: "frame" }, + ], + ], + [ + 3657, + [ + { answer: "any" }, + { answer: "any" }, + { scrub: 4 }, + { scrub: 1 }, + { answer: "any" }, + { save: "liveRetime", fate: "refused" }, + { save: "undoStart", fate: "frame" }, + { answer: "any" }, + ], + ], + ] as Array<[number, Step[]]> + ).map(([seed, steps]): Fixed => [`round-9 seed ${seed}`, steps, { seed, two: seed % 2 === 1 }]), + // The round-8 generator's seeds that found a class without the fix, kept as it generated them: 50 a recovery + // dropping saved timing; 80 and 261 a recovery rewinding a newer scrub; 312, 147 and 377 a port rejection taken + // for a missing reply. + ...( + [ + [ + 50, + [ + { save: "undoLabel", fate: "frame" }, + { answer: "any" }, + { answer: "any" }, + { scrub: 4 }, + { save: "undoBoth", fate: "refused" }, + { reloadFrame: true }, + { save: "liveRetime", fate: "refused" }, + { save: "patch", fate: "frame" }, + ], + ], + [ + 80, + [ + { scrub: 1 }, + { save: "undoBoth", fate: "frame" }, + { answer: "any" }, + { save: "liveRetime", fate: "refused" }, + { save: "run", fate: "frame" }, + { save: "retime", fate: "frame" }, + { scrub: 4 }, + { save: "run", fate: "refused" }, + ], + ], + [ + 261, + [ + { scrub: 3 }, + { scrub: 1 }, + { save: "liveRetime", fate: "refused" }, + { save: "retime", fate: "frame" }, + { reloadFrame: true }, + { save: "liveRetime", fate: "refused" }, + { scrub: 3 }, + { answer: "any" }, + ], + ], + [ + 312, + [ + { answer: "any" }, + { scrub: 4 }, + { reloadFrame: true }, + { answer: "any" }, + { reloadFrame: true }, + { save: "liveRetime", fate: "rejected" }, + { scrub: 4 }, + { save: "run", fate: "frame" }, + ], + ], + [ + 147, + [ + { save: "patch", fate: "frame" }, + { answer: "any" }, + { scrub: 3 }, + { save: "patch", fate: "frame" }, + { answer: "any" }, + { save: "undoBoth", fate: "rejected" }, + { save: "liveRetime", fate: "frame" }, + { save: "patch", fate: "rejected" }, + ], + ], + [ + 377, + [ + { save: "undoBoth", fate: "rejected" }, + { answer: "any" }, + { reloadFrame: true }, + { save: "patch", fate: "frame" }, + { answer: "any" }, + { scrub: 4 }, + { save: "undoBoth", fate: "rejected" }, + { save: "liveRetime", fate: "refused" }, + ], + ], + ] as Array<[number, Step[]]> + ).map(([seed, steps]): Fixed => [`round-8 seed ${seed}`, steps, { seed }]), +]; + +describe("sealed preview after late answers in any order", () => { + it.each(SEEDS)("%s", async (name, steps, { seed, two, reloads: expected } = {}) => { + const { shown, fresh, reloads, reloadRefusals, playhead } = await play(steps, seed, two); + expect(shown).toEqual(fresh); + expect(playhead.shown).toBeCloseTo(playhead.studio, 1); + // A two-script file has no single script to snapshot, so a recovery there may only reload. + if (reloadRefusals === 0 && !two) expect(reloads).toBe(0); + if (expected !== undefined) expect(reloads).toBe(expected); + // The frame cannot set a title in place, so the refused undo recovers only by reloading. + if (name.includes("title")) expect(reloads).toBeGreaterThan(0); + }); +}); diff --git a/packages/studio/src/utils/sealedPreviewOrderingGenerated.browser.test.ts b/packages/studio/src/utils/sealedPreviewOrderingGenerated.browser.test.ts new file mode 100644 index 0000000000..a2dc218d10 --- /dev/null +++ b/packages/studio/src/utils/sealedPreviewOrderingGenerated.browser.test.ts @@ -0,0 +1,25 @@ +// Real Chrome, sealed preview: fresh generated sequences of Studio's saves, late replies, scrubs, missed deadlines and +// reloads, each checked against a fresh load of the saved file (sealedOrderingFixture.ts). +import type { Browser } from "puppeteer-core"; +import { afterAll, beforeAll, it, vi } from "vitest"; +import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils"; +import { expectGenerated } from "../../tests/sealedOrderingFixture"; +import { buildStudioBundle } from "../../tests/sealedPreviewHarness"; + +vi.setConfig({ testTimeout: 120_000, hookTimeout: 60_000 }); +let browser: Browser; +let studioBundle: string; + +beforeAll(async () => { + browser = await launchTestChrome(); + studioBundle = await buildStudioBundle(); +}); +afterAll(() => closeTestChrome(browser)); + +const base = Number(process.env.HF_ORDERING_SEED_BASE ?? 0); +const listed = process.env.HF_ORDERING_SEED_LIST?.split(",").map(Number); +const seeds = + listed ?? + Array.from({ length: Number(process.env.HF_ORDERING_SEEDS ?? 40) }, (_, i) => base + i + 1); + +it.each(seeds)("generated sequence %i", (seed) => expectGenerated(browser, studioBundle, seed)); diff --git a/packages/studio/src/utils/sealedRestoreSend.ts b/packages/studio/src/utils/sealedRestoreSend.ts new file mode 100644 index 0000000000..4cb1a2ba28 --- /dev/null +++ b/packages/studio/src/utils/sealedRestoreSend.ts @@ -0,0 +1,55 @@ +// Sends an undo's restore to a sealed preview; a restore the frame does not apply reloads it. +import type { EditingParams } from "@hyperframes/core/runtime/editing-port"; +import { + SAVED_STATE_DEADLINE_MS, + confirmPreviewRerun, + sendPreviewWrite, + takePreviewTicket, + ticketLoadLive, + type PreviewWrite, +} from "./sealedPreviewLedger"; + +export type SealedRestore = Omit, "time">; + +/** The restored file as a complete snapshot, when the restore re-runs its script. */ +export function restoredSnapshot( + { rerun }: SealedRestore, + active: { restored: string; previous: string } | undefined, + version: number | undefined, +): PreviewWrite | null { + if (!rerun || !active) return null; + const { restored: authoredHtml, previous: previousHtml } = active; + return { scriptText: rerun.script, authoredHtml, previousHtml, version }; +} + +export function sendSealedRestore( + iframe: HTMLIFrameElement, + { + sent: restore, + snapshot, + version, + }: { sent: SealedRestore; snapshot: PreviewWrite | null; version?: number }, + currentTime: number, + reloadPreview: () => void, + onShownInPlace?: () => void, +): void { + const scriptText = restore.rerun?.script ?? ""; + const ticket = takePreviewTicket(iframe, { + scriptText, + snapshot, + attributes: true, + timing: false, + version, + }); + const params = { ...restore, time: currentTime }; + void sendPreviewWrite(ticket, "restore-attributes", params, SAVED_STATE_DEADLINE_MS).then( + (answer) => { + if (!ticketLoadLive(ticket)) return; + const reply = typeof answer === "object" ? answer : null; + // Refused or stale: its attributes are not on screen, and a newer re-run does not set them. + if (!reply?.applied) return reloadPreview(); + if (reply.reran === true) confirmPreviewRerun(ticket); + onShownInPlace?.(); + }, + ); +} diff --git a/packages/studio/tests/chromeTestUtils.ts b/packages/studio/tests/chromeTestUtils.ts index 9875c3166c..c3eb1bcb2b 100644 --- a/packages/studio/tests/chromeTestUtils.ts +++ b/packages/studio/tests/chromeTestUtils.ts @@ -2,6 +2,7 @@ import { readFileSync } from "node:fs"; import { createRequire } from "node:module"; import { inspect } from "node:util"; import puppeteer, { TimeoutError, type Browser, type Page } from "puppeteer-core"; +import type { Plugin } from "esbuild"; import { browserVersion, findSystemChrome } from "../vite.browser"; const require = createRequire(import.meta.url); @@ -86,3 +87,13 @@ export async function showWithRuntime(page: Page, html: string): Promise { await page.evaluate(readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8")); await page.waitForFunction(() => "__player" in window); } + +// recast imports these, and its code that uses them is dropped from the bundle. A new +// built-in fails the build instead of turning into an empty module the way Vite makes it. +export const emptyNodeBuiltins: Plugin = { + name: "empty-node-builtins", + setup(build) { + build.onResolve({ filter: /^(node:)?(fs|os)$/ }, ({ path }) => ({ path, namespace: "empty" })); + build.onLoad({ filter: /.*/, namespace: "empty" }, () => ({ contents: "module.exports = {}" })); + }, +}; diff --git a/packages/studio/tests/previewAnswerMock.ts b/packages/studio/tests/previewAnswerMock.ts new file mode 100644 index 0000000000..52b6cf48a6 --- /dev/null +++ b/packages/studio/tests/previewAnswerMock.ts @@ -0,0 +1,8 @@ +// previewAnswer over a mocked request, as the channel runs it: the send gate's admit, then the request. +export function admittedAnswer(request: (...args: unknown[]) => unknown, stale: symbol) { + return (...args: unknown[]) => { + const admit = args[4] as (() => boolean) | undefined; + if (admit && !admit()) return Promise.resolve(stale); + return request(...args.slice(0, 4)); + }; +} diff --git a/packages/studio/tests/sealedOrderingFixture.ts b/packages/studio/tests/sealedOrderingFixture.ts new file mode 100644 index 0000000000..42b0a2597f --- /dev/null +++ b/packages/studio/tests/sealedOrderingFixture.ts @@ -0,0 +1,271 @@ +// The ordering tables' saved file, the saves Studio sends and the sequence generator, shared by both tables. +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import type { Browser, Page } from "puppeteer-core"; +import { expect } from "vitest"; +import type { Studio } from "./sealedPreviewHarness"; +import { + playSequence, + type SequenceFixture, + type SaveFate, + type SequenceStep, +} from "./sealedPreviewSequence"; + +const require = createRequire(import.meta.url); +const GSAP = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8"); +const RUNTIME = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); +const MARK = ''; + +/** The saved file, as the fields a step can change. */ +interface Saved { + gen: number; + x: number; + start: number; + dur: number; + /** `data-start` of a clip no script animates, so the frame restores it in place. */ + dStart: number; + label: string; + title: string; +} +const FIRST: Saved = { gen: 0, x: 10, start: 0, dur: 4, dStart: 0, label: "a", title: "a" }; + +const script = (s: Saved) => `(function () { + window.__timelines = window.__timelines || {}; + var tl = gsap.timeline({ paused: true }); + tl.set("#target", { x: ${s.x} }, 0); + tl.to("#target", { y: 100, duration: ${s.dur}, ease: "none" }, 0); + window.__timelines["main"] = tl; + window.__ran = { main: "g${s.gen}" }; + })();`; +const root = (s: Saved) => + `
` + + `
` + + `
` + + `
` + + `
`; +/** A second GSAP script, so the file has no single script to re-run. */ +const SIDE = `window.__timelines = window.__timelines || {}; + window.__timelines["side"] = gsap.timeline({ paused: true }).to("#c", { opacity: 0.5, duration: 4 }, 0);`; +const scripts = (s: Saved, two: boolean) => + `${two ? `` : ""}`; +/** The saved file as Studio reads it; every element carries the `data-hf-id` Studio's server gives it. */ +const file = (s: Saved, two = false) => `${root(s)}${scripts(s, two)}`; +/** The saved file as the preview loads it. */ +const page = (s: Saved, two = false) => + `${MARK} + + ${root(s)}${scripts(s, two)}`; + +// A label is restore-safe and applies in place; a title is not (restoreAttributes.ts), so the frame refuses it. +export type Save = + | "run" + | "patch" + | "retime" + | "liveRetime" + | "undoLabel" + | "undoTitle" + | "undoBoth" + | "undoStart"; +export type Step = SequenceStep; + +const next: Record Saved> = { + run: (s) => ({ ...s, gen: s.gen + 1 }), + patch: (s, n) => ({ ...s, x: 20 + n }), + retime: (s) => ({ ...s, start: 1 - s.start }), + liveRetime: (s) => ({ ...s, start: 1 - s.start, dur: s.dur === 4 ? 3 : 4 }), + undoLabel: (s) => ({ ...s, label: s.label === "a" ? "b" : "a" }), + undoTitle: (s) => ({ ...s, title: s.title === "a" ? "b" : "a" }), + undoBoth: (s) => ({ ...s, gen: s.gen + 1, title: s.title === "a" ? "b" : "a" }), + undoStart: (s) => ({ ...s, dStart: 1 - s.dStart }), +}; + +/** Sends `save` the way Studio does after writing the file from `before` to `after`. */ +/** Marks a write request as Studio does when it goes out, and reads the file revision it took. */ +function mark(studioPage: Page) { + return studioPage.evaluate(() => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + studio.markStudioWriteToken(`save-${Math.random()}`); + return studio.studioFileRevision(); + }); +} + +/** Sends `save` the way Studio does after writing the file from `before` to `after`. */ +function send( + studioPage: Page, + save: Save, + [before, after]: [Saved, Saved], + revision: number, + two: boolean, +) { + return studioPage.evaluate( + (kind, prev, saved, savedPage, x, text, version) => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const w = window as unknown as { + __saved: string; + __savedVersion?: number; + __reload: () => void; + __refusals: number; + }; + // The file on disk is the newest save's, whichever preview sync goes out last. + if (version > (w.__savedVersion ?? -1)) { + w.__saved = savedPage; + w.__savedVersion = version; + } + // A reload Studio asks for because nothing can apply in place counts as a refusal that allows one. + const reloadNow = () => { + w.__refusals++; + w.__reload(); + }; + let sending = true; + const reloadPreview = () => (sending ? reloadNow() : w.__reload()); + const iframe = document.querySelector("iframe")!; + const time = studio.usePlayerStore.getState().currentTime; + const rerun = { currentTimeOverride: time, authoredHtml: saved, previousHtml: prev }; + // As Studio's timing sync (timelineTimingSync.ts): move the live tweens, or re-run the script with its timing + // at the playhead then. + if (kind === "liveRetime") + void Promise.resolve( + studio.moveLiveTweens(iframe, text, time, w.__reload, { + before: prev, + after: saved, + revision: version, + }), + ).then((moved) => { + if (moved) return; + const now = studio.usePlayerStore.getState().currentTime; + const options = { + ...rerun, + currentTimeOverride: now, + timingEdit: true, + version, + onAsyncFailure: w.__reload, + }; + if (studio.applySoftReload(iframe, text, options) === "cannot-soft-reload") reloadNow(); + }); + // As Studio's preview sync: a run nothing can apply in place reloads. + const rerunOrReload = (timingEdit: boolean) => { + const options = { ...rerun, timingEdit, version, onAsyncFailure: w.__reload }; + if (studio.applySoftReload(iframe, text, options) === "cannot-soft-reload") reloadNow(); + }; + if (kind === "run") rerunOrReload(false); + if (kind === "retime") rerunOrReload(true); + if (kind === "patch") { + const instantPatch = { + selector: "#target", + change: { kind: "set" as const, props: { x } }, + }; + const result = { + ok: true, + scriptText: text, + before: prev, + after: saved, + revision: version, + }; + studio.applyPreviewSync( + iframe, + result, + { label: "drag", softReload: true, instantPatch }, + reloadPreview, + ); + } + if (kind.startsWith("undo")) { + const files = { "index.html": { previous: prev, restored: saved } }; + studio.applyUndoRestoreToPreview(iframe, null, files, time, reloadPreview, null, version); + } + sending = false; + }, + save, + file(before, two), + file(after, two), + page(after, two), + after.x, + script(after), + revision, + ); +} + +const fixture = (two: boolean): SequenceFixture => ({ + first: FIRST, + page: (s) => page(s, two), + next, + mark, + send: (studioPage, save, before, after, revision) => + send(studioPage, save, [before, after], revision, two), + at: 2, + /** What a viewer sees: the script that ran, the clip timing, the label and title, and the tween's values. */ + read: (frame) => + frame.evaluate(() => { + const target = document.getElementById("target")!; + const m = new DOMMatrix(getComputedStyle(target).transform); + return { + ran: (window as unknown as { __ran: { main: string } }).__ran.main, + start: target.getAttribute("data-start"), + dStart: document.getElementById("d")!.getAttribute("data-start"), + label: document.getElementById("c")!.getAttribute("data-label"), + title: document.getElementById("c")!.getAttribute("title"), + x: Math.round(m.m41), + y: Math.round(m.m42), + }; + }), +}); +const ONE_SCRIPT = fixture(false); +const TWO_SCRIPTS = fixture(true); +export const playOrdering = ( + browser: Browser, + bundle: string, + steps: Step[], + seed = 1, + two = false, +) => playSequence(browser, bundle, two ? TWO_SCRIPTS : ONE_SCRIPT, steps, seed); + +const SAVES = Object.keys(next) as Save[]; +const FATES: SaveFate[] = ["frame", "frame", "refused", "rejected", "never"]; +const SCRUBS = [1, 3, 4]; +const generated = (seed: number): Step[] => { + let state = seed; + const random = () => (state = (state * 1103515245 + 12345) % 2 ** 31) / 2 ** 31; + const pick = (list: T[]) => list[Math.floor(random() * list.length)]!; + return Array.from({ length: 8 }, (): Step => { + const roll = random(); + if (roll < 0.06) return { reloadFrame: true }; + if (roll < 0.14) return { scrub: pick(SCRUBS) }; + if (roll < 0.2) return { pastDeadline: true }; + // A timing sync's preview sync runs after the file lock, so a newer save's can go out first. + if (roll < 0.25) + return { + reversed: [ + pick(["liveRetime", "retime"]), + pick(["run", "patch", "undoLabel", "undoStart"]), + ], + ...(random() < 0.3 ? { reload: true as const } : {}), + }; + if (roll < 0.5) return { answer: "any" }; + return { save: pick(SAVES), fate: pick(FATES) }; + }); +}; + +/** Plays generated sequence `seed` (odd seeds in a two-script file) and checks it against a fresh load. */ +export async function expectGenerated(browser: Browser, bundle: string, seed: number) { + const steps = generated(seed); + const two = seed % 2 === 1; + const { shown, fresh, reloads, reloadRefusals, playhead } = await playOrdering( + browser, + bundle, + steps, + seed, + two, + ); + expect({ steps, state: shown }).toEqual({ steps, state: fresh }); + // The preview's playhead stays where Studio last put it, within a frame. + expect({ + steps, + off: Math.abs(playhead.shown - playhead.studio) > 1 / 30, + playhead, + }).toMatchObject({ + steps, + off: false, + }); + // Only a refused re-run or restore, or a two-script file, leaves nothing to recover in place. + if (reloadRefusals === 0 && !two) expect({ steps, reloads }).toEqual({ steps, reloads: 0 }); +} diff --git a/packages/studio/tests/sealedPreviewHarness.ts b/packages/studio/tests/sealedPreviewHarness.ts new file mode 100644 index 0000000000..2f5f1a4fa6 --- /dev/null +++ b/packages/studio/tests/sealedPreviewHarness.ts @@ -0,0 +1,198 @@ +// Studio's page in real Chrome around a preview frame: the Studio bundle, the frame's replies held or answered +// by the test, and the MotionPath plugin request held until released. +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import type { Browser, Frame, HTTPRequest, Page } from "puppeteer-core"; +import { build } from "esbuild"; +import { expect } from "vitest"; +import { emptyNodeBuiltins } from "./chromeTestUtils"; + +const require = createRequire(import.meta.url); + +export type Studio = typeof import("../src/utils/gsapSoftReload") & { + previewRequest: typeof import("../src/player/lib/previewChannel").previewRequest; + patchRuntimeTweenInPlace: typeof import("../src/hooks/gsapRuntimePatch").patchRuntimeTweenInPlace; + applyPreviewSync: typeof import("../src/hooks/useGsapScriptCommits").applyPreviewSync; + applyUndoRestoreToPreview: typeof import("../src/utils/gsapUndoRestore").applyUndoRestoreToPreview; + moveLiveTweens: typeof import("../src/utils/gsapLiveRetime").moveLiveTweens; + usePlayerStore: typeof import("../src/player/store/playerStore").usePlayerStore; + markStudioWriteToken: typeof import("../src/utils/studioFileVersion").markStudioWriteToken; + studioFileRevision: typeof import("../src/utils/studioFileVersion").studioFileRevision; + previewLoadShows: typeof import("../src/utils/sealedPreviewLedger").previewLoadShows; +}; + +/** Studio's preview code, bundled for the page as `window.hfStudio`. */ +export async function buildStudioBundle(): Promise { + const out = await build({ + stdin: { + contents: [ + `export * from "./utils/gsapSoftReload";`, + `export { previewRequest } from "./player/lib/previewChannel";`, + `export { patchRuntimeTweenInPlace } from "./hooks/gsapRuntimePatch";`, + `export { applyPreviewSync } from "./hooks/useGsapScriptCommits";`, + `export { applyUndoRestoreToPreview } from "./utils/gsapUndoRestore";`, + `export { moveLiveTweens } from "./utils/gsapLiveRetime";`, + `export { usePlayerStore } from "./player/store/playerStore";`, + `export { markStudioWriteToken, studioFileRevision } from "./utils/studioFileVersion";`, + `export { previewLoadShows } from "./utils/sealedPreviewLedger";`, + ].join(" "), + resolveDir: fileURLToPath(new URL("../src", import.meta.url)), + }, + bundle: true, + write: false, + platform: "browser", + format: "iife", + globalName: "hfStudio", + alias: { canvas: fileURLToPath(new URL("../src/shims/canvasBrowserStub.js", import.meta.url)) }, + plugins: [emptyNodeBuiltins], + define: { "import.meta.env": "{}" }, + }); + return out.outputFiles[0]!.text; +} + +/** Studio's end of the editing port keeps the frame's replies while `__hold` is set, to deliver them later. */ +function holdReplies() { + const w = window as unknown as { + __hold: boolean; + __held: Array<(result?: unknown) => void>; + __swallow: Set; + __swallowed: Array<{ kind: string; answer: (result: unknown) => void }>; + __posted: number; + __rejecting: boolean; + __neverAnswer: boolean; + __refusals: number; + }; + w.__hold = false; + w.__held = []; + w.__swallow = new Set(); + w.__swallowed = []; + w.__posted = 0; + w.__rejecting = false; + w.__neverAnswer = false; + w.__refusals = 0; + const own = Object.getOwnPropertyDescriptor(MessagePort.prototype, "onmessage")!; + // A request of a swallowed kind never reaches the frame; the test answers it as the frame would. + const post = MessagePort.prototype.postMessage; + MessagePort.prototype.postMessage = function ( + this: MessagePort, + data: unknown, + ...rest: never[] + ) { + const request = data as { v?: unknown; id?: unknown; kind?: string } | null; + if (typeof request?.id === "number") w.__posted++; + if (typeof request?.id !== "number" || !w.__swallow.has(request.kind ?? "")) + return post.call(this, data, ...rest); + // Never answered: only its deadline settles it. + if (w.__neverAnswer) return; + const rejected = w.__rejecting; + w.__swallowed.push({ + kind: request.kind!, + // Arrives now, at the step that answers it, never back in the held queue. A rejection is the port's own + // refusal of the request before the frame applied anything. + answer: (result) => { + const error = { code: "invalid-params", message: "rejected before applying" }; + const data = rejected + ? { v: request.v, id: request.id, ok: false, error } + : { v: request.v, id: request.id, ok: true, result }; + if (rejected && request.kind !== "patch-tweens") w.__refusals++; + const hold = w.__hold; + w.__hold = false; + own.get!.call(this)?.call(this, new MessageEvent("message", { data })); + w.__hold = hold; + }, + }); + }; + Object.defineProperty(MessagePort.prototype, "onmessage", { + configurable: true, + get() { + return own.get!.call(this); + }, + set(handler: ((event: MessageEvent) => void) | null) { + // Counts each refusal Studio receives that leaves it nothing to recover in place. + const deliver = (data: { result?: { result?: unknown; applied?: unknown } }) => { + const result = data?.result; + if (result?.result === "cannot-soft-reload" || result?.applied === false) w.__refusals++; + handler?.call(this, new MessageEvent("message", { data })); + }; + own.set!.call(this, (event: MessageEvent) => { + const reply = typeof event.data?.id === "number"; + if (!reply) return handler?.call(this, event); + if (!w.__hold) return deliver(event.data); + w.__held.push((result) => + deliver(result === undefined ? event.data : { ...event.data, result }), + ); + }); + }, + }); +} + +/** Opens the preview in Studio's page; the plugin request waits until `release` is called. */ +export async function openPreview( + browser: Browser, + studioBundle: string, + html: string, + mode: string, +) { + const page: Page = await browser.newPage(); + const plugin = readFileSync(require.resolve("gsap/dist/MotionPathPlugin.min.js"), "utf8"); + const held: HTTPRequest[] = []; + let holding = true; + await page.setRequestInterception(true); + page.on("request", (request) => { + if (!/MotionPathPlugin/.test(request.url())) return void request.continue(); + const serve = () => + request.respond({ status: 200, contentType: "text/javascript", body: plugin }); + if (holding) held.push(request); + else void serve(); + }); + const release = async (status: 200 | 404) => { + holding = false; + for (const request of held.splice(0)) + await request.respond({ + status, + contentType: "text/javascript", + body: status === 200 ? plugin : "", + }); + }; + await page.setContent(""); + await page.evaluate(holdReplies); + await page.evaluate(studioBundle); + await page.evaluate( + (srcdoc, sealed) => { + const iframe = document.createElement("iframe"); + if (sealed) iframe.setAttribute("sandbox", "allow-scripts"); + iframe.style.cssText = "width: 1920px; height: 1080px; border: 0"; + iframe.srcdoc = srcdoc; + document.body.append(iframe); + }, + html, + mode === "sealed", + ); + const frame: Frame = await (async () => { + for (;;) { + const found = page.frames().find((f) => f !== page.mainFrame()); + if (found) return found; + await new Promise((resolve) => setTimeout(resolve, 20)); + } + })(); + await frame.waitForFunction(() => "__player" in window); + const time = () => + frame.evaluate(() => + (window as unknown as { __player: { getTime(): number } }).__player.getTime(), + ); + const seek = async (to: number) => { + await page.evaluate((t) => { + document + .querySelector("iframe")! + .contentWindow!.postMessage( + { source: "hf-parent", type: "control", action: "seek", timeSeconds: t }, + "*", + ); + }, to); + await expect.poll(time).toBeCloseTo(to, 2); + }; + return { page, frame, held, release, seek, time }; +} + +export type Preview = Awaited>; diff --git a/packages/studio/tests/sealedPreviewSequence.ts b/packages/studio/tests/sealedPreviewSequence.ts new file mode 100644 index 0000000000..83171f414f --- /dev/null +++ b/packages/studio/tests/sealedPreviewSequence.ts @@ -0,0 +1,418 @@ +// A sealed preview driven by a sequence of saves, replies and reloads, then compared with a fresh load of the +// saved file. A fixture says what a save changes, how Studio sends it, and what a viewer sees. +import type { Browser, Frame, Page } from "puppeteer-core"; +import { openPreview, type Studio } from "./sealedPreviewHarness"; + +/** A save reaches the frame, is refused by it, or is rejected by the port before the frame applies anything. */ +export type SaveFate = "frame" | "refused" | "rejected" | "never"; + +export type SequenceStep = + | { save: Save; fate: SaveFate } + | { answer: "any" | "oldest" | "newest" | string } + | { scrub: number } + /** Two saves whose responses come back newest first, so the older one's preview sync goes out last. */ + | { reversed: [Save, Save]; reload?: true } + /** The oldest request deadline still pending passes; a reply after it arrives too late. */ + | { pastDeadline: true } + | { reloadFrame: true }; + +export interface SequenceFixture { + first: Saved; + /** The saved file as the preview loads it. */ + page(saved: Saved): string; + next: Record Saved>; + /** Marks a save's write request as Studio does when it goes out; resolves to the file revision it took. */ + mark(studioPage: Page): Promise; + /** Sends `save` the way Studio does after writing the file; `window.__reload` is Studio's full reload. */ + send( + studioPage: Page, + save: Save, + before: Saved, + after: Saved, + revision: number, + ): Promise; + /** What a viewer sees, read once the preview has been sought to `at` seconds. */ + read(frame: Frame): Promise; + at: number; +} + +/** The refusal a frame that never took the request would send, by request kind. */ +const REFUSAL: Record = { + "soft-reload": { result: "cannot-soft-reload" }, + "patch-tweens": { patched: false }, + "restore-attributes": { applied: false, reran: false }, + "live-retime": { result: "unchanged" }, +}; + +const SAVE_KINDS = ["soft-reload", "patch-tweens", "restore-attributes", "live-retime"]; + +const ready = (frame: Frame) => + frame.waitForFunction(() => "__player" in window && "__timelines" in window); + +/** Seeks the `index`th frame of `studioPage` to `at` and waits for the render. */ +async function seekTo(studioPage: Page, frame: Frame, index: number, at: number) { + await studioPage.evaluate( + (i, t) => { + document + .querySelectorAll("iframe") + [i]!.contentWindow!.postMessage( + { source: "hf-parent", type: "control", action: "seek", timeSeconds: t }, + "*", + ); + }, + index, + at, + ); + await frame.waitForFunction( + (t) => + Math.abs((window as unknown as { __player: { getTime(): number } }).__player.getTime() - t) < + 0.01, + {}, + at, + ); + await frame.evaluate( + () => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))), + ); +} + +/** Studio's page: every reply held until answered; a full reload loads the newest saved file and is counted. */ +async function openStudio(browser: Browser, bundle: string, first: string, at: number) { + const preview = await openPreview(browser, bundle, first, "sealed"); + await preview.release(200); + await scrub(preview.page, preview.frame, at); + await preview.page.evaluate((first) => { + const w = window as unknown as { + __hold: boolean; + __saved: string; + __reloads: number; + __reload: () => void; + __load: () => void; + __loading: boolean; + __refusals: number; + }; + w.__hold = true; + w.__saved = first; + w.__reloads = 0; + // As Studio's shadow reload (useShadowPreviewReload.ts): a save during the load loads the newer file again. + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + w.__load = () => { + const iframe = document.querySelector("iframe")!; + const content = w.__saved; + const revision = studio.studioFileRevision(); + w.__loading = true; + iframe.addEventListener( + "load", + () => { + if (w.__saved !== content) return w.__load(); + studio.previewLoadShows(iframe, revision); + w.__loading = false; + }, + { once: true }, + ); + iframe.srcdoc = content; + }; + w.__loading = false; + w.__reload = () => { + w.__reloads++; + w.__load(); + }; + // A deadline (4 s or more) fires only when a step or the drain says it passes, never on its own. + const deadlines = new Map void>(); + let nextDeadline = -1; + const set = window.setTimeout.bind(window); + const clear = window.clearTimeout.bind(window); + window.setTimeout = (( + handler: (...args: unknown[]) => void, + ms?: number, + ...args: unknown[] + ) => { + if (typeof ms !== "number" || ms < 4_000) return set(handler, ms, ...args); + const id = nextDeadline--; + deadlines.set(id, () => handler(...args)); + return id; + }) as typeof window.setTimeout; + window.clearTimeout = ((id?: number) => { + if (id === undefined || !deadlines.delete(id)) clear(id); + }) as typeof window.clearTimeout; + (window as unknown as { __passDeadlines: (all: boolean) => number }).__passDeadlines = ( + all, + ) => { + const due = all ? [...deadlines.keys()] : [...deadlines.keys()].slice(0, 1); + for (const id of due) { + const fire = deadlines.get(id)!; + deadlines.delete(id); + // A missed reply may leave nothing to recover in place. + w.__refusals++; + fire(); + } + return due.length; + }; + // A new load is shown at Studio's playhead, as the real preview's shadow reload shows it. + window.addEventListener("message", (event) => { + const iframe = document.querySelector("iframe")!; + const data = event.data as { source?: string; type?: string } | null; + if ( + event.source !== iframe.contentWindow || + data?.source !== "hf-preview" || + data.type !== "ready" + ) + return; + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const timeSeconds = studio.usePlayerStore.getState().currentTime; + iframe.contentWindow!.postMessage( + { source: "hf-parent", type: "control", action: "seek", timeSeconds }, + "*", + ); + }); + }, first); + return preview; +} + +type Pending = { kind: string; refused: boolean }; + +const pending = (studioPage: Page) => + studioPage.evaluate(() => { + const w = window as unknown as { + __held: unknown[]; + __heldKinds?: string[]; + __swallowed: Array<{ kind: string }>; + }; + return [ + ...w.__held.map(() => ({ kind: "reply", refused: false })), + ...w.__swallowed.map(({ kind }) => ({ kind, refused: true })), + ] as Pending[]; + }); + +/** Answers one pending request: a held reply as the frame sent it, or a refused one with its refusal. */ +function answer(studioPage: Page, pick: number, kind: string | null) { + return studioPage.evaluate( + (at, wanted, refusals) => { + const w = window as unknown as { + __held: Array<() => void>; + __swallowed: Array<{ kind: string; answer: (result: unknown) => void }>; + }; + const refuse = (entry: { kind: string; answer: (result: unknown) => void }) => + entry.answer(refusals[entry.kind]); + if (wanted === "oldest") return w.__held.shift()?.(); + if (wanted === "newest") return w.__held.pop()?.(); + const refusedAt = wanted ? w.__swallowed.findIndex((entry) => entry.kind === wanted) : -1; + if (refusedAt >= 0) return refuse(w.__swallowed.splice(refusedAt, 1)[0]!); + const all = w.__held.length + w.__swallowed.length; + if (all === 0) return; + const i = at % all; + if (i < w.__held.length) return w.__held.splice(i, 1)[0]!(); + refuse(w.__swallowed.splice(i - w.__held.length, 1)[0]!); + }, + pick, + kind, + REFUSAL, + ); +} + +/** Moves Studio's playhead to `at`, as a scrub does: the player store and the frame together. */ +async function scrub(studioPage: Page, frame: Frame, at: number) { + await studioPage.evaluate((t) => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + studio.usePlayerStore.getState().setCurrentTime(t); + }, at); + await seekTo(studioPage, frame, 0, at); +} + +/** Where the preview's playhead is, and where Studio thinks it is, once a pending seek has had time to land. */ +const playheads = async (studioPage: Page, frame: Frame) => { + const studio = await studioPage.evaluate( + () => + (window as unknown as { hfStudio: Studio }).hfStudio.usePlayerStore.getState().currentTime, + ); + await frame + .waitForFunction( + (t) => + Math.abs( + (window as unknown as { __player: { getTime(): number } }).__player.getTime() - t, + ) < + 1 / 30, + { timeout: 1_000 }, + studio, + ) + .catch(() => {}); + return readPlayheads(studioPage, frame); +}; + +const readPlayheads = (studioPage: Page, frame: Frame) => + Promise.all([ + frame.evaluate(() => + (window as unknown as { __player: { getTime(): number } }).__player.getTime(), + ), + studioPage.evaluate( + () => + (window as unknown as { hfStudio: Studio }).hfStudio.usePlayerStore.getState().currentTime, + ), + ]).then(([shown, studio]) => ({ shown, studio })); + +/** Sends one save with its fate, and waits until Studio has posted its request or reloaded. */ +async function sendSave( + studioPage: Page, + fixture: SequenceFixture, + save: Save, + fate: SaveFate, + [before, after]: [Saved, Saved], + revision: number, +) { + await studioPage.evaluate( + (fate, kinds) => { + const w = window as unknown as { + __swallow: Set; + __rejecting: boolean; + __neverAnswer: boolean; + }; + w.__swallow = new Set(fate === "frame" ? [] : kinds); + w.__rejecting = fate === "rejected"; + w.__neverAnswer = fate === "never"; + }, + fate, + SAVE_KINDS, + ); + const sent = () => + studioPage.evaluate(() => { + const w = window as unknown as { __posted: number; __reloads: number }; + return w.__posted + w.__reloads; + }); + const count = await sent(); + await fixture.send(studioPage, save, before, after, revision); + // Studio posts the request a tick later, or reloads when nothing can apply in place; its fate holds until then. + await studioPage.waitForFunction( + (n) => { + const w = window as unknown as { __posted: number; __reloads: number }; + return w.__posted + w.__reloads > n; + }, + {}, + count, + ); + await studioPage.evaluate(() => { + (window as unknown as { __swallow: Set }).__swallow = new Set(); + }); +} + +/** Waits until a reload in flight has shown the newest saved file. */ +async function loaded(studioPage: Page, frame: Frame) { + await studioPage.waitForFunction(() => !(window as unknown as { __loading: boolean }).__loading); + await ready(frame); +} + +const passDeadlines = (studioPage: Page, all: boolean) => + studioPage.evaluate( + (every) => + (window as unknown as { __passDeadlines: (all: boolean) => number }).__passDeadlines(every), + all, + ); + +/** + * Answers everything still pending, new recoveries included, until nothing is left and the frame is loaded; then + * every deadline still pending passes, and it drains again. + */ +async function drain(studioPage: Page, frame: Frame, random: () => number) { + await studioPage.evaluate(() => { + (window as unknown as { __swallow: Set }).__swallow = new Set(); + }); + for (let quiet = 0; quiet < 3; ) { + await loaded(studioPage, frame); + await frame.evaluate(() => new Promise((done) => requestAnimationFrame(() => done(null)))); + const left = await pending(studioPage); + if (left.length === 0 && quiet === 2 && (await passDeadlines(studioPage, true)) > 0) quiet = 0; + else if (left.length === 0) quiet++; + else { + quiet = 0; + await answer(studioPage, Math.floor(random() * 1000), null); + } + } +} + +/** A fresh load of `saved` in a page of its own. */ +async function freshLoad( + browser: Browser, + bundle: string, + fixture: SequenceFixture, + saved: Saved, +) { + const fresh = await openPreview(browser, bundle, fixture.page(saved), "sealed"); + await ready(fresh.frame); + await seekTo(fresh.page, fresh.frame, 0, fixture.at); + const shown = await fixture.read(fresh.frame); + await fresh.page.close(); + return shown; +} + +/** Plays `steps`, settles every reply, and compares the preview with a fresh load of the saved file. */ +/** Two saves whose responses come back newest first: the newer's sync goes out, then the older's. */ +async function playReversed( + studioPage: Page, + frame: Frame, + fixture: SequenceFixture, + step: { reversed: [Save, Save]; reload?: true }, + [saved, n]: [Saved, number], +) { + const [older, newer] = step.reversed; + const middle = fixture.next[older](saved, n); + const after = fixture.next[newer](middle, n); + const olderRevision = await fixture.mark(studioPage); + const newerRevision = await fixture.mark(studioPage); + await sendSave(studioPage, fixture, newer, "frame", [middle, after], newerRevision); + // The frame loads the newer saved file before the older sync goes out. + if (step.reload) { + await studioPage.evaluate(() => (window as unknown as { __load: () => void }).__load()); + await loaded(studioPage, frame); + } + const reloads = () => + studioPage.evaluate(() => (window as unknown as { __reloads: number }).__reloads); + const before = await reloads(); + await sendSave(studioPage, fixture, older, "frame", [saved, middle], olderRevision); + // Studio does not send the older write over the newer file; a reload there is that refusal. + if ((await reloads()) > before) + await studioPage.evaluate(() => (window as unknown as { __refusals: number }).__refusals++); +} + +export async function playSequence( + browser: Browser, + bundle: string, + fixture: SequenceFixture, + steps: SequenceStep[], + seed = 1, +) { + let state = seed; + const random = () => (state = (state * 1103515245 + 12345) % 2 ** 31) / 2 ** 31; + const preview = await openStudio(browser, bundle, fixture.page(fixture.first), fixture.at); + const { page: studioPage, frame } = preview; + let saved = fixture.first; + for (const [n, step] of steps.entries()) { + if ("save" in step) { + const after = fixture.next[step.save](saved, n); + const revision = await fixture.mark(studioPage); + await sendSave(studioPage, fixture, step.save, step.fate, [saved, after], revision); + saved = after; + } else if ("reversed" in step) { + await playReversed(studioPage, frame, fixture, step, [saved, n]); + saved = fixture.next[step.reversed[1]](fixture.next[step.reversed[0]](saved, n), n); + } else if ("pastDeadline" in step) { + await passDeadlines(studioPage, false); + } else if ("scrub" in step) { + await scrub(studioPage, frame, step.scrub); + } else if ("reloadFrame" in step) { + await studioPage.evaluate(() => (window as unknown as { __load: () => void }).__load()); + await loaded(studioPage, frame); + } else { + const kind = step.answer === "any" ? null : step.answer; + await answer(studioPage, Math.floor(random() * 1000), kind); + } + } + await drain(studioPage, frame, random); + const playhead = await playheads(studioPage, frame); + await seekTo(studioPage, frame, 0, fixture.at); + const shown = await fixture.read(frame); + const { reloads, reloadRefusals } = await studioPage.evaluate(() => { + const w = window as unknown as { __reloads: number; __refusals: number }; + return { reloads: w.__reloads, reloadRefusals: w.__refusals }; + }); + await studioPage.close(); + const fresh = await freshLoad(browser, bundle, fixture, saved); + return { shown, fresh, reloads, reloadRefusals, playhead }; +} From 75c83d87723595b07a058c504efefca1c6be0170 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sat, 21 Nov 2026 23:40:18 +0000 Subject: [PATCH 059/367] fix(engine): a capture proxy request whose name will not resolve is reported as failed (#8409) --- .../publicNetwork/captureProxy.test.ts | 39 +++++++++++++++++++ .../services/publicNetwork/captureProxy.ts | 17 ++++++-- 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/packages/engine/src/services/publicNetwork/captureProxy.test.ts b/packages/engine/src/services/publicNetwork/captureProxy.test.ts index 8675c717f0..2f70711563 100644 --- a/packages/engine/src/services/publicNetwork/captureProxy.test.ts +++ b/packages/engine/src/services/publicNetwork/captureProxy.test.ts @@ -112,6 +112,45 @@ describe("capture proxy", () => { expect(refused).toEqual([]); }); + // fails without the fix: a name that would not resolve answered 403 and reported nothing, refused or failed. + it("reports a name that would not resolve as a failed request, plain and tunneled", async () => { + const failures: CaptureFailure[] = []; + const refused: string[] = []; + const proxy = await startCaptureProxy(null, (c) => refused.push(c), undefined, { + onFailed: (failure) => failures.push(failure), + }); + proxies.push(proxy); + const plain = (path: string) => + new Promise((resolve, reject) => { + const req = request(proxy.url, { path }, (res) => { + res.resume(); + res.on("end", () => resolve(res.statusCode!)); + }); + req.on("error", reject); + req.end(); + }); + const tunnel = (authority: string) => + new Promise((resolve) => { + const socket = connect(Number(new URL(proxy.url).port), "127.0.0.1"); + socket.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\n\r\n`); + socket.once("data", (data) => { + resolve(String(data).split("\r\n")[0]!); + socket.destroy(); + }); + }); + resolveAddress.mockRejectedValue(new Error("DNS timed out")); + expect(await plain("http://slow.example.com/")).toBe(403); + expect(await tunnel("slow.example.com:443")).toBe("HTTP/1.1 403 Forbidden"); + expect(failures.map((failure) => failure.reason)).toEqual([ + "upstream_failed", + "upstream_failed", + ]); + resolveAddress.mockRejectedValue(new NonPublicHostError("refused", "private")); + expect(await plain("http://inside.example.com/")).toBe(403); + expect(failures).toHaveLength(2); + expect(refused).toEqual(["private"]); + }); + it("listens on the fixed loopback port it is given", async () => { const free = createServer(); await new Promise((resolve) => free.listen(0, "127.0.0.1", resolve)); diff --git a/packages/engine/src/services/publicNetwork/captureProxy.ts b/packages/engine/src/services/publicNetwork/captureProxy.ts index e36c658069..2cc6c10b9d 100644 --- a/packages/engine/src/services/publicNetwork/captureProxy.ts +++ b/packages/engine/src/services/publicNetwork/captureProxy.ts @@ -90,9 +90,18 @@ function refuse(response: ServerResponse): void { response.end(); } -async function httpPeer(url: URL, proxy: UpstreamProxy | undefined) { +async function resolveOrReportFailure(hostname: string, fail: () => void): Promise { + try { + return await resolvePublicAddress(hostname); + } catch (error) { + if (!(error instanceof NonPublicHostError)) fail(); + throw error; + } +} + +async function httpPeer(url: URL, proxy: UpstreamProxy | undefined, fail: () => void) { if (!proxy) { - const hostname = await resolvePublicAddress(url.hostname); + const hostname = await resolveOrReportFailure(url.hostname, fail); return { hostname, family: 4, port: url.port || 80, path: url.pathname + url.search }; } assertPublicHostname(url.hostname); @@ -109,7 +118,7 @@ async function forwardHttp( ): Promise { try { const url = destination(incoming.url ?? "", false); - const peer = await httpPeer(url, proxy); + const peer = await httpPeer(url, proxy, fail); if (incoming.destroyed || response.destroyed) return; const headers = forwardHeaders(incoming); headers.host = url.host; @@ -198,7 +207,7 @@ async function forwardTunnel( assertPublicHostname(url.hostname); return await forwardTunnelViaUpstream(url, proxy, client, head, sockets, fail); } - const address = await resolvePublicAddress(url.hostname); + const address = await resolveOrReportFailure(url.hostname, fail); if (client.destroyed) return; const upstream = connect({ host: address, family: 4, port: Number(url.port || 443) }); trackSocket(upstream, sockets); From c1f4a193a9e3e72776a1433ba72298f5d38237d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 00:24:06 +0000 Subject: [PATCH 060/367] fix(studio): a refused delete no longer brings back another delete still saving (#8413) A refused delete, or a ripple shift that fails after its delete, now moves back only the clips that delete shifted, on the timeline as it is now, instead of restoring the timeline from before it. --- .../src/hooks/useTimelineDeleteOps.test.tsx | 38 +++++++++++++++++-- .../studio/src/hooks/useTimelineDeleteOps.ts | 19 +++++++++- 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx index a98abd941f..e7743774f7 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -143,15 +143,17 @@ describe("useTimelineDeleteOps: ripple undo label", () => { ); }); - // fails without the fix: the second delete saved between the first delete and its ripple. - it("saves a delete made right after another after the first one's ripple", async () => { + // Deletes hf-a, then hf-b once hf-a's ripple slid it to 0, both saving through one edit queue. + async function deleteTwoInARow(refused?: string) { const writes: string[] = []; vi.stubGlobal( "fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { if (String(input).includes("/file-mutations/remove-elements/")) { const { targets } = JSON.parse(String(init?.body)) as { targets: Array<{ id: string }> }; - writes.push(`delete ${targets.map((t) => t.id).join(",")}`); + const write = `delete ${targets.map((t) => t.id).join(",")}`; + writes.push(write); + if (write === refused) return new Response("{}", { status: 500 }); } return new Response(JSON.stringify({ content: html }), { status: 200 }); }), @@ -166,7 +168,9 @@ describe("useTimelineDeleteOps: ripple undo label", () => { const run = editQueueRef.current.then(async () => { await options?.beforeTiming; await serializeStudioFileMutations(writeProjectFile, ["index.html"], async () => { - writes.push(`move ${changes.map((c) => c.element.id).join(",")}`); + const write = `move ${changes.map((c) => c.element.id).join(",")}`; + writes.push(write); + if (write === refused) throw new Error("refused"); }); }); editQueueRef.current = run.catch(() => undefined); @@ -183,11 +187,37 @@ describe("useTimelineDeleteOps: ripple undo label", () => { const shiftedB = usePlayerStore.getState().elements.find((e) => e.id === "hf-b")!; await Promise.all([first, getHook().handleTimelineElementDelete(shiftedB)]); }); + return writes; + } + + // fails without the fix: the second delete saved between the first delete and its ripple. + it("saves a delete made right after another after the first one's ripple", async () => { + const writes = await deleteTwoInARow(); expect(writes).toEqual(["delete hf-a", "move hf-b,hf-c", "delete hf-b", "move hf-c"]); expect(usePlayerStore.getState().elements).toEqual([el("hf-c", 0, 2)]); }); + // fails without the fix: the refused write restored the timeline from before it, so hf-b came back. + it.each([ + [ + "delete hf-a", + ["delete hf-a", "delete hf-b", "move hf-c"], + [el("hf-c", 2, 2), el("hf-a", 0, 2)], + ], + [ + "move hf-b,hf-c", + ["delete hf-a", "move hf-b,hf-c", "delete hf-b", "move hf-c"], + [el("hf-c", 2, 2)], + ], + ])( + "a refused %s rolls back only itself, so the next delete stays gone", + async (refused, tried, after) => { + expect(await deleteTwoInARow(refused)).toEqual(tried); + expect(usePlayerStore.getState().elements).toEqual(after); + }, + ); + it("removes a multi-clip selection with one request, however many clips it holds", async () => { const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined); const { elements, getHook } = mountDeleteHarness({ handleTimelineGroupMove }); diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts index 50ea2e35b7..e118fb544f 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.ts +++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts @@ -42,6 +42,21 @@ export function applyRippleShifts( }); } +/** Move the clips one delete's ripple shifted back on the timeline as it is now and put + * `restore` back, so a later delete still saving stays gone. */ +function undoRippleShift(changes: TimelineGroupMoveChange[] | null, restore: TimelineElement[]) { + const keyOf = (te: TimelineElement) => te.key ?? te.id; + const back = new Map( + changes?.map((c) => [keyOf(c.element), c.element.start - c.start]), + ); + const { elements, setElements } = usePlayerStore.getState(); + const unshifted = elements.map((te) => { + const by = back.get(keyOf(te)); + return by ? { ...te, start: te.start + by } : te; + }); + setElements([...unshifted, ...restore]); +} + interface UseTimelineDeleteOpsOptions { projectIdRef: MutableRefObject; activeCompPath: string | null; @@ -200,7 +215,7 @@ export function useTimelineDeleteOps({ await deleted; } catch (error) { rollbackDuration(); - usePlayerStore.getState().setElements(elements); + undoRippleShift(rippleChanges, sameFile); void shifted?.catch(() => undefined); reloadPreview(); throw error; @@ -214,7 +229,7 @@ export function useTimelineDeleteOps({ // toggle-off behaviour would have left anyway — not worth undoing // an otherwise-successful delete over. rippleFailed = true; - usePlayerStore.getState().setElements(survivors); + undoRippleShift(rippleChanges, []); console.error("[Timeline] ripple-edit failed to persist after delete", error); showToast("Clip deleted, but the gap could not be closed.", "error"); } From 8929d116499e10f06622c701ef54d31637c3aef5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 00:25:18 +0000 Subject: [PATCH 061/367] fix(studio): an insert on drop never lets linked partners overlap or start before 0 (#8416) The partner check now places every clip in a partner's lane where it will land, moving or not, and refuses a partner that would start before 0. --- .../components/timelineMainTrackInsert.test.ts | 17 +++++++++++++++++ .../components/timelineMainTrackInsert.ts | 13 +++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/packages/studio/src/player/components/timelineMainTrackInsert.test.ts b/packages/studio/src/player/components/timelineMainTrackInsert.test.ts index 4abfaf9f8d..051fb3f86a 100644 --- a/packages/studio/src/player/components/timelineMainTrackInsert.test.ts +++ b/packages/studio/src/player/components/timelineMainTrackInsert.test.ts @@ -41,6 +41,23 @@ describe("resolveMainTrackInsert", () => { expect(resolveMainTrackInsert([a, b, cLinked, cAudio, music], cLinked, 0, true)).toBeNull(); }); + // fails without the fix: each partner was checked only against clips that stay put. + it("is null when two moving linked partners would overlap each other in one lane", () => { + const aLinked = { ...a, link: "la" }; + const aAudio = { ...el("a-audio", 0, 2, 1), tag: "audio", link: "la" }; + const cLinked = { ...c, link: "lc" }; + const cAudio = { ...el("c-audio", 4.5, 2, 1), tag: "audio", link: "lc" }; + const all = [aLinked, b, cLinked, aAudio, cAudio]; + expect(resolveMainTrackInsert(all, cLinked, 0, true)).toBeNull(); + }); + + // fails without the fix: a partner's new start was never checked against 0. + it("is null when a linked partner would start before 0", () => { + const cLinked = { ...c, link: "l1" }; + const cAudio = { ...el("c-audio", 3, 2, 1), tag: "audio", link: "l1" }; + expect(resolveMainTrackInsert([a, b, cLinked, cAudio], cLinked, 0, true)).toBeNull(); + }); + it("is null when a clip that would move is locked", () => { const lockedA = { ...a, timelineLocked: true }; expect(resolveMainTrackInsert([lockedA, b, c], c, 0, true)).toBeNull(); diff --git a/packages/studio/src/player/components/timelineMainTrackInsert.ts b/packages/studio/src/player/components/timelineMainTrackInsert.ts index 27543ac54d..0f22a1a404 100644 --- a/packages/studio/src/player/components/timelineMainTrackInsert.ts +++ b/packages/studio/src/player/components/timelineMainTrackInsert.ts @@ -47,22 +47,23 @@ export function resolveMainTrackInsert( return [{ element: partner, start: round3(partner.start + lead.start - lead.element.start) }]; }); const moves = [...main, ...partners]; - const moving = new Set(moves.map((m) => keyOf(m.element))); - // A partner may not land on a clip that stays put in its lane; main-track moves only reorder, so they cannot. + const landed = new Map(moves.map((m) => [keyOf(m.element), m.start])); + const startAfter = (e: TimelineElement) => landed.get(keyOf(e)) ?? e.start; + // A partner may not land on a clip in its lane, moved or not, nor start before 0; main-track moves only reorder. const lands = partners.some(({ element, start }) => elements.some( (other) => other.track === element.track && - !moving.has(keyOf(other)) && + keyOf(other) !== keyOf(element) && timeRangesOverlap( start, start + element.duration, - other.start, - other.start + other.duration, + startAfter(other), + startAfter(other) + other.duration, ), ), ); - if (lands) return null; + if (lands || partners.some((p) => p.start < 0)) return null; return moves.every((m) => getTimelineEditCapabilities(m.element).canMove) ? moves : null; } From da1476e48d701d89187f8236ca9f4fc6b9e12158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 00:46:02 +0000 Subject: [PATCH 062/367] fix(engine): an asset download fails once when the egress proxy drops its tunnel (#8417) * test(engine): a tunnel the egress proxy drops fails the download after its one retry * fix(engine): an asset download fails once when the egress proxy drops its tunnel undici 7 keeps a request queued and reopens the tunnel with no pause or limit when the proxy closes it without a reply. The proxy transport's pools now report that close as a reset, so the request fails and the downloader's one retry is the bound. --- .../urlDownloader.restrictedNetwork.test.ts | 8 ++++ packages/engine/src/utils/urlDownloader.ts | 39 ++++++++++++++++--- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/packages/engine/src/utils/urlDownloader.restrictedNetwork.test.ts b/packages/engine/src/utils/urlDownloader.restrictedNetwork.test.ts index 3d49219a84..7f3679892e 100644 --- a/packages/engine/src/utils/urlDownloader.restrictedNetwork.test.ts +++ b/packages/engine/src/utils/urlDownloader.restrictedNetwork.test.ts @@ -293,6 +293,7 @@ describe("downloads with the render-service setting off", () => { describe("downloads on a render service through the egress proxy in HYPERFRAMES_CAPTURE_PROXY", () => { const HOST = "cdn.egress-assets.com"; + const HOST_WHOSE_TUNNEL_THE_PROXY_DROPS = "gone.egress-assets.com"; const tunnels: string[] = []; const defaultCAs = getCACertificates("default"); let origin: Server; @@ -316,6 +317,7 @@ describe("downloads on a render service through the egress proxy in HYPERFRAMES_ egress = createServer(); egress.on("connect", (request, client) => { tunnels.push(request.url ?? ""); + if (request.url === `${HOST_WHOSE_TUNNEL_THE_PROXY_DROPS}:443`) return void client.destroy(); const upstream = connect(originPort, "127.0.0.1", () => { client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); upstream.pipe(client).pipe(upstream); @@ -340,6 +342,12 @@ describe("downloads on a render service through the egress proxy in HYPERFRAMES_ ); }); + it("a tunnel the proxy drops fails the download without opening it again and again", async () => { + const url = `https://${HOST_WHOSE_TUNNEL_THE_PROXY_DROPS}/a.png`; + await expect(downloadToTemp(url, tempDir())).rejects.toMatchObject({ kind: "network" }); + expect(tunnels).toEqual([0, 1].map(() => `${HOST_WHOSE_TUNNEL_THE_PROXY_DROPS}:443`)); + }, 10_000); + it("downloads by hostname through the proxy, with the usual headers, resolving no names", async () => { routes[`https://${HOST}/a.png`] = { status: 200, body: BODY }; const path = await downloadToTemp(`https://${HOST}/a.png`, tempDir()); diff --git a/packages/engine/src/utils/urlDownloader.ts b/packages/engine/src/utils/urlDownloader.ts index d0cd0d8c2e..d0c17aa604 100644 --- a/packages/engine/src/utils/urlDownloader.ts +++ b/packages/engine/src/utils/urlDownloader.ts @@ -20,6 +20,7 @@ import { createHash, randomUUID } from "crypto"; import dns from "node:dns"; import { fetchGoesThroughEnvProxy } from "@hyperframes/core/env-proxy"; import { type LookupFunction } from "node:net"; +import type { buildConnector } from "undici"; import { isBlockedNetworkHost } from "./networkPolicy.js"; import { resolveRestrictPageNetwork } from "../config.js"; import { @@ -515,16 +516,44 @@ function undiciTransport(lookup: LookupFunction): Promise { const proxyTransports = new Map>(); +/** undici 7 reopens a tunnel the proxy closed without a reply with no pause or limit; this fails the request. */ +function failRequestOnDroppedTunnel(connect: buildConnector.connector): buildConnector.connector { + return (options, callback) => + connect(options, (...result) => { + const [error] = result; + if (error && "code" in error && error.code === "UND_ERR_SOCKET") { + const closed = new Error("The egress proxy closed the tunnel", { cause: error }); + return callback(Object.assign(closed, { code: "ECONNRESET" }), null); + } + callback(...result); + }); +} + function egressProxyTransport(proxy: UpstreamProxy): Promise { const uri = `http://${proxy.host.includes(":") ? `[${proxy.host}]` : proxy.host}:${proxy.port}`; const key = `${uri} ${proxy.authorization ?? ""}`; let transport = proxyTransports.get(key); if (!transport) { - transport = importUndiciPackageEvenUnderBun().then(({ ProxyAgent, fetch: undiciFetch }) => { - const dispatcher = new ProxyAgent({ uri, token: proxy.authorization }); - return (target, options) => - undiciFetch(target, { ...(options as object), dispatcher }) as unknown as Promise; - }); + transport = importUndiciPackageEvenUnderBun().then( + ({ Pool, ProxyAgent, fetch: undiciFetch }) => { + const dispatcher = new ProxyAgent({ + uri, + token: proxy.authorization, + factory: (origin, options) => + new Pool(origin, { + ...options, + connect: failRequestOnDroppedTunnel( + (options as { connect: buildConnector.connector }).connect, + ), + }), + }); + return (target, options) => + undiciFetch(target, { + ...(options as object), + dispatcher, + }) as unknown as Promise; + }, + ); proxyTransports.set(key, transport); } return transport; From 2b4706f193c6d42a9bfa630d8f0e009aaa3c4b1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 00:50:54 +0000 Subject: [PATCH 063/367] test(engine): the frame-tag checks get the time a real encode needs (#8415) They run ffmpeg and ffprobe like the raw SDR colour check, which already allows 30 s; at vitest's 5 s default a busy Windows runner timed one out. --- .../src/services/streamingEncoder.test.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/packages/engine/src/services/streamingEncoder.test.ts b/packages/engine/src/services/streamingEncoder.test.ts index a02f31df31..b04b7130cd 100644 --- a/packages/engine/src/services/streamingEncoder.test.ts +++ b/packages/engine/src/services/streamingEncoder.test.ts @@ -1296,17 +1296,22 @@ describe.skipIf(spawnSync("ffmpeg", ["-version"]).status !== 0)( } }; const tiny = { width: 64, height: 16 }; + const REAL_ENCODE_TIMEOUT_MS = 30_000; it.each([ ["captured frames", {}], ["raw RGB frames", { rawInputFormat: "rgb48le" as const }], - ])("tags BT.709 on %s, so an encoder that reads only them tags the stream", (_, extra) => { - const args = buildStreamingArgs({ ...baseSdr, ...tiny, ...extra }, "o.mp4"); + ])( + "tags BT.709 on %s, so an encoder that reads only them tags the stream", + (_, extra) => { + const args = buildStreamingArgs({ ...baseSdr, ...tiny, ...extra }, "o.mp4"); - expect(streamTagsThrough(args, ["-c:v", "libx264", "-preset", "ultrafast"])).toBe( - "bt709,bt709,bt709", - ); - }); + expect(streamTagsThrough(args, ["-c:v", "libx264", "-preset", "ultrafast"])).toBe( + "bt709,bt709,bt709", + ); + }, + REAL_ENCODE_TIMEOUT_MS, + ); it.each([ [baseHdrPq, "smpte2084", null], @@ -1327,6 +1332,7 @@ describe.skipIf(spawnSync("ffmpeg", ["-version"]).status !== 0)( expect(streamTagsThrough(args, x265)).toBe(`bt2020nc,${trc},bt2020`); }, + REAL_ENCODE_TIMEOUT_MS, ); }, ); From 1aa4a785c832bb07e1faed6eea86dd7c4b756960 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 01:40:53 +0000 Subject: [PATCH 064/367] chore: release v0.9.80 (#8414) * chore: release v0.9.80 * chore: release v0.9.80 notes list the changes merged since the draft * chore: release v0.9.80 notes list the changes merged since the draft --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- docs/changelog.mdx | 36 ++++++++++++++++++++++++ gemini-extension.json | 2 +- 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/inspector/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/share/package.json | 2 +- packages/studio-server/package.json | 2 +- packages/studio/package.json | 2 +- plugin.json | 2 +- releases/v0.9.80.md | 35 +++++++++++++++++++++++ 22 files changed, 91 insertions(+), 20 deletions(-) create mode 100644 releases/v0.9.80.md diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index c4612124ef..eee92e764d 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 capture for HyperFrames.", - "version": "0.9.79", + "version": "0.9.80", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 1c88b5446d..cffa7c67b0 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "hyperframes", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.", - "version": "0.9.79", + "version": "0.9.80", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index a3090ddeaa..d7ed6d6d79 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -3,7 +3,7 @@ "name": "hyperframes", "displayName": "HyperFrames by HeyGen", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.", - "version": "0.9.79", + "version": "0.9.80", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com" diff --git a/docs/changelog.mdx b/docs/changelog.mdx index 93b4bc336f..c90ace5759 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -8,6 +8,42 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio {/* New release entries are prepended by `bun run changelog:draft --write`. */} + +Dropping a clip onto main-track clips can now insert it there. Studio previews match the export more closely, and a drive that stops answering no longer stalls a project. + +## Features + +- **Studio:** Dropping a clip onto main-track clips can insert it there ([08bd7fc12](https://github.com/heygen-com/hyperframes/commit/08bd7fc126b1ae158bc9503672acbd88099c9cab), [#8397](https://github.com/heygen-com/hyperframes/pull/8397)). + +## Fixes + +- **Engine:** An asset download fails once when the egress proxy drops its tunnel ([da1476e48](https://github.com/heygen-com/hyperframes/commit/da1476e48d701d89187f8236ca9f4fc6b9e12158), [#8417](https://github.com/heygen-com/hyperframes/pull/8417)). +- **Studio:** An insert on drop never lets linked partners overlap or start before 0 ([8929d1164](https://github.com/heygen-com/hyperframes/commit/8929d116499e10f06622c701ef54d31637c3aef5), [#8416](https://github.com/heygen-com/hyperframes/pull/8416)). +- **Studio:** A refused delete no longer brings back another delete still saving ([c1f4a193a](https://github.com/heygen-com/hyperframes/commit/c1f4a193a9e3e72776a1433ba72298f5d38237d4), [#8413](https://github.com/heygen-com/hyperframes/pull/8413)). +- **Engine:** A capture proxy request whose name will not resolve is reported as failed ([75c83d877](https://github.com/heygen-com/hyperframes/commit/75c83d87723595b07a058c504efefca1c6be0170), [#8409](https://github.com/heygen-com/hyperframes/pull/8409)). +- **Studio:** A sealed undo of a GSAP-animated layer's style shows in place ([c3a673990](https://github.com/heygen-com/hyperframes/commit/c3a67399039ce87adaf2e78d4f7acf6e9a46f20a), [#8320](https://github.com/heygen-com/hyperframes/pull/8320)). +- **Media Use:** A project manifest's provider claim never writes a sound credit ([ec1839e4a](https://github.com/heygen-com/hyperframes/commit/ec1839e4a17925d9c04dce5bfd5153b4f3ca8a27), [#8410](https://github.com/heygen-com/hyperframes/pull/8410)). +- **Studio Server:** A file the drive never answers no longer holds a project's first history copy ([267ffc46c](https://github.com/heygen-com/hyperframes/commit/267ffc46c990e18246f964e8f96bd50a10784707), [#8187](https://github.com/heygen-com/hyperframes/pull/8187)). +- **Studio:** Fx badges in a sealed preview show the clip's look, crop and duck ([8a69ea039](https://github.com/heygen-com/hyperframes/commit/8a69ea039594d2eb353b7be40ba5b430c854faec), [#8411](https://github.com/heygen-com/hyperframes/pull/8411)). +- **Studio:** A paused untagged video shows the colours the export renders ([71907274a](https://github.com/heygen-com/hyperframes/commit/71907274a7aa0710717db15bec4ec1ab7b7fe8ee), [#8405](https://github.com/heygen-com/hyperframes/pull/8405)). +- **CLI:** Show copy file names in check progress lines as visible text ([4a5a5eb27](https://github.com/heygen-com/hyperframes/commit/4a5a5eb27e643a2b9daf3cceab95607c32558324), [#8407](https://github.com/heygen-com/hyperframes/pull/8407)). +- **Studio:** A delete and its ripple shift save as one edit ([7ec38388b](https://github.com/heygen-com/hyperframes/commit/7ec38388bf9066bdf33d87ac4cd15c63c96068d5), [#8404](https://github.com/heygen-com/hyperframes/pull/8404)). +- **Studio:** The poster rendered for the next open no longer delays a clip's picture ([da46c89e2](https://github.com/heygen-com/hyperframes/commit/da46c89e2a0b8d3427cf291b0ee1531d695e74c8), [#8400](https://github.com/heygen-com/hyperframes/pull/8400)). +- **Studio Server:** A file the drive never answers no longer holds a project's first copy ([71dc6f2fe](https://github.com/heygen-com/hyperframes/commit/71dc6f2fe1fdbd797ea72c35a420f649ba88a905), [#8403](https://github.com/heygen-com/hyperframes/pull/8403)). +- **CLI:** The compile cache lives only in the private HyperFrames cache folder ([8127bb885](https://github.com/heygen-com/hyperframes/commit/8127bb8856d51df14764224c234427d66bbe0642), [#8401](https://github.com/heygen-com/hyperframes/pull/8401)). + +## Internal + +- **Engine:** The frame-tag checks get the time a real encode needs ([2b4706f19](https://github.com/heygen-com/hyperframes/commit/2b4706f193c6d42a9bfa630d8f0e009aaa3c4b1d), [#8415](https://github.com/heygen-com/hyperframes/pull/8415)). +- **Studio Server:** The Windows workflow fails when the link tests cannot run ([b008e37b4](https://github.com/heygen-com/hyperframes/commit/b008e37b46148b4baebe6e11d72a6b9801a289ea), [#8395](https://github.com/heygen-com/hyperframes/pull/8395)). + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.9.79...v0.9.80). + + Date: Sun, 22 Nov 2026 01:59:05 +0000 Subject: [PATCH 065/367] fix(media-use): refuse links under .media before reserving, writing or recording (#8327) * fix(media-use): refuse links under .media before reserving, writing or recording A received project could carry links at .media, at a type folder, at the next asset name or its .tmp name, or at the preferences store's temp names, and resolve or prefs record wrote through them to files outside the project. - ownMediaDir now checks every folder down to the type folder, making each one level at a time, before the lock, the allocator, the record append or a project preference write touches anything inside it. - The allocator ignores ids past nine digits, so a planted huge id can't push it back onto a name the project holds, and it skips any name that already exists. - The asset writers and the LUT .tmp writers create new files only. - The preferences store writes through replaceFile, a random temp name created exclusively and renamed into place. Both copies of manifest.mjs and prefs-store.mjs change together. * test(media-use): read the preferences file through one no-follow handle The test checked the file's type and then read it by path, which CodeQL reports as a check-then-use race. Open it once without following a link and check and read through that handle. * fix(media-use): keep a failed write's error when replaceFile can't remove its temp file The preferences store now writes through replaceFile. Its old write made temp cleanup best-effort, so a cleanup error never hid the write error, and the store's tests guard that. replaceFile now does the same. * fix(media-use): leave freezeUrl's write as it was CodeQL's http-to-file-access rule flags every write of downloaded bytes, and main already carries that alert on this line. Adding the wx flag only re-keyed it as new. The reserved name freezeUrl writes is already checked free in a checked folder, so the line goes back to main's text; copying a local file keeps COPYFILE_EXCL. * Revert "fix(media-use): leave freezeUrl's write as it was" This reverts commit 1427e73ec280edbe00e1fa591547e7ca8add975d. --- packages/cli/src/media-use/lib/cache.mjs | 8 +- packages/cli/src/media-use/lib/freeze.mjs | 7 +- packages/cli/src/media-use/lib/links.test.mjs | 195 ++++++++++++++++++ packages/cli/src/media-use/lib/manifest.mjs | 22 +- .../cli/src/media-use/lib/prefs-store.mjs | 16 +- skills-manifest.json | 2 +- skills/media-use/scripts/lib/manifest.mjs | 22 +- skills/media-use/scripts/lib/prefs-store.mjs | 16 +- 8 files changed, 244 insertions(+), 44 deletions(-) create mode 100644 packages/cli/src/media-use/lib/links.test.mjs diff --git a/packages/cli/src/media-use/lib/cache.mjs b/packages/cli/src/media-use/lib/cache.mjs index 768488b560..d7dc552e94 100644 --- a/packages/cli/src/media-use/lib/cache.mjs +++ b/packages/cli/src/media-use/lib/cache.mjs @@ -5,10 +5,11 @@ import { existsSync, copyFileSync, statSync, + constants, } from "node:fs"; import { join, basename } from "node:path"; import { createHash } from "node:crypto"; -import { readManifest, appendRecord, normalizePrompt } from "./manifest.mjs"; +import { readManifest, appendRecord, normalizePrompt, ownTypeDir } from "./manifest.mjs"; import { globalMediaDir, mediaHome } from "./media-home.mjs"; export { globalMediaDir }; @@ -129,10 +130,9 @@ export function importFromCache(cacheRecord, projectDir, localId, localPath) { const sha = cacheRecord.sha; const cachedFile = cacheRecord.cached_path; - mkdirSync(join(projectDir, ".media"), { recursive: true }); + ownTypeDir(projectDir, cacheRecord.type); const fullDest = join(projectDir, localPath); - mkdirSync(join(fullDest, ".."), { recursive: true }); - copyFileSync(cachedFile, fullDest); + copyFileSync(cachedFile, fullDest, constants.COPYFILE_EXCL); const projectRecord = { ...cacheRecord, diff --git a/packages/cli/src/media-use/lib/freeze.mjs b/packages/cli/src/media-use/lib/freeze.mjs index d5505a5261..a70abfbcdd 100644 --- a/packages/cli/src/media-use/lib/freeze.mjs +++ b/packages/cli/src/media-use/lib/freeze.mjs @@ -1,6 +1,6 @@ import { fetchMedia, isPublicMediaUrl, readCappedBody } from "./media-fetch.mjs"; import { sanitizeSvg } from "./svg-sanitize.mjs"; -import { writeFileSync, copyFileSync, mkdirSync, readFileSync } from "node:fs"; +import { writeFileSync, copyFileSync, mkdirSync, readFileSync, constants } from "node:fs"; import { dirname } from "node:path"; // ponytail: bound the download so a hostile/runaway URL can't fill the disk. @@ -16,7 +16,8 @@ const isSvgPath = (destPath) => /\.svg$/i.test(destPath); function writeFrozen(destPath, buffer) { mkdirSync(dirname(destPath), { recursive: true }); const bytes = isSvgPath(destPath) ? Buffer.from(sanitizeSvg(buffer.toString("utf8"))) : buffer; - writeFileSync(destPath, bytes); + // "wx": a new file only, so a link planted at the name fails the write instead of being followed. + writeFileSync(destPath, bytes, { flag: "wx" }); return bytes.byteLength; } @@ -47,7 +48,7 @@ export function freezeLocalFile(srcPath, destPath) { return; } mkdirSync(dirname(destPath), { recursive: true }); - copyFileSync(srcPath, destPath); + copyFileSync(srcPath, destPath, constants.COPYFILE_EXCL); } // Ingest accepts a DIRECT public media URL only — not a platform page. yt-dlp is diff --git a/packages/cli/src/media-use/lib/links.test.mjs b/packages/cli/src/media-use/lib/links.test.mjs new file mode 100644 index 0000000000..97770fc0eb --- /dev/null +++ b/packages/cli/src/media-use/lib/links.test.mjs @@ -0,0 +1,195 @@ +import { strict as assert } from "node:assert"; +import { + closeSync, + constants, + existsSync, + fstatSync, + lstatSync, + mkdirSync, + mkdtempSync, + openSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { test } from "node:test"; +import { appendRecord, withReservedFileSync } from "./manifest.mjs"; +import { freezeLocalFile } from "./freeze.mjs"; +import { freezeLibraryLut, matchColorLook } from "./lut-preset-provider.mjs"; +import { projectPrefsPath, recordPreference } from "./prefs-store.mjs"; + +// Planting a link needs no privileges on macOS and Linux; Windows needs developer mode for file links. +const posixOnly = { skip: process.platform === "win32" }; + +/** A project folder and a folder outside it holding one file that must survive every test. */ +function withSandbox(fn) { + const root = realpathSync(mkdtempSync(join(tmpdir(), "mu-links-"))); + const project = join(root, "project"); + const outside = join(root, "outside"); + mkdirSync(project); + mkdirSync(outside); + writeFileSync(join(outside, "keep.txt"), "keep me\n"); + const outsideUnchanged = () => { + assert.deepEqual(readdirSync(outside), ["keep.txt"]); + assert.equal(readFileSync(join(outside, "keep.txt"), "utf8"), "keep me\n"); + }; + return Promise.resolve(fn({ root, project, outside, outsideUnchanged })).finally(() => + rmSync(root, { recursive: true, force: true }), + ); +} + +function plantLink(target, at) { + mkdirSync(dirname(at), { recursive: true }); + symlinkSync(target, at); +} + +function reserveAndWrite(project, type, ext) { + return withReservedFileSync(project, type, ext, ({ fullPath, localPath }) => { + writeFileSync(fullPath, "asset", { flag: "wx" }); + return localPath; + }); +} + +test("a reservation refuses a linked .media before taking the lock", posixOnly, () => + withSandbox(({ project, outside, outsideUnchanged }) => { + symlinkSync(outside, join(project, ".media")); + assert.throws( + () => reserveAndWrite(project, "image", ".png"), + /leads outside the project|is a link/, + ); + outsideUnchanged(); + }), +); + +for (const [linked, type] of [ + ["images", "image"], + ["audio", "sfx"], + ["audio/sfx", "sfx"], + ["video", "video"], + ["luts", "lut"], +]) { + test( + `a reservation refuses a linked .media/${linked} before making anything in it`, + posixOnly, + () => + withSandbox(({ project, outside, outsideUnchanged }) => { + plantLink(outside, join(project, ".media", linked)); + assert.throws( + () => reserveAndWrite(project, type, ".bin"), + /leads outside the project|is a link/, + ); + outsideUnchanged(); + }), + ); +} + +test("appending a record refuses a linked type folder", posixOnly, () => + withSandbox(({ project, outside, outsideUnchanged }) => { + plantLink(outside, join(project, ".media", "images")); + assert.throws( + () => appendRecord(project, { id: "image_001", type: "image", path: ".media/images/x.png" }), + /leads outside the project|is a link/, + ); + outsideUnchanged(); + }), +); + +test("an id past exact integers never lands on a name the project already holds", posixOnly, () => + withSandbox(({ project, outside, outsideUnchanged }) => { + const huge = "9007199254740992"; + mkdirSync(join(project, ".media", "images"), { recursive: true }); + writeFileSync( + join(project, ".media", "manifest.jsonl"), + `${JSON.stringify({ id: `image_${huge}`, type: "image", path: "x" })}\n`, + ); + plantLink(join(outside, "planted.png"), join(project, ".media", "images", `image_${huge}.png`)); + const source = join(project, "source.png"); + writeFileSync(source, "png"); + + const localPath = withReservedFileSync(project, "image", ".png", ({ fullPath, localPath }) => { + freezeLocalFile(source, fullPath); + return localPath; + }); + + assert.equal(localPath, ".media/images/image_001.png"); + assert.ok(lstatSync(join(project, localPath)).isFile()); + outsideUnchanged(); + }), +); + +test("the asset writers refuse a link at their own name instead of following it", posixOnly, () => + withSandbox(({ project, outside, outsideUnchanged }) => { + const source = join(project, "source"); + writeFileSync(source, ""); + for (const ext of [".png", ".svg"]) { + const dest = join(project, `dest${ext}`); + symlinkSync(join(outside, `target${ext}`), dest); + assert.throws(() => freezeLocalFile(source, dest), /EEXIST/); + } + outsideUnchanged(); + }), +); + +test("a frozen LUT never writes through a link at its .tmp name", posixOnly, () => + withSandbox(async ({ project, outside, outsideUnchanged }) => { + const huge = "9007199254740992"; + mkdirSync(join(project, ".media", "luts"), { recursive: true }); + writeFileSync( + join(project, ".media", "manifest.jsonl"), + `${JSON.stringify({ id: `lut_${huge}`, type: "lut", path: "x" })}\n`, + ); + plantLink( + join(outside, "planted.cube"), + join(project, ".media", "luts", `lut_${huge}.cube.tmp`), + ); + const match = matchColorLook("teal orange blockbuster"); + + const frozen = await freezeLibraryLut(match, { + projectDir: project, + type: "lut", + localOnly: true, + }); + + assert.equal(frozen.localPath, ".media/luts/lut_001.cube"); + outsideUnchanged(); + }), +); + +test("a project preference refuses a linked .media and writes nothing", posixOnly, () => + withSandbox(({ project, outside, outsideUnchanged }) => { + symlinkSync(outside, join(project, ".media")); + assert.throws( + () => recordPreference({ projectDir: project, key: "aspect", value: "16:9" }), + /leads outside the project|is a link/, + ); + outsideUnchanged(); + }), +); + +test("a project preference never writes through links at predictable temp names", posixOnly, () => + withSandbox(({ project, outside, outsideUnchanged }) => { + const prefs = projectPrefsPath(project); + mkdirSync(dirname(prefs), { recursive: true }); + for (let pid = process.pid - 5; pid <= process.pid + 5; pid += 1) { + symlinkSync(join(outside, `planted-${pid}`), `${prefs}.${pid}.tmp`); + } + + recordPreference({ projectDir: project, key: "aspect", value: "16:9" }); + + // Opened without following a link, so a link left at the name would fail the open itself. + const fd = openSync(prefs, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); + try { + assert.ok(fstatSync(fd).isFile()); + assert.equal(JSON.parse(readFileSync(fd, "utf8")).preferences.aspect.value, "16:9"); + } finally { + closeSync(fd); + } + assert.equal(existsSync(join(outside, `planted-${process.pid}`)), false); + outsideUnchanged(); + }), +); diff --git a/packages/cli/src/media-use/lib/manifest.mjs b/packages/cli/src/media-use/lib/manifest.mjs index 72fa0f6f5c..dee46b397a 100644 --- a/packages/cli/src/media-use/lib/manifest.mjs +++ b/packages/cli/src/media-use/lib/manifest.mjs @@ -123,8 +123,12 @@ export function writeTempBeside(path, content) { try { writeFileSync(temp, content, { flag: "wx" }); } catch (error) { - // EEXIST: the random name belongs to another writer, so it is left alone. - if (error?.code !== "EEXIST") rmSync(temp, { force: true }); + // EEXIST: the random name belongs to another writer, so it is left alone. A failed cleanup must not hide `error`. + if (error?.code !== "EEXIST") { + try { + rmSync(temp, { force: true }); + } catch {} + } throw error; } return temp; @@ -309,7 +313,7 @@ export function withMediaLock(projectDir, fn) { export function allocateId(projectDir, type, ext) { ownTypeDir(projectDir, type); return withMediaLock(projectDir, () => { - const id = nextFreeId(projectDir, type); + const id = nextFreeId(projectDir, type, ext); const localPath = `.media/${typeSubdir(type)}/${id}${ext}`; // Same shape as core atomicTempPath: an empty file at the final name would be committed. const markerPath = `${join(projectDir, localPath)}.hf${randomBytes(3).toString("hex")}.tmp`; @@ -318,9 +322,10 @@ export function allocateId(projectDir, type, ext) { }); } -// Call under the lock: counts recorded ids and ids reserved by a file not yet recorded. -function nextFreeId(projectDir, type) { - const re = new RegExp(`^${type}_(\\d+)`); +// Call under the lock: counts recorded ids and ids reserved by a file not yet recorded. Ids past nine digits are +// ignored, so a planted huge id can't push the count past exact integers, and a name already taken is skipped. +function nextFreeId(projectDir, type, ext) { + const re = new RegExp(`^${type}_(\\d{1,9})(?!\\d)`); let max = 0; for (const r of readManifest(projectDir)) { if (r.type !== type) continue; @@ -332,7 +337,10 @@ function nextFreeId(projectDir, type) { const m = f.match(re); if (m) max = Math.max(max, parseInt(m[1], 10)); } - return `${type}_${String(max + 1).padStart(3, "0")}`; + const idFor = (n) => `${type}_${String(n).padStart(3, "0")}`; + let next = max + 1; + while (lstatSync(join(typeDir, `${idFor(next)}${ext}`), { throwIfNoEntry: false })) next += 1; + return idFor(next); } function reservedFile(projectDir, type, ext) { diff --git a/packages/cli/src/media-use/lib/prefs-store.mjs b/packages/cli/src/media-use/lib/prefs-store.mjs index 36f87d9eda..ac146c642c 100644 --- a/packages/cli/src/media-use/lib/prefs-store.mjs +++ b/packages/cli/src/media-use/lib/prefs-store.mjs @@ -1,8 +1,9 @@ -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; import * as fs from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { withFileLock } from "./config-lock.mjs"; import { globalMediaDir } from "./media-home.mjs"; +import { ownMediaDir, replaceFile } from "./manifest.mjs"; /** * Remembered defaults — the lightweight tier of HyperFrames user memory. @@ -70,17 +71,9 @@ function readPrefsFile(path) { } } -/** Atomic write (tmp + rename) so a crash never leaves a torn file. */ +/** Atomic write (a new temp file under a random name, then rename), so a crash never leaves a torn file. */ function writePrefsFile(path, file) { - const tmp = `${path}.${process.pid}.tmp`; - try { - writeFileSync(tmp, `${JSON.stringify(file, null, 2)}\n`); - renameSync(tmp, path); - } finally { - try { - fs.rmSync(tmp, { force: true }); - } catch {} - } + replaceFile(path, `${JSON.stringify(file, null, 2)}\n`); } function updatePrefsFile(path, update) { @@ -129,6 +122,7 @@ function dedupe(list) { * provenance over (the old confirmations vouched for the old value). */ function recordProjectTier(projectDir, fullKey, value, projectName, now) { + ownMediaDir(projectDir); return updatePrefsFile(projectPrefsPath(projectDir), (file) => { const previous = file.preferences[fullKey]; const keepProvenance = validEntry(previous) && previous.value === value; diff --git a/skills-manifest.json b/skills-manifest.json index 305e4066d3..61143030f9 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -18,7 +18,7 @@ "files": 13 }, "media-use": { - "hash": "57b04c9c7e313609", + "hash": "defe29366d34a42b", "files": 131 }, "remotion-to-hyperframes": { diff --git a/skills/media-use/scripts/lib/manifest.mjs b/skills/media-use/scripts/lib/manifest.mjs index 72fa0f6f5c..dee46b397a 100644 --- a/skills/media-use/scripts/lib/manifest.mjs +++ b/skills/media-use/scripts/lib/manifest.mjs @@ -123,8 +123,12 @@ export function writeTempBeside(path, content) { try { writeFileSync(temp, content, { flag: "wx" }); } catch (error) { - // EEXIST: the random name belongs to another writer, so it is left alone. - if (error?.code !== "EEXIST") rmSync(temp, { force: true }); + // EEXIST: the random name belongs to another writer, so it is left alone. A failed cleanup must not hide `error`. + if (error?.code !== "EEXIST") { + try { + rmSync(temp, { force: true }); + } catch {} + } throw error; } return temp; @@ -309,7 +313,7 @@ export function withMediaLock(projectDir, fn) { export function allocateId(projectDir, type, ext) { ownTypeDir(projectDir, type); return withMediaLock(projectDir, () => { - const id = nextFreeId(projectDir, type); + const id = nextFreeId(projectDir, type, ext); const localPath = `.media/${typeSubdir(type)}/${id}${ext}`; // Same shape as core atomicTempPath: an empty file at the final name would be committed. const markerPath = `${join(projectDir, localPath)}.hf${randomBytes(3).toString("hex")}.tmp`; @@ -318,9 +322,10 @@ export function allocateId(projectDir, type, ext) { }); } -// Call under the lock: counts recorded ids and ids reserved by a file not yet recorded. -function nextFreeId(projectDir, type) { - const re = new RegExp(`^${type}_(\\d+)`); +// Call under the lock: counts recorded ids and ids reserved by a file not yet recorded. Ids past nine digits are +// ignored, so a planted huge id can't push the count past exact integers, and a name already taken is skipped. +function nextFreeId(projectDir, type, ext) { + const re = new RegExp(`^${type}_(\\d{1,9})(?!\\d)`); let max = 0; for (const r of readManifest(projectDir)) { if (r.type !== type) continue; @@ -332,7 +337,10 @@ function nextFreeId(projectDir, type) { const m = f.match(re); if (m) max = Math.max(max, parseInt(m[1], 10)); } - return `${type}_${String(max + 1).padStart(3, "0")}`; + const idFor = (n) => `${type}_${String(n).padStart(3, "0")}`; + let next = max + 1; + while (lstatSync(join(typeDir, `${idFor(next)}${ext}`), { throwIfNoEntry: false })) next += 1; + return idFor(next); } function reservedFile(projectDir, type, ext) { diff --git a/skills/media-use/scripts/lib/prefs-store.mjs b/skills/media-use/scripts/lib/prefs-store.mjs index 36f87d9eda..ac146c642c 100644 --- a/skills/media-use/scripts/lib/prefs-store.mjs +++ b/skills/media-use/scripts/lib/prefs-store.mjs @@ -1,8 +1,9 @@ -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; import * as fs from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { withFileLock } from "./config-lock.mjs"; import { globalMediaDir } from "./media-home.mjs"; +import { ownMediaDir, replaceFile } from "./manifest.mjs"; /** * Remembered defaults — the lightweight tier of HyperFrames user memory. @@ -70,17 +71,9 @@ function readPrefsFile(path) { } } -/** Atomic write (tmp + rename) so a crash never leaves a torn file. */ +/** Atomic write (a new temp file under a random name, then rename), so a crash never leaves a torn file. */ function writePrefsFile(path, file) { - const tmp = `${path}.${process.pid}.tmp`; - try { - writeFileSync(tmp, `${JSON.stringify(file, null, 2)}\n`); - renameSync(tmp, path); - } finally { - try { - fs.rmSync(tmp, { force: true }); - } catch {} - } + replaceFile(path, `${JSON.stringify(file, null, 2)}\n`); } function updatePrefsFile(path, update) { @@ -129,6 +122,7 @@ function dedupe(list) { * provenance over (the old confirmations vouched for the old value). */ function recordProjectTier(projectDir, fullKey, value, projectName, now) { + ownMediaDir(projectDir); return updatePrefsFile(projectPrefsPath(projectDir), (file) => { const previous = file.preferences[fullKey]; const keepProvenance = validEntry(previous) && previous.value === value; From 28502224a57631af0894d9a6e2bb6cd9aa9449cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 02:04:37 +0000 Subject: [PATCH 066/367] fix(studio): show a sealed composition's clip on the timeline (#8408) * fix(studio): show a sealed composition's clip on the timeline * fix(studio): keep a sealed load's clip bound to its own preview and length * fix(studio): an older preview read never replaces a newer timeline * fix(studio): only the preview on screen writes the timeline * fix(studio): a removed preview frame's pending read writes nothing --- .../hooks/timelineSyncHydration.test.ts | 1 + .../src/player/hooks/timelineSyncHydration.ts | 48 ++- .../player/hooks/useShadowPreviewReload.ts | 2 + ...useTimelinePlayer.reloadedTimeline.test.ts | 1 + .../useTimelineSyncCallbacks.sealed.test.ts | 304 +++++++++++++++++- .../player/hooks/useTimelineSyncCallbacks.ts | 85 +++-- .../lib/sealedPreviewFrame.test-helpers.ts | 6 + .../studio/src/player/lib/timelineRevision.ts | 17 + 8 files changed, 421 insertions(+), 43 deletions(-) create mode 100644 packages/studio/src/player/lib/timelineRevision.ts diff --git a/packages/studio/src/player/hooks/timelineSyncHydration.test.ts b/packages/studio/src/player/hooks/timelineSyncHydration.test.ts index 23e6180739..cf7cd85df6 100644 --- a/packages/studio/src/player/hooks/timelineSyncHydration.test.ts +++ b/packages/studio/src/player/hooks/timelineSyncHydration.test.ts @@ -156,6 +156,7 @@ describe("hydrateTimelineFromPreview", () => { iframe, adapter: { getDuration: () => 1 } as unknown as PlaybackAdapter, processTimelineMessage: vi.fn(), + readSealedTimeline: vi.fn(), enrichMissingCompositions: vi.fn(), applyPreviewAudioState: vi.fn(), attachIframeShortcutListeners, diff --git a/packages/studio/src/player/hooks/timelineSyncHydration.ts b/packages/studio/src/player/hooks/timelineSyncHydration.ts index 75cb76bb7f..d8666afb24 100644 --- a/packages/studio/src/player/hooks/timelineSyncHydration.ts +++ b/packages/studio/src/player/hooks/timelineSyncHydration.ts @@ -30,6 +30,7 @@ import { normalizePreviewViewport, } from "../lib/timelineIframeHelpers"; import { inspectStudioRuntimeMessage } from "../lib/runtimeProtocol"; +import { previewClipManifest, previewFrameOpaque } from "../lib/previewChannel"; /** Reject non-finite, non-positive, and absurdly large (loop-inflated) values. */ export function sanitizeDurationSeconds(value: number): number { @@ -342,19 +343,15 @@ export function syncAdapterDuration( * Without it a composition the runtime never enumerated shows an empty timeline * rather than one row spanning its own duration. */ -function syncFallbackTimelineFromDom( +export function fallbackTimelineFromDom( doc: Document, iframe: HTMLIFrameElement | null, rootDuration: number, - syncTimelineElements: (els: TimelineElement[], duration?: number) => void, -): void { +): TimelineElement[] { const els = parseTimelineFromDOM(doc, rootDuration); - if (els.length > 0) { - syncTimelineElements(els); - return; - } + if (els.length > 0) return els; const rootComp = doc.querySelector("[data-composition-id]"); - if (!rootComp || rootDuration <= 0) return; + if (!rootComp || rootDuration <= 0) return []; const fallbackElement = buildStandaloneRootTimelineElement({ compositionId: rootComp.getAttribute("data-composition-id") || "composition", tagName: (rootComp as HTMLElement).tagName || "div", @@ -362,7 +359,7 @@ function syncFallbackTimelineFromDom( iframeSrc: iframe?.src || "", selector: getTimelineElementSelector(rootComp), }); - if (fallbackElement) syncTimelineElements([fallbackElement]); + return fallbackElement ? [fallbackElement] : []; } /** The runtime's timeline message, as the preview posts it. */ @@ -400,10 +397,18 @@ export function isPreviewReadinessMessage( return inspectStudioRuntimeMessage(data).status !== "unsupported"; } +/** Reads a sealed frame's rows for a clip list still on its way; `null` from it commits nothing. */ +export type SealedTimelineRead = ( + iframe: HTMLIFrameElement, + manifest: Promise, + previewDuration: number, +) => void; + export interface HydrateTimelineFromPreviewInput { iframe: HTMLIFrameElement | null; adapter: PlaybackAdapter; processTimelineMessage: (manifest: RuntimeTimelineMessage) => void; + readSealedTimeline: SealedTimelineRead; enrichMissingCompositions: () => void; applyPreviewAudioState: () => void; attachIframeShortcutListeners: () => void; @@ -426,12 +431,20 @@ function normalizePreviewDom(doc: Document | null, iframeWin: IframeWindow | nul } /** Hand the runtime's own clip manifest to the timeline, if it published one. */ -function applyRuntimeClipManifest( - iframeWin: IframeWindow | null, - processTimelineMessage: (manifest: RuntimeTimelineMessage) => void, -): void { - const manifest = iframeWin?.__clipManifest; - if (manifest && manifest.clips.length > 0) processTimelineMessage(manifest); +function applyRuntimeClipManifest(input: HydrateTimelineFromPreviewInput): void { + const { iframe, adapter } = input; + if (iframe && previewFrameOpaque(iframe)) { + // The frame's own clip list decides, empty included; with none posted yet, only an empty timeline falls back. + const manifest = previewClipManifest(iframe).then((found) => + found || usePlayerStore.getState().elements.length > 0 + ? found + : { clips: [], durationInFrames: 0 }, + ); + input.readSealedTimeline(iframe, manifest, adapter.getDuration()); + return; + } + const manifest = (iframe?.contentWindow as IframeWindow | null)?.__clipManifest; + if (manifest) input.processTimelineMessage(manifest); } export function hydrateTimelineFromPreview(input: HydrateTimelineFromPreviewInput): void { @@ -441,11 +454,12 @@ export function hydrateTimelineFromPreview(input: HydrateTimelineFromPreviewInpu const iframeWin = (iframe?.contentWindow as IframeWindow | null) ?? null; normalizePreviewDom(doc, iframeWin); input.attachIframeShortcutListeners(); - applyRuntimeClipManifest(iframeWin, input.processTimelineMessage); + applyRuntimeClipManifest(input); input.enrichMissingCompositions(); input.applyPreviewAudioState(); if (doc && usePlayerStore.getState().elements.length === 0) { - syncFallbackTimelineFromDom(doc, iframe, adapter.getDuration(), syncTimelineElements); + const els = fallbackTimelineFromDom(doc, iframe, adapter.getDuration()); + if (els.length > 0) syncTimelineElements(els); } } catch { // Cross-origin or mid-navigation preview — the adapter is still initialised. diff --git a/packages/studio/src/player/hooks/useShadowPreviewReload.ts b/packages/studio/src/player/hooks/useShadowPreviewReload.ts index 392084238e..956a98f01e 100644 --- a/packages/studio/src/player/hooks/useShadowPreviewReload.ts +++ b/packages/studio/src/player/hooks/useShadowPreviewReload.ts @@ -336,6 +336,7 @@ export function useShadowPreviewReload({ const getShadowAdapter = useCallback(() => getAdapter(shadowIframeRef.current), [getAdapter]); const isCurrentShadow = useCallback((gen?: number) => gen === shadowGenRef.current, []); + const liveFrame = useCallback(() => iframeRef.current, [iframeRef]); const previewGeneration = useCallback(() => shadowGenRef.current, []); const markAdapterReady = useCallback( (iframe: HTMLIFrameElement | null, gen: number | undefined, commit: () => void) => { @@ -370,6 +371,7 @@ export function useShadowPreviewReload({ onAdapterReady: markAdapterReady, isCurrent: isCurrentShadow, hostOwnsDeadline: true, + liveFrame, }); cancelPendingLoadRef.current = cancelPendingLoad; diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.reloadedTimeline.test.ts b/packages/studio/src/player/hooks/useTimelinePlayer.reloadedTimeline.test.ts index 7dd6c14583..9d122cc16a 100644 --- a/packages/studio/src/player/hooks/useTimelinePlayer.reloadedTimeline.test.ts +++ b/packages/studio/src/player/hooks/useTimelinePlayer.reloadedTimeline.test.ts @@ -42,6 +42,7 @@ function reloadedFilm() { const { win } = makeAdapterWindow({ duration: 2 }); const frame = win as unknown as Record; const iframe = detachedFakeIframe(frame); + Object.defineProperty(iframe, "isConnected", { value: true }); iframe.contentDocument!.body.innerHTML = FILM; frame.__clipManifest = RELOADED; const markup = { diff --git a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts index 3c616bcd43..5e37174470 100644 --- a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts +++ b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts @@ -4,8 +4,11 @@ import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, expect, it, onTestFinished, vi } from "vitest"; import { usePlayerStore, type TimelineElement } from "../store/playerStore"; +import type { PlaybackAdapter } from "../lib/playbackTypes"; import { useTimelineSyncCallbacks } from "./useTimelineSyncCallbacks"; import { sealedPreviewFrame } from "../lib/sealedPreviewFrame.test-helpers"; +import { previewClipParents, previewDocumentCopy } from "../lib/previewChannel"; +import { detachedFakeIframe } from "./timelinePlayerTestHarness"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -13,16 +16,22 @@ afterEach(() => { document.body.innerHTML = ""; }); -function processWith(iframe: HTMLIFrameElement) { - const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>(); +function processWith( + iframe: HTMLIFrameElement, + adapter: PlaybackAdapter | null = null, + isCurrent?: () => boolean, + sync = vi.fn<(els: TimelineElement[], duration?: number) => void>(), + liveFrame?: () => HTMLIFrameElement | null, +) { let callbacks: ReturnType | undefined; + const iframeRef: { current: HTMLIFrameElement | null } = { current: iframe }; function Harness() { callbacks = useTimelineSyncCallbacks({ - iframeRef: { current: iframe }, + iframeRef, probeIntervalRef: { current: undefined }, pendingSeekRef: { current: null }, isRefreshingRef: { current: false }, - getAdapter: () => null, + getAdapter: () => adapter, syncTimelineElements: sync, setDuration: () => {}, setCurrentTime: () => {}, @@ -30,12 +39,22 @@ function processWith(iframe: HTMLIFrameElement) { setIsPlaying: () => {}, attachIframeShortcutListeners: () => {}, applyPreviewAudioState: () => {}, + onAdapterReady: (_iframe, _context, commit) => commit(), + isCurrent, + liveFrame, }); return null; } const host = document.createElement("div"); act(() => createRoot(host).render(createElement(Harness))); - return { sync, process: callbacks!.processTimelineMessage }; + const { processTimelineMessage, initializeAdapter, onIframeLoad } = callbacks!; + return { + sync, + iframeRef, + process: processTimelineMessage, + initialize: () => act(() => initializeAdapter()), + load: () => act(() => onIframeLoad()), + }; } const boxClip = { @@ -104,3 +123,278 @@ it("fills a sealed scene's children and the runtime's clip parents", async () => await vi.waitFor(() => expect(usePlayerStore.getState().clipParentMap.get("cue")).toBe("scene")); expect(usePlayerStore.getState().domClipChildren.map((child) => child.id)).toContain("title"); }); + +const rootOnly = `
+

Scene 6

+
`; + +const adapterOf = (duration: number): PlaybackAdapter => ({ + pause() {}, + seek() {}, + play() {}, + getTime: () => 0, + getDuration: () => duration, + isPlaying: () => false, +}); + +function rootRow(sync: ReturnType["sync"]) { + return sync.mock.calls.at(-1)?.[0].map((row) => `${row.id}@${row.start}+${row.duration}`); +} + +// fails without the fix: an empty clip list from a sealed frame committed no rows, so the composition had no clip. +it("shows a sealed composition the runtime lists no clips for as its own row", async () => { + document.body.innerHTML = rootOnly; + const { sync, process } = processWith(sealedPreviewFrame().iframe); + + process({ clips: [], durationInFrames: 0 }); + + await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"])); +}); + +// fails without the fix: reading the sealed frame's manifest threw, so loading it ended with no clip. +it("gives a sealed composition its row when the preview loads", async () => { + document.body.innerHTML = rootOnly; + usePlayerStore.getState().setElements([]); + const { sync, initialize } = processWith(sealedPreviewFrame().iframe, adapterOf(5)); + + initialize(); + + await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"])); +}); + +// fails without the fix: the reply was read against the frame ref, which a shadow promotion has already cleared. +it("keeps a sealed load's row when its frame is promoted before the reply", async () => { + document.body.innerHTML = rootOnly; + usePlayerStore.getState().setElements([]); + const promoted = sealedPreviewFrame().iframe; + // The shadow's own ref lets go at promotion; the live ref, the one on screen, now holds its frame. + const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>(); + const shadow = processWith( + promoted, + adapterOf(5), + () => true, + sync, + () => promoted, + ); + + shadow.initialize(); + shadow.iframeRef.current = null; + + await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"])); +}); + +// fails without the fix: the previous preview's late reply replaced the rows of the preview loaded after it. +it("drops a sealed load's reply that arrives after the next preview loaded", async () => { + document.body.innerHTML = rootOnly; + (window as unknown as { __clipManifest: unknown }).__clipManifest = { + clips: [{ ...boxClip, id: "stale" }], + durationInFrames: 60, + }; + onTestFinished(() => delete (window as unknown as { __clipManifest?: unknown }).__clipManifest); + usePlayerStore.getState().setElements([]); + const sealed = sealedPreviewFrame().iframe; + const { sync, iframeRef, initialize, load } = processWith(sealed, adapterOf(5)); + initialize(); + + iframeRef.current = detachedFakeIframe({ + __clipManifest: { clips: [{ ...boxClip, id: "next" }], durationInFrames: 60 }, + scrollTo() {}, + }); + load(); + // The channel answers in order: once a later request is back, the first load's reply has landed too. + await previewDocumentCopy(sealed); + await previewClipParents(sealed); + + expect(sync.mock.calls.flatMap(([rows]) => rows.map((row) => row.id))).not.toContain("stale"); + expect(rootRow(sync)).toEqual(["next@0+2"]); +}); + +// fails without the fix: the row took the frame-rounded total, 151 frames, instead of the authored 5.01 s. +it("gives a composition's own row its authored length, not the frame-rounded total", async () => { + document.body.innerHTML = rootOnly.replace('data-duration="5"', 'data-duration="5.01"'); + const { sync, process } = processWith(sealedPreviewFrame().iframe); + + process({ clips: [], durationInFrames: 151 }); + + await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5.01"])); +}); + +// fails without the fix: with no clip list and no authored length, the preview's own duration was ignored. +it("gives a sealed composition with no authored length the preview's duration", async () => { + document.body.innerHTML = rootOnly.replace(' data-duration="5"', ""); + usePlayerStore.getState().setElements([]); + const { sync, initialize } = processWith(sealedPreviewFrame().iframe, adapterOf(4)); + + initialize(); + + await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+4"])); +}); + +/** Studio's end of the port, holding the frame's replies until released, newest first: an older read lands last. */ +function heldReplies() { + const queue: MessageEvent[] = []; + let holding = false; + let deliver: ((event: MessageEvent) => void) | null = null; + const wrap = (port: MessagePort) => + ({ + postMessage: (data: unknown) => port.postMessage(data), + start: () => port.start(), + close: () => port.close(), + get onmessage() { + return port.onmessage; + }, + set onmessage(listener: ((event: MessageEvent) => void) | null) { + deliver = listener; + port.onmessage = listener && ((event) => (holding ? queue.push(event) : listener(event))); + }, + }) as unknown as MessagePort; + const releaseNewestFirst = () => { + holding = false; + for (const event of queue.splice(0).reverse()) deliver?.(event); + }; + return { wrap, hold: () => (holding = true), held: () => queue.length, releaseNewestFirst }; +} + +// fails without the fix: an empty clip list was dropped while the timeline held rows, so a deleted clip stayed. +it("replaces the timeline's rows when a sealed load's own clip list is empty", async () => { + document.body.innerHTML = rootOnly; + (window as unknown as { __clipManifest: unknown }).__clipManifest = { + clips: [], + durationInFrames: 0, + }; + onTestFinished(() => delete (window as unknown as { __clipManifest?: unknown }).__clipManifest); + usePlayerStore + .getState() + .setElements([{ id: "deleted", start: 0, duration: 2 } as TimelineElement]); + const { sync, initialize } = processWith(sealedPreviewFrame().iframe, adapterOf(5)); + + initialize(); + + await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"])); +}); + +// fails without the fix: the shadow's and the live hook's reads were ordered apart, so the older one landed last. +it("keeps a newer clip list over a promotion's read that answers after it", async () => { + document.body.innerHTML = `
+
+
`; + (window as unknown as { __clipManifest: unknown }).__clipManifest = { + clips: [{ ...boxClip, id: "old" }], + durationInFrames: 60, + }; + onTestFinished(() => delete (window as unknown as { __clipManifest?: unknown }).__clipManifest); + const replies = heldReplies(); + const frame = sealedPreviewFrame({ wrapHandedOverPort: replies.wrap }).iframe; + await previewDocumentCopy(frame); + const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>(); + const shadow = processWith(frame, adapterOf(2), () => true, sync); + const live = processWith(frame, adapterOf(2), undefined, sync); + + replies.hold(); + shadow.initialize(); + live.process({ clips: [{ ...boxClip, id: "fresh" }], durationInFrames: 60 }); + // The promotion's clip list, copy and tree, then the live message's copy and tree. + await vi.waitFor(() => expect(replies.held()).toBe(5)); + replies.releaseNewestFirst(); + await vi.waitFor(() => expect(sync).toHaveBeenCalled()); + await previewDocumentCopy(frame); + + expect(rootRow(sync)).toEqual(["fresh@0+2"]); +}); + +// fails without the fix: the row took the preview's 4 s, then the empty list's default total clamped it to 1 s. +it("keeps a sealed root row at the preview's length over an empty list's default total", async () => { + document.body.innerHTML = rootOnly.replace(' data-duration="5"', ""); + const { sync, process } = processWith(sealedPreviewFrame().iframe, adapterOf(4)); + + process({ clips: [], durationInFrames: 30 }); + + await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+4"])); +}); + +// fails without the fix: a replaced frame's reply still landed until the replacement's load callback ran. +it("drops a reply from a frame once another is on screen, before that one loads", async () => { + document.body.innerHTML = `
`; + const replaced = sealedPreviewFrame().iframe; + const { sync, iframeRef, process } = processWith(replaced, adapterOf(2)); + + process({ clips: [{ ...boxClip, id: "stale" }], durationInFrames: 60 }); + iframeRef.current = detachedFakeIframe({ scrollTo() {} }); + await previewDocumentCopy(replaced); + await previewClipParents(replaced); + + expect(sync).not.toHaveBeenCalled(); +}); + +// fails without the fix: the hidden reload's load cancelled the on-screen frame's read, so its rows never came. +it("keeps the on-screen frame's read when a hidden reload starts loading", async () => { + document.body.innerHTML = `
`; + const onScreen = sealedPreviewFrame().iframe; + const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>(); + const live = processWith(onScreen, adapterOf(2), undefined, sync); + const hidden = processWith( + detachedFakeIframe({ scrollTo() {} }), + null, + () => true, + sync, + () => live.iframeRef.current, + ); + + live.process({ clips: [{ ...boxClip, id: "fresh" }], durationInFrames: 60 }); + hidden.load(); + + await vi.waitFor(() => expect(rootRow(sync)).toEqual(["fresh@0+2"])); +}); + +// fails without the fix: Studio left the player while the read was out, and its old rows still landed. +it("drops a sealed read whose frame its player removed before the reply", async () => { + document.body.innerHTML = `
`; + (window as unknown as { __clipManifest: unknown }).__clipManifest = { + clips: [{ ...boxClip, id: "old" }], + durationInFrames: 60, + }; + onTestFinished(() => delete (window as unknown as { __clipManifest?: unknown }).__clipManifest); + const replies = heldReplies(); + const promoted = sealedPreviewFrame({ wrapHandedOverPort: replies.wrap }).iframe; + await previewDocumentCopy(promoted); + const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>(); + const shadow = processWith( + promoted, + adapterOf(2), + () => true, + sync, + () => promoted, + ); + + replies.hold(); + shadow.initialize(); + await vi.waitFor(() => expect(replies.held()).toBe(3)); + promoted.remove(); + replies.releaseNewestFirst(); + await previewDocumentCopy(promoted); + + expect(sync).not.toHaveBeenCalled(); +}); + +// Pins the promotion path: the retiring live Player's removal must not take the promoted frame's read with it. +it("lands a promoted frame's read after the old live player is removed", async () => { + document.body.innerHTML = rootOnly; + usePlayerStore.getState().setElements([]); + const retiring = sealedPreviewFrame().iframe; + const promoted = sealedPreviewFrame().iframe; + const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>(); + const live = processWith(retiring, adapterOf(5), undefined, sync); + const shadow = processWith( + promoted, + adapterOf(5), + () => true, + sync, + () => live.iframeRef.current, + ); + + live.iframeRef.current = promoted; + shadow.initialize(); + retiring.remove(); + + await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"])); +}); diff --git a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts index 790ea71e29..3c91d25303 100644 --- a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts +++ b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts @@ -19,6 +19,7 @@ import { previewClipParents, previewDocumentCopy, previewFrameOpaque } from "../ import { useLinkedClipPreferences } from "../../utils/linkedClipPreferences"; import { buildTimelineElementsFromClips, + fallbackTimelineFromDom, syncManifestTimeline, clipTreeParentMap, collectSubCompositionDomChildren, @@ -30,7 +31,13 @@ import { seekAdapterToRestorePoint, syncAdapterDuration, type RuntimeTimelineMessage, + type SealedTimelineRead, } from "./timelineSyncHydration"; +import { + landTimelineRevision, + nextTimelineRevision, + supersedeTimelineReads, +} from "../lib/timelineRevision"; // Re-exported for the tests and callers that have always imported it from here. export { resolveReloadSeekTime } from "./timelineSyncHydration"; @@ -62,6 +69,8 @@ export interface UseTimelineSyncCallbacksParams { /** Fires when no adapter appeared within the wait window. */ onLoadGiveUp?: (context?: number) => void; hostOwnsDeadline?: boolean; + /** The frame on screen, when it is not this hook's own (a shadow, hidden until promoted). */ + liveFrame?: () => HTMLIFrameElement | null; } /** @@ -179,10 +188,25 @@ export function useTimelineSyncCallbacks({ isCurrent, onLoadGiveUp, hostOwnsDeadline, + liveFrame, }: UseTimelineSyncCallbacksParams) { + const onScreen = useCallback( + () => (liveFrame ? liveFrame() : iframeRef.current), + [liveFrame, iframeRef], + ); // Convert a runtime timeline message (from iframe postMessage) into TimelineElements const applyTimelineMessage = useCallback( - (data: RuntimeTimelineMessage, iframeDoc: Document | null, parentMap: Map) => { + ( + data: RuntimeTimelineMessage, + iframeDoc: Document | null, + parentMap: Map, + iframe: HTMLIFrameElement | null, + previewDuration: number, + revision: number, + ) => { + // A read lands only from the frame on screen, and only over nothing newer. + if (iframe !== onScreen() || !landTimelineRevision(revision)) return; + usePlayerStore.getState().setClipManifest(data.clips); // Show root-level clips: no parentCompositionId, OR parent is a "phantom wrapper" const clipCompositionIds = new Set(data.clips.map((c) => c.compositionId).filter(Boolean)); const filtered = data.clips.filter( @@ -199,7 +223,6 @@ export function useTimelineSyncCallbacks({ // A document the walk cannot read leaves the maps empty. } - const els = buildTimelineElementsFromClips(filtered, iframeDoc); // Clamp non-finite or absurdly large durations — the runtime can emit // Infinity when it detects a loop-inflated GSAP timeline without an // explicit data-duration on the root composition. Floor the manifest total @@ -212,36 +235,52 @@ export function useTimelineSyncCallbacks({ manifestDurationSeconds: data.durationInFrames / fps, authoredRootDurationSeconds: readTimelineDurationFromDocument(iframeDoc), }); + // The composition's own row keeps its exact length; the transport total is frame-rounded. + const ownDuration = + sanitizeDurationSeconds(readTimelineDurationFromDocument(iframeDoc)) || + sanitizeDurationSeconds(previewDuration) || + newDuration; + const fallback = data.clips.length === 0 && iframeDoc !== null; + const els = fallback + ? fallbackTimelineFromDom(iframeDoc, iframe, ownDuration) + : buildTimelineElementsFromClips(filtered, iframeDoc); syncManifestTimeline( els, - newDuration, + fallback ? Math.max(newDuration, ownDuration) : newDuration, usePlayerStore.getState().duration, syncTimelineElements, ); }, - [syncTimelineElements], + [onScreen, syncTimelineElements], ); - const timelineReads = useRef(0); - const processTimelineMessage = useCallback( - (data: RuntimeTimelineMessage) => { - if (!data.clips) return; - usePlayerStore.getState().setClipManifest(data.clips); - const iframe = iframeRef.current; - const read = ++timelineReads.current; - if (!iframe || !previewFrameOpaque(iframe)) { - applyTimelineMessage(data, safeContentDocument(iframe), openClipParents(iframe)); - return; - } - // A sealed frame's rows bind to its document copy and clip tree from the editing port; the newest read wins. - void Promise.all([previewDocumentCopy(iframe), previewClipParents(iframe)]).then( - ([doc, parents]) => { - if (read === timelineReads.current && iframeRef.current === iframe) - applyTimelineMessage(data, doc, parents); + // A sealed frame's rows bind to its document copy and clip tree from the editing port. + const readSealedTimeline = useCallback( + (iframe, manifest, previewDuration) => { + const revision = nextTimelineRevision(); + void Promise.all([manifest, previewDocumentCopy(iframe), previewClipParents(iframe)]).then( + ([data, doc, parents]) => { + // A frame its player removed is gone: callback refs keep it (promotion repoints them), the page does not. + if (data && iframe.isConnected) + applyTimelineMessage(data, doc, parents, iframe, previewDuration, revision); }, ); }, - [iframeRef, applyTimelineMessage], + [applyTimelineMessage], + ); + + const processTimelineMessage = useCallback( + (data: RuntimeTimelineMessage) => { + if (!data.clips) return; + const iframe = iframeRef.current; + const previewDuration = getAdapter()?.getDuration() ?? 0; + if (iframe && previewFrameOpaque(iframe)) + return readSealedTimeline(iframe, Promise.resolve(data), previewDuration); + const doc = safeContentDocument(iframe); + const parents = openClipParents(iframe); + applyTimelineMessage(data, doc, parents, iframe, previewDuration, nextTimelineRevision()); + }, + [iframeRef, getAdapter, readSealedTimeline, applyTimelineMessage], ); const enrichMissingCompositions = useCallback(() => { @@ -296,6 +335,7 @@ export function useTimelineSyncCallbacks({ iframe: iframeRef.current, adapter, processTimelineMessage, + readSealedTimeline, enrichMissingCompositions, applyPreviewAudioState, attachIframeShortcutListeners, @@ -312,6 +352,7 @@ export function useTimelineSyncCallbacks({ requestTimelineReady, setIsPlaying, processTimelineMessage, + readSealedTimeline, enrichMissingCompositions, syncTimelineElements, attachIframeShortcutListeners, @@ -329,6 +370,7 @@ export function useTimelineSyncCallbacks({ const onIframeLoad = useCallback( (context?: number) => { + if (onScreen() === iframeRef.current) supersedeTimelineReads(); const loadedDoc = safeContentDocument(iframeRef.current); if (loadedDoc) usePlayerStore.getState().markPreviewLoadStep(loadedDoc); applyPreviewAudioState(); @@ -385,6 +427,7 @@ export function useTimelineSyncCallbacks({ applyPreviewAudioState, onLoadGiveUp, hostOwnsDeadline, + onScreen, ], ); diff --git a/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts b/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts index 55080fd24e..8b095e6c7d 100644 --- a/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts +++ b/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts @@ -26,6 +26,12 @@ export function sealedPreviewFrame( }); const iframe = detachedFakeIframe(frame); Object.defineProperty(iframe, "contentDocument", { value: null }); + let onPageUntilPlayerRemovesIt = true; + Object.defineProperty(iframe, "isConnected", { + configurable: true, + get: () => onPageUntilPlayerRemovesIt, + }); + iframe.remove = () => void (onPageUntilPlayerRemovesIt = false); const wrap = options.wrapHandedOverPort ?? ((port: MessagePort) => port); const parent = { postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => diff --git a/packages/studio/src/player/lib/timelineRevision.ts b/packages/studio/src/player/lib/timelineRevision.ts new file mode 100644 index 0000000000..ea772c4e8b --- /dev/null +++ b/packages/studio/src/player/lib/timelineRevision.ts @@ -0,0 +1,17 @@ +// An older preview read never replaces a newer one on the timeline, whichever frame or hook it came through. +let issued = 0; +let landed = 0; + +export function nextTimelineRevision(): number { + return ++issued; +} + +export function landTimelineRevision(revision: number): boolean { + if (revision < landed) return false; + landed = revision; + return true; +} + +export function supersedeTimelineReads(): void { + landed = ++issued; +} From 8ad7cbae247661d38638e0b4ae0569288ab1ffa5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 02:04:39 +0000 Subject: [PATCH 067/367] fix(studio): a reload that gives up says whether its frame was missing, blank or unreadable (#8419) * fix(studio): a reload that gives up says whether its frame was missing, blank or unreadable A shadow reload that times out with no page used to say "no-page" for three different stalls. It now says no-frame (none added, or gone), blank (added, still about:blank) or unreadable (added, document not readable), and for the last two whether the frame was given a page address and how long ago it was added. * refactor(studio): the frame's added time lives beside the give-up message * fix(studio): a sealed preview's give-up names its step as sealed --- .../player/hooks/useShadowPreviewReload.ts | 19 ++++++-- .../useTimelinePlayer.shadowReload.test.ts | 46 +++++++++++++++++-- 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/packages/studio/src/player/hooks/useShadowPreviewReload.ts b/packages/studio/src/player/hooks/useShadowPreviewReload.ts index 956a98f01e..848dcf511a 100644 --- a/packages/studio/src/player/hooks/useShadowPreviewReload.ts +++ b/packages/studio/src/player/hooks/useShadowPreviewReload.ts @@ -75,8 +75,10 @@ function shadowPlayerReachable(iframe: HTMLIFrameElement | null): boolean { } function shadowPagePhase(iframe: HTMLIFrameElement | null): string { - const doc = iframe?.contentDocument; - if (!doc || doc.URL === "about:blank") return "no-page"; + const doc = iframe?.isConnected ? iframe.contentDocument : undefined; + if (doc === undefined) return "no-frame"; + if (!doc) return "unreadable"; + if (doc.URL === "about:blank") return "blank"; const win = iframe!.contentWindow as unknown as Record; if (doc.readyState === "loading") return "page-loading"; if (win.__hfStartupError) return "startup-error"; @@ -85,8 +87,14 @@ function shadowPagePhase(iframe: HTMLIFrameElement | null): string { return "no-player"; } -const pageGotTo = (iframe: HTMLIFrameElement | null) => - shadowPlayerReachable(iframe) ? "" : ` Its page had got to: ${shadowPagePhase(iframe)}.`; +const frameAddedAt = new WeakMap(); +function pageGotTo(iframe: HTMLIFrameElement | null): string { + const phase = shadowPlayerReachable(iframe) ? null : shadowPagePhase(iframe); + if (phase !== "blank" && phase !== "unreadable") + return phase ? ` Its page had got to: ${phase}.` : ""; + const given = /^(about:blank)?$/.test(iframe!.getAttribute("src") ?? "") ? "was never" : "was"; + return ` Its page had got to: ${phase}. Its frame ${given} given a page address and was added ${Date.now() - frameAddedAt.get(iframe!)!} ms ago.`; +} function hyperframesPlayerOf(iframe: HTMLIFrameElement): Element | null { const root = iframe.getRootNode(); @@ -220,7 +228,7 @@ export function useShadowPreviewReload({ : sealed ? "its runtime to report a timeline" : "its timeline to be ready"; - const got = sealed ? "" : pageGotTo(shadow); + const got = sealed ? " Its page had got to: sealed." : pageGotTo(shadow); shadowGenRef.current += 1; const failedGen = shadowGenRef.current; stopPendingShadow(); @@ -424,6 +432,7 @@ export function useShadowPreviewReload({ const setShadowIframeNode = useCallback((node: HTMLIFrameElement | null) => { shadowIframeRef.current = node; + if (node) frameAddedAt.set(node, Date.now()); if (node) hyperframesPlayerOf(node)?.toggleAttribute("inert", true); const gen = budgetGenRef.current; if (!node || !shadowFrameLeftPageRef.current || gen == null || gen !== shadowGenRef.current) diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.shadowReload.test.ts b/packages/studio/src/player/hooks/useTimelinePlayer.shadowReload.test.ts index 0973d01d2f..e17efc4854 100644 --- a/packages/studio/src/player/hooks/useTimelinePlayer.shadowReload.test.ts +++ b/packages/studio/src/player/hooks/useTimelinePlayer.shadowReload.test.ts @@ -429,7 +429,8 @@ describe("shadow reload readiness and failure", () => { const loaded = { URL: "http://127.0.0.1/preview", readyState: "complete" }; it.each([ - ["no-page", {}, { ...loaded, URL: "about:blank" }], + ["blank", {}, { ...loaded, URL: "about:blank" }], + ["unreadable", {}, null], ["page-loading", {}, { ...loaded, readyState: "loading" }], ["startup-error", { __hfStartupError: "failed", __hyperframes: {} }, loaded], ["runtime-not-run", {}, loaded], @@ -457,6 +458,44 @@ describe("shadow reload readiness and failure", () => { }, ); + it("says no frame was there when a shadow gives up before its frame is added", () => { + vi.useFakeTimers(); + vi.spyOn(console, "error").mockImplementation(() => {}); + const onPreviewReloadFailed = vi.fn(); + const { root } = beginReload({ onPreviewReloadFailed }); + act(() => void vi.advanceTimersByTime(FULL_WAIT_MS)); + const [message] = onPreviewReloadFailed.mock.calls[0]!; + expect(message).toContain("Its page had got to: no-frame."); + expect(message).not.toContain("Its frame"); + unmount(root); + }); + + it.each([ + ["/api/projects/demo/preview", "was given"], + [null, "was never given"], + ])( + "says whether a blank shadow frame was given a page address (%s) and when it was added", + (src, given) => { + vi.useFakeTimers(); + vi.spyOn(console, "error").mockImplementation(() => {}); + const onPreviewReloadFailed = vi.fn(); + const { getApi, root } = beginReload({ onPreviewReloadFailed }); + act(() => void vi.advanceTimersByTime(1000)); + const shadow = makeFakeIframe({}); + if (src) shadow.setAttribute("src", src); + Object.defineProperty(shadow, "contentDocument", { + value: { ...loaded, URL: "about:blank" }, + }); + act(() => getApi().setShadowIframeNode(shadow)); + act(() => void vi.advanceTimersByTime(FULL_WAIT_MS)); + const [message] = onPreviewReloadFailed.mock.calls[0]!; + expect(message).toContain( + `Its page had got to: blank. Its frame ${given} a page address and was added ${FULL_WAIT_MS - 1000} ms ago.`, + ); + unmount(root); + }, + ); + it("names the timeline when a shadow's runtime runs but never reports a length", () => { vi.useFakeTimers(); vi.spyOn(console, "error").mockImplementation(() => {}); @@ -478,7 +517,7 @@ describe("shadow reload readiness and failure", () => { }); // fails without the fix: a sealed shadow refuses every read, so it was always reported as a page that never loaded. - it("says only what a sealed shadow reported when it fails to reload", () => { + it("names a sealed shadow's step as sealed, without reading its page, when it fails to reload", () => { vi.useFakeTimers(); vi.spyOn(console, "error").mockImplementation(() => {}); const onPreviewReloadFailed = vi.fn(); @@ -494,7 +533,8 @@ describe("shadow reload readiness and failure", () => { const [message] = onPreviewReloadFailed.mock.calls[0]!; expect(message).toContain("still waiting for its runtime to report a timeline"); - expect(message).not.toContain("Its page had got to"); + expect(message).toContain("Its page had got to: sealed."); + expect(message).not.toContain("Its frame"); unmount(root); }); From 925cea1f1f59bfde0d507c3575791f77a775939f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 02:04:41 +0000 Subject: [PATCH 068/367] fix(studio): a refused delete also refuses the ripple shifts queued behind it (#8421) * fix(studio): a refused delete no longer brings back another delete still saving A refused delete, or a ripple shift that fails after its delete, now moves back only the clips that delete shifted, on the timeline as it is now, instead of restoring the timeline from before it. * fix(studio): a refused delete also refuses the ripple shifts queued behind it A delete's ripple shift saves absolute starts worked out with every earlier pending delete applied. When one of those is refused, the shifts queued behind it are refused too and leave their gap, so the saved file never puts a clip on top of the restored one. --- .../src/hooks/useTimelineDeleteOps.test.tsx | 51 ++++++++++++------- .../studio/src/hooks/useTimelineDeleteOps.ts | 12 ++++- 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx index e7743774f7..5b6321fb1e 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -144,8 +144,9 @@ describe("useTimelineDeleteOps: ripple undo label", () => { }); // Deletes hf-a, then hf-b once hf-a's ripple slid it to 0, both saving through one edit queue. - async function deleteTwoInARow(refused?: string) { + async function deleteTwoInARow(refuseOnce?: string) { const writes: string[] = []; + let refused = refuseOnce; vi.stubGlobal( "fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { @@ -153,7 +154,10 @@ describe("useTimelineDeleteOps: ripple undo label", () => { const { targets } = JSON.parse(String(init?.body)) as { targets: Array<{ id: string }> }; const write = `delete ${targets.map((t) => t.id).join(",")}`; writes.push(write); - if (write === refused) return new Response("{}", { status: 500 }); + if (write === refused) { + refused = undefined; + return new Response("{}", { status: 500 }); + } } return new Response(JSON.stringify({ content: html }), { status: 200 }); }), @@ -168,9 +172,12 @@ describe("useTimelineDeleteOps: ripple undo label", () => { const run = editQueueRef.current.then(async () => { await options?.beforeTiming; await serializeStudioFileMutations(writeProjectFile, ["index.html"], async () => { - const write = `move ${changes.map((c) => c.element.id).join(",")}`; + const write = `move ${changes.map((c) => `${c.element.id}@${c.start}`).join(",")}`; writes.push(write); - if (write === refused) throw new Error("refused"); + if (write === refused) { + refused = undefined; + throw new Error("refused"); + } }); }); editQueueRef.current = run.catch(() => undefined); @@ -187,37 +194,43 @@ describe("useTimelineDeleteOps: ripple undo label", () => { const shiftedB = usePlayerStore.getState().elements.find((e) => e.id === "hf-b")!; await Promise.all([first, getHook().handleTimelineElementDelete(shiftedB)]); }); - return writes; + return { writes, getHook }; } // fails without the fix: the second delete saved between the first delete and its ripple. it("saves a delete made right after another after the first one's ripple", async () => { - const writes = await deleteTwoInARow(); + const { writes } = await deleteTwoInARow(); - expect(writes).toEqual(["delete hf-a", "move hf-b,hf-c", "delete hf-b", "move hf-c"]); + expect(writes).toEqual(["delete hf-a", "move hf-b@0,hf-c@2", "delete hf-b", "move hf-c@0"]); expect(usePlayerStore.getState().elements).toEqual([el("hf-c", 0, 2)]); }); - // fails without the fix: the refused write restored the timeline from before it, so hf-b came back. + // fails without the fix: deleting hf-b saved hf-c at 0, on top of hf-a, though hf-a's delete or shift was refused. it.each([ + ["delete hf-a", ["delete hf-a", "delete hf-b"], [el("hf-c", 4, 2), el("hf-a", 0, 2)]], [ - "delete hf-a", - ["delete hf-a", "delete hf-b", "move hf-c"], - [el("hf-c", 2, 2), el("hf-a", 0, 2)], - ], - [ - "move hf-b,hf-c", - ["delete hf-a", "move hf-b,hf-c", "delete hf-b", "move hf-c"], - [el("hf-c", 2, 2)], + "move hf-b@0,hf-c@2", + ["delete hf-a", "move hf-b@0,hf-c@2", "delete hf-b"], + [el("hf-c", 4, 2)], ], ])( - "a refused %s rolls back only itself, so the next delete stays gone", - async (refused, tried, after) => { - expect(await deleteTwoInARow(refused)).toEqual(tried); + "a refused %s refuses the next delete's shift too, so hf-c is never saved at 0 on hf-a", + async (refused, saved, after) => { + expect((await deleteTwoInARow(refused)).writes).toEqual(saved); expect(usePlayerStore.getState().elements).toEqual(after); }, ); + it("a delete made once a refusal has settled still closes its gap", async () => { + const { writes, getHook } = await deleteTwoInARow("delete hf-a"); + const a = usePlayerStore.getState().elements.find((e) => e.id === "hf-a")!; + + await act(() => getHook().handleTimelineElementDelete(a)); + + expect(writes.slice(2)).toEqual(["delete hf-a", "move hf-c@2"]); + expect(usePlayerStore.getState().elements).toEqual([el("hf-c", 2, 2)]); + }); + it("removes a multi-clip selection with one request, however many clips it holds", async () => { const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined); const { elements, getHook } = mountDeleteHarness({ handleTimelineGroupMove }); diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts index e118fb544f..40b90aad95 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.ts +++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts @@ -99,6 +99,8 @@ export function useTimelineDeleteOps({ // toast system has no action buttons, so Undo and the toggle location are // named in words instead. const rippleNoticeShownRef = useRef(false); + // Rejects once a pending delete or its shift is refused: shifts queued behind it were placed after it. + const placedRef = useRef>(Promise.resolve()); // fallow-ignore-next-line complexity const handleTimelineElementsDelete = useCallback( // fallow-ignore-next-line complexity @@ -198,10 +200,11 @@ export function useTimelineDeleteOps({ }); editQueueRef.current = deleted.catch(() => undefined); // One call queues both, so no later edit can land between the delete and its shift. + const placed = Promise.all([deleted, placedRef.current]).then(() => undefined); const shifted = rippleChanges && handleTimelineGroupMove(rippleChanges, { - beforeTiming: deleted, + beforeTiming: placed, coalesceKey: step.coalesceKey, // Coalescing keeps the LAST entry's label; without this the undo // toast reads "Undid Move timeline clips" after a delete, naming @@ -211,6 +214,13 @@ export function useTimelineDeleteOps({ // the generic one would tell the user about one action twice. suppressFailureToast: true, }); + const mine = shifted ?? placed; + placedRef.current = mine; + void mine + .catch(() => undefined) + .then(() => { + if (placedRef.current === mine) placedRef.current = Promise.resolve(); + }); try { await deleted; } catch (error) { From 826b4fcc69f3adf33c068e095504f496f13e48af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 02:04:44 +0000 Subject: [PATCH 069/367] test(cli): a missed late SVG image in snapshot says which wait came up short (#8435) --- .../snapshot.lateImages.browser.test.ts | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/commands/snapshot.lateImages.browser.test.ts b/packages/cli/src/commands/snapshot.lateImages.browser.test.ts index ad52605313..a37e3aa87b 100644 --- a/packages/cli/src/commands/snapshot.lateImages.browser.test.ts +++ b/packages/cli/src/commands/snapshot.lateImages.browser.test.ts @@ -53,6 +53,9 @@ function writeProject(name: string, reveal: string): string {
+ + + `; return insertBeforeCloseTag(html, "body", tag) ?? `${html}${tag}`; } @@ -97,7 +93,7 @@ async function underToken(res: Response, headers: Headers, projectId: string, to const base = previewBase(projectId); headers.delete("content-length"); const rebased = (await res.text()).replaceAll(base, `${base}~${token}/`); - const html = withStudioEditsReappliedAfterSeeks(rebased); + const html = withSeekReapplyArmedForAnyEdit(rebased); return new Response(html, { status: res.status, headers }); } diff --git a/packages/studio-server/src/routes/preview.opaqueFrameLoads.test.ts b/packages/studio-server/src/routes/preview.opaqueFrameLoads.test.ts index 231e54da22..d462b095a6 100644 --- a/packages/studio-server/src/routes/preview.opaqueFrameLoads.test.ts +++ b/packages/studio-server/src/routes/preview.opaqueFrameLoads.test.ts @@ -210,7 +210,9 @@ describe("an opaque preview frame's loads under its token", () => { expect(html.replaceAll(tokened, "")).not.toContain("/api/projects/demo/preview/"); }); - it("puts Studio's seek reapply last in a sealed document with a Studio edit, and only there", async () => { + // fails without the fix: a sealed document with no Studio edit yet got no reapply, so the first edit an undo or redo + // put back on it could not be kept in place. + it("puts Studio's seek reapply last in every sealed document, edited or not, and in no plain one", async () => { const reapply = "//# sourceURL=hyperframes://position-seek-reapply"; const sealed = await (await load("comp/sized.html", { "sec-fetch-dest": "iframe" })).text(); expect(sealed).toContain(reapply); @@ -220,7 +222,7 @@ describe("an opaque preview frame's loads under its token", () => { }); expect(await plain.text()).not.toContain(reapply); const unedited = await (await load("comp/scene.html", { "sec-fetch-dest": "iframe" })).text(); - expect(unedited).not.toContain(reapply); + expect(unedited).toContain(reapply); }); it("serves the main preview under the token, re-based", async () => { From 926e1b560178651346b18c0dfb105589d61a1419 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 08:08:47 +0000 Subject: [PATCH 089/367] fix(studio): a sealed resize keeps a self-centring layer where it is (#8467) --- packages/core/src/runtime/editingDraft.ts | 14 ++++-- .../src/runtime/editingGestureStart.test.ts | 42 +++++++++++++++++ .../core/src/runtime/editingGestureStart.ts | 46 ++++++++++++++++++- .../editor/domEditOverlayGestures.ts | 1 + .../editor/domEditOverlayStartGesture.ts | 1 + .../editor/previewGestureStartRead.test.ts | 11 +++-- .../editor/previewGestureStartRead.ts | 9 ++++ .../src/components/editor/resizeDraft.test.ts | 26 +++++++++++ .../src/components/editor/resizeDraft.ts | 16 +++++-- .../studio/src/player/lib/previewElements.ts | 6 ++- 10 files changed, 157 insertions(+), 15 deletions(-) create mode 100644 packages/studio/src/components/editor/resizeDraft.test.ts diff --git a/packages/core/src/runtime/editingDraft.ts b/packages/core/src/runtime/editingDraft.ts index c7b254ae1f..ee8416c091 100644 --- a/packages/core/src/runtime/editingDraft.ts +++ b/packages/core/src/runtime/editingDraft.ts @@ -7,7 +7,7 @@ import { isStylableElement, type StylableElement as Styled } from "./domRealm"; import { elementForHandle } from "./editingHandles"; import type { EditingDraft, EditingDraftRotate } from "./editingPort"; -const SIZE_PROPERTIES = [ +export const SIZE_PROPERTIES = [ "box-sizing", "width", "height", @@ -113,9 +113,10 @@ function drawTranslate(element: Styled, offset: { x: number; y: number }): void element.style.setProperty("translate", movedTranslate(beforeOf(element).translate, offset)); } -function drawSize(element: Styled, size: { width: number; height: number }): void { - beforeOf(element); - const { style } = element; +export function writeDrawnSize( + style: CSSStyleDeclaration, + size: { width: number; height: number }, +): void { style.setProperty("box-sizing", "border-box"); style.setProperty("width", `${size.width}px`); style.setProperty("height", `${size.height}px`); @@ -123,6 +124,11 @@ function drawSize(element: Styled, size: { width: number; height: number }): voi for (const name of ["max-width", "max-height"]) style.setProperty(name, "none"); } +function drawSize(element: Styled, size: { width: number; height: number }): void { + beforeOf(element); + writeDrawnSize(element.style, size); +} + function restoreGsapRotation(element: Styled): void { const rotation = before.get(element)?.gsapRotation; if (rotation !== undefined) frameGsap()?.set?.(element, { rotation }); diff --git a/packages/core/src/runtime/editingGestureStart.test.ts b/packages/core/src/runtime/editingGestureStart.test.ts index 6fc618787a..f32852ec30 100644 --- a/packages/core/src/runtime/editingGestureStart.test.ts +++ b/packages/core/src/runtime/editingGestureStart.test.ts @@ -80,7 +80,49 @@ const tween = (target: unknown, vars: Record, duration = 0): Tw duration: () => duration, }); +/** A 200x100 box whose centre moves `share` of its drawn growth: 0.5 from its corner, 0 self-centred. */ +function growingCard(share: number): HTMLElement { + document.body.innerHTML = `
`; + const card = document.getElementById("card")!; + Object.defineProperty(card, "offsetWidth", { value: 200 }); + Object.defineProperty(card, "offsetHeight", { value: 100 }); + card.getBoundingClientRect = () => { + const width = parseFloat(card.style.width) || 200; + const height = parseFloat(card.style.height) || 100; + const [cx, cy] = [200 + (width - 200) * share, 100 + (height - 100) * share]; + const [x, y] = [cx - width / 2, cy - height / 2]; + return { + x, + y, + width, + height, + left: x, + top: y, + right: x + width, + bottom: y + height, + } as DOMRect; + }; + return card; +} + describe("gesture start", () => { + it("says how far a box's centre moves as its drawn size grows, and puts its size back", () => { + const plain = growingCard(0.5); + expect(gestureStart([handleFor(plain)]).elements[0]!.grow).toEqual({ + a: 0.5, + b: 0, + c: 0, + d: 0.5, + }); + expect(plain.getAttribute("style")).toBe("width: 200px;"); + const centred = growingCard(0); + expect(gestureStart([handleFor(centred)]).elements[0]!.grow).toEqual({ + a: 0, + b: 0, + c: 0, + d: 0, + }); + }); it("reads a GSAP-held element's x/y, its layout size and how it moves, and puts its translate back", () => { const card = turnedCard("translate: 10px 20px"); Object.assign(card, { _gsap: { renderTransform: () => {} } }); diff --git a/packages/core/src/runtime/editingGestureStart.ts b/packages/core/src/runtime/editingGestureStart.ts index f78c9a4cc9..38f07acec3 100644 --- a/packages/core/src/runtime/editingGestureStart.ts +++ b/packages/core/src/runtime/editingGestureStart.ts @@ -6,7 +6,12 @@ */ import { isStylableElement, type StylableElement } from "./domRealm"; import type { EditingElementHandle } from "./editingElement"; -import { computedTranslateAxes, movedTranslate } from "./editingDraft"; +import { + computedTranslateAxes, + movedTranslate, + SIZE_PROPERTIES, + writeDrawnSize, +} from "./editingDraft"; import { boxOf, elementGeometry, @@ -23,6 +28,8 @@ export interface EditingGestureStart extends EditingElementGeometry { layout: { width: number; height: number }; /** Frame px its centre moves per px of translate, columns `a, b` (x) and `c, d` (y); null when it does not move measurably. */ move: { a: number; b: number; c: number; d: number } | null; + /** Frame px its centre moves per px of drawn width, `a, b`, and height, `c, d`; null when it has no box. */ + grow: { a: number; b: number; c: number; d: number } | null; /** Set when GSAP owns its position: its x/y now, and whether a tween with a duration moves it. */ gsap: { x: number; y: number; moving: boolean } | null; /** GSAP's rotation now when it owns the element's turn; null when it turns by its own CSS `rotate`. */ @@ -68,6 +75,39 @@ function measureMoveResponse(element: StylableElement): EditingGestureStart["mov } } +/** Where its centre goes as a draft draws its size, so a resize can pin it; its inline size put back. */ +function measureGrowResponse( + element: StylableElement, + layout: { width: number; height: number }, +): EditingGestureStart["grow"] { + const { style } = element; + const kept = SIZE_PROPERTIES.map( + (name) => [name, style.getPropertyValue(name), style.getPropertyPriority(name)] as const, + ); + const centre = (width: number, height: number): Point | null => { + writeDrawnSize(style, { width, height }); + const box = element.getBoundingClientRect(); + return box.width > 0 || box.height > 0 + ? { x: box.left + box.width / 2, y: box.top + box.height / 2 } + : null; + }; + try { + if (layout.width < 1 || layout.height < 1) return null; + const origin = centre(layout.width, layout.height); + const wider = centre(layout.width + PROBE_PX, layout.height); + const taller = centre(layout.width, layout.height + PROBE_PX); + if (!origin || !wider || !taller) return null; + const per = (p: Point) => [(p.x - origin.x) / PROBE_PX, (p.y - origin.y) / PROBE_PX]; + const [[a, b], [c, d]] = [per(wider), per(taller)] as [number[], number[]]; + return [a, b, c, d].every(Number.isFinite) ? { a: a!, b: b!, c: c!, d: d! } : null; + } finally { + for (const [name, value, priority] of kept) { + if (value) style.setProperty(name, value, priority); + else style.removeProperty(name); + } + } +} + type GsapTween = { vars?: Record; targets?: () => unknown[]; @@ -152,10 +192,12 @@ export function gestureStart(handles: readonly EditingElementHandle[]): { const element = pressed[i]; if (!geometry || !isStylableElement(element)) return null; const { offsetWidth = 0, offsetHeight = 0 } = element as Partial; + const layout = { width: offsetWidth, height: offsetHeight }; return { ...geometry, - layout: { width: offsetWidth, height: offsetHeight }, + layout, move: measureMoveResponse(element), + grow: measureGrowResponse(element, layout), gsap: gsapPosition(element), gsapRotation: gsapRotation(element), planar: planarOf(element), diff --git a/packages/studio/src/components/editor/domEditOverlayGestures.ts b/packages/studio/src/components/editor/domEditOverlayGestures.ts index 70c3101ce7..869cbbdbdf 100644 --- a/packages/studio/src/components/editor/domEditOverlayGestures.ts +++ b/packages/studio/src/components/editor/domEditOverlayGestures.ts @@ -96,6 +96,7 @@ export interface GestureState { */ resizeFixedCenterStart?: { x: number; y: number }; resizePressFromCorner?: { x: number; y: number }; + resizeGrow?: { a: number; b: number; c: number; d: number }; } export interface GroupGestureState { diff --git a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts index d4ecac4e16..fcb7be32a6 100644 --- a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts +++ b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts @@ -329,6 +329,7 @@ export function startGesture( ? { x: e.clientX - options.resizeCorner.x, y: e.clientY - options.resizeCorner.y } : undefined, resizeFixedCenterStart, + resizeGrow: kind === "resize" ? start?.grow : undefined, }; if (kind === "resize") { resetResizeMoveLog(); diff --git a/packages/studio/src/components/editor/previewGestureStartRead.test.ts b/packages/studio/src/components/editor/previewGestureStartRead.test.ts index 31d051e648..8e3aeb41f6 100644 --- a/packages/studio/src/components/editor/previewGestureStartRead.test.ts +++ b/packages/studio/src/components/editor/previewGestureStartRead.test.ts @@ -53,7 +53,7 @@ function sized(element: Element, [x, y, width, height]: number[]) { return element; } -/** The card sits in a mirrored parent: a px of translate x moves it a px left, y moves it down. */ +/** In a mirrored parent: a px of translate x moves it left, y moves it down; it grows leftward. */ function mirroredCard(card: HTMLElement) { sized(card, [0, 0, 200, 100]); card.getBoundingClientRect = () => { @@ -62,9 +62,13 @@ function mirroredCard(card: HTMLElement) { .map((axis) => [...axis.matchAll(/-?[\d.]+px/g)].reduce((sum, [px]) => sum + Number.parseFloat(px), 0), ); - const left = 600 - x; + const [width, height] = [ + parseFloat(card.style.width) || 200, + parseFloat(card.style.height) || 100, + ]; + const left = 600 - x - (width - 200); const top = 300 + y; - return { x: left, y: top, width: 200, height: 100, left, top } as DOMRect; + return { x: left, y: top, width, height, left, top } as DOMRect; }; } @@ -154,6 +158,7 @@ describe("a gesture's start on an opaque frame", () => { screenToOffset: { a: -2, b: 0, c: 0, d: 2 }, gsap: { x: 200, y: 5, moving: false }, gsapRotation: 0, + grow: { a: -0.25, b: 0, c: 0, d: 0.25 }, }); const selection = { ...makeSelection("card", standIn), handle }; const made = createManualOffsetDragMember({ diff --git a/packages/studio/src/components/editor/previewGestureStartRead.ts b/packages/studio/src/components/editor/previewGestureStartRead.ts index 547dd9b2d0..93e61d0d5f 100644 --- a/packages/studio/src/components/editor/previewGestureStartRead.ts +++ b/packages/studio/src/components/editor/previewGestureStartRead.ts @@ -17,6 +17,7 @@ export interface PreviewGestureStart { /** GSAP's x/y when it owns the element's position, and whether a tween with a duration moves it. */ gsap: { x: number; y: number; moving: boolean } | null; gsapRotation?: number | null; + grow?: { a: number; b: number; c: number; d: number }; } export interface PreviewGestureStarts { @@ -70,6 +71,14 @@ export async function measurePreviewGestureStart( screenToOffset: screenToOffset(start.move), gsap: start.gsap, gsapRotation: start.gsapRotation, + grow: start.grow + ? { + a: start.grow.a * sx, + b: start.grow.b * sy, + c: start.grow.c * sx, + d: start.grow.d * sy, + } + : undefined, }, }, ), diff --git a/packages/studio/src/components/editor/resizeDraft.test.ts b/packages/studio/src/components/editor/resizeDraft.test.ts new file mode 100644 index 0000000000..439219df88 --- /dev/null +++ b/packages/studio/src/components/editor/resizeDraft.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; +import type { GestureState } from "./domEditOverlayGestures"; +import { sealedResizeAnchor } from "./resizeDraft"; + +const gesture = (resizeGrow?: GestureState["resizeGrow"]) => + ({ + actualWidth: 240, + actualHeight: 160, + editScaleX: 0.5, + editScaleY: 0.5, + resizeGrow, + }) as GestureState; +const written = { width: 340, height: 220 }; + +describe("a sealed resize's centre pin", () => { + it("takes back only as much as the frame measured the centre moving", () => { + const plain = sealedResizeAnchor(gesture({ a: 0.25, b: 0, c: 0, d: 0.25 }), written); + expect(plain).toEqual({ dx: -25, dy: -15 }); + const centred = sealedResizeAnchor(gesture({ a: 0, b: 0, c: 0, d: 0 }), written); + expect([centred.dx, centred.dy].map(Math.abs)).toEqual([0, 0]); + }); + + it("pins half the growth when the frame did not measure it", () => { + expect(sealedResizeAnchor(gesture(), written)).toEqual({ dx: -25, dy: -15 }); + }); +}); diff --git a/packages/studio/src/components/editor/resizeDraft.ts b/packages/studio/src/components/editor/resizeDraft.ts index d631875ab7..00fe59d849 100644 --- a/packages/studio/src/components/editor/resizeDraft.ts +++ b/packages/studio/src/components/editor/resizeDraft.ts @@ -84,6 +84,17 @@ function resolveAnchoredResizeDraft( } /** A frame Studio cannot measure: the box grows about its centre by the size the draft wrote. */ +/** The pin that keeps a sealed resize's centre still: back by what the frame measured the drawn size moving it. */ +export function sealedResizeAnchor( + g: GestureState, + written: { width: number; height: number }, +): { dx: number; dy: number } { + const [w, h] = [g.actualWidth - written.width, g.actualHeight - written.height]; + const grow = g.resizeGrow; + if (!grow) return { dx: (w / 2) * g.editScaleX, dy: (h / 2) * g.editScaleY }; + return { dx: grow.a * w + grow.c * h, dy: grow.b * w + grow.d * h }; +} + function resolveUnmeasuredResizeDraft( g: GestureState, element: HTMLElement, @@ -92,10 +103,7 @@ function resolveUnmeasuredResizeDraft( const width = (g.originWidth * written.width) / g.actualWidth; const height = (g.originHeight * written.height) / g.actualHeight; if (g.pathOffsetMember) { - const anchor = { - dx: ((g.actualWidth - written.width) / 2) * g.editScaleX, - dy: ((g.actualHeight - written.height) / 2) * g.editScaleY, - }; + const anchor = sealedResizeAnchor(g, written); g.lastResizeAnchor = anchor; applyManualOffsetDragDraft(g.pathOffsetMember, anchor.dx, anchor.dy); } diff --git a/packages/studio/src/player/lib/previewElements.ts b/packages/studio/src/player/lib/previewElements.ts index 82b9f95b27..a7b15d7625 100644 --- a/packages/studio/src/player/lib/previewElements.ts +++ b/packages/studio/src/player/lib/previewElements.ts @@ -258,13 +258,14 @@ const isTurnOrNull = (value: unknown) => const kept = (value: T, valid: boolean) => (valid ? value : undefined); -export type ReadGestureStart = Omit & { +export type ReadGestureStart = Omit & { gsapRotation?: number | null; + grow?: EditingGestureStart["grow"]; }; const readGestureStart = (value: unknown): ReadGestureStart | null => { if (!readGeometry(value) || !isFields(value)) return null; - const { layout, move, gsap, gsapRotation } = value; + const { layout, move, gsap, gsapRotation, grow } = value; const valid = [ isLayout(layout), move === null || isFiniteFields(move, ["a", "b", "c", "d"]), @@ -275,6 +276,7 @@ const readGestureStart = (value: unknown): ReadGestureStart | null => { return { ...start, gsapRotation: kept(start.gsapRotation, isTurnOrNull(gsapRotation)), + grow: kept(start.grow, isFiniteFields(grow, ["a", "b", "c", "d"])), }; }; From e98ca56c4abe575b88ca76566e85773cf378438b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 08:15:29 +0000 Subject: [PATCH 090/367] fix(studio): an in-place tween patch that throws says why it fell back to a reload (#8454) * test(studio): an in-place tween patch that throws reports the error's name * fix(studio): an in-place tween patch that throws says why it fell back to a reload * test(studio): a composition's own error class name reports as other * fix(studio): only built-in error names leave an in-place patch's report * test(studio): a built-in error from the preview frame's realm reports its name * fix(studio): an in-place patch reads a thrown error's name from any realm --- .../studio/src/hooks/gsapRuntimePatch.test.ts | 83 +++++++++++++++++++ packages/studio/src/hooks/gsapRuntimePatch.ts | 28 ++++++- 2 files changed, 110 insertions(+), 1 deletion(-) diff --git a/packages/studio/src/hooks/gsapRuntimePatch.test.ts b/packages/studio/src/hooks/gsapRuntimePatch.test.ts index e34d293a41..dcb9fc951f 100644 --- a/packages/studio/src/hooks/gsapRuntimePatch.test.ts +++ b/packages/studio/src/hooks/gsapRuntimePatch.test.ts @@ -1,5 +1,9 @@ +import { runInNewContext } from "node:vm"; import { describe, expect, it, vi } from "vitest"; import { patchRuntimeTweenInPlace } from "./gsapRuntimePatch"; +import { trackStudioEvent } from "../utils/studioTelemetry"; + +vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); /** * The helper patches ONE tween's values in `window.__timelines[compKey]` in place, @@ -566,3 +570,82 @@ describe("patchRuntimeTweenInPlace — deferSeek", () => { expect(rendered).toEqual({ a: 500, b: 600 }); }); }); + +describe("patchRuntimeTweenInPlace — a throw inside the patch", () => { + // fails without the fix: the reload fallback hid the error, so a broken patch path looked like a slow edit. + // The composition's GSAP throws here, so the edit still falls back to a reload. + it("falls back, and reports the error's name, never its message", () => { + const logged = vi.spyOn(console, "error").mockImplementation(() => {}); + const el = { id: "box" }; + const iframe = { + contentWindow: { + gsap: { + set: () => { + throw new TypeError("user script text"); + }, + }, + }, + contentDocument: { querySelector: (sel: string) => (sel === "#box" ? el : null) }, + } as unknown as HTMLIFrameElement; + + expect(patchRuntimeTweenInPlace(iframe, "#box", { kind: "global-set", props: { x: 1 } })).toBe( + false, + ); + expect(trackStudioEvent).toHaveBeenCalledWith("gsap_instant_patch_threw", { + error_name: "TypeError", + }); + expect(logged).toHaveBeenCalledTimes(1); + logged.mockRestore(); + }); + + // fails without the fix: a TypeError from the preview frame's realm is not instanceof this realm's Error, so every + // real throw reported 'other'. + it("reports a built-in error thrown in the preview frame's realm by its name", () => { + const logged = vi.spyOn(console, "error").mockImplementation(() => {}); + const el = { id: "box" }; + const iframe = { + contentWindow: { + gsap: { + set: () => { + throw runInNewContext("new TypeError('user script text')"); + }, + }, + }, + contentDocument: { querySelector: (sel: string) => (sel === "#box" ? el : null) }, + } as unknown as HTMLIFrameElement; + + expect(patchRuntimeTweenInPlace(iframe, "#box", { kind: "global-set", props: { x: 1 } })).toBe( + false, + ); + expect(trackStudioEvent).toHaveBeenLastCalledWith("gsap_instant_patch_threw", { + error_name: "TypeError", + }); + logged.mockRestore(); + }); + + it("reports a name the composition gave its own error class as 'other'", () => { + const logged = vi.spyOn(console, "error").mockImplementation(() => {}); + class FilmError extends Error { + override name = "user script text"; + } + const el = { id: "box" }; + const iframe = { + contentWindow: { + gsap: { + set: () => { + throw new FilmError(); + }, + }, + }, + contentDocument: { querySelector: (sel: string) => (sel === "#box" ? el : null) }, + } as unknown as HTMLIFrameElement; + + expect(patchRuntimeTweenInPlace(iframe, "#box", { kind: "global-set", props: { x: 1 } })).toBe( + false, + ); + expect(trackStudioEvent).toHaveBeenLastCalledWith("gsap_instant_patch_threw", { + error_name: "other", + }); + logged.mockRestore(); + }); +}); diff --git a/packages/studio/src/hooks/gsapRuntimePatch.ts b/packages/studio/src/hooks/gsapRuntimePatch.ts index 806f931b39..7b7cb3cf89 100644 --- a/packages/studio/src/hooks/gsapRuntimePatch.ts +++ b/packages/studio/src/hooks/gsapRuntimePatch.ts @@ -11,9 +11,31 @@ import { type RuntimeTweenChange, } from "@hyperframes/core/runtime/patch-tween"; import { swapWaiting, type SoftReloadWindow } from "@hyperframes/core/runtime/soft-reload"; +import { trackStudioEvent } from "../utils/studioTelemetry"; export type { RuntimeTweenChange, SetPatchProps } from "@hyperframes/core/runtime/patch-tween"; +// A composition can name its own error class anything, so only these names leave the machine. +const REPORTED_ERROR_NAMES = new Set([ + "Error", + "TypeError", + "RangeError", + "ReferenceError", + "SyntaxError", + "EvalError", + "URIError", + "AggregateError", + "SecurityError", + "InvalidStateError", + "NotFoundError", + "DataCloneError", +]); +// The error may come from the preview frame's realm, so its name is read, never checked with instanceof. +function reportedErrorName(error: unknown): string { + const name = (error as { name?: unknown } | null)?.name; + return typeof name === "string" && REPORTED_ERROR_NAMES.has(name) ? name : "other"; +} + function reachablePreview(iframe: HTMLIFrameElement): PatchTarget { const win = iframe.contentWindow as | (Window & { @@ -48,7 +70,11 @@ export function patchRuntimeTweenInPlace( if (change.kind !== "global-set") return patchTween(target, selector, change, compositionId, deferSeek); return applyGlobalSet(target, selector, change.props) !== null; - } catch { + } catch (error) { + trackStudioEvent("gsap_instant_patch_threw", { + error_name: reportedErrorName(error), + }); + console.error("[Studio] An in-place tween patch threw; reloading the preview instead", error); return false; } } From deb478a3f630aaf4ba5eeb77b497c7e4be9e8656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 08:22:31 +0000 Subject: [PATCH 091/367] refactor(studio): a preview clip's number and track rules live in one place (#8471) --- packages/studio/src/player/lib/manifestClips.ts | 15 ++++++++++----- packages/studio/src/player/lib/timelineDOM.ts | 8 ++++---- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/packages/studio/src/player/lib/manifestClips.ts b/packages/studio/src/player/lib/manifestClips.ts index 787a806ff2..55816f0958 100644 --- a/packages/studio/src/player/lib/manifestClips.ts +++ b/packages/studio/src/player/lib/manifestClips.ts @@ -2,15 +2,20 @@ import type { ClipManifestClip } from "./playbackTypes"; const OPTIONAL_NUMBERS = ["zIndex", "playbackStart", "playbackRate"] as const; -const finiteNumber = (value: unknown): boolean => - typeof value === "number" && Number.isFinite(value); +export const clipNumber = (value: unknown): number | null => + typeof value === "number" && Number.isFinite(value) ? value : null; + +export const clipTrack = (value: unknown): number | null => + typeof value === "number" && Number.isSafeInteger(value) ? value : null; function wellFormedClip(clip: unknown): clip is ClipManifestClip { if (typeof clip !== "object" || clip === null) return false; const fields = clip as Record; - if (!finiteNumber(fields.start) || !finiteNumber(fields.duration)) return false; - if (!Number.isInteger(fields.track)) return false; - return OPTIONAL_NUMBERS.every((name) => fields[name] == null || finiteNumber(fields[name])); + if (clipNumber(fields.start) === null || clipNumber(fields.duration) === null) return false; + if (clipTrack(fields.track) === null) return false; + return OPTIONAL_NUMBERS.every( + (name) => fields[name] == null || clipNumber(fields[name]) !== null, + ); } /** A preview frame's clip list, keeping only clips whose timing and track are numbers. */ diff --git a/packages/studio/src/player/lib/timelineDOM.ts b/packages/studio/src/player/lib/timelineDOM.ts index 3307013c98..6f985de87a 100644 --- a/packages/studio/src/player/lib/timelineDOM.ts +++ b/packages/studio/src/player/lib/timelineDOM.ts @@ -17,7 +17,7 @@ import { readMasterFxChain } from "@hyperframes/core/audio-groups"; import { linkScopeOf } from "@hyperframes/core/media-link"; import { createRuntimeStartTimeResolver } from "@hyperframes/core/runtime/start-resolver"; import { previewWithoutFrameToken } from "./frameToken"; -import { finiteNumber } from "../../components/editor/manualEditsParsing"; +import { clipNumber, clipTrack } from "./manifestClips"; import { groupInfoFor } from "./timelineGroupInfo"; import { receivedTimelineText } from "./timelineText"; import { transitionLabelsForDocument } from "./timelineTransitionMetadata"; @@ -82,7 +82,7 @@ export function createTimelineElementFromManifestClip(params: { hostEl?: Element | null; }): TimelineElement { const { clip, fallbackIndex, doc } = params; - const numericTrack = Number.isSafeInteger(clip.track) ? clip.track : 0; + const numericTrack = clipTrack(clip.track) ?? 0; let hostEl = params.hostEl ?? null; const transitionLabels = doc ? transitionLabelsForDocument(doc, (doc.defaultView as IframeWindow | null)?.__timelines) @@ -127,8 +127,8 @@ export function createTimelineElementFromManifestClip(params: { key: identity.key, kind: clip.kind, tag: resolveClipTag(clip), - start: finiteNumber(clip.start) ?? 0, - duration: finiteNumber(clip.duration) ?? 0, + start: clipNumber(clip.start) ?? 0, + duration: clipNumber(clip.duration) ?? 0, track: numericTrack, // clip.track IS the authored data-track-index verbatim (the runtime honors // it; see parseAuthoredTrack in core/runtime/timeline.ts). Record it at this From 05d1bc8b1c1cbff2fcb447a36da5b5db4e7bad79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 08:40:03 +0000 Subject: [PATCH 092/367] fix(studio): a sealed crop draws a layer's insets at its own scale and follows a seek (#8451) * test(studio): a sealed scaled card's crop insets draw at its own scale before any press * test(studio): a sealed crop re-reads a resized card and drops a read from an earlier selection * fix(studio): a sealed crop draws a scaled layer's insets at its own scale before any press * style(studio): wrap the sealed crop read's comment under the line limit * test(studio): a sealed scaled layer picked in the Layers panel crops at its own scale * refactor(studio): read a sealed crop's start in its own hook * test(studio): overlays wake on a sealed preview's posts and only on Studio's own preview frame * fix(studio): a sealed preview's playhead posts wake the editor overlays after a seek * test(studio): a seek that keeps a sealed card's painted box still re-reads its crop scale * fix(studio): a sealed crop re-reads its layer's scale when the playhead moves * test(studio): a sealed crop re-reads once the frame shows the seek, not on Studio's playhead * fix(studio): a sealed crop re-reads its scale when the frame applies a seek --- .../components/CaptionOverlay.sealed.test.ts | 40 +--- .../editor/DomEditCropHandles.sealed.test.ts | 171 +++++++++++++++--- .../components/editor/DomEditCropHandles.tsx | 71 +++++++- .../editor/LayersPanel.opaque.test.ts | 34 ++++ .../editor/overlayFrameLoop.test.ts | 71 ++++++++ .../src/components/editor/overlayFrameLoop.ts | 16 +- .../studio/src/player/lib/bridgePlayback.ts | 28 ++- .../lib/sealedPreviewFrame.test-helpers.ts | 35 ++++ 8 files changed, 390 insertions(+), 76 deletions(-) diff --git a/packages/studio/src/captions/components/CaptionOverlay.sealed.test.ts b/packages/studio/src/captions/components/CaptionOverlay.sealed.test.ts index d2d44f298a..c1359d8e98 100644 --- a/packages/studio/src/captions/components/CaptionOverlay.sealed.test.ts +++ b/packages/studio/src/captions/components/CaptionOverlay.sealed.test.ts @@ -3,7 +3,11 @@ import { act, createElement, Fragment, useRef } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, expect, it, vi } from "vitest"; import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness"; -import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; +import { + answerTap, + sealedPreviewFrame, + type PortRequest, +} from "../../player/lib/sealedPreviewFrame.test-helpers"; import { previewRequest } from "../../player/lib/previewChannel"; import { usePreviewIframeStore } from "../../player/store/previewIframeStore"; import { useCaptionDetection } from "../../hooks/useCaptionDetection"; @@ -33,42 +37,12 @@ afterEach(() => { vi.unstubAllGlobals(); }); -type PortRequest = { id?: unknown; kind?: unknown; params?: unknown }; - /** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ function opaqueFrame() { - let pick: ((request: PortRequest) => boolean) | null = null; - const heldIds = new Set(); - const held: Array<() => void> = []; - // Studio's end of the port, so a test can keep the frame's answer to a request until it releases it. - const tap = (port: MessagePort) => { - const end = { - onmessage: null as ((event: MessageEvent) => void) | null, - postMessage(request: PortRequest) { - if (pick?.(request)) heldIds.add(request.id); - port.postMessage(request); - }, - close: () => port.close(), - }; - port.onmessage = (event) => { - const deliver = () => end.onmessage?.(event); - if (heldIds.has(event.data?.id)) held.push(deliver); - else deliver(); - }; - return end as unknown as MessagePort; - }; - const { iframe } = sealedPreviewFrame({ wrapHandedOverPort: tap }); + const { wrapHandedOverPort, hold, held } = answerTap(); + const { iframe } = sealedPreviewFrame({ wrapHandedOverPort }); iframe.style.width = "1920px"; iframe.getBoundingClientRect = () => new DOMRect(0, 0, 1920, 1080); - /** Keeps the answers to the requests `match` picks; the returned call hands them to Studio. */ - const hold = (match: (request: PortRequest) => boolean) => { - pick = match; - return () => { - pick = null; - heldIds.clear(); - held.splice(0).forEach((deliver) => deliver()); - }; - }; return { iframe, hold, held }; } diff --git a/packages/studio/src/components/editor/DomEditCropHandles.sealed.test.ts b/packages/studio/src/components/editor/DomEditCropHandles.sealed.test.ts index 77c92ae195..681a04d812 100644 --- a/packages/studio/src/components/editor/DomEditCropHandles.sealed.test.ts +++ b/packages/studio/src/components/editor/DomEditCropHandles.sealed.test.ts @@ -3,15 +3,23 @@ import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, expect, it, vi } from "vitest"; import { watchPreviewFrame } from "../../player/lib/bridgePlayback"; -import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements"; -import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; +import { usePlayerStore } from "../../player/store/playerStore"; +import { + describePreviewElements, + previewGeometry, + queryPreviewElements, +} from "../../player/lib/previewElements"; +import { answerTap, sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; import type { DomEditSelection } from "./domEditing"; import { DomEditCropHandles } from "./DomEditCropHandles"; +import { rememberFrameClipPath } from "./domEditOverlayCrop"; +import { previewStandIn } from "./previewDrafts"; import { standInFor } from "./previewSelection"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; afterEach(() => { + usePlayerStore.getState().setCurrentTime(0); document.body.innerHTML = ""; }); @@ -23,24 +31,25 @@ function sized(element: Element, [x, y, width, height]: number[]) { return element; } -/** A 200 x 100 card painted under `transform` on a frame Studio cannot script, and its stand-in. */ -async function sealedCard(transform: string, painted: number[]) { - document.body.innerHTML = `
`; - const card = sized(document.getElementById("card")!, [0, 0, 200, 100]); - card.getBoundingClientRect = () => { - const [x, y, width, height] = painted; - return { - x, - y, - width, - height, - left: x, - top: y, - right: x + width, - bottom: y + height, - } as DOMRect; - }; - const { iframe: sealed, frame } = sealedPreviewFrame(); +/** `element` laid out at `width` x `height` and painted on screen at `painted`. */ +function paint(element: Element, [width, height]: number[], painted: number[]) { + sized(element, [0, 0, width, height]); + const [x, y, w, h] = painted; + element.getBoundingClientRect = () => + ({ x, y, width: w, height: h, left: x, top: y, right: x + w, bottom: y + h }) as DOMRect; +} + +type Card = { id: string; transform: string; painted: number[]; clip?: string }; + +/** 200 x 100 cards painted under their `transform` on a frame Studio cannot script, and their stand-ins. */ +async function sealedCards(cards: Card[], options?: Parameters[0]) { + const markup = cards.map( + ({ id, transform, clip }) => + `
`, + ); + document.body.innerHTML = `
${markup.join("")}
`; + for (const { id, painted } of cards) paint(document.getElementById(id)!, [200, 100], painted); + const { iframe: sealed, frame } = sealedPreviewFrame(options); const iframe = sized(sealed, [0, 0, 1920, 1080]) as HTMLIFrameElement; watchPreviewFrame(iframe); window.dispatchEvent( @@ -50,8 +59,21 @@ async function sealedCard(transform: string, painted: number[]) { data: { source: "hf-preview", type: "stage-size", width: 1920, height: 1080 }, }), ); - const handle = (await queryPreviewElements(iframe, "#card"))!.matches[0]!.handle; - return standInFor(iframe, (await describePreviewElements(iframe, [handle]))![0]!); + const standIns: HTMLElement[] = []; + for (const { id } of cards) { + const handle = (await queryPreviewElements(iframe, `#${id}`))!.matches[0]!.handle; + const described = (await describePreviewElements(iframe, [handle]))![0]!; + const standIn = standInFor(iframe, described); + // As a selection takes it (previewSelection.ts): the stand-in's clip-path is the one the frame reports. + rememberFrameClipPath(standIn, described.inlineStyles["clip-path"] ?? "", ""); + standIns.push(standIn); + } + return standIns; +} + +/** A 200 x 100 card painted under `transform` on a frame Studio cannot script, and its stand-in. */ +async function sealedCard(transform: string, painted: number[], clip?: string) { + return (await sealedCards([{ id: "card", transform, painted, clip }]))[0]!; } type Shown = { left: number; top: number; width: number; height: number; angle?: number }; @@ -61,14 +83,14 @@ function cropHandles(standIn: HTMLElement, onStyleCommit = vi.fn()) { const host = document.createElement("div"); document.body.append(host); const root = createRoot(host); - const show = (shown: Shown) => + const show = (shown: Shown, element = standIn) => act(() => root.render( createElement(DomEditCropHandles, { selection: { - element: standIn, - id: "card", - selector: "#card", + element, + id: element.id || "card", + selector: `#${element.id || "card"}`, } as unknown as DomEditSelection, overlayRect: { ...shown, editScaleX: 1, editScaleY: 1 }, onStyleCommit, @@ -77,7 +99,9 @@ function cropHandles(standIn: HTMLElement, onStyleCommit = vi.fn()) { ); const turn = () => document.querySelector("[data-dom-edit-crop-frame]")!.style.transform; - return { root, show, turn }; + const outline = () => + document.querySelector("[data-dom-edit-crop-frame] .border-dashed")!.style.width; + return { root, show, turn, outline }; } /** Drags the right crop edge by `dx, dy` screen px and lets go, all before the frame answers. */ @@ -132,6 +156,99 @@ it("draws a sealed turned card's crop frame turned before any press", async () = act(() => root.unmount()); }); +// fails without the fix: before a press, a sealed crop drew its insets at the overlay's zoom alone, as if the card +// had no scale of its own, until a press measured its size. +it("draws a sealed scaled card's crop insets at the card's own scale before any press", async () => { + const standIn = await sealedCard( + "matrix(2, 0, 0, 2, 0, 0)", + [0, 0, 400, 200], + "inset(0px 20px 0px 0px)", + ); + const { root, show, outline } = cropHandles(standIn); + + show({ left: 0, top: 0, width: 400, height: 200 }); + + await vi.waitFor(() => expect(outline()).toBe("360px")); + act(() => root.unmount()); +}); + +// fails without the fix: the size read at selection was kept while the card's size changed under it. +it("re-reads a sealed card's size when it changes while selected, before any press", async () => { + const standIn = await sealedCard( + "matrix(2, 0, 0, 2, 0, 0)", + [0, 0, 400, 200], + "inset(0px 20px 0px 0px)", + ); + const { root, show, outline } = cropHandles(standIn); + show({ left: 0, top: 0, width: 400, height: 200 }); + await vi.waitFor(() => expect(outline()).toBe("360px")); + + paint(document.getElementById("card")!, [300, 100], [0, 0, 600, 200]); + show({ left: 0, top: 0, width: 600, height: 200 }); + + await vi.waitFor(() => expect(outline()).toBe("560px")); + act(() => root.unmount()); +}); + +// fails without the fix: the crop re-read when Studio's playhead moved, before the frame applied the seek, so a seek +// that changed the card's size and scale but kept its painted box drew the old scale (360 px where 380 px is right). +it("re-reads a sealed card's size once the frame shows the seek's time, not when Studio's playhead moves", async () => { + const standIn = await sealedCard( + "matrix(2, 0, 0, 2, 0, 0)", + [0, 0, 400, 200], + "inset(0px 20px 0px 0px)", + ); + const { iframe, handle } = previewStandIn(standIn)!; + const { root, show, outline } = cropHandles(standIn); + show({ left: 0, top: 0, width: 400, height: 200 }); + await vi.waitFor(() => expect(outline()).toBe("360px")); + + act(() => usePlayerStore.getState().setCurrentTime(3.5)); + // The frame answers in order: anything the playhead move asked is answered, at the old size, before this. + await previewGeometry(iframe, [handle]); + paint(document.getElementById("card")!, [400, 200], [0, 0, 400, 200]); + window.dispatchEvent( + new MessageEvent("message", { + source: iframe.contentWindow, + origin: "null", + data: { source: "hf-preview", type: "state", currentTime: 3.5, isPlaying: false }, + }), + ); + + await vi.waitFor(() => expect(outline()).toBe("380px")); + act(() => root.unmount()); +}); + +// fails without the fix: a read sent for a card's first selection, landing after it was selected again, was taken +// over the newer one. +it("draws a card selected again by its newest size, not by a read sent before it was left", async () => { + const tap = answerTap(); + const [card, other] = await sealedCards( + [ + { + id: "card", + transform: "matrix(2, 0, 0, 2, 0, 0)", + painted: [0, 0, 400, 200], + clip: "inset(0px 20px 0px 0px)", + }, + { id: "other", transform: "none", painted: [500, 0, 200, 100] }, + ], + { wrapHandedOverPort: tap.wrapHandedOverPort }, + ); + const { root, show, outline } = cropHandles(card!); + const release = tap.hold(({ kind }) => kind === "gesture-start"); + show({ left: 0, top: 0, width: 400, height: 200 }); + await vi.waitFor(() => expect(tap.held).toHaveLength(1)); + + paint(document.getElementById("card")!, [300, 100], [0, 0, 600, 200]); + show({ left: 500, top: 0, width: 200, height: 100 }, other); + show({ left: 0, top: 0, width: 600, height: 200 }, card); + release(); + + await vi.waitFor(() => expect(outline()).toBe("560px")); + act(() => root.unmount()); +}); + // fails without the fix: the turn measured at a press was held until the selection changed. it("redraws a sealed crop frame at the turn the card has after a scrub, once a press measured it", async () => { const standIn = await sealedCard("rotate(30deg)", [0, 0, 223, 187]); diff --git a/packages/studio/src/components/editor/DomEditCropHandles.tsx b/packages/studio/src/components/editor/DomEditCropHandles.tsx index 4203580fc0..1c56499518 100644 --- a/packages/studio/src/components/editor/DomEditCropHandles.tsx +++ b/packages/studio/src/components/editor/DomEditCropHandles.tsx @@ -1,5 +1,12 @@ import { trackPreviewEditResult, type PreviewMethod } from "../../utils/previewFeatureUsage"; -import { useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react"; +import { + useEffect, + useRef, + useState, + type Dispatch, + type PointerEvent as ReactPointerEvent, + type SetStateAction, +} from "react"; import type { DomEditSelection } from "./domEditing"; import { type OverlayRect, RESIZE_HANDLE_HIT_PX } from "./domEditOverlayGeometry"; import { @@ -22,6 +29,7 @@ import { isCropBarTarget, useCropPresetBarStore } from "./cropPresetStore"; import { CropPresetBar } from "./CropPresetBar"; import { movesGesture } from "./domEditOverlayGestures"; import { previewStandIn } from "./previewDrafts"; +import { onFrameShowsTime } from "../../player/lib/bridgePlayback"; import { gestureStartLayout, readCropFrameStart } from "./previewGestureStartRead"; interface CropGestureState { @@ -151,6 +159,64 @@ function insetsAfterDrag(gesture: CropGestureState, x: number, y: number): ClipP return resolveCropInsetFromEdgeDrag({ ...drag, edge, width, height }); } +type StartReads = { token: number; busy: boolean; again: boolean; element: HTMLElement }; + +/** A stand-in has no size of its own: the frame measures it while selected and when its overlay size changes, so its + * insets draw at the element's own scale before any press, as an unsealed crop reads it live. One read at a time, one + * more when it lands if anything changed meanwhile; a new selection or a press (a new `token`) drops one still out. */ +function readStandInStart( + r: StartReads, + take: (element: HTMLElement, start: CropFrameStart) => void, +): void { + const el = r.element; + const standIn = previewStandIn(el); + if (!standIn) return; + if (r.busy) return void (r.again = true); + r.busy = true; + const token = r.token; + void readCropFrameStart(standIn.iframe, standIn.handle).then((start) => { + r.busy = false; + if (start && token === r.token) take(el, start); + if (r.again) { + r.again = false; + readStandInStart(r, take); + } + }); +} + +/** `readStandInStart` while `element` is selected and not dragged: again when its box moves or a seek lands. */ +/** Counts the seeks `element`'s sealed frame has applied, as its runtime reports them. */ +function useFrameSeeks(element: HTMLElement): number { + const [seeks, setSeeks] = useState(0); + useEffect(() => { + const frame = previewStandIn(element)?.iframe; + if (!frame) return; + return onFrameShowsTime((iframe) => iframe === frame && setSeeks((n) => n + 1)); + }, [element]); + return seeks; +} + +function useStandInStart( + element: HTMLElement, + overlayRect: { width: number; height: number }, + dragging: boolean, + setState: Dispatch>, +) { + const reads = useRef({ token: 0, busy: false, again: false, element }); + const shownSize = `${Math.round(overlayRect.width)}x${Math.round(overlayRect.height)}`; + const seeks = useFrameSeeks(element); + useEffect(() => { + const r = reads.current; + if (r.element !== element) r.token++; + r.element = element; + if (!dragging) + readStandInStart(r, (el, start) => + setState((prev) => (prev.element === el ? { ...prev, start } : prev)), + ); + }, [element, shownSize, seeks, dragging, setState]); + return reads; +} + function letGoOf(ref: { current: CropGestureState | null }, gesture: CropGestureState): void { if (ref.current === gesture) ref.current = null; } @@ -252,6 +318,8 @@ export function DomEditCropHandles({ return () => dropElementCropLift(el); }, [selection.element]); + const reads = useStandInStart(selection.element, overlayRect, dragging, setState); + // The crop applies in the element's LOCAL frame (clip-path precedes the // transform), so all crop UI is drawn inside a container rotated with the // element — on a rotated element an axis-aligned dim visually "straightens" @@ -296,6 +364,7 @@ export function DomEditCropHandles({ setState((prev) => ({ ...prev, insets: pressed })); setDragging(true); const { element } = selection; + reads.current.token++; void measurePressOnFrame(element, overlayRect, gesture).then((start) => settleMeasuredPress(start, gesture, gestureRef.current, { refuse: refuseCropPress, diff --git a/packages/studio/src/components/editor/LayersPanel.opaque.test.ts b/packages/studio/src/components/editor/LayersPanel.opaque.test.ts index bfe8fab7a7..4faadf1056 100644 --- a/packages/studio/src/components/editor/LayersPanel.opaque.test.ts +++ b/packages/studio/src/components/editor/LayersPanel.opaque.test.ts @@ -6,6 +6,7 @@ import { afterEach, expect, it, vi } from "vitest"; import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness"; import { usePreviewIframeStore } from "../../player/store/previewIframeStore"; import { LayersPanel } from "./LayersPanel"; +import { DomEditCropHandles } from "./DomEditCropHandles"; import type { LayerReorderEvent } from "./useLayerDrag"; import type { DomEditLayerItem, DomEditSelection } from "./domEditing"; import { announcePreviewDocumentLoaded } from "../../player/sceneSwap"; @@ -242,3 +243,36 @@ it("lists the layers in their new order after an undo restacks them in place", a expect(reload).not.toHaveBeenCalled(); await vi.waitFor(() => expect(rows()).toEqual(["Back", "Front"])); }); + +// fails without the fix: a layer picked in the Layers panel was never pressed on the canvas, so its sealed crop drew +// the insets at the overlay's zoom alone, as if the layer had no scale of its own. +it("draws the crop of a sealed scaled layer picked in the Layers panel at the layer's own scale", async () => { + document.body.innerHTML = `
`; + const card = document.getElementById("card")!; + Object.defineProperty(card, "offsetWidth", { value: 200 }); + Object.defineProperty(card, "offsetHeight", { value: 100 }); + card.getBoundingClientRect = () => + ({ x: 0, y: 0, width: 400, height: 200, left: 0, top: 0, right: 400, bottom: 200 }) as DOMRect; + const rows = renderPanel(sealedPreviewFrame().iframe); + await vi.waitFor(() => expect(rows()).toHaveLength(1)); + act(() => document.querySelector("[data-layer-index]")!.click()); + await vi.waitFor(() => expect(mocks.applyDomSelection).toHaveBeenCalled()); + const picked = mocks.applyDomSelection.mock.calls[0]![0] as DomEditSelection; + + const host = document.body.appendChild(document.createElement("div")); + const root = createRoot(host); + act(() => + root.render( + createElement(DomEditCropHandles, { + selection: picked, + overlayRect: { left: 0, top: 0, width: 400, height: 200, editScaleX: 1, editScaleY: 1 }, + onStyleCommit: vi.fn(), + }), + ), + ); + closers.push(() => act(() => root.unmount())); + + const outline = () => + host.querySelector("[data-dom-edit-crop-frame] .border-dashed")?.style.width; + await vi.waitFor(() => expect(outline()).toBe("360px")); +}); diff --git a/packages/studio/src/components/editor/overlayFrameLoop.test.ts b/packages/studio/src/components/editor/overlayFrameLoop.test.ts index 35148e388c..c004e7a15f 100644 --- a/packages/studio/src/components/editor/overlayFrameLoop.test.ts +++ b/packages/studio/src/components/editor/overlayFrameLoop.test.ts @@ -10,6 +10,8 @@ import { subscribeOverlayFrame, } from "./overlayFrameLoop"; import { usePlayerStore } from "../../player/store/playerStore"; +import { watchPreviewFrame } from "../../player/lib/bridgePlayback"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; /** * The editor's overlay polls run on one shared, parkable frame loop. The two @@ -20,6 +22,8 @@ describe("overlay frame loop", () => { const originalRaf = window.requestAnimationFrame; const originalCancelRaf = window.cancelAnimationFrame; let queued: Array<() => void>; + /** The window of the preview frame Studio built, whose posts wake the loop. */ + let preview: Window; /** Run whatever frames are queued, once. */ const step = (): number => { @@ -40,6 +44,9 @@ describe("overlay frame loop", () => { }; beforeEach(() => { + const frame = document.body.appendChild(document.createElement("iframe")); + watchPreviewFrame(frame); + preview = frame.contentWindow!; usePlayerStore.setState({ previewBooted: true }); vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance", "Date"] }); queued = []; @@ -54,6 +61,7 @@ describe("overlay frame loop", () => { afterEach(() => { resetOverlayFrameLoopForTests(); + document.body.innerHTML = ""; vi.useRealTimers(); window.requestAnimationFrame = originalRaf; window.cancelAnimationFrame = originalCancelRaf; @@ -180,6 +188,7 @@ describe("overlay frame loop", () => { new MessageEvent("message", { data: { source: "hf-preview", type: "state", frame, isPlaying }, origin: window.location.origin, + source: preview, }), ); }; @@ -197,6 +206,67 @@ describe("overlay frame loop", () => { expect(runs).toBeGreaterThan(5); }); + // fails without the fix: a sealed preview posts from an opaque origin, so after a seek the overlays waited for the + // idle poll (up to MAX_IDLE_POLL_MS) to redraw the selection at the layer's new size. + it("wakes to full rate when a sealed preview Studio built reports a new frame from its opaque origin", () => { + const { iframe, frame } = sealedPreviewFrame(); + watchPreviewFrame(iframe); + let runs = 0; + subscribeOverlayFrame(() => { + runs += 1; + }); + framesOver(1000); + runs = 0; + window.dispatchEvent( + new MessageEvent("message", { + data: { source: "hf-preview", type: "state", frame: 3, isPlaying: false }, + origin: "null", + source: frame as unknown as Window, + }), + ); + framesOver(200); + expect(runs).toBeGreaterThan(5); + }); + + it("ignores an opaque-origin preview post from a frame Studio did not build", () => { + const stranger = sealedPreviewFrame().frame; + let runs = 0; + subscribeOverlayFrame(() => { + runs += 1; + }); + framesOver(1000); + runs = 0; + window.dispatchEvent( + new MessageEvent("message", { + data: { source: "hf-preview", type: "state", frame: 4, isPlaying: false }, + origin: "null", + source: stranger as unknown as Window, + }), + ); + framesOver(200); + expect(runs).toBeLessThanOrEqual(2); + }); + + // fails without the fix: any window on Studio's own origin could post the preview's payload and wake the loop. + it("ignores a same-origin preview post from a window that is not the preview frame Studio built", () => { + const stranger = document.body.appendChild(document.createElement("iframe")).contentWindow!; + let runs = 0; + subscribeOverlayFrame(() => { + runs += 1; + }); + framesOver(1000); + runs = 0; + window.dispatchEvent( + new MessageEvent("message", { + data: { source: "hf-preview", type: "state", frame: 5, isPlaying: false }, + origin: window.location.origin, + source: stranger, + }), + ); + framesOver(200); + expect(runs).toBeLessThanOrEqual(2); + }); + it("ignores the paused heartbeat, which repeats a frame the overlays already drew", () => { let runs = 0; subscribeOverlayFrame(() => { @@ -309,6 +379,7 @@ describe("overlay frame loop", () => { new MessageEvent("message", { data: { source: "hf-preview", type: "timeline", clips: [] }, origin: window.location.origin, + source: preview, }), ); framesOver(200); diff --git a/packages/studio/src/components/editor/overlayFrameLoop.ts b/packages/studio/src/components/editor/overlayFrameLoop.ts index b0aa58a530..fc7e8dae85 100644 --- a/packages/studio/src/components/editor/overlayFrameLoop.ts +++ b/packages/studio/src/components/editor/overlayFrameLoop.ts @@ -25,6 +25,7 @@ * the next couple of hundred milliseconds, and no further event is dispatched * while it does. */ +import { fromStudioPreview } from "../../player/lib/bridgePlayback"; import { usePlayerStore } from "../../player/store/playerStore"; const AWAKE_MS = 400; @@ -64,17 +65,6 @@ const WINDOW_EVENTS = [ let lastPreviewFrame: number | null = null; let lastPreviewPlaying: boolean | null = null; -/** - * The preview iframe is served by the editor's own origin (`useTimelinePlayer` - * builds its src against `window.location.origin`), so a message from anywhere - * else is not the preview whatever its payload claims. Answered before the - * payload is read, because a sender we do not trust controls every field in it. - */ -function isFromPreviewOrigin(event: MessageEvent): boolean { - if (typeof window === "undefined") return true; - return event.origin === window.location.origin; -} - /** * `window` also receives postMessage traffic from extensions, devtools and any * other embed on the page. Waking on those would hold the overlays awake for @@ -98,7 +88,9 @@ function previewStateOf(data: { } function onPreviewMessage(event: MessageEvent): void { - if (!isFromPreviewOrigin(event)) return; + // Only a preview frame Studio built, from an origin it can have (a sealed one's is opaque): anything else on the page + // can post the same payload. Checked before the payload is read. + if (!fromStudioPreview(event)) return; const data: unknown = event.data; if (!isPreviewPayload(data)) return; const state = previewStateOf(data); diff --git a/packages/studio/src/player/lib/bridgePlayback.ts b/packages/studio/src/player/lib/bridgePlayback.ts index 0c27f09dbd..652e3419ff 100644 --- a/packages/studio/src/player/lib/bridgePlayback.ts +++ b/packages/studio/src/player/lib/bridgePlayback.ts @@ -15,6 +15,8 @@ interface PlaybackMirror { seekUntil: number; /** The composition's declared size from the runtime's `stage-size` post. */ stageSize: { width: number; height: number } | null; + /** The paused time the runtime last said it shows. */ + shown: number | null; } const SEEK_CONFIRM_MS = 500; @@ -37,6 +39,7 @@ function mirrorOf(iframe: HTMLIFrameElement): PlaybackMirror | null { seekTo: null, seekUntil: 0, stageSize: null, + shown: null, }; mirrors.set(frame, mirror); } @@ -112,6 +115,17 @@ function mirrorState( mirror.seekTo = null; mirror.time = currentTime; mirror.playing = playing; + if (playing || mirror.shown === currentTime) return; + mirror.shown = currentTime; + for (const listener of shownListeners) listener(mirror.iframe); +} + +const shownListeners = new Set<(iframe: HTMLIFrameElement) => void>(); + +/** Calls `listener` with a registered frame each time its runtime says it shows a new paused time: a seek applied. */ +export function onFrameShowsTime(listener: (iframe: HTMLIFrameElement) => void): () => void { + shownListeners.add(listener); + return () => void shownListeners.delete(listener); } function mirrorPost(mirror: PlaybackMirror, message: Record, fps: number | null) { @@ -125,10 +139,18 @@ function mirrorPost(mirror: PlaybackMirror, message: Record, fp } } -function mirrorRuntimePlayback(event: MessageEvent): void { - // Only a frame Studio built, posting from an origin that frame can have. +function studioPreviewMirror(event: MessageEvent): PlaybackMirror | undefined { const mirror = event.source ? mirrors.get(event.source) : undefined; - if (!mirror || !frameOrigins(mirror.iframe).includes(event.origin)) return; + return mirror && frameOrigins(mirror.iframe).includes(event.origin) ? mirror : undefined; +} + +/** Whether `event` came from a preview frame Studio built, a sealed one's opaque origin included. */ +export const fromStudioPreview = (event: MessageEvent): boolean => + studioPreviewMirror(event) !== undefined; + +function mirrorRuntimePlayback(event: MessageEvent): void { + const mirror = studioPreviewMirror(event); + if (!mirror) return; const post = runtimePost(event.data); if (post) mirrorPost(mirror, post.message, post.fps); } diff --git a/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts b/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts index 8b095e6c7d..e8ca3f79de 100644 --- a/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts +++ b/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts @@ -42,3 +42,38 @@ export function sealedPreviewFrame( onTestFinished(() => agent.dispose()); return { iframe, frame }; } + +export type PortRequest = { id?: unknown; kind?: unknown; params?: unknown }; + +/** Studio's end of the frame's port, for `wrapHandedOverPort`: `hold` keeps the frame's answers to the requests it + * picks until the call it returns hands them to Studio, in order. */ +export function answerTap() { + let pick: ((request: PortRequest) => boolean) | null = null; + const heldIds = new Set(); + const held: Array<() => void> = []; + const wrapHandedOverPort = (port: MessagePort) => { + const end = { + onmessage: null as ((event: MessageEvent) => void) | null, + postMessage(request: PortRequest) { + if (pick?.(request)) heldIds.add(request.id); + port.postMessage(request); + }, + close: () => port.close(), + }; + port.onmessage = (event) => { + const deliver = () => end.onmessage?.(event); + if (heldIds.has(event.data?.id)) held.push(deliver); + else deliver(); + }; + return end as unknown as MessagePort; + }; + const hold = (match: (request: PortRequest) => boolean) => { + pick = match; + return () => { + pick = null; + heldIds.clear(); + held.splice(0).forEach((deliver) => deliver()); + }; + }; + return { wrapHandedOverPort, hold, held }; +} From 3e101f9654033d73d47ac8a791d0f98c80755226 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 08:41:27 +0000 Subject: [PATCH 093/367] fix(studio): a timeline edit queued before a project switch stays in its own project (#8458) * fix(studio): a refused delete no longer brings back another delete still saving A refused delete, or a ripple shift that fails after its delete, now moves back only the clips that delete shifted, on the timeline as it is now, instead of restoring the timeline from before it. * fix(studio): a refused delete also refuses the ripple shifts queued behind it A delete's ripple shift saves absolute starts worked out with every earlier pending delete applied. When one of those is refused, the shifts queued behind it are refused too and leave their gap, so the saved file never puts a clip on top of the restored one. * fix(studio): a ripple shift queued behind a refused edit is refused before it writes The timeline's edit queue now has one owner. It knows when an edit still pending is refused, and a ripple shift (after a delete or a trim) queued behind it is refused instead of saving starts that assumed that edit. The trim ripple's rollback moves clips back by its own shift only. Drags, single-clip timing and link edits are unchanged. * fix(studio): a refused edit refuses trims behind it, per project, until every save settles - A queued save stays tracked until it settles, so a later failure still refuses the ripple queued behind it. - A trim's own resize is refused behind a refused edit too: its start and duration were read from the timeline that edit left. - Each project gets its own queue. - A refused trim shift reloads the preview, as a refused delete does. * test(studio): the project-switch case keeps the old project's save pending * fix(studio): a single-clip SDK timing save waits its turn in the edit queue The SDK move and resize now run inside the queued edit, with the file-write fallback in the same entry, so the earlier-refusal check guards both paths and later edits see these saves. * test(studio): give the clip-timing tests a 10 s timeline so every case can use the SDK path * fix(studio): a queued timeline edit reads and writes only the project it was queued in Each edit queue now carries the project it was made for and hands that id to every queued edit, so the SDK readers, the file writes and the tween rewrite never follow a project switch that happens while an edit waits. * test(studio): hold the old project's save from the start in the project-switch case * revert(studio): leave project isolation of queued edits to its own change Takes out the per-project queue and the project binding of queued edits. Main already lets a queued edit follow a project switch, through more handles than the project id (preview, timeline store, history), so that fix moves to one change that covers every handle. * fix(studio): a timeline edit queued before a project switch stays in its own project Each edit queue carries the project it was made for and is closed when the editor shows another one. A queued edit reads, writes and records history in its own project; its live side (preview patches and reloads, the SDK session, the timeline store and its rollbacks, the pending-path set) runs only while that project is shown. Gestures still saving are forgotten on a switch, so no drag or resize rolls back the new project's timeline. * test(studio): the project-switch test covers a single-clip move and every reach into the preview * test(studio): type the preview spy's traps * refactor(studio): let the queue's names carry what two doc lines said * fix(studio): a queued single-clip SDK save reads the project it was made in Main read the project as the save started, right away; queued, it read it when its turn came. The move and resize now take the project when the gesture queues them, for the SDK reader and the tween rewrite. * fix(studio): a project's edits keep one order across a switch away and back A new project's queue starts from the previous queue's tail, so returning to a project never runs its next edit beside a save it left waiting. Refusals and the closed flag stay per queue. The old queue is closed, and pending gestures forgotten, when the switch commits, not during render. * fix(studio): a refused edit refuses only later edits of its own project Each queued edit carries the project it was queued in, and the queue tracks refusals per project, so a refusal left behind by a project the editor has moved away from never refuses an edit in the one now open. * test(studio): the switch matrix's stand-in SDK session finds no element, like an unknown target --- .../src/hooks/timelineEditQueue.test.tsx | 87 ++++++++- .../studio/src/hooks/timelineEditQueue.ts | 54 +++++- .../useTimelineClipTimingEditing.test.tsx | 47 +++-- .../src/hooks/useTimelineClipTimingEditing.ts | 77 ++++---- .../src/hooks/useTimelineDeleteOps.test.tsx | 18 +- .../studio/src/hooks/useTimelineDeleteOps.ts | 33 ++-- .../useTimelineEditing.projectSwitch.test.tsx | 170 ++++++++++++++++++ .../studio/src/hooks/useTimelineEditing.ts | 7 +- .../hooks/useTimelineGroupEditing.test.tsx | 18 +- .../src/hooks/useTimelineGroupEditing.ts | 57 +++--- .../src/hooks/useTimelineTrimRipple.test.tsx | 1 + .../studio/src/hooks/useTimelineTrimRipple.ts | 7 +- .../components/timelineOptimisticRevision.ts | 6 +- 13 files changed, 466 insertions(+), 116 deletions(-) create mode 100644 packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx diff --git a/packages/studio/src/hooks/timelineEditQueue.test.tsx b/packages/studio/src/hooks/timelineEditQueue.test.tsx index 4d673a120b..7368dae2c7 100644 --- a/packages/studio/src/hooks/timelineEditQueue.test.tsx +++ b/packages/studio/src/hooks/timelineEditQueue.test.tsx @@ -1,9 +1,17 @@ -import { describe, expect, it } from "vitest"; +// @vitest-environment happy-dom + +import { StrictMode, act } from "react"; +import { describe, expect, it, vi } from "vitest"; import { enqueueTimelineEdit, refuseWithEarlier, + useTimelineEditQueue, + whileShown, type TimelineEditQueue, } from "./timelineEditQueue"; +import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness"; + +installReactActEnvironment(); function deferred() { let reject: (error: Error) => void = () => {}; @@ -16,7 +24,7 @@ const settle = () => new Promise((resolve) => setImmediate(resolve)); describe("enqueueTimelineEdit", () => { // fails without the fix: A's failure cleared the tracking of B's save still in flight. it("refuses a ripple queued during a save that then fails, after an earlier save already failed", async () => { - const queue: TimelineEditQueue = { current: Promise.resolve() }; + const queue: TimelineEditQueue = { current: Promise.resolve(), projectId: "project" }; const a = deferred(); const b = deferred(); const writes: string[] = []; @@ -36,3 +44,78 @@ describe("enqueueTimelineEdit", () => { expect(writes).toEqual([]); }); }); + +describe("useTimelineEditQueue", () => { + // fails without the fix: StrictMode's mount, cleanup and remount left the shown project's queue closed. + it("keeps the shown project's queue open under StrictMode, so its live steps run", () => { + let queue: TimelineEditQueue | null = null; + function Harness({ projectId }: { projectId: string }) { + queue = useTimelineEditQueue(projectId); + return null; + } + const root = mountReactHarness( + + + , + ); + const liveStep = vi.fn(); + + whileShown(queue!, liveStep); + + expect(liveStep).toHaveBeenCalledOnce(); + act(() => root.unmount()); + }); + + // fails without the fix: back in A, A's next edit ran beside A's held save, which then wrote over it. + it("keeps one order across a switch away and back, so a held save is never written over", async () => { + const files: Record = { A: "" }; + let queue: TimelineEditQueue | null = null; + function Harness({ projectId }: { projectId: string }) { + queue = useTimelineEditQueue(projectId); + return null; + } + const root = mountReactHarness(); + let release: () => void = () => {}; + const held = new Promise((done) => (release = done)); + const first = enqueueTimelineEdit(queue!, async (pid) => { + const before = files[pid]; + await held; + files[pid] = `${before}1`; + }); + act(() => root.render()); + act(() => root.render()); + const second = enqueueTimelineEdit(queue!, async (pid) => { + files[pid] = `${files[pid]}2`; + }); + + release(); + await Promise.all([first, second]); + + expect(files.A).toBe("12"); + act(() => root.unmount()); + }); + + // fails without the fix: the old project's refused delete refused the new project's ripple. + it("gives a new project its own queue, so a refusal in the old one never touches it", async () => { + let queue: TimelineEditQueue | null = null; + function Harness({ projectId }: { projectId: string }) { + queue = useTimelineEditQueue(projectId); + return null; + } + const root = mountReactHarness(); + const oldSave = deferred(); + const refused = enqueueTimelineEdit(queue!, () => oldSave.promise); + act(() => root.render()); + const writes: string[] = []; + + const ripple = enqueueTimelineEdit(queue!, async () => void writes.push("ripple"), { + ifEarlierRefused: refuseWithEarlier, + }); + oldSave.reject(new Error("refused")); + + await expect(refused).rejects.toThrow("refused"); + await expect(ripple).resolves.toBeUndefined(); + expect(writes).toEqual(["ripple"]); + act(() => root.unmount()); + }); +}); diff --git a/packages/studio/src/hooks/timelineEditQueue.ts b/packages/studio/src/hooks/timelineEditQueue.ts index 5a5799dcc7..c185900ef2 100644 --- a/packages/studio/src/hooks/timelineEditQueue.ts +++ b/packages/studio/src/hooks/timelineEditQueue.ts @@ -1,9 +1,54 @@ -import type { MutableRefObject } from "react"; +import { useLayoutEffect, useRef, type MutableRefObject, type RefObject } from "react"; +import type { PublishSdkSession } from "../utils/sdkCutover"; +import { forgetTimelineOptimisticGestures } from "../player/components/timelineOptimisticRevision"; /** The editor's one timeline edit queue. `placed` holds, per project, a promise that rejects * when an edit of that project still pending is refused. */ export interface TimelineEditQueue extends MutableRefObject> { + /** Per project, a promise that rejects when an edit of that project still pending is refused. */ placed?: Map>; + readonly projectId: string | null; + readonly shownProjectId?: { readonly current: string | null }; +} + +export function useTimelineEditQueue(projectId: string | null): TimelineEditQueue { + const shownProjectId = useRef(projectId); + shownProjectId.current = projectId; + const owner = useRef(null); + if (owner.current?.projectId !== projectId) { + const { current = Promise.resolve(), placed = new Map() } = owner.current ?? {}; + owner.current = { current, placed, projectId, shownProjectId }; + } + useLayoutEffect(() => () => forgetTimelineOptimisticGestures(), [projectId]); + return owner.current; +} + +export const isClosed = (queue: TimelineEditQueue) => + queue.shownProjectId !== undefined && queue.shownProjectId.current !== queue.projectId; + +/** Runs a queued edit's live-preview or timeline-store side only while its project is shown. */ +export function whileShown(queue: TimelineEditQueue, effect: () => void): void { + if (!isClosed(queue)) effect(); +} + +/** A queued edit's way to the live preview, inert once its project is no longer shown. */ +export function shownPreview( + queue: TimelineEditQueue, + live: { + iframeRef: RefObject; + reloadPreview: () => void; + publishSdkSession?: PublishSdkSession; + }, +) { + const publish = live.publishSdkSession; + return { + iframe: () => (isClosed(queue) ? null : live.iframeRef.current), + reload: () => whileShown(queue, live.reloadPreview), + publish: + publish && + ((publication: Parameters[0]) => + isClosed(queue) ? ("rejected-inactive-target" as const) : publish(publication)), + }; } export const refuseWithEarlier = (error: unknown): never => { @@ -14,11 +59,11 @@ export const refuseWithEarlier = (error: unknown): never => { * refused, `ifEarlierRefused` runs first, and throwing refuses this edit too. */ export function enqueueTimelineEdit( queue: TimelineEditQueue, - run: () => Promise, + run: (projectId: string) => Promise, { label, ifEarlierRefused, - projectId = null, + projectId = queue.projectId, }: { label?: string; ifEarlierRefused?: (error: unknown) => void; @@ -29,7 +74,8 @@ export function enqueueTimelineEdit( const earlier = byProject.get(projectId) ?? Promise.resolve(); const task = queue.current.then(async () => { if (ifEarlierRefused) await earlier.catch(ifEarlierRefused); - return run(); + if (!projectId) throw new Error("No project to save this edit to"); + return run(projectId); }); const placed = Promise.allSettled([earlier, task]).then((settled) => { for (const result of settled) if (result.status === "rejected") throw result.reason; diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx index aedec0b3e9..6323627b78 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx @@ -6,7 +6,11 @@ import { usePlayerStore, type TimelineElement } from "../player"; import { sdkTimingPersist, type CutoverResult } from "../utils/sdkCutover"; import { persistTimelineEdit } from "./timelineEditingHelpers"; import { finishClipTimingFallback } from "./timelineTimingSync"; -import { enqueueTimelineEdit, type TimelineEditQueue } from "./timelineEditQueue"; +import { + enqueueTimelineEdit, + useTimelineEditQueue, + type TimelineEditQueue, +} from "./timelineEditQueue"; import { useTimelineClipTimingEditing } from "./useTimelineClipTimingEditing"; import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness"; @@ -30,9 +34,9 @@ const sdkWrites = vi.mocked(sdkTimingPersist); const fileWrites = vi.mocked(persistTimelineEdit); const gsapSyncs = vi.mocked(finishClipTimingFallback); -function mountClipTiming(projectIdRef = { current: "project" as string | null }) { +function mountClipTiming() { usePlayerStore.getState().setDuration(10); - const queue: TimelineEditQueue = { current: Promise.resolve() }; + const queue: TimelineEditQueue = { current: Promise.resolve(), projectId: "project" }; let hook: ReturnType | null = null; function Harness() { hook = useTimelineClipTimingEditing({ @@ -46,7 +50,6 @@ function mountClipTiming(projectIdRef = { current: "project" as string | null }) pendingTimelineEditPathRef: { current: new Set() }, sdkSession: {} as never, editQueueRef: queue, - projectIdRef, }); return null; } @@ -97,26 +100,44 @@ describe.each<[string, CutoverResult]>([ }); }); -describe("a single-clip SDK trim queued behind another save", () => { +describe("a single-clip trim queued before a project switch", () => { afterEach(() => vi.clearAllMocks()); - // fails without the fix: after a project switch the queued trim read the newly opened project's file. - it("reads the project it was made in, as it did before it joined the queue", async () => { + // fails without the fix: the queued SDK trim read index.html from the newly opened project. + it("reads and writes only the project it was queued in", async () => { + usePlayerStore.getState().setDuration(10); sdkWrites.mockResolvedValue({ status: "committed", version: "1", before: "", after: "" }); - const projectIdRef = { current: "old" as string | null }; - const { queue, getHook, unmount } = mountClipTiming(projectIdRef); + let hook: ReturnType | null = null; + let queue: TimelineEditQueue | null = null; + function Harness({ projectId }: { projectId: string }) { + queue = useTimelineEditQueue(projectId); + hook = useTimelineClipTimingEditing({ + activeCompPath: "index.html", + timelineElements: [], + showToast: vi.fn(), + writeProjectFile: vi.fn(), + recordEdit: vi.fn(), + reloadPreview: vi.fn(), + previewIframeRef: { current: null }, + pendingTimelineEditPathRef: { current: new Set() }, + sdkSession: {} as never, + editQueueRef: queue, + }); + return null; + } + const root = mountReactHarness(); let release: () => void = () => {}; const held = new Promise((done) => (release = done)); - void enqueueTimelineEdit(queue, () => held); - const trim = getHook().handleTimelineElementResize(clipB, { start: 2, duration: 3 }); + void enqueueTimelineEdit(queue!, () => held); + const trim = hook!.handleTimelineElementResize(clipB, { start: 2, duration: 3 }); - projectIdRef.current = "new"; + act(() => root.render()); release(); await act(() => trim); const sdkDeps = sdkWrites.mock.calls[0]?.[4]; await expect(sdkDeps?.readProjectFile?.("index.html")).resolves.toBe("old:index.html"); expect(gsapSyncs.mock.calls.map(([sync]) => sync.projectId)).toEqual(["old"]); - unmount(); + act(() => root.unmount()); }); }); diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts index 243a759f52..3de067741b 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts @@ -1,4 +1,4 @@ -import { useCallback, type MutableRefObject } from "react"; +import { useCallback } from "react"; import type { TimelineElement } from "../player"; import { toAuthoredStart, toCompositionTime } from "../player/store/timelineElement"; import { @@ -30,6 +30,9 @@ import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics"; import { enqueueTimelineEdit, refuseWithEarlier, + isClosed, + shownPreview, + whileShown, type TimelineEditQueue, } from "./timelineEditQueue"; @@ -51,7 +54,6 @@ type UseTimelineClipTimingEditingOptions = Pick< | "handleDomZIndexReorderCommitRef" > & { editQueueRef: TimelineEditQueue; - projectIdRef: MutableRefObject; }; /** One clip's move and resize: the timing write, then its tween rewrite, as one undo step. */ @@ -71,7 +73,6 @@ export function useTimelineClipTimingEditing({ invalidateGsapCache, handleDomZIndexReorderCommitRef, editQueueRef, - projectIdRef, }: UseTimelineClipTimingEditingOptions) { const enqueueEdit = useCallback( ( @@ -84,19 +85,18 @@ export function useTimelineClipTimingEditing({ trySdk, }: { ifEarlierRefused?: (error: unknown) => void; - trySdk?: () => Promise; + trySdk?: (projectId: string) => Promise; } = {}, ): Promise => { if (isRecordingRef?.current) { showToast("Cannot edit timeline while recording", "error"); return Promise.resolve(undefined); } - const pid = projectIdRef.current; - if (!pid) return Promise.resolve(undefined); + if (!editQueueRef.projectId) return Promise.resolve(undefined); return enqueueTimelineEdit( editQueueRef, - async () => { - const sdk = await trySdk?.(); + async (pid) => { + const sdk = await trySdk?.(pid); if (sdk && cutoverCommittedOrThrow(sdk)) return sdk; await persistTimelineEdit({ projectId: pid, @@ -106,13 +106,15 @@ export function useTimelineClipTimingEditing({ buildPatches, writeProjectFile, recordEdit, - pendingTimelineEditPathRef, + pendingTimelineEditPathRef: isClosed(editQueueRef) + ? { current: new Set() } + : pendingTimelineEditPathRef, ...step, }); - forceReloadSdkSession?.(); + whileShown(editQueueRef, () => forceReloadSdkSession?.()); return undefined; }, - { label, ifEarlierRefused, projectId: pid }, + { label, ifEarlierRefused }, ); }, [ @@ -124,13 +126,11 @@ export function useTimelineClipTimingEditing({ isRecordingRef, forceReloadSdkSession, editQueueRef, - projectIdRef, ], ); const handleTimelineElementMove = useCallback( // fallow-ignore-next-line complexity (element: TimelineElement, updates: TimelineMoveUpdates) => { - const projectId = projectIdRef.current; // fallow-ignore-next-line complexity const commitMove = () => { const targetPath = element.sourceFile || activeCompPath || "index.html"; @@ -180,12 +180,17 @@ export function useTimelineClipTimingEditing({ ); }; const step = timingGestureStep("timeline-move"); + const shown = shownPreview(editQueueRef, { + iframeRef: previewIframeRef, + reloadPreview, + publishSdkSession, + }); const finishMoveGsapSync = (sdkGsap?: ReturnType) => // One GSAP sync per edit: the SDK commit's own (sdkGsap), else the server rewrite here. finishClipTimingFallback({ - iframe: previewIframeRef.current, - reloadPreview, - projectId, + iframe: shown.iframe(), + reloadPreview: shown.reload, + projectId: editQueueRef.projectId, targetPath, domId: element.domId, label: "Move timeline clip", @@ -194,12 +199,12 @@ export function useTimelineClipTimingEditing({ writeProjectFile, edit: { kind: "shift", delta: updates.start - element.start }, sdkGsap, - }).finally(() => invalidateGsapCache?.()); + }).finally(() => whileShown(editQueueRef, () => invalidateGsapCache?.())); const hfId = element.hfId; // SDK setTiming writes start only; a lane change needs the fallback's track patch. const sdkMove = sdkSession && hfId && !element.link && !needsExtension && !trackChanged - ? () => + ? (projectId: string) => sdkTimingPersist( hfId, targetPath, @@ -208,12 +213,12 @@ export function useTimelineClipTimingEditing({ { editHistory: { recordEdit }, writeProjectFile, - reloadPreview, + reloadPreview: shown.reload, compositionPath: activeCompPath, // Capture on-disk bytes as the undo `before` so undoing a timing move // restores the file verbatim, not a normalized full-DOM re-emit. - readProjectFile: (path) => readFileContent(projectId ?? "", path), - publishSession: publishSdkSession, + readProjectFile: (path) => readFileContent(projectId, path), + publishSession: shown.publish, }, { label: "Move timeline clip", ...step, skipRefresh: true }, ) @@ -225,7 +230,7 @@ export function useTimelineClipTimingEditing({ .then((sdk) => finishMoveGsapSync(sdk && sdkTimingGsapSync(sdk))) .catch((error) => { // Failed persist: revert the optimistic duration readout + live root. - rollbackDuration(); + whileShown(editQueueRef, rollbackDuration); showToast(getStudioSaveErrorMessage(error), "error"); throw error; }); @@ -245,7 +250,7 @@ export function useTimelineClipTimingEditing({ handleDomZIndexReorderCommitRef, showToast, invalidateGsapCache, - projectIdRef, + editQueueRef, ], ); @@ -255,7 +260,6 @@ export function useTimelineClipTimingEditing({ element: TimelineElement, updates: Pick, ) => { - const projectId = projectIdRef.current; const authoredStart = toAuthoredStart(element, updates.start); const liveAttrs: Array<[string, string]> = [ ["data-start", formatTimelineAttributeNumber(authoredStart)], @@ -285,11 +289,16 @@ export function useTimelineClipTimingEditing({ // script (timing-only resize) — same no-flash path as move; full reload is // the fallback. const step = timingGestureStep("timeline-resize"); + const shown = shownPreview(editQueueRef, { + iframeRef: previewIframeRef, + reloadPreview, + publishSdkSession, + }); const finishResizeGsapSync = (sdkGsap?: ReturnType) => finishClipTimingFallback({ - iframe: previewIframeRef.current, - reloadPreview, - projectId, + iframe: shown.iframe(), + reloadPreview: shown.reload, + projectId: editQueueRef.projectId, targetPath, domId: element.domId, label: "Resize timeline clip", @@ -302,11 +311,11 @@ export function useTimelineClipTimingEditing({ to: { start: toCompositionTime(element, updates.start), duration: updates.duration }, }, sdkGsap, - }).finally(() => invalidateGsapCache?.()); + }).finally(() => whileShown(editQueueRef, () => invalidateGsapCache?.())); const hfId = element.hfId; const sdkResize = sdkSession && hfId && !element.link && !hasPbsAdjustment && !needsExtension - ? () => + ? (projectId: string) => sdkTimingPersist( hfId, targetPath, @@ -315,12 +324,12 @@ export function useTimelineClipTimingEditing({ { editHistory: { recordEdit }, writeProjectFile, - reloadPreview, + reloadPreview: shown.reload, compositionPath: activeCompPath, // Capture on-disk bytes as the undo `before` so undoing a timing // resize restores the file verbatim, not a normalized full-DOM re-emit. - readProjectFile: (path) => readFileContent(projectId ?? "", path), - publishSession: publishSdkSession, + readProjectFile: (path) => readFileContent(projectId, path), + publishSession: shown.publish, }, { label: "Resize timeline clip", ...step, skipRefresh: true }, ) @@ -331,7 +340,7 @@ export function useTimelineClipTimingEditing({ }).then((sdk) => finishResizeGsapSync(sdk && sdkTimingGsapSync(sdk))); return persistDone.catch((error) => { // Failed persist: revert the optimistic duration readout + live root. - rollbackDuration(); + whileShown(editQueueRef, rollbackDuration); showToast(getStudioSaveErrorMessage(error), "error"); throw error; }); @@ -347,7 +356,7 @@ export function useTimelineClipTimingEditing({ reloadPreview, showToast, invalidateGsapCache, - projectIdRef, + editQueueRef, ], ); diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx index a3bd405e64..f92f40f8c1 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -72,12 +72,14 @@ describe("useTimelineDeleteOps: ripple undo label", () => { alsoMount?: () => void; }) { const elements = [el("hf-a", 0, 2), el("hf-b", 2, 2), el("hf-c", 4, 2)]; - const editQueueRef = overrides.editQueueRef ?? { current: Promise.resolve() }; + const editQueueRef = overrides.editQueueRef ?? { + current: Promise.resolve(), + projectId: "test-project", + }; usePlayerStore.getState().setElements(elements); let hook: ReturnType | null = null; function Harness() { hook = useTimelineDeleteOps({ - projectIdRef: { current: "test-project" }, activeCompPath: "index.html", showToast: overrides.showToast ?? vi.fn(), writeProjectFile: overrides.writeProjectFile ?? vi.fn().mockResolvedValue(undefined), @@ -171,7 +173,10 @@ describe("useTimelineDeleteOps: ripple undo label", () => { }), ); // Stands in for the editor's group commits: each joins the edit queue, then writes the file. - const editQueueRef: TimelineEditQueue = { current: Promise.resolve() }; + const editQueueRef: TimelineEditQueue = { + current: Promise.resolve(), + projectId: "test-project", + }; const writeProjectFile = vi.fn().mockResolvedValue(undefined); const save = (write: string, options?: TimelineGroupCommitOptions) => enqueueTimelineEdit( @@ -204,6 +209,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => { handleTimelineGroupMove, showToast: vi.fn(), reloadPreview: vi.fn(), + editQueueRef, }); }, }); @@ -434,14 +440,13 @@ describe("useTimelineDeleteOps: undo race", () => { function Harness() { const track = useTrackPendingTimelineEdit(); const hook = useTimelineDeleteOps({ - projectIdRef: { current: "test-project" }, activeCompPath: "index.html", showToast: vi.fn(), writeProjectFile: vi.fn().mockResolvedValue(undefined), recordEdit, reloadPreview: vi.fn(), previewIframeRef: { current: null }, - editQueueRef: { current: Promise.resolve() }, + editQueueRef: { current: Promise.resolve(), projectId: "test-project" }, handleTimelineGroupMove: vi.fn().mockResolvedValue(undefined), }); tracked = track(hook.handleTimelineElementsDelete); @@ -536,14 +541,13 @@ describe("useTimelineDeleteOps: live preview", () => { let hook: ReturnType | null = null; function Harness() { hook = useTimelineDeleteOps({ - projectIdRef: { current: "test-project" }, activeCompPath: "index.html", showToast: vi.fn(), writeProjectFile: vi.fn().mockResolvedValue(undefined), recordEdit: vi.fn().mockResolvedValue(undefined), reloadPreview: vi.fn(), previewIframeRef: { current: iframe }, - editQueueRef: { current: Promise.resolve() }, + editQueueRef: { current: Promise.resolve(), projectId: "test-project" }, handleTimelineGroupMove: vi.fn().mockResolvedValue(undefined), }); return null; diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts index ca2a1b75c2..63a5d37fb0 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.ts +++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts @@ -28,6 +28,8 @@ import { studioApiFetch } from "../utils/studioApiFetch"; import { countOf } from "../utils/countOf"; import { enqueueTimelineEdit, + isClosed, + whileShown, refuseWithEarlier, type TimelineEditQueue, } from "./timelineEditQueue"; @@ -63,7 +65,6 @@ function undoRippleShift(changes: TimelineGroupMoveChange[] | null, restore: Tim } interface UseTimelineDeleteOpsOptions { - projectIdRef: MutableRefObject; activeCompPath: string | null; showToast: (message: string, tone?: "error" | "info") => void; writeProjectFile: (path: string, content: string, expectedContent?: string) => Promise; @@ -88,7 +89,6 @@ function unlinkInSource(source: string, survivors: readonly TimelineElement[]): } export function useTimelineDeleteOps({ - projectIdRef, activeCompPath, showToast, writeProjectFile, @@ -112,8 +112,7 @@ export function useTimelineDeleteOps({ showToast("Cannot edit timeline while recording", "error"); return; } - const pid = projectIdRef.current; - if (!pid) throw new Error("No active project"); + if (!editQueueRef.projectId) throw new Error("No active project"); const [element] = selection; if (!element) return; const label = @@ -148,9 +147,7 @@ export function useTimelineDeleteOps({ usePlayerStore.getState().setElements(applyRippleShifts(survivors, rippleChanges)); removeIframeTimelineElements(previewIframeRef.current, sameFile, activeCompPath); let rollbackDuration = () => {}; - const inThisProject = (run: () => Promise) => - enqueueTimelineEdit(editQueueRef, run, { projectId: pid }); - const deleted = inThisProject(async () => { + const deleted = enqueueTimelineEdit(editQueueRef, async (pid) => { await saveServerRewriteWithHistory({ projectId: pid, path: targetPath, @@ -195,10 +192,12 @@ export function useTimelineDeleteOps({ const patchedContent = unlinkInSource(synced.source, alsoUnlink); // Optimistically reflect the shrunk length in the readout/seek bar, // rolling it back if the persist below fails (see captureDurationRollback). - rollbackDuration = captureDurationRollback(previewIframeRef.current); - if (synced.contentEnd > 0 && targetPath === (activeCompPath || "index.html")) { - usePlayerStore.getState().setDuration(synced.contentEnd); - } + whileShown(editQueueRef, () => { + rollbackDuration = captureDurationRollback(previewIframeRef.current); + if (synced.contentEnd > 0 && targetPath === (activeCompPath || "index.html")) { + usePlayerStore.getState().setDuration(synced.contentEnd); + } + }); return { disk: removedContent, after: patchedContent }; }, }); @@ -221,10 +220,12 @@ export function useTimelineDeleteOps({ try { await deleted; } catch (error) { - rollbackDuration(); - undoRippleShift(rippleChanges, sameFile); void shifted?.catch(() => undefined); - reloadPreview(); + whileShown(editQueueRef, () => { + rollbackDuration(); + undoRippleShift(rippleChanges, sameFile); + reloadPreview(); + }); throw error; } let rippleFailed = false; @@ -236,12 +237,13 @@ export function useTimelineDeleteOps({ // toggle-off behaviour would have left anyway — not worth undoing // an otherwise-successful delete over. rippleFailed = true; - undoRippleShift(rippleChanges, []); + whileShown(editQueueRef, () => undoRippleShift(rippleChanges, [])); console.error("[Timeline] ripple-edit failed to persist after delete", error); showToast("Clip deleted, but the gap could not be closed.", "error"); } } + if (isClosed(editQueueRef)) return; usePlayerStore.getState().setSelectedElementId(null); usePlayerStore.getState().setSelectedElementIds(new Set()); forceReloadSdkSession?.(); @@ -269,7 +271,6 @@ export function useTimelineDeleteOps({ }, [ activeCompPath, - projectIdRef, recordEdit, showToast, writeProjectFile, diff --git a/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx b/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx new file mode 100644 index 0000000000..f42b07a729 --- /dev/null +++ b/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx @@ -0,0 +1,170 @@ +// @vitest-environment happy-dom + +import React, { act } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { usePlayerStore, type TimelineElement } from "../player"; +import { jsonResponse, requestUrl } from "./fetchStubTestUtils"; +import { useTimelineEditing } from "./useTimelineEditing"; + +(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +afterEach(() => { + document.body.innerHTML = ""; + usePlayerStore.getState().reset(); + vi.unstubAllGlobals(); +}); + +const clip = (id: string, start: number): TimelineElement => ({ + id, + key: `index.html#${id}`, + domId: id, + tag: "div", + start, + duration: 2, + track: 0, + sourceFile: "index.html", +}); +const SOURCE = ["a", "b", "c", "d"] + .map( + (id, i) => + `
`, + ) + .join("\n"); + +/** Every request to project "new" is a leak; project "old" answers like a server. */ +function stubFetch(leaks: string[]) { + vi.stubGlobal( + "fetch", + vi.fn(async (input: Parameters[0]) => { + const url = requestUrl(input); + if (url.includes("/projects/new/")) { + leaks.push(url); + return jsonResponse({}, 500); + } + if (url.includes("/remove-elements/")) return jsonResponse({ content: SOURCE }); + if (url.includes("/gsap-mutation-capabilities")) + return jsonResponse({ atomicOwnershipPairs: true }); + if (url.includes("/gsap-mutations")) { + return jsonResponse({ mutated: false, scriptText: null, before: SOURCE, after: SOURCE }); + } + if (url.includes("/files/")) return jsonResponse({ content: SOURCE }); + throw new Error(`Unexpected fetch: ${url}`); + }), + ); +} + +/** An iframe stand-in that records every way anyone reaches into it, `instanceof` included. */ +function spyIframe(touched: string[]): HTMLIFrameElement { + return new Proxy({} as HTMLIFrameElement, { + get: (_, property) => { + touched.push(`get ${String(property)}`); + return undefined; + }, + has: (_, property) => { + touched.push(`has ${String(property)}`); + return false; + }, + getPrototypeOf: () => { + touched.push("getPrototypeOf"); + return null; + }, + }); +} + +describe.each(["lands", "is refused"])( + "edits queued in one project while its first save %s, then a project switch", + (outcome) => { + // fails without the fix: the old project's queued edits patched and reloaded the new preview. + it("never touch the new project's preview, timeline store, files or history", async () => { + const leaks: string[] = []; + stubFetch(leaks); + const store = usePlayerStore.getState(); + store.setRippleEditEnabled(true); + store.setDuration(10); + store.setElements([clip("a", 0), clip("b", 2), clip("c", 4), clip("d", 6)]); + + let releaseFirstSave: (error?: Error) => void = () => {}; + const firstSave = new Promise((done, fail) => { + releaseFirstSave = (error) => (error ? fail(error) : done()); + }); + const oldWrite = vi.fn().mockReturnValueOnce(firstSave).mockResolvedValue(undefined); + const newProject = { write: vi.fn(), recordEdit: vi.fn() }; + const shared = { + reloadPreview: vi.fn(), + forceReloadSdkSession: vi.fn(), + invalidateGsapCache: vi.fn(), + pending: { current: new Set() }, + }; + const oldIframe = document.createElement("iframe"); + document.body.append(oldIframe); + const previewIframeRef: { current: HTMLIFrameElement | null } = { current: oldIframe }; + + let hook: ReturnType | null = null; + function Harness({ projectId }: { projectId: "old" | "new" }) { + const own = projectId === "old" ? { write: oldWrite, recordEdit: vi.fn() } : newProject; + hook = useTimelineEditing({ + projectId, + activeCompPath: "index.html", + timelineElements: usePlayerStore.getState().elements, + showToast: vi.fn(), + writeProjectFile: own.write, + recordEdit: own.recordEdit, + reloadPreview: shared.reloadPreview, + previewIframeRef, + pendingTimelineEditPathRef: shared.pending, + uploadProjectFiles: vi.fn(), + forceReloadSdkSession: shared.forceReloadSdkSession, + invalidateGsapCache: shared.invalidateGsapCache, + }); + return null; + } + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + act(() => root.render()); + + const [a, b, c, d] = usePlayerStore.getState().elements; + const queued: Array> = []; + act(() => { + queued.push(Promise.resolve(hook!.handleTimelineElementsDelete([b!]))); + queued.push( + Promise.resolve(hook!.handleTimelineElementResize(a!, { start: 0, duration: 1 })), + ); + queued.push(Promise.resolve(hook!.handleTimelineGroupMove([{ element: c!, start: 7 }]))); + queued.push(Promise.resolve(hook!.handleTimelineElementMove(d!, { start: 9, track: 0 }))); + }); + + const touchedIframe: string[] = []; + const newElements = [clip("x", 0), clip("y", 2)]; + act(() => { + previewIframeRef.current = spyIframe(touchedIframe); + usePlayerStore.getState().setElements(newElements); + root.render(); + }); + for (const spy of Object.values(shared)) if (typeof spy === "function") spy.mockClear(); + shared.pending.current.clear(); + const storeChanges = vi.fn(); + const stopWatching = usePlayerStore.subscribe(storeChanges); + + await act(async () => { + releaseFirstSave(outcome === "lands" ? undefined : new Error("refused")); + await Promise.allSettled(queued); + }); + stopWatching(); + + expect(touchedIframe).toEqual([]); + expect(shared.reloadPreview).not.toHaveBeenCalled(); + expect(shared.forceReloadSdkSession).not.toHaveBeenCalled(); + expect(shared.invalidateGsapCache).not.toHaveBeenCalled(); + expect([...shared.pending.current]).toEqual([]); + expect(storeChanges).not.toHaveBeenCalled(); + expect(usePlayerStore.getState().elements).toEqual(newElements); + expect(newProject.write).not.toHaveBeenCalled(); + expect(newProject.recordEdit).not.toHaveBeenCalled(); + expect(leaks).toEqual([]); + if (outcome === "lands") expect(oldWrite.mock.calls.length).toBeGreaterThan(1); + act(() => root.unmount()); + }); + }, +); diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts index 6de351c915..1554f77e52 100644 --- a/packages/studio/src/hooks/useTimelineEditing.ts +++ b/packages/studio/src/hooks/useTimelineEditing.ts @@ -24,6 +24,7 @@ import { import { useTimelineGroupEditing } from "./useTimelineGroupEditing"; import { useTimelineClipTimingEditing } from "./useTimelineClipTimingEditing"; import { useTimelineTrimRipple } from "./useTimelineTrimRipple"; +import { useTimelineEditQueue } from "./timelineEditQueue"; import { useBlockedTimelineEditToast } from "./useBlockedTimelineEditToast"; import { useTimelineEditGate, type TimelineEditOutcome } from "./timelineEditPermission"; import type { UseTimelineEditingOptions } from "./useTimelineEditingTypes"; @@ -50,7 +51,7 @@ export function useTimelineEditing({ }: UseTimelineEditingOptions) { const projectIdRef = useRef(projectId); projectIdRef.current = projectId; - const editQueueRef = useRef(Promise.resolve()); + const editQueueRef = useTimelineEditQueue(projectId); const track = useTrackPendingTimelineEdit(); const checkEditable = useTimelineEditGate(canEdit, showToast); const guard = useTimelineEditGuard(canEdit, showToast); @@ -63,7 +64,6 @@ export function useTimelineEditing({ isRecordingRef, pendingTimelineEditPathRef, previewIframeRef, - projectIdRef, recordEdit, reloadPreview, sdkSession, @@ -87,7 +87,6 @@ export function useTimelineEditing({ invalidateGsapCache, handleDomZIndexReorderCommitRef, editQueueRef, - projectIdRef, }); const { handleTrimElement, handleTrimElements } = useTimelineTrimRipple({ @@ -96,6 +95,7 @@ export function useTimelineEditing({ handleTimelineGroupMove: groupEditing.handleTimelineGroupMove, showToast, reloadPreview, + editQueueRef, }); const handleToggleTrackHidden = useTimelineTrackVisibilityEditing({ @@ -169,7 +169,6 @@ export function useTimelineEditing({ }); const { handleTimelineElementsDelete } = useTimelineDeleteOps({ - projectIdRef, activeCompPath, showToast, writeProjectFile, diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx index e13dcd54b9..83e197d66d 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx @@ -46,10 +46,9 @@ describe("useTimelineGroupEditing: handleTimelineGroupMove suppressFailureToast" function Harness() { hook = useTimelineGroupEditing({ activeCompPath: "index.html", - editQueueRef: { current: Promise.resolve() }, + editQueueRef: { current: Promise.resolve(), projectId: null }, pendingTimelineEditPathRef: { current: new Set() }, previewIframeRef: { current: null }, - projectIdRef: { current: null }, recordEdit: vi.fn().mockResolvedValue(undefined), reloadPreview: vi.fn(), showToast, @@ -115,10 +114,9 @@ it.each([false, true])( function Harness() { hook = useTimelineGroupEditing({ activeCompPath: "index.html", - editQueueRef: { current: Promise.resolve() }, + editQueueRef: { current: Promise.resolve(), projectId: "fixture" }, pendingTimelineEditPathRef: { current: new Set() }, previewIframeRef: { current: iframe }, - projectIdRef: { current: "fixture" }, recordEdit, writeProjectFile, reloadPreview: vi.fn(), @@ -166,11 +164,9 @@ it.each([false, true])( // The real group commits on a queue whose first edit was refused. function mountBehindRefusedEdit(showToast = vi.fn()) { - const editQueueRef: TimelineEditQueue = { current: Promise.resolve() }; - const earlier = enqueueTimelineEdit( - editQueueRef, - () => Promise.reject(new Error("delete refused")), - { projectId: "fixture" }, + const editQueueRef: TimelineEditQueue = { current: Promise.resolve(), projectId: "fixture" }; + const earlier = enqueueTimelineEdit(editQueueRef, () => + Promise.reject(new Error("delete refused")), ); const fetchMock = vi.fn(async () => new Response(JSON.stringify({ content: "" }))); vi.stubGlobal("fetch", fetchMock); @@ -181,7 +177,6 @@ function mountBehindRefusedEdit(showToast = vi.fn()) { editQueueRef, pendingTimelineEditPathRef: { current: new Set() }, previewIframeRef: { current: null }, - projectIdRef: { current: "fixture" }, recordEdit: vi.fn(), reloadPreview: vi.fn(), showToast, @@ -266,10 +261,9 @@ it("undoes each group move with its GSAP rewrite in one step, however long the r editHistory = usePersistentEditHistory({ projectId: "demo" }); editing = useTimelineGroupEditing({ activeCompPath: "index.html", - editQueueRef: { current: Promise.resolve() }, + editQueueRef: { current: Promise.resolve(), projectId: "demo" }, pendingTimelineEditPathRef: { current: new Set() }, previewIframeRef: { current: null }, - projectIdRef: { current: "demo" }, recordEdit: editHistory.recordEdit, reloadPreview: vi.fn(), showToast: vi.fn(), diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts index 6a43d0d330..79cc622c90 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.ts +++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts @@ -36,6 +36,9 @@ import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics"; import { enqueueTimelineEdit, refuseWithEarlier, + isClosed, + shownPreview, + whileShown, type TimelineEditQueue, } from "./timelineEditQueue"; @@ -77,7 +80,6 @@ interface UseTimelineGroupEditingOptions { isRecordingRef?: RefObject; pendingTimelineEditPathRef: MutableRefObject>; previewIframeRef: RefObject; - projectIdRef: MutableRefObject; recordEdit: (input: RecordEditInput) => Promise; reloadPreview: () => void; sdkSession?: Composition | null; @@ -125,7 +127,6 @@ export function useTimelineGroupEditing({ isRecordingRef, pendingTimelineEditPathRef, previewIframeRef, - projectIdRef, recordEdit, reloadPreview, sdkSession, @@ -143,16 +144,14 @@ export function useTimelineGroupEditing({ showToast("Cannot edit timeline while recording", "error"); return Promise.reject(new Error(`${label}: blocked while recording`)); } - const projectId = projectIdRef.current; - if (!projectId) return Promise.reject(new Error(`${label}: no active project`)); + if (!editQueueRef.projectId) return Promise.reject(new Error(`${label}: no active project`)); // The raw (rejecting) promise lets the gesture owner roll back on a real failure. - return enqueueTimelineEdit(editQueueRef, () => operation(projectId), { + return enqueueTimelineEdit(editQueueRef, operation, { label, ifEarlierRefused, - projectId, }); }, - [editQueueRef, isRecordingRef, projectIdRef, showToast], + [editQueueRef, isRecordingRef, showToast], ); const persistServerBatch = useCallback( @@ -170,14 +169,17 @@ export function useTimelineGroupEditing({ changes: batchChanges, writeProjectFile, recordEdit, - pendingTimelineEditPathRef, + pendingTimelineEditPathRef: isClosed(editQueueRef) + ? { current: new Set() } + : pendingTimelineEditPathRef, coalesceKey, coalesceMs, }); - forceReloadSdkSession?.(); + whileShown(editQueueRef, () => forceReloadSdkSession?.()); }, [ activeCompPath, + editQueueRef, forceReloadSdkSession, pendingTimelineEditPathRef, recordEdit, @@ -191,6 +193,7 @@ export function useTimelineGroupEditing({ // server syncs) when it handled the edit; null → caller falls through to the server. const trySdkBatchPersist = useCallback( async (input: { + projectId: string; changes: readonly { element: TimelineElement }[]; sdkChanges: Array<{ hfId: string; @@ -209,6 +212,11 @@ export function useTimelineGroupEditing({ input.eligible && input.sdkChanges.every((change) => change !== null); if (!canUseSdk) return null; + const shown = shownPreview(editQueueRef, { + iframeRef: previewIframeRef, + reloadPreview, + publishSdkSession, + }); const result = await sdkTimingBatchPersist( input.sdkChanges.filter((change): change is NonNullable => change !== null), sharedPath, @@ -216,10 +224,10 @@ export function useTimelineGroupEditing({ { editHistory: { recordEdit }, writeProjectFile, - reloadPreview, + reloadPreview: shown.reload, compositionPath: activeCompPath, - readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path), - publishSession: publishSdkSession, + readProjectFile: (path) => readFileContent(input.projectId, path), + publishSession: shown.publish, }, { label: input.label, @@ -232,7 +240,8 @@ export function useTimelineGroupEditing({ }, [ activeCompPath, - projectIdRef, + editQueueRef, + previewIframeRef, publishSdkSession, recordEdit, reloadPreview, @@ -276,6 +285,7 @@ export function useTimelineGroupEditing({ // Snapshot the duration BEFORE the optimistic updates below so a failed // persist can roll the readout + live root back (see captureDurationRollback). const rollbackDuration = captureDurationRollback(previewIframeRef.current); + const shown = shownPreview(editQueueRef, { iframeRef: previewIframeRef, reloadPreview }); // needsExtension gates the SDK path (setTiming can't grow the root duration), // so read the store BEFORE the readout sync below optimistically updates it. // Track-only batches leave every clip end unchanged, so both this and the @@ -290,6 +300,7 @@ export function useTimelineGroupEditing({ return enqueueGroupOperation(label, options?.ifEarlierRefused, async (projectId) => { await options?.beforeTiming; const sdk = await trySdkBatchPersist({ + projectId, changes, sdkChanges: toSdkTimingChanges(changes, (change) => ({ start: toAuthoredStart(change.element, change.start), @@ -333,8 +344,8 @@ export function useTimelineGroupEditing({ try { await finishGroupTimingGsapFallback({ projectId, - iframe: previewIframeRef.current, - reloadPreview, + iframe: shown.iframe(), + reloadPreview: shown.reload, label, errorLabel: "Failed to shift GSAP positions", coalesceKey, @@ -348,12 +359,12 @@ export function useTimelineGroupEditing({ shiftGsapMutation(change.element.domId, change.start - change.element.start), }); } finally { - invalidateGsapCache?.(); + whileShown(editQueueRef, () => invalidateGsapCache?.()); } }).catch((error) => { // Failed persist: revert the optimistic duration readout + live root // alongside the gesture owner's store rollback. - rollbackDuration(); + whileShown(editQueueRef, rollbackDuration); if (options?.suppressFailureToast) { console.error("[Timeline] group move failed to persist", error); } else { @@ -364,6 +375,7 @@ export function useTimelineGroupEditing({ }, [ activeCompPath, + editQueueRef, enqueueGroupOperation, persistServerBatch, previewIframeRef, @@ -398,6 +410,7 @@ export function useTimelineGroupEditing({ // Snapshot the duration BEFORE the optimistic updates below so a failed // persist can roll the readout + live root back (see captureDurationRollback). const rollbackDuration = captureDurationRollback(previewIframeRef.current); + const shown = shownPreview(editQueueRef, { iframeRef: previewIframeRef, reloadPreview }); // needsExtension gates the SDK path (setTiming can't grow the root duration), // so read the store BEFORE the readout sync below optimistically updates it. const needsExtension = extendRootDurationIfNeeded(maxEnd); @@ -409,6 +422,7 @@ export function useTimelineGroupEditing({ return enqueueGroupOperation("Resize timeline clips", derivedStarts, async (projectId) => { await options?.beforeTiming; const sdk = await trySdkBatchPersist({ + projectId, changes, sdkChanges: toSdkTimingChanges(changes, (change) => ({ start: toAuthoredStart(change.element, change.start), @@ -442,8 +456,8 @@ export function useTimelineGroupEditing({ try { await finishGroupTimingGsapFallback({ projectId, - iframe: previewIframeRef.current, - reloadPreview, + iframe: shown.iframe(), + reloadPreview: shown.reload, label: "Resize timeline clips", errorLabel: "Failed to scale GSAP positions", coalesceKey, @@ -463,18 +477,19 @@ export function useTimelineGroupEditing({ ), }); } finally { - invalidateGsapCache?.(); + whileShown(editQueueRef, () => invalidateGsapCache?.()); } }).catch((error) => { // Failed persist: revert the optimistic duration readout + live root // alongside the gesture owner's store rollback. - rollbackDuration(); + whileShown(editQueueRef, rollbackDuration); showToast(getStudioSaveErrorMessage(error), "error"); throw error; }); }, [ activeCompPath, + editQueueRef, enqueueGroupOperation, persistServerBatch, previewIframeRef, diff --git a/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx b/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx index 72d8d89013..3f639eab40 100644 --- a/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx +++ b/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx @@ -50,6 +50,7 @@ function mountTrimRipple(rippleOn: boolean, elements: TimelineElement[]) { handleTimelineGroupMove, showToast: vi.fn(), reloadPreview, + editQueueRef: { current: Promise.resolve(), projectId: "project" }, }); return null; } diff --git a/packages/studio/src/hooks/useTimelineTrimRipple.ts b/packages/studio/src/hooks/useTimelineTrimRipple.ts index 823bf4ac1e..548a47fa84 100644 --- a/packages/studio/src/hooks/useTimelineTrimRipple.ts +++ b/packages/studio/src/hooks/useTimelineTrimRipple.ts @@ -3,7 +3,7 @@ import { usePlayerStore, type TimelineElement } from "../player"; import { batchElementUpdates } from "../player/store/batchElementUpdates"; import { resolveMainTrackTrimRipple } from "../player/components/timelineGapCommit"; import { timingGestureStep } from "./timelineTimingSync"; -import { refuseWithEarlier } from "./timelineEditQueue"; +import { isClosed, refuseWithEarlier, type TimelineEditQueue } from "./timelineEditQueue"; import type { TimelineGroupCommitOptions, TimelineGroupMoveChange, @@ -24,6 +24,7 @@ interface UseTimelineTrimRippleOptions { ) => Promise; showToast: (message: string, tone?: "error" | "info") => void; reloadPreview: () => void; + editQueueRef: TimelineEditQueue; } function setStarts(changes: ReadonlyArray<{ element: TimelineElement; start: number }>) { @@ -41,6 +42,7 @@ export function useTimelineTrimRipple({ handleTimelineGroupMove, showToast, reloadPreview, + editQueueRef, }: UseTimelineTrimRippleOptions) { const persistWithRipple = useCallback( async ( @@ -54,6 +56,7 @@ export function useTimelineTrimRipple({ if (!ripple) return persistTrimAlone(); const { coalesceKey } = timingGestureStep("timeline-resize", given); const undoRipple = () => { + if (isClosed(editQueueRef)) return; const now = new Map(usePlayerStore.getState().elements.map((e) => [e.key ?? e.id, e])); setStarts( ripple.map(({ element, start }) => ({ @@ -89,7 +92,7 @@ export function useTimelineTrimRipple({ showToast("Clip trimmed, but the gap could not be closed.", "error"); } }, - [handleTimelineGroupResize, handleTimelineGroupMove, showToast, reloadPreview], + [handleTimelineGroupResize, handleTimelineGroupMove, showToast, reloadPreview, editQueueRef], ); const handleTrimElement = useCallback( diff --git a/packages/studio/src/player/components/timelineOptimisticRevision.ts b/packages/studio/src/player/components/timelineOptimisticRevision.ts index ea6dbecae6..857ad634f6 100644 --- a/packages/studio/src/player/components/timelineOptimisticRevision.ts +++ b/packages/studio/src/player/components/timelineOptimisticRevision.ts @@ -3,7 +3,11 @@ import { batchElementUpdates } from "../store/batchElementUpdates"; type UpdateElement = (key: string, updates: Partial) => void; type RevisionScope = "timing" | "membership"; -const revisionsByUpdater = new WeakMap>>(); +let revisionsByUpdater = new WeakMap>>(); + +export function forgetTimelineOptimisticGestures(): void { + revisionsByUpdater = new WeakMap(); +} export function beginTimelineOptimisticGesture( updateElement: UpdateElement, From 969eeba6eea5d04daa50586a62871d2861130513 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 09:03:34 +0000 Subject: [PATCH 094/367] fix(engine): a heavy page starts only as many capture browsers as the machine's memory holds (#8452) * fix(engine): a heavy page starts only as many capture browsers as the machine's memory holds Worker 0 loads the page alone; its browsers' measured memory caps how many more launch, and the frames are split again across the ones kept. A worker phase that starts after the pool was cancelled no longer leaves its own failure unhandled. * refactor(engine): drop a frame-range update the capped first worker never reads * chore(engine): its packed size budget grows by the 1,040 bytes the worker memory cap adds * test(engine): the re-split pool test builds its folder paths the way Windows does --- .../parallelCoordinator-memoryFit.test.ts | 71 ++++++++++ .../parallelCoordinator-peerAbort.test.ts | 2 +- .../src/services/parallelCoordinator.test.ts | 58 ++++++++ .../src/services/parallelCoordinator.ts | 129 +++++++++++++++--- scripts/package-size-budgets.json | 2 +- 5 files changed, 241 insertions(+), 21 deletions(-) create mode 100644 packages/engine/src/services/parallelCoordinator-memoryFit.test.ts diff --git a/packages/engine/src/services/parallelCoordinator-memoryFit.test.ts b/packages/engine/src/services/parallelCoordinator-memoryFit.test.ts new file mode 100644 index 0000000000..a86f2f6963 --- /dev/null +++ b/packages/engine/src/services/parallelCoordinator-memoryFit.test.ts @@ -0,0 +1,71 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { CaptureSession } from "./frameCapture.js"; + +const GIB = 1024; + +describe("a parallel capture whose page is heavier than the memory budget assumes", () => { + afterEach(() => { + vi.resetModules(); + vi.doUnmock("./frameCapture.js"); + vi.doUnmock("./systemMemory.js"); + }); + + it("launches only the browsers that fit, measured from worker 0's loaded page, and captures every frame", async () => { + const root = mkdtempSync(join(tmpdir(), "hf-memory-fit-")); + const launched: string[] = []; + const captured: number[] = []; + vi.doMock("./systemMemory.js", async (importOriginal) => ({ + ...(await importOriginal()), + getSystemTotalMb: () => 24 * GIB, + })); + vi.doMock("./frameCapture.js", () => ({ + createCaptureSession: vi.fn(async (_url: string, outputDir: string) => { + launched.push(outputDir.slice(-8)); + return { + options: {}, + browserConsoleBuffer: [], + chromeMemory: { + sampleOnce: async () => {}, + stats: () => ({ samples: 1, rssLastMb: 3_700 }), + }, + } as unknown as CaptureSession; + }), + initializeSession: vi.fn(async () => {}), + captureFrame: vi.fn(async (_session: CaptureSession, frameIndex: number) => { + captured.push(frameIndex); + return { path: join(root, `frame_${frameIndex}.png`) }; + }), + captureFrameToBuffer: vi.fn(), + captureFrameToBufferPipelined: vi.fn(), + closeCaptureSession: vi.fn(async () => {}), + getCapturePerfSummary: vi.fn(() => ({ frames: 0 })), + })); + + try { + const { distributeFrames, executeParallelCapture } = await import("./parallelCoordinator.js"); + const tasks = distributeFrames(60, 6, root); + const results = await executeParallelCapture( + "http://127.0.0.1", + root, + tasks, + { width: 1920, height: 1080, fps: { num: 30, den: 1 } }, + () => null, + ); + + // 24 GiB x 0.5 / 3.7 GiB per browser = 3 browsers, not the 6 the split asked for. + expect(launched).toEqual(["worker-0", "worker-1", "worker-2"]); + expect(results.map((r) => [r.startFrame, r.endFrame])).toEqual([ + [0, 20], + [20, 40], + [40, 60], + ]); + expect(tasks).toHaveLength(3); + expect([...captured].sort((a, b) => a - b)).toEqual(Array.from({ length: 60 }, (_, i) => i)); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/engine/src/services/parallelCoordinator-peerAbort.test.ts b/packages/engine/src/services/parallelCoordinator-peerAbort.test.ts index 4dae2fa0b0..a365e8a8ed 100644 --- a/packages/engine/src/services/parallelCoordinator-peerAbort.test.ts +++ b/packages/engine/src/services/parallelCoordinator-peerAbort.test.ts @@ -78,7 +78,7 @@ describe("executeParallelCapture peer abort", () => { } as unknown as CaptureSession & { workerId: number }; }), initializeSession: vi.fn(async (session: CaptureSession & { workerId: number }) => { - if (session.workerId === 0) throw new Error("Composition has zero duration."); + if (session.workerId === 1) throw new Error("Composition has zero duration."); await Promise.resolve(); }), captureFrame: vi.fn().mockResolvedValue(undefined), diff --git a/packages/engine/src/services/parallelCoordinator.test.ts b/packages/engine/src/services/parallelCoordinator.test.ts index f381ea89a8..c56250859d 100644 --- a/packages/engine/src/services/parallelCoordinator.test.ts +++ b/packages/engine/src/services/parallelCoordinator.test.ts @@ -1,4 +1,5 @@ import { availableParallelism, totalmem } from "os"; +import { join } from "path"; import { getHeapStatistics } from "v8"; import { afterEach, describe, it, expect, vi } from "vitest"; import { @@ -6,6 +7,7 @@ import { computeWorkerSizing, createPoolFailureHandler, distributeFrames, + distributeFramesInterleaved, expectedFramesForTask, flagSilentWorkerExits, formatPoolFailure, @@ -16,6 +18,7 @@ import { selectWorkerDiagnostics, shouldDisableBrowserPoolForParallelWorker, shouldVerifyWorkerGpu, + shrinkTasks, synthesizeSilentWorkerExitError, withParallelWorkerDeadline, resolveParallelDeVerifySamples, @@ -52,6 +55,61 @@ describe("parallel worker phase deadline", () => { }); }); +describe("a worker phase started after the pool was cancelled", () => { + it("rejects as cancelled and leaves no unhandled rejection when the phase fails later", async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + try { + const controller = new AbortController(); + controller.abort(); + let failPhase!: (error: Error) => void; + const phase = new Promise((_, reject) => (failPhase = reject)); + const diagnostic = { + workerId: 1, + phase: "session_init" as const, + browserExecutable: "chrome", + browserVersion: "unknown", + canvasDrawElement: false, + gpuBackend: "unknown", + }; + await expect( + withParallelWorkerDeadline(phase, diagnostic, 0, controller.signal), + ).rejects.toThrow("Parallel worker cancelled"); + failPhase(new Error("page failed to load")); + await new Promise((settle) => setImmediate(settle)); + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); +}); + +describe("shrinkTasks", () => { + it("re-splits an interleaved pool across the kept workers, covering every frame once", () => { + const tasks = distributeFramesInterleaved(10, 4, "/tmp/work", 100); + expect(shrinkTasks(tasks, 2)).toBe(true); + const frames = tasks.flatMap((task) => { + const out: number[] = []; + for (let f = task.startFrame; f < task.endFrame; f += task.frameStride ?? 1) out.push(f); + return out; + }); + expect(tasks.map((task) => task.outputDir)).toEqual([ + join("/tmp/work", "worker-0"), + join("/tmp/work", "worker-1"), + ]); + expect(frames.sort((a, b) => a - b)).toEqual(Array.from({ length: 10 }, (_, i) => 100 + i)); + }); + + it("leaves a pool it cannot re-split unchanged", () => { + const tasks = distributeFrames(10, 3, "/tmp/work"); + tasks[1]!.startFrame = 5; + const before = structuredClone(tasks); + expect(shrinkTasks(tasks, 2)).toBe(false); + expect(tasks).toEqual(before); + }); +}); + describe("distributeFrames", () => { it("distributes frames evenly across workers", () => { const tasks = distributeFrames(100, 4, "/tmp/work"); diff --git a/packages/engine/src/services/parallelCoordinator.ts b/packages/engine/src/services/parallelCoordinator.ts index 7f885c171c..6c5d3f09dd 100644 --- a/packages/engine/src/services/parallelCoordinator.ts +++ b/packages/engine/src/services/parallelCoordinator.ts @@ -153,6 +153,8 @@ type WorkerBrowserPoolDecision = { // Chrome-under-capture RSS and let memory-constrained hosts overcommit (wild // 16GB black-slab report; 0.7.66 heap-OOM report on 24GB with 6 auto workers). const MEMORY_PER_WORKER_MB = 1536; +/** Share of the machine's (or container's) memory the capture browsers may take together. */ +const WORKER_MEMORY_SHARE = 0.5; // Parent-process V8 heap the coordinator itself needs regardless of worker // count (compile artifacts, puppeteer sessions, encoder state). const HEAP_RESERVED_MB = 1024; @@ -358,7 +360,10 @@ export function computeWorkerSizing( 1, cpuQuota === null ? cpuCount - 2 : Math.min(cpuCount - 2, Math.floor(cpuQuota)), ); - const memoryBasedWorkers = Math.max(1, Math.floor((totalMemoryMb * 0.5) / MEMORY_PER_WORKER_MB)); + const memoryBasedWorkers = Math.max( + 1, + Math.floor((totalMemoryMb * WORKER_MEMORY_SHARE) / MEMORY_PER_WORKER_MB), + ); const frameBasedWorkers = Math.floor(totalFrames / MIN_FRAMES_PER_WORKER); const captureCostMultiplier = Math.max(1, config?.captureCostMultiplier ?? 1); @@ -512,6 +517,55 @@ export function distributeFramesInterleaved( return tasks; } +/** Workers whose browsers fit the memory share, at the RSS one browser measured with the page loaded. */ +function workersWithinMemory( + requested: number, + browserRssMb: number | undefined, + totalMemoryMb: number = getSystemTotalMb(), +): number { + if (browserRssMb === undefined || browserRssMb <= 0) return requested; + const fit = Math.floor((totalMemoryMb * WORKER_MEMORY_SHARE) / browserRssMb); + return Math.max(MIN_WORKERS, Math.min(requested, fit)); +} + +/** + * Re-split a contiguous or interleaved pool for its first `keep` workers, in place. Worker 0 keeps its task (its + * page is loaded); the others keep their output folders. Returns false, unchanged, for any other shape of split. + */ +export function shrinkTasks(tasks: WorkerTask[], keep: number): boolean { + const first = tasks[0]; + if (!first || keep < 1 || keep >= tasks.length) return false; + const stride = first.frameStride ?? 1; + const contiguous = tasks.every( + (task, i) => + (task.frameStride ?? 1) === 1 && (i === 0 || task.startFrame === tasks[i - 1]!.endFrame), + ); + const interleaved = + stride === tasks.length && + tasks.every( + (task, i) => + task.frameStride === stride && + task.startFrame === first.startFrame + i && + task.endFrame === first.endFrame, + ); + if (!contiguous && !interleaved) return false; + const end = contiguous ? tasks[tasks.length - 1]!.endFrame : first.endFrame; + const split = (contiguous ? distributeFrames : distributeFramesInterleaved)( + end - first.startFrame, + keep, + "", + first.startFrame, + ); + split.forEach((range, i) => { + const task = tasks[i]!; + task.startFrame = range.startFrame; + task.endFrame = range.endFrame; + if (interleaved) task.frameStride = range.frameStride; + }); + tasks.splice(split.length); + return true; +} + /** * Decide whether a parallel worker should run the per-worker SwiftShader * assertion. Gated to worker 0 only: workers within a chunk share the same @@ -546,7 +600,10 @@ export function withParallelWorkerDeadline( timeoutMs: number, signal?: AbortSignal, ): Promise { - if (signal?.aborted) return Promise.reject(new Error("Parallel worker cancelled")); + if (signal?.aborted) { + promise.catch(() => {}); + return Promise.reject(new Error("Parallel worker cancelled")); + } return new Promise((resolve, reject) => { let timer: ReturnType | undefined; const cleanup = () => { @@ -901,6 +958,7 @@ async function executeWorkerTask( onWorkerPhase?: (diagnostic: ParallelWorkerPhaseDiagnostic) => void, onWorkerOperation?: (diagnostic: ParallelWorkerPhaseDiagnostic) => void, gate?: FirstSessionGate, + onLoaded?: (session: CaptureSession) => Promise, ): Promise { const startTime = Date.now(); let framesCaptured = 0; @@ -969,6 +1027,7 @@ async function executeWorkerTask( await assertSwiftShader(activeSession.page, readWebGlVendorInfoFromCanvas); } await initializeSession(activeSession); + await onLoaded?.(activeSession); if (gate) await (task.workerId === 0 ? gate.verify(activeSession) : gate.wait()); }); canvasDrawElement = activeSession.captureMode === "drawelement"; @@ -1151,6 +1210,39 @@ export function createPoolFailureHandler(args: { }; } +/** + * Worker 0 loads the page alone; its browser's memory then caps how many more launch, so a heavy page cannot + * start more browsers than the container holds. The others start when worker 0 is loaded or has failed. + */ +async function launchWithinMemory( + tasks: WorkerTask[], + run: ( + task: WorkerTask, + onLoaded?: (session: CaptureSession) => Promise, + ) => Promise, +): Promise { + const [first] = tasks; + if (!first || tasks.length === 1) return Promise.all(tasks.map((task) => run(task))); + const requested = tasks.length; + let release!: () => void; + const loaded = new Promise((resolve) => (release = resolve)); + const firstResult = run(first, async (session) => { + await session.chromeMemory?.sampleOnce(); + const browserRssMb = session.chromeMemory?.stats().rssLastMb; + const keep = workersWithinMemory(requested, browserRssMb); + if (shrinkTasks(tasks, keep)) { + console.warn("[Parallel] capture workers capped to fit memory", { + requested, + keep, + browserRssMb, + }); + } + release(); + }).finally(release); + await loaded; + return Promise.all([firstResult, ...tasks.slice(1).map((task) => run(task))]); +} + export async function executeParallelCapture( serverUrl: string, workDir: string, @@ -1226,23 +1318,22 @@ export async function executeParallelCapture( }); const onFailure = failureHandler.onFailure; const gate = hooks?.verifyFirstSession && createFirstSessionGate(hooks.verifyFirstSession); - const results = await Promise.all( - tasks.map((task) => - executeWorkerTask( - task, - serverUrl, - workerCaptureOptions, - createBeforeCaptureHook, - workerSignal, - onFrameCaptured, - onFrameBuffer, - config, - parallel, - onFailure, - onWorkerPhase, - hooks?.onWorkerOperation, - gate, - ), + const results = await launchWithinMemory(tasks, (task, onLoaded) => + executeWorkerTask( + task, + serverUrl, + workerCaptureOptions, + createBeforeCaptureHook, + workerSignal, + onFrameCaptured, + onFrameBuffer, + config, + parallel, + onFailure, + onWorkerPhase, + hooks?.onWorkerOperation, + gate, + onLoaded, ), ); diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index b531ee7d2d..2a816727a4 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -12,7 +12,7 @@ "unpacked": 4898942 }, "@hyperframes/engine": { - "packed": 510000, + "packed": 511040, "unpacked": 1742862 }, "@hyperframes/gcp-cloud-run": { From f51e57b26ea1526ee3f5a3ce6b3838243b801087 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 09:32:54 +0000 Subject: [PATCH 095/367] fix(studio): a thrown value whose name getter throws still falls back to a reload (#8474) * test(studio): a thrown value whose name getter throws still falls back and reports other * fix(studio): a thrown value's name that throws reports other and keeps the reload * style(studio): keep the thrown-name note to one line --- .../studio/src/hooks/gsapRuntimePatch.test.ts | 30 +++++++++++++++++++ packages/studio/src/hooks/gsapRuntimePatch.ts | 10 +++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/packages/studio/src/hooks/gsapRuntimePatch.test.ts b/packages/studio/src/hooks/gsapRuntimePatch.test.ts index dcb9fc951f..558d75cb60 100644 --- a/packages/studio/src/hooks/gsapRuntimePatch.test.ts +++ b/packages/studio/src/hooks/gsapRuntimePatch.test.ts @@ -623,6 +623,36 @@ describe("patchRuntimeTweenInPlace — a throw inside the patch", () => { logged.mockRestore(); }); + // fails without the fix: reading the name of a thrown object whose name getter throws escaped the catch and skipped + // the reload fallback. + it("still falls back, and reports 'other', when reading the thrown value's name throws", () => { + const logged = vi.spyOn(console, "error").mockImplementation(() => {}); + const el = { id: "box" }; + const thrown = { + get name(): string { + throw new Error("name getter"); + }, + }; + const iframe = { + contentWindow: { + gsap: { + set: () => { + throw thrown; + }, + }, + }, + contentDocument: { querySelector: (sel: string) => (sel === "#box" ? el : null) }, + } as unknown as HTMLIFrameElement; + + expect(patchRuntimeTweenInPlace(iframe, "#box", { kind: "global-set", props: { x: 1 } })).toBe( + false, + ); + expect(trackStudioEvent).toHaveBeenLastCalledWith("gsap_instant_patch_threw", { + error_name: "other", + }); + logged.mockRestore(); + }); + it("reports a name the composition gave its own error class as 'other'", () => { const logged = vi.spyOn(console, "error").mockImplementation(() => {}); class FilmError extends Error { diff --git a/packages/studio/src/hooks/gsapRuntimePatch.ts b/packages/studio/src/hooks/gsapRuntimePatch.ts index 7b7cb3cf89..741214f0bc 100644 --- a/packages/studio/src/hooks/gsapRuntimePatch.ts +++ b/packages/studio/src/hooks/gsapRuntimePatch.ts @@ -30,10 +30,14 @@ const REPORTED_ERROR_NAMES = new Set([ "NotFoundError", "DataCloneError", ]); -// The error may come from the preview frame's realm, so its name is read, never checked with instanceof. +// The film controls the thrown value and its realm: read its name (never instanceof); a throwing name is 'other'. function reportedErrorName(error: unknown): string { - const name = (error as { name?: unknown } | null)?.name; - return typeof name === "string" && REPORTED_ERROR_NAMES.has(name) ? name : "other"; + try { + const name = (error as { name?: unknown } | null)?.name; + return typeof name === "string" && REPORTED_ERROR_NAMES.has(name) ? name : "other"; + } catch { + return "other"; + } } function reachablePreview(iframe: HTMLIFrameElement): PatchTarget { From a638c31aa1a0cd44a02019930a0cf506f28bef72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 09:32:57 +0000 Subject: [PATCH 096/367] ci(windows): run the engine and CLI tests in three shards, not two, to stay under the step deadline (#8476) --- .github/workflows/windows-render.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/windows-render.yml b/.github/workflows/windows-render.yml index 1c12f01415..fc457862a9 100644 --- a/.github/workflows/windows-render.yml +++ b/.github/workflows/windows-render.yml @@ -433,18 +433,22 @@ jobs: studio_shard: 2/2 - lane: core packages: --filter @hyperframes/core --filter @hyperframes/player --filter @hyperframes/shader-transitions - # Engine and CLI ran one after the other in a single lane (about 5 + 11 min), 16 min of a 16 min deadline; - # each half runs the same two packages with Vitest's --shard, so the lanes end together. + # Engine and CLI run the same two packages in thirds with Vitest's --shard: halves sat at 842-934 s of + # the 960 s step deadline, so a slow runner failed them. - lane: engine-cli-1 packages: --filter @hyperframes/engine --filter @hyperframes/cli - test_shard: 1/2 + test_shard: 1/3 process_tests: true - lane: engine-cli-2 packages: --filter @hyperframes/engine --filter @hyperframes/cli - test_shard: 2/2 + test_shard: 2/3 process_tests: true once_checks: true runtime_contract: true + - lane: engine-cli-3 + packages: --filter @hyperframes/engine --filter @hyperframes/cli + test_shard: 3/3 + process_tests: true steps: - name: Disable Windows Defender real-time monitoring From 4157992664d3a9bd456594252fb7a5061ff45c27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 09:40:47 +0000 Subject: [PATCH 097/367] fix(core): load the motion path plugin only for a page that tweens along a path (#8449) * fix(core): load the motion path plugin only for a page that tweens along a path * fix(core): a path tween an external script builds still gets the motion path plugin * test(studio): a path tween from an external script gets the plugin when Studio connects * fix(core): a page with a script the preview cannot read still gets the motion path plugin * fix(studio-server): the preview builder, not a file name, decides a page needs no path plugin * refactor(studio-server): split the preview builder's script check * fix(studio-server): a script the preview builder cannot read leaves the page unmarked * fix(studio-server): the preview builder reads scripts off the event loop, within a time budget * fix(studio-server): the preview builder resolves script paths off the event loop too * fix(studio-server): the preview builder's script scan stays inside the request's deadline * fix(core): the async project path check answers null for a path it cannot resolve --- packages/core/src/gsapCdn.ts | 4 + .../core/src/runtime/editing/softReload.ts | 14 +- packages/core/src/safePath.test.ts | 15 ++ packages/core/src/safePath.ts | 19 ++- .../studio-server/src/helpers/projectDisk.ts | 10 +- .../src/routes/preview.noPathTween.test.ts | 133 ++++++++++++++++++ .../src/routes/preview.scanDeadline.test.ts | 56 ++++++++ .../studio-server/src/routes/preview.test.ts | 33 +++++ packages/studio-server/src/routes/preview.ts | 121 ++++++++++++++-- .../studio/src/utils/gsapSoftReload.test.ts | 29 +++- packages/studio/src/utils/gsapSoftReload.ts | 6 +- .../utils/gsapSoftReloadWait.browser.test.ts | 120 ++++++++++++++-- packages/studio/tests/sealedPreviewHarness.ts | 6 +- 13 files changed, 537 insertions(+), 29 deletions(-) create mode 100644 packages/studio-server/src/routes/preview.noPathTween.test.ts create mode 100644 packages/studio-server/src/routes/preview.scanDeadline.test.ts diff --git a/packages/core/src/gsapCdn.ts b/packages/core/src/gsapCdn.ts index 1091a94734..cd26c30a8e 100644 --- a/packages/core/src/gsapCdn.ts +++ b/packages/core/src/gsapCdn.ts @@ -1,6 +1,10 @@ export const GSAP_CDN_VERSION = "3.15.0"; const GSAP_CDN_BASE_URL = "https://cdn.jsdelivr.net/npm"; export const GSAP_BASE_URL_META = "hyperframes-gsap-base-url"; +export const GSAP_PLUGIN_LOAD_ATTR = "data-hf-gsap-plugin"; +export const NO_PATH_TWEEN_META = "hf-no-path-tween"; + +export const namesMotionPath = (script: string) => /motionPath["']?\s*[:{]/.test(script); function isLoopbackHost(hostname: string): boolean { return hostname === "localhost" || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(hostname); diff --git a/packages/core/src/runtime/editing/softReload.ts b/packages/core/src/runtime/editing/softReload.ts index b297a9504c..f4d7947b1b 100644 --- a/packages/core/src/runtime/editing/softReload.ts +++ b/packages/core/src/runtime/editing/softReload.ts @@ -1,7 +1,13 @@ // A GSAP script edit re-runs the edited composition's script in the live preview, without a reload. // Studio runs it on a frame it can reach; a sealed frame runs it on itself through the editing port, // with the script Studio saved and the authored styles Studio read from that file. -import { GSAP_BASE_URL_META, motionPathPluginUrl } from "../../gsapCdn"; +import { + GSAP_BASE_URL_META, + GSAP_PLUGIN_LOAD_ATTR, + NO_PATH_TWEEN_META, + motionPathPluginUrl, + namesMotionPath, +} from "../../gsapCdn"; import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading"; import { escapeCssString } from "../editingElement"; import { applyAuthoredTiming } from "../../studioPreviewMark"; @@ -407,6 +413,7 @@ function whenMotionPathLoaded( }; const pluginScript = doc.createElement("script"); pluginScript.src = previewMotionPathUrl(doc, win.gsap?.version); + pluginScript.setAttribute(GSAP_PLUGIN_LOAD_ATTR, ""); pluginScript.onload = () => settle(Boolean(win.MotionPathPlugin)); // Running the script without the plugin would leave a motionPath tween that cannot play. pluginScript.onerror = () => settle(false); @@ -455,12 +462,13 @@ export function swapWaiting(win: SoftReloadWindow = window as SoftReloadWindow): return (win.__hfSwapsWaiting ?? 0) > 0; } -/** Loads and registers MotionPathPlugin ahead of the first re-run that needs it, as Studio does same-origin. */ +/** Loads and registers MotionPathPlugin ahead of a re-run that needs it, unless the page is marked path-free. */ export function preloadMotionPath( win: SoftReloadWindow = window as SoftReloadWindow, doc: Document = document, ): void { if (win.MotionPathPlugin || win.__hfMotionPathWaiters || !win.gsap) return; + if (doc.querySelector(`meta[name="${NO_PATH_TWEEN_META}"]`)) return; const register = () => win.MotionPathPlugin && win.gsap?.registerPlugin?.(win.MotionPathPlugin); whenMotionPathLoaded(win, doc, register, () => {}); } @@ -523,7 +531,7 @@ export function softReloadFrame( return ran && !builtDom; }; - const needsMotionPath = /motionPath\s*[:{]/.test(script); + const needsMotionPath = namesMotionPath(script); if (!needsMotionPath || win.MotionPathPlugin || !win.gsap) { if (!swap(currentTime)) return "cannot-soft-reload"; return verifyTimelinesPopulated(win, targetKeys) ? "applied" : "verify-failed"; diff --git a/packages/core/src/safePath.test.ts b/packages/core/src/safePath.test.ts index 00ec9f7062..db3f2e8e74 100644 --- a/packages/core/src/safePath.test.ts +++ b/packages/core/src/safePath.test.ts @@ -16,6 +16,7 @@ import { isSafePath, isStudioPrivatePath, mkdirWithinProject, + resolveExistingWithinProjectOff, resolveWithinProject, toolTrustedFileKind, } from "./safePath.js"; @@ -189,6 +190,20 @@ describe("resolveWithinProject", () => { if (!tryCreateSymlink(external, join(base, "link"), "dir")) return; expect(resolveWithinProject(base, "link/secret.txt")).toBeNull(); }); + + it("answers the same off the event loop for a file that exists", async () => { + const base = tmpDir("rwp-base-"); + const external = tmpDir("rwp-external-"); + writeFileSync(join(base, "in.js"), "in"); + writeFileSync(join(external, "secret.txt"), "top secret"); + expect(await resolveExistingWithinProjectOff(base, "in.js")).toBe(join(base, "in.js")); + // fails without the fix: a path that does not resolve threw instead of answering null. + expect(await resolveExistingWithinProjectOff(base, "missing.js")).toBeNull(); + const escape = join("..", basename(external), "secret.txt"); + expect(await resolveExistingWithinProjectOff(base, escape)).toBeNull(); + if (!tryCreateSymlink(external, join(base, "link"), "dir")) return; + expect(await resolveExistingWithinProjectOff(base, "link/secret.txt")).toBeNull(); + }); }); describe("mkdirWithinProject", () => { diff --git a/packages/core/src/safePath.ts b/packages/core/src/safePath.ts index 14f1b27664..b30eab7f1b 100644 --- a/packages/core/src/safePath.ts +++ b/packages/core/src/safePath.ts @@ -105,10 +105,27 @@ export function isSafePath(base: string, resolved: string): boolean { const targetReal = trailing.length ? join(ancestorReal, ...[...trailing].reverse()) : ancestorReal; - return targetReal === baseReal || targetReal.startsWith(baseReal + sep); + return realPathWithin(baseReal, targetReal); } } +/** The containment rule once both sides are real paths. */ +export const realPathWithin = (baseReal: string, targetReal: string): boolean => + targetReal === baseReal || targetReal.startsWith(baseReal + sep); + +/** `resolveWithinProject` off the event loop: the absolute path of an existing entry inside `base`, else null. */ +export async function resolveExistingWithinProjectOff( + base: string, + relativePath: string, +): Promise { + const resolved = resolve(base, relativePath); + if (namesAnotherNetworkRoot(resolve(base), resolved)) return null; + const real = await Promise.all([realpathOff(resolve(base)), realpathOff(resolved)]).catch( + () => null, + ); + return real !== null && realPathWithin(real[0], real[1]) ? resolved : null; +} + /** * Resolve `relativePath` against `base` and return the absolute path only if it * stays within `base` (after symlink resolution); otherwise return `null`. diff --git a/packages/studio-server/src/helpers/projectDisk.ts b/packages/studio-server/src/helpers/projectDisk.ts index 45fc068c8c..84b30ba239 100644 --- a/packages/studio-server/src/helpers/projectDisk.ts +++ b/packages/studio-server/src/helpers/projectDisk.ts @@ -1,6 +1,6 @@ import type { Stats } from "node:fs"; import { stat } from "node:fs/promises"; -import { realpathOff } from "@hyperframes/core/safe-path"; +import { realpathOff, resolveExistingWithinProjectOff } from "@hyperframes/core/safe-path"; import { basename, dirname, join, relative, sep } from "node:path"; import { isPrivateProjectPath } from "./safePath.js"; @@ -37,3 +37,11 @@ export async function isPrivateProjectFileOff( ); return real === unresolvable || isPrivateProjectPath(rel(real[0], real[1])); } + +export async function resolveExistingProjectFileOff( + base: string, + relativePath: string, +): Promise { + const file = await resolveExistingWithinProjectOff(base, relativePath); + return file === null || (await isPrivateProjectFileOff(base, file)) ? null : file; +} diff --git a/packages/studio-server/src/routes/preview.noPathTween.test.ts b/packages/studio-server/src/routes/preview.noPathTween.test.ts new file mode 100644 index 0000000000..a5cc851d61 --- /dev/null +++ b/packages/studio-server/src/routes/preview.noPathTween.test.ts @@ -0,0 +1,133 @@ +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { NO_PATH_TWEEN_META } from "@hyperframes/core/gsap-cdn"; +import { describe, expect, it, onTestFinished } from "vitest"; +import { + injectStudioPreviewAugmentations, + provesNoPathTween, + withPreviewBase, + withPreviewRuntime, +} from "./preview"; + +const GSAP_FILE = "/*! GSAP 3.12.5 */ window.gsap = { timeline: function () {} };"; +const PLAIN_TWEEN = ''; +const LATE_PATH_TWEEN = + 'window.buildPathTween = function () { gsap.to("#card", { motionPath: { path: [{ x: 50, y: 0 }] } }); };'; + +function projectDir(files: Record, links: Record = {}): string { + const dir = mkdtempSync(join(tmpdir(), "hf-no-path-tween-")); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + for (const [rel, content] of Object.entries(files)) { + mkdirSync(join(dir, rel, ".."), { recursive: true }); + writeFileSync(join(dir, rel), content, "utf-8"); + } + for (const [rel, target] of Object.entries(links)) symlinkSync(target, join(dir, rel)); + return dir; +} + +/** The main preview page for `scripts` in the head, as the preview route builds it, and the project it reads. */ +function page( + scripts: string, + files: Record = {}, + links: Record = {}, +) { + const index = `${scripts}
${PLAIN_TWEEN}`; + const dir = projectDir({ "index.html": index, ...files }, links); + return { html: withPreviewRuntime(withPreviewBase(index, "film"), "/api/runtime.js"), dir }; +} + +const pathFree = ( + scripts: string, + files?: Record, + links?: Record, +) => { + const { html, dir } = page(scripts, files, links); + return provesNoPathTween(html, dir); +}; + +describe("the preview builder's proof that no script can tween along a path", () => { + // fails without the fix: no preview carried the mark, so every one loaded the plugin. + it("holds for a page whose scripts are read and name no path: its own GSAP file and inline tweens", async () => { + const own = ''; + expect(await pathFree(own, { "gsap.min.js": GSAP_FILE })).toBe(true); + }); + + it("holds for a page that loads GSAP from its CDN", async () => { + const cdn = ''; + expect(await pathFree(cdn)).toBe(true); + }); + + it("fails for a project script that builds a path tween, whatever its name", async () => { + const authored = ''; + expect(await pathFree(authored, { "authored/gsap.js": LATE_PATH_TWEEN })).toBe(false); + }); + + it("fails for a script it cannot read: another host, a missing file, a module, a folder", async () => { + expect(await pathFree('')).toBe(false); + expect(await pathFree('')).toBe(false); + const module = ''; + expect(await pathFree(module, { "gsap.min.js": GSAP_FILE })).toBe(false); + expect(await pathFree('', { "assets/a.txt": "a" })).toBe(false); + }); + + it("fails for a script that links out of the project", async () => { + const outside = projectDir({ "gsap.min.js": GSAP_FILE }); + const own = ''; + expect(await pathFree(own, {}, { "gsap.min.js": join(outside, "gsap.min.js") })).toBe(false); + }); + + // fails without the fix: each project script's path was resolved with a synchronous realpath on the server thread. + it("resolves project scripts without a synchronous realpath", async () => { + const { html, dir } = page('', { "gsap.min.js": GSAP_FILE }); + const fs = createRequire(import.meta.url)("node:fs") as typeof import("node:fs"); + const native = fs.realpathSync.native; + let syncCalls = 0; + fs.realpathSync.native = ((...args: Parameters) => ( + syncCalls++, native(...args) + )) as typeof native; + onTestFinished(() => void (fs.realpathSync.native = native)); + expect(await provesNoPathTween(html, dir)).toBe(true); + expect(syncCalls).toBe(0); + }); + + // fails without the fix: the scan resolved and read the disk on the route's event loop, with no limit on a silent + // drive. + it.each([ + [ + "resolving its path", + { resolve: () => new Promise(() => {}), read: async () => GSAP_FILE }, + ], + [ + "reading it", + { + resolve: async (base: string, rel: string) => join(base, rel), + read: () => new Promise(() => {}), + }, + ], + ])("fails when %s does not answer within the budget", async (_, files) => { + const { html, dir } = page('', { "gsap.min.js": GSAP_FILE }); + expect(await provesNoPathTween(html, dir, performance.now() + 100, files)).toBe(false); + }); + + it("fails for a page whose own text names a path", async () => { + expect(await pathFree('')).toBe(false); + }); +}); + +describe("the preview's path-free mark", () => { + it("is set only when the builder proved the page path-free", () => { + const { html, dir } = page(""); + const augmented = (proved: boolean) => + injectStudioPreviewAugmentations(html, "/api/runtime.js", "signature", dir, "index.html", { + capture: false, + gsapBaseUrl: "https://cdn.jsdelivr.net/npm", + sandboxedCapture: false, + pathFree: proved, + }); + const mark = ``; + expect(augmented(true)).toContain(mark); + expect(augmented(false)).not.toContain(mark); + }); +}); diff --git a/packages/studio-server/src/routes/preview.scanDeadline.test.ts b/packages/studio-server/src/routes/preview.scanDeadline.test.ts new file mode 100644 index 0000000000..ffe0b36e62 --- /dev/null +++ b/packages/studio-server/src/routes/preview.scanDeadline.test.ts @@ -0,0 +1,56 @@ +// @vitest-environment node +import { afterAll, describe, expect, it, vi } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createStudioApi } from "../createStudioApi"; +import type { StudioApiAdapter } from "../types"; + +vi.mock("../helpers/projectDisk.js", async (real) => { + const disk = await real(); + return { + ...disk, + resolveExistingProjectFileOff: (base: string, rel: string) => + rel.endsWith("held.js") + ? new Promise(() => {}) + : disk.resolveExistingProjectFileOff(base, rel), + }; +}); + +const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-scan-deadline-")); +mkdirSync(join(projectDir, "scenes")); +writeFileSync(join(projectDir, "index.html"), ""); +writeFileSync(join(projectDir, "held.js"), "window.held = true;"); +const scene = (script: string) => + `

Hi

${script}
`; +writeFileSync(join(projectDir, "scenes", "plain.html"), scene("")); +writeFileSync(join(projectDir, "scenes", "held.html"), scene('')); +afterAll(() => rmSync(projectDir, { recursive: true, force: true })); + +const adapter: StudioApiAdapter = { + listProjects: () => [], + resolveProject: async (id: string) => ({ id, dir: projectDir }), + bundle: async () => null, + lint: async () => ({ findings: [] }), + runtimeUrl: "/api/runtime.js", + rendersDir: () => join(projectDir, "renders"), + startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }), +}; +const DEADLINE_MS = 200; +const api = createStudioApi(adapter, { subCompositionDeadlineMs: DEADLINE_MS }); +// Starts the build worker both share, which a 200 ms request cannot wait for. +const patient = createStudioApi(adapter, { subCompositionDeadlineMs: 60_000 }); +const comp = (file: string, on = api) => + on.request(`http://localhost/projects/demo/preview/comp/scenes/${file}`); + +describe("the preview builder's script scan inside a request's deadline", () => { + // fails without the fix: a held lookup kept the request for the scan's own 1 s, past a 200 ms deadline. + it("gives up within the request's time, and the preview is still served", async () => { + expect((await comp("plain.html", patient)).status).toBe(200); + expect((await comp("plain.html")).status).toBe(200); + const started = performance.now(); + const res = await comp("held.html"); + expect(res.status).toBe(200); + expect(performance.now() - started).toBeLessThan(500); + }, 30_000); +}); diff --git a/packages/studio-server/src/routes/preview.test.ts b/packages/studio-server/src/routes/preview.test.ts index 59aa5baffe..e9732f40d5 100644 --- a/packages/studio-server/src/routes/preview.test.ts +++ b/packages/studio-server/src/routes/preview.test.ts @@ -27,6 +27,7 @@ import { STUDIO_PREVIEW_MARK_META, } from "@hyperframes/core/studio-preview-mark"; import { AFTER_FONTS_SCRIPT_TYPE } from "@hyperframes/core/compiler"; +import { GSAP_PLUGIN_LOAD_ATTR } from "@hyperframes/core/gsap-cdn"; import { PREVIEW_BUNDLE_OPTIONS, PREVIEW_CAPTURE_PARAM, @@ -375,6 +376,38 @@ describe("registerPreviewRoutes", () => { expect(message).toContain(appended[0]?.src); }); + // fails without the fix: a failed MotionPath preload was loaded again from the CDN and reported as the film's GSAP. + it("leaves the preview's own plugin load to its loader: no fallback load, no report", async () => { + const app = new Hono(); + registerPreviewRoutes(app, createAdapter(createProjectDir())); + const html = await (await app.request("http://localhost/projects/demo/preview")).text(); + const fallback = /`): string { const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8"); const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); const box = (id: string, track: number, style: string) => @@ -65,7 +66,7 @@ function previewHtml(): string { ${box("target", 1, "left: 100px; top: 100px")}${box("b", 2, "left: 600px; top: 100px")}
- + ${main} `; } @@ -300,24 +301,123 @@ describe.each(MODES)("a re-run waiting for the MotionPath plugin, %s", (mode) => }); }); +const PATH_TWEEN = `(function () { + window.__timelines = window.__timelines || {}; + var tl = gsap.timeline({ paused: true }); + tl.to("#target", { motionPath: { path: [{ x: 0, y: 0 }, { x: 50, y: 0 }] }, duration: 4, ease: "none" }, 0); + window.__timelines["main"] = tl; +})();`; +const PATH_TWEEN_URL = "https://fixture.hyperframes.test/path-tween.js"; + +/** Studio meeting a freshly loaded preview: the same-origin preload (NLEContext), then the editing port. */ +const connect = (page: Page) => + page.evaluate(async () => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const iframe = document.querySelector("iframe")!; + studio.ensureMotionPathPluginLoaded(iframe); + await studio.previewRequest(iframe, "runtime-snapshot", {}); + }); +const pluginScripts = ({ frame }: Preview) => + frame.evaluate(() => document.querySelectorAll('script[src*="MotionPathPlugin"]').length); + // Parity: a same-origin preview gets the plugin on load (NLEContext), and a sealed one when Studio connects. it.each(MODES)( "the first motion-path re-run after load finds the plugin loaded (%s)", async (mode) => { - const { page, frame, release } = await openPreview(mode); + const { page, frame, release } = await openSharedPreview( + browser, + studioBundle, + previewHtml(``), + mode, + ); await release(200); - await page.evaluate(async () => { - const studio = (window as unknown as { hfStudio: Studio }).hfStudio; - const iframe = document.querySelector("iframe")!; - studio.ensureMotionPathPluginLoaded(iframe); - await studio.previewRequest(iframe, "runtime-snapshot", {}); - }); + await connect(page); await frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 }); expect(await rerun(page, timeline("main", "older", 60, true), 1)).toBe("applied"); await page.close(); }, ); +// fails without the fix: the preload read only inline scripts, so this page's plugin was never requested. +it.each(MODES)( + "a path tween from an external script gets the plugin when Studio connects (%s)", + async (mode) => { + const preview = await openSharedPreview( + browser, + studioBundle, + previewHtml(``), + mode, + { [PATH_TWEEN_URL]: PATH_TWEEN }, + ); + await preview.release(200); + await connect(preview.page); + expect(await pluginScripts(preview)).toBe(1); + await preview.frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 }); + await preview.page.close(); + }, +); + +const LATE_PATH_TWEEN = `(function () { + window.__timelines = window.__timelines || {}; + var tl = gsap.timeline({ paused: true }); + window.__timelines["main"] = tl; + window.buildPathTween = function () { + tl.to("#target", { motionPath: { path: [{ x: 0, y: 0 }, { x: 50, y: 0 }] }, duration: 4, ease: "none" }, 0); + }; +})();`; + +const LATE_TWEEN_CASES = MODES.flatMap((mode) => + [PATH_TWEEN_URL, "https://fixture.hyperframes.test/authored/gsap.js"].map( + (url) => [mode, url] as const, + ), +); + +// fails without the fix: an external script that builds its first path tween after connect, named gsap.js, got no +// plugin and stayed at 0. +it.each(LATE_TWEEN_CASES)( + "a path tween an external script builds after connect plays (%s, %s)", + async (mode, url) => { + const preview = await openSharedPreview( + browser, + studioBundle, + previewHtml(``), + mode, + { [url]: LATE_PATH_TWEEN }, + ); + await preview.release(200); + await connect(preview.page); + await preview.frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 }); + await preview.frame.evaluate(() => + (window as unknown as { buildPathTween(): void }).buildPathTween(), + ); + await preview.seek(4); + const x = await preview.frame.evaluate(() => + Number( + ( + window as unknown as { gsap: { getProperty(t: string, p: string): unknown } } + ).gsap.getProperty("#target", "x"), + ), + ); + expect(x).toBeCloseTo(50, 0); + await preview.page.close(); + }, +); + +// fails without the fix: every preview Studio connected to requested the plugin. +it.each(MODES)( + "a page the preview builder marked as path-free requests no plugin (%s)", + async (mode) => { + const marked = previewHtml().replace( + STUDIO_MARK, + `${STUDIO_MARK}`, + ); + const preview = await openSharedPreview(browser, studioBundle, marked, mode); + await connect(preview.page); + expect(await pluginScripts(preview)).toBe(0); + await preview.page.close(); + }, +); + // fails without the fix: all but "still recovers an older script refusal after an unrelated successful patch", // which guards the coverage rule against dropping a refusal no re-run carries. describe("late answers held in transit, sealed", () => { diff --git a/packages/studio/tests/sealedPreviewHarness.ts b/packages/studio/tests/sealedPreviewHarness.ts index 2f5f1a4fa6..cbb25c42b8 100644 --- a/packages/studio/tests/sealedPreviewHarness.ts +++ b/packages/studio/tests/sealedPreviewHarness.ts @@ -127,12 +127,13 @@ function holdReplies() { }); } -/** Opens the preview in Studio's page; the plugin request waits until `release` is called. */ +/** Opens the preview in Studio's page; the plugin request waits until `release`; a `scripts` URL gets its script. */ export async function openPreview( browser: Browser, studioBundle: string, html: string, mode: string, + scripts: Record = {}, ) { const page: Page = await browser.newPage(); const plugin = readFileSync(require.resolve("gsap/dist/MotionPathPlugin.min.js"), "utf8"); @@ -140,6 +141,9 @@ export async function openPreview( let holding = true; await page.setRequestInterception(true); page.on("request", (request) => { + const script = scripts[request.url()]; + if (script !== undefined) + return void request.respond({ status: 200, contentType: "text/javascript", body: script }); if (!/MotionPathPlugin/.test(request.url())) return void request.continue(); const serve = () => request.respond({ status: 200, contentType: "text/javascript", body: plugin }); From 7e26a6d3c0ac6df0e9cc881b8e3009046ff47015 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 09:43:18 +0000 Subject: [PATCH 098/367] fix(studio): a sealed move or resize ends its draft in the save's own frame message (#8473) * fix(studio): a sealed move's save ends its drag draft in the same frame message A sealed move on GSAP's route sent its saved x/y as patch-tweens and the end of the drawn translate as a later draft message, so the frame could paint one frame with both: the layer one whole drag too far. The save now carries the draft's end and the frame applies both in one task. An end that nothing takes goes once, as one message, and an end naming an older draft is ignored. * refactor(core): parse patch-tweens' draft ends in a wrapper, leaving the patch parser as it was * refactor(studio): a drag member's draft end moves to its own module, under the 600-line limit --- .../src/runtime/editing/patchTween.test.ts | 88 +++++++++++++- .../core/src/runtime/editing/patchTween.ts | 24 +++- .../core/src/runtime/editingDraft.test.ts | 50 +++++++- packages/core/src/runtime/editingDraft.ts | 31 +++-- packages/core/src/runtime/editingDraftEnd.ts | 26 ++++ packages/core/src/runtime/editingPort.ts | 16 +-- .../editor/gsapMoveSealedPreview.test.ts | 112 +++++++++++++++++- .../components/editor/manualOffsetDraftEnd.ts | 30 +++++ .../src/components/editor/manualOffsetDrag.ts | 33 ++---- .../src/components/editor/previewDrafts.ts | 89 ++++++++++++-- packages/studio/src/hooks/sealedTweenPatch.ts | 26 +++- 11 files changed, 464 insertions(+), 61 deletions(-) create mode 100644 packages/core/src/runtime/editingDraftEnd.ts create mode 100644 packages/studio/src/components/editor/manualOffsetDraftEnd.ts diff --git a/packages/core/src/runtime/editing/patchTween.test.ts b/packages/core/src/runtime/editing/patchTween.test.ts index d19a89539e..dbf5f818f8 100644 --- a/packages/core/src/runtime/editing/patchTween.test.ts +++ b/packages/core/src/runtime/editing/patchTween.test.ts @@ -1,5 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { parsePatchTweens, patchTweens } from "./patchTween"; +import { drawDrafts } from "../editingDraft"; +import { handleFor } from "../editingHandles"; +import { parsePatchTweens, parsePatchTweensRequest, patchTweens } from "./patchTween"; afterEach(() => { document.body.innerHTML = ""; @@ -139,3 +141,87 @@ describe("patch-tweens parser", () => { expect(parsePatchTweens({ patches: many, seek: true })).toBeNull(); }); }); + +// fails without the fix: a sealed move's save set GSAP's x/y while the drag's drawn translate was still on, so +// one frame showed the layer moved twice before the teardown's draft end arrived. +describe("patch-tweens ending a gesture's draft", () => { + const moved = () => { + frameWithSets(); + const set = vi.fn(); + Object.assign(window, { gsap: { set } }); + const element = document.getElementById("b")!; + const handle = handleFor(element); + const { drafts } = drawDrafts([{ handle, translate: { x: 90, y: 60 }, size: null }]); + return { element, handle, set, draft: drafts[handle]! }; + }; + const save = { + selector: "#b", + change: { kind: "global-set", props: { x: 130, y: 80 } }, + } as const; + + it("drops the drawn translate in the same task that sets the saved position", () => { + const { element, handle, set, draft } = moved(); + + const reply = patchTweens({ + patches: [save], + seek: true, + endsDrafts: [{ handle, draft, end: "keep-size" }], + }); + + expect(reply).toEqual({ patched: true }); + expect(set).toHaveBeenCalledExactlyOnceWith(element, { x: 130, y: 80 }); + expect(element.style.translate).toBe(""); + }); + + it("leaves a live draft alone when the patch ends none", () => { + const { element } = moved(); + + patchTweens({ patches: [save], seek: true }); + + expect(element.style.translate).not.toBe(""); + }); + + it("leaves a newer draft alone when the end names an older one", () => { + const { element, handle, draft } = moved(); + drawDrafts([{ handle, end: "keep" }]); + drawDrafts([{ handle, translate: { x: 5, y: 0 }, size: null }]); + + patchTweens({ patches: [save], seek: true, endsDrafts: [{ handle, draft, end: "keep-size" }] }); + + expect(element.style.translate).not.toBe(""); + }); + + it("ends nothing when a patch does not land, so Studio's own end still finds the draft", () => { + const { element, handle, draft } = moved(); + Reflect.deleteProperty(window, "gsap"); + + const reply = patchTweens({ + patches: [save], + seek: true, + endsDrafts: [{ handle, draft, end: "keep-size" }], + }); + + expect(reply).toEqual({ patched: false }); + expect(element.style.translate).not.toBe(""); + drawDrafts([{ handle, draft, end: "keep-size" }]); + expect(element.style.translate).toBe(""); + }); + + it("parses the ends it carries and refuses a malformed one", () => { + const handle = "0123456789abcdef:1"; + const base = { patches: [save], seek: true }; + expect( + parsePatchTweensRequest({ ...base, endsDrafts: [{ handle, draft: 3, end: "keep-size" }] }), + ).toEqual({ + ...base, + endsDrafts: [{ handle, draft: 3, end: "keep-size" }], + }); + expect( + parsePatchTweensRequest({ ...base, endsDrafts: [{ handle, draft: 0, end: "keep" }] }), + ).toBeNull(); + expect( + parsePatchTweensRequest({ ...base, endsDrafts: [{ handle, end: "keep-size" }] }), + ).toBeNull(); + expect(parsePatchTweensRequest({ ...base, endsDrafts: "all" })).toBeNull(); + }); +}); diff --git a/packages/core/src/runtime/editing/patchTween.ts b/packages/core/src/runtime/editing/patchTween.ts index db7d664d1d..918fa58a7b 100644 --- a/packages/core/src/runtime/editing/patchTween.ts +++ b/packages/core/src/runtime/editing/patchTween.ts @@ -3,6 +3,8 @@ // a sealed frame on itself through the editing port. import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading"; import { recordLiveSet, swapWaiting } from "./softReload"; +import { drawDrafts } from "../editingDraft"; +import { parseDraftEnd, type EditingDraftEnd } from "../editingDraftEnd"; export interface SetPatchProps { x?: number; @@ -375,6 +377,7 @@ export function lastTweenPatch(patches: ReadonlyArray<{ change: RuntimeTweenChan export type PatchTweensParams = { patches: Array<{ selector: string; change: RuntimeTweenChange }>; seek: boolean; + endsDrafts?: EditingDraftEnd[]; }; const isRecord = (value: unknown): value is Record => @@ -419,6 +422,13 @@ function parseChange(value: unknown): RuntimeTweenChange | null { return props ? { kind, props } : null; } +function parseEnds(value: unknown): EditingDraftEnd[] | null { + if (value === undefined) return []; + if (!Array.isArray(value) || value.length > MAX_PATCHES) return null; + const ends = value.map(parseDraftEnd); + return ends.includes(null) ? null : (ends as EditingDraftEnd[]); +} + export function parsePatchTweens(params: unknown): PatchTweensParams | null { if (!isRecord(params) || Object.keys(params).sort().join() !== "patches,seek") return null; const { patches, seek } = params; @@ -437,8 +447,19 @@ export function parsePatchTweens(params: unknown): PatchTweensParams | null { return { patches: parsed, seek }; } +export function parsePatchTweensRequest(params: unknown): PatchTweensParams | null { + if (!isRecord(params)) return null; + const { endsDrafts, ...rest } = params; + const parsed = parsePatchTweens(rest); + const ends = parseEnds(endsDrafts); + if (!parsed || !ends) return null; + return ends.length ? { ...parsed, endsDrafts: ends } : parsed; +} + /** The frame patching its own timelines: every patch must land, and it renders once at the end. */ -export function patchTweens({ patches, seek }: PatchTweensParams): { patched: boolean } { +export function patchTweens({ patches, seek, endsDrafts }: PatchTweensParams): { + patched: boolean; +} { const win = window as unknown as { __timelines?: Record; gsap?: PatchTarget["gsap"]; @@ -457,5 +478,6 @@ export function patchTweens({ patches, seek }: PatchTweensParams): { patched: bo return applyGlobalSet(target, selector, change.props) === null; return !patchTween(target, selector, change, undefined, !(seek && index === renderAt)); }); + if (missed === undefined && endsDrafts) drawDrafts(endsDrafts); return { patched: missed === undefined }; } diff --git a/packages/core/src/runtime/editingDraft.test.ts b/packages/core/src/runtime/editingDraft.test.ts index 9f53e80f87..3f9ce81681 100644 --- a/packages/core/src/runtime/editingDraft.test.ts +++ b/packages/core/src/runtime/editingDraft.test.ts @@ -58,7 +58,9 @@ describe("rotation drafts", () => { describe("drafts", () => { it("adds a drag to the translate the element had, and restores it on a cancel", () => { const { element, handle } = card("translate: 10px 20px; width: 50px"); - expect(drawDrafts([{ handle, translate: { x: 5, y: -4 }, size: null }])).toEqual({ drawn: 1 }); + expect(drawDrafts([{ handle, translate: { x: 5, y: -4 }, size: null }])).toMatchObject({ + drawn: 1, + }); expect(shown(element)).toEqual([15, 16]); drawDrafts([{ handle, translate: { x: 30, y: 0 }, size: null }]); expect(shown(element)).toEqual([40, 20]); @@ -101,6 +103,50 @@ describe("drafts", () => { }); it("skips a handle this load does not have", () => { - expect(drawDrafts([{ handle: "0123456789abcdef:999", end: "restore" }])).toEqual({ drawn: 0 }); + expect(drawDrafts([{ handle: "0123456789abcdef:999", end: "restore" }])).toEqual({ + drawn: 0, + drafts: {}, + }); + }); +}); + +// fails without the fix: a sealed resize's end went as {translate:null} then {end:keep}, two frame tasks. +describe("draft ends by number", () => { + it("answers each draw with its draft's number, the same until the draft ends", () => { + const { handle } = card("width: 50px"); + const first = drawDrafts([{ handle, translate: { x: 1, y: 0 }, size: null }]).drafts[handle]; + expect(drawDrafts([{ handle, translate: { x: 2, y: 0 }, size: null }]).drafts[handle]).toBe( + first, + ); + drawDrafts([{ handle, end: "keep" }]); + const next = drawDrafts([{ handle, translate: { x: 3, y: 0 }, size: null }]).drafts[handle]; + expect(next).toBeGreaterThan(first!); + }); + + it("keep-size drops the drawn translate and keeps the drawn size in one end", () => { + const { element, handle } = card("translate: 10px 20px; width: 50px"); + const { drafts } = drawDrafts([ + { handle, translate: { x: 5, y: 5 }, size: { width: 80, height: 40 } }, + ]); + + drawDrafts([{ handle, draft: drafts[handle]!, end: "keep-size" }]); + + expect([element.style.translate, element.style.width, element.style.height]).toEqual([ + "10px 20px", + "80px", + "40px", + ]); + }); + + it("an end for an older draft leaves the newer one drawn and restorable", () => { + const { element, handle } = card("width: 50px"); + const old = drawDrafts([{ handle, translate: { x: 5, y: 0 }, size: null }]).drafts[handle]!; + drawDrafts([{ handle, end: "restore" }]); + drawDrafts([{ handle, translate: { x: 9, y: 0 }, size: null }]); + + drawDrafts([{ handle, draft: old, end: "restore" }]); + expect(shown(element)).toEqual([9, 0]); + drawDrafts([{ handle, end: "restore" }]); + expect(element.style.translate).toBe(""); }); }); diff --git a/packages/core/src/runtime/editingDraft.ts b/packages/core/src/runtime/editingDraft.ts index ee8416c091..cb051bf09d 100644 --- a/packages/core/src/runtime/editingDraft.ts +++ b/packages/core/src/runtime/editingDraft.ts @@ -5,6 +5,7 @@ */ import { isStylableElement, type StylableElement as Styled } from "./domRealm"; import { elementForHandle } from "./editingHandles"; +import type { EditingDraftEnd, EditingDraftReply } from "./editingDraftEnd"; import type { EditingDraft, EditingDraftRotate } from "./editingPort"; export const SIZE_PROPERTIES = [ @@ -19,6 +20,7 @@ export const SIZE_PROPERTIES = [ const DRAWN = ["translate", "rotate", ...SIZE_PROPERTIES] as const; interface Before { + draft: number; inline: Array<[name: string, value: string, priority: string]>; /** The computed translate, split into its axes with each % as px, that a draft's translate adds to. */ translate: string[]; @@ -33,6 +35,7 @@ type Gsap = { const frameGsap = () => (window as unknown as { gsap?: Gsap }).gsap; const before = new WeakMap(); +let lastDraft = 0; /** "calc(50% + 2px) 4px" as its top-level parts. */ function axes(value: string): string[] { @@ -82,6 +85,7 @@ function beforeOf(element: Styled): Before { if (!saved) { const { style } = element; saved = { + draft: ++lastDraft, inline: DRAWN.map((name) => [ name, style.getPropertyValue(name), @@ -147,15 +151,19 @@ function drawRotate(element: Styled, rotate: EditingDraftRotate | null): void { gsap?.set?.(element, { rotation: rotate.angle }); } -function apply(element: Styled, draft: EditingDraft): void { - if ("end" in draft) { - if (draft.end === "restore") { - restore(element, DRAWN); - restoreGsapRotation(element); - } - before.delete(element); - return; +function end(element: Styled, ending: EditingDraftEnd): void { + const saved = before.get(element); + if (!saved || ("draft" in ending && ending.draft !== saved.draft)) return; + if (ending.end === "restore") { + restore(element, DRAWN); + restoreGsapRotation(element); } + if (ending.end === "keep-size") restore(element, ["translate"]); + before.delete(element); +} + +function apply(element: Styled, draft: EditingDraft): void { + if ("end" in draft) return end(element, draft); if ("rotate" in draft) drawRotate(element, draft.rotate ?? null); if (draft.translate) drawTranslate(element, draft.translate); else restore(element, ["translate"]); @@ -164,13 +172,16 @@ function apply(element: Styled, draft: EditingDraft): void { } /** Applies each draft in order; one for an element this load no longer has is skipped. */ -export function drawDrafts(drafts: readonly EditingDraft[]): { drawn: number } { +export function drawDrafts(drafts: readonly EditingDraft[]): EditingDraftReply { let drawn = 0; + const numbers: Record = {}; for (const draft of drafts) { const element = elementForHandle(draft.handle); if (!isStylableElement(element)) continue; apply(element, draft); drawn++; + const saved = before.get(element); + if (saved) numbers[draft.handle] = saved.draft; } - return { drawn }; + return { drawn, drafts: numbers }; } diff --git a/packages/core/src/runtime/editingDraftEnd.ts b/packages/core/src/runtime/editingDraftEnd.ts new file mode 100644 index 0000000000..eee8e81663 --- /dev/null +++ b/packages/core/src/runtime/editingDraftEnd.ts @@ -0,0 +1,26 @@ +import { EDITING_ELEMENT_HANDLE, type EditingElementHandle } from "./editingElement"; + +/** `keep-size` drops the drawn translate and keeps the drawn size. + * An end naming an older `draft` than the element has does nothing. */ +export type EditingDraftEnd = + | { handle: EditingElementHandle; end: "keep" | "restore" } + | { handle: EditingElementHandle; end: "keep" | "restore" | "keep-size"; draft: number }; + +/** `drafts` numbers each element still drawn, for the end that names its draft. */ +export type EditingDraftReply = { drawn: number; drafts: Record }; + +const isRecord = (value: unknown): value is Record => + Object.prototype.toString.call(value) === "[object Object]"; + +export function parseDraftEnd(value: unknown): EditingDraftEnd | null { + if (!isRecord(value)) return null; + const { handle, end, draft } = value; + if (typeof handle !== "string" || !EDITING_ELEMENT_HANDLE.test(handle)) return null; + const keys = Object.keys(value).sort().join(); + if (keys === "end,handle") return end === "keep" || end === "restore" ? { handle, end } : null; + if (keys !== "draft,end,handle" || !Number.isSafeInteger(draft) || (draft as number) < 1) + return null; + return end === "keep" || end === "restore" || end === "keep-size" + ? { handle, end, draft: draft as number } + : null; +} diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index b014d7e222..d9e327f4c8 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -30,7 +30,8 @@ import type { GsapSnapshot } from "./editing/gsapSnapshot"; import type { MotionPathFrameHome } from "./editing/motionPathHome"; import type { EditingLayer, EditingStackingSibling } from "./editingLayers"; import { parseGsapSet, type GsapSetParams } from "./editing/gsapSet"; -import { parsePatchTweens, type PatchTweensParams } from "./editing/patchTween"; +import { parsePatchTweensRequest, type PatchTweensParams } from "./editing/patchTween"; +import { parseDraftEnd, type EditingDraftEnd, type EditingDraftReply } from "./editingDraftEnd"; import { parseRestoreAttributesRerun, parseSoftReload, @@ -258,7 +259,8 @@ export type EditingKeyMessage = { /** The `rotate` property's whole value in degrees, or GSAP's rotation; null takes the drawn turn back. */ export type EditingDraftRotate = { angle: number; route: "css" | "gsap" }; -/** A gesture's draft on one element: null puts that part back; `end` keeps what is drawn or restores. */ +export type { EditingDraftEnd }; +/** A gesture's draft on one element: null puts that part back; an end keeps what is drawn or restores. */ export type EditingDraft = | { handle: EditingElementHandle; @@ -266,7 +268,7 @@ export type EditingDraft = size: { width: number; height: number } | null; rotate?: EditingDraftRotate | null; } - | { handle: EditingElementHandle; end: "keep" | "restore" }; + | EditingDraftEnd; type NoParams = Record; export interface EditingRequests { @@ -324,7 +326,7 @@ export interface EditingRequests { result: { layers: EditingLayer[]; truncated: boolean; missingGroup: boolean }; }; /** Gesture drafts in order, up to MAX_DESCRIBE_HANDLES; `drawn` counts the elements still here. */ - draft: { params: { drafts: EditingDraft[] }; result: { drawn: number } }; + draft: { params: { drafts: EditingDraft[] }; result: EditingDraftReply }; "gesture-start": { params: { handles: EditingElementHandle[] }; result: { elements: Array; snap: EditingElementBox[] }; @@ -485,9 +487,7 @@ function draftRotate(value: unknown): boolean { function draftEntry(value: unknown): EditingDraft | null { if (!isPlainRecord(value) || !isHandle(value.handle)) return null; - const { handle, end } = value; - if (hasKeys(value, "end,handle")) - return end === "keep" || end === "restore" ? { handle, end } : null; + if ("end" in value) return parseDraftEnd(value); return drawnParts(value) ? (value as EditingDraft) : null; } @@ -602,7 +602,7 @@ const PARAM_PARSERS: { "stacking-family": (params) => hasKeys(params, "handle") && isHandle(params.handle) ? { handle: params.handle } : null, "gsap-set": parseGsapSet, - "patch-tweens": parsePatchTweens, + "patch-tweens": parsePatchTweensRequest, "soft-reload": parseSoftReload, "hold-scenes": parseHoldScenes, "mark-scenes-stale": parseMarkScenesStale, diff --git a/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts b/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts index ca5ec52430..eab4af52cf 100644 --- a/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts +++ b/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts @@ -19,7 +19,19 @@ import { endManualOffsetDragMembers, type ManualOffsetDragMember, } from "./manualOffsetDrag"; -import { drawPreviewDraft } from "./previewDrafts"; +import { drawPreviewDraft, endPreviewDraft } from "./previewDrafts"; +import { patchSealedPreview } from "../../hooks/sealedTweenPatch"; +import { takePreviewTicket } from "../../utils/sealedPreviewLedger"; +import { previewAnswer, previewRequest } from "../../player/lib/previewChannel"; + +vi.mock("../../player/lib/previewChannel", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + previewAnswer: vi.fn(actual.previewAnswer), + previewRequest: vi.fn(actual.previewRequest), + }; +}); import { measurePreviewGestureStart } from "./previewGestureStartRead"; import { captureStudioRotation } from "./manualEditsSnapshot"; import { @@ -145,6 +157,7 @@ async function dragBoxOnSealedFrame( script: string, beforePress?: (iframe: HTMLIFrameElement) => void, beforeEnd?: (standIn: Element, member: ManualOffsetDragMember) => void, + save?: (iframe: HTMLIFrameElement, standIn: Element) => Promise, ) { const box = document.getElementById("box")!; const iframe = opaqueFrame(); @@ -178,8 +191,9 @@ async function dragBoxOnSealedFrame( }, ); beforeEnd?.(standIn, member); + await save?.(iframe, standIn); endManualOffsetDragMembers([member]); - return { started, start, anim: anim!, outcome, commit }; + return { started, start, anim: anim!, outcome, commit, iframe, standIn, member }; } // fails without the fix: the frame kept the drag's drawn translate on top of the x the save gave GSAP. @@ -431,3 +445,97 @@ it("keeps a sealed element's move start when GSAP's rotation is out of range, an expect(start.gsap).toEqual({ x: 100, y: 40, moving: true }); expect(start.gsapRotation).toBeUndefined(); }); + +const draftEnds = () => + vi + .mocked(previewRequest) + .mock.calls.filter(([, kind]) => kind === "draft") + .flatMap(([, , params]) => (params as { drafts: object[] }).drafts) + .filter((op) => "end" in op || ("translate" in op && op.translate === null)); +const patchRequests = () => + vi.mocked(previewAnswer).mock.calls.filter(([, kind]) => kind === "patch-tweens"); +const drawsSettled = () => new Promise((resolve) => setTimeout(resolve, 30)); + +/** The save a sealed move on GSAP's route sends: the new x and y as a base set, as patch-tweens. */ +function savePosition(change: { kind: "global-set" | "set"; props: { x: number; y: number } }) { + return async (iframe: HTMLIFrameElement) => { + await drawsSettled(); + vi.mocked(previewRequest).mockClear(); + vi.mocked(previewAnswer).mockClear(); + const ticket = takePreviewTicket(iframe, { + scriptText: SCRIPT, + snapshot: null, + attributes: false, + timing: false, + }); + patchSealedPreview(ticket, [{ selector: "#box", change }], true, () => undefined); + await vi.waitFor(() => expect(patchRequests()).toHaveLength(1)); + await vi.mocked(previewAnswer).mock.results.at(-1)!.value; + }; +} + +// fails without the fix: the save set GSAP's x/y and the draft end followed as its own message, so the frame +// painted the drawn translate on top of the saved position (the layer moved twice) for a frame. +it("a sealed move's save ends its draft in the same frame message, and the teardown sends no other end", async () => { + mount(SCRIPT); + const { iframe } = await dragBoxOnSealedFrame(SCRIPT, undefined, undefined, async (frame) => { + await savePosition({ kind: "global-set", props: { x: 110, y: 40 } })(frame); + const box = document.getElementById("box")!; + expect([box.style.translate, drawnAt(box)]).toEqual(["", { x: 110, y: 40 }]); + }); + const [[, , params]] = patchRequests() as unknown as [ + [unknown, unknown, { endsDrafts?: unknown[] }], + ]; + expect(params.endsDrafts).toEqual([expect.objectContaining({ end: "keep-size" })]); + await drawsSettled(); + expect(draftEnds()).toEqual([]); + expect(iframe).toBeDefined(); +}); + +// fails without the fix: a gesture with no save ended its draft as {translate:null} then {end:keep}, two messages. +it("a sealed move with no save ends its draft once, as one end", async () => { + mount(SCRIPT); + vi.mocked(previewRequest).mockClear(); + await dragBoxOnSealedFrame(SCRIPT, undefined, undefined, drawsSettled); + + await vi.waitFor(() => expect(document.getElementById("box")!.style.translate).toBe("")); + expect(draftEnds()).toEqual([ + expect.objectContaining({ end: "keep-size", draft: expect.any(Number) }), + ]); +}); + +it("a save the frame cannot apply leaves the end to go alone, so the draft still ends", async () => { + mount(SCRIPT); + await dragBoxOnSealedFrame( + SCRIPT, + undefined, + undefined, + savePosition({ kind: "set", props: { x: 110, y: 40 } }), + ); + + await vi.waitFor(() => expect(document.getElementById("box")!.style.translate).toBe("")); + expect(draftEnds()).toEqual([expect.objectContaining({ end: "keep-size" })]); +}); + +it("a failed save's restore still takes the draft back", async () => { + mount(SCRIPT); + await dragBoxOnSealedFrame(SCRIPT, undefined, (standIn) => endPreviewDraft(standIn, "restore")); + + await vi.waitFor(() => + expect(drawnAt(document.getElementById("box")!)).toEqual({ x: 100, y: 40 }), + ); +}); + +it("an older gesture's save leaves a regrab's draft alone", async () => { + mount(SCRIPT); + await dragBoxOnSealedFrame(SCRIPT, undefined, undefined, async (iframe, standIn) => { + endPreviewDraft(standIn, "keep"); + drawPreviewDraft(standIn, { translate: { x: 7, y: 0 } }); + await savePosition({ kind: "global-set", props: { x: 110, y: 40 } })(iframe); + const [[, , params]] = patchRequests() as unknown as [ + [unknown, unknown, { endsDrafts?: unknown }], + ]; + expect(params.endsDrafts).toBeUndefined(); + expect(drawnTranslate(document.getElementById("box")!)[0]).not.toBe(0); + }); +}); diff --git a/packages/studio/src/components/editor/manualOffsetDraftEnd.ts b/packages/studio/src/components/editor/manualOffsetDraftEnd.ts new file mode 100644 index 0000000000..7bbe71e58c --- /dev/null +++ b/packages/studio/src/components/editor/manualOffsetDraftEnd.ts @@ -0,0 +1,30 @@ +import { selectorFromSelection } from "../../hooks/gsapShared"; +import type { ManualOffsetDragMember } from "./manualOffsetDrag"; +import { + armPreviewDraftEnd, + endPreviewDraft, + endPreviewDraftKeepingSizeOnly, +} from "./previewDrafts"; + +export function armDraftEndOnRelease(member: ManualOffsetDragMember): void { + if (!member.plainTranslate) + armPreviewDraftEnd(member.element, selectorFromSelection(member.selection)); +} + +// Drop the draft's `translate: none` so the soft reload starts clean (#1673). When GSAP owns +// the position it folded any translate into its transform, so one still showing applies twice. +export function settleDraftTranslate(element: HTMLElement, gsapOwnsPosition: boolean): void { + if (element.style.getPropertyValue("translate") === "none") { + element.style.removeProperty("translate"); + } + if (!gsapOwnsPosition) return; + const view = element.ownerDocument.defaultView; + const underneath = view?.getComputedStyle(element).getPropertyValue("translate"); + if (underneath && underneath !== "none") element.style.setProperty("translate", "none"); +} + +export function endDraftKeepingWhatTheSaveWrites(member: ManualOffsetDragMember): void { + if (member.plainTranslate) endPreviewDraft(member.element, "keep"); + else if (member.sizeSavedAsScale) endPreviewDraft(member.element, "restore"); + else endPreviewDraftKeepingSizeOnly(member.element); +} diff --git a/packages/studio/src/components/editor/manualOffsetDrag.ts b/packages/studio/src/components/editor/manualOffsetDrag.ts index af1e44145e..ffa52e871a 100644 --- a/packages/studio/src/components/editor/manualOffsetDrag.ts +++ b/packages/studio/src/components/editor/manualOffsetDrag.ts @@ -21,7 +21,12 @@ import { } from "../../hooks/draggedGsapPosition"; import { editsPlainCss } from "../../hooks/gsapRuntimeKeyframes"; import { readTranslatePx, UNREADABLE_TRANSLATE, writeTranslatePx } from "./plainTranslate"; -import { drawPreviewDraft, endPreviewDraft, endPreviewDraftKeepingSizeOnly } from "./previewDrafts"; +import { drawPreviewDraft, endPreviewDraft } from "./previewDrafts"; +import { + armDraftEndOnRelease, + endDraftKeepingWhatTheSaveWrites, + settleDraftTranslate, +} from "./manualOffsetDraftEnd"; import type { PreviewGestureStart } from "./previewGestureStartRead"; interface OffsetDragGsap { @@ -476,7 +481,12 @@ export function applyManualOffsetDragCommit( dx: number, dy: number, ): { x: number; y: number } { - return applyManualOffsetCommitValue(member, resolveManualOffsetDragMemberOffset(member, dx, dy)); + const offset = applyManualOffsetCommitValue( + member, + resolveManualOffsetDragMemberOffset(member, dx, dy), + ); + armDraftEndOnRelease(member); + return offset; } /** @@ -524,25 +534,6 @@ export function restoreManualOffsetDragMembers(members: ManualOffsetDragMember[] } } -// Drop the draft's `translate: none` so the soft reload starts clean (#1673). When GSAP owns -// the position it folded any translate into its transform, so one still showing applies twice. -function settleDraftTranslate(element: HTMLElement, gsapOwnsPosition: boolean): void { - if (element.style.getPropertyValue("translate") === "none") { - element.style.removeProperty("translate"); - } - if (!gsapOwnsPosition) return; - const view = element.ownerDocument.defaultView; - const underneath = view?.getComputedStyle(element).getPropertyValue("translate"); - if (underneath && underneath !== "none") element.style.setProperty("translate", "none"); -} - -/** Teardown after a COMMITTED drag. */ -function endDraftKeepingWhatTheSaveWrites(member: ManualOffsetDragMember): void { - if (member.plainTranslate) endPreviewDraft(member.element, "keep"); - else if (member.sizeSavedAsScale) endPreviewDraft(member.element, "restore"); - else endPreviewDraftKeepingSizeOnly(member.element); -} - export function endManualOffsetDragMembers(members: ManualOffsetDragMember[]): void { for (const member of members) { if (!isStudioManualEditGestureCurrent(member.element, member.gestureToken)) continue; diff --git a/packages/studio/src/components/editor/previewDrafts.ts b/packages/studio/src/components/editor/previewDrafts.ts index 107f09a8fe..303fe0b449 100644 --- a/packages/studio/src/components/editor/previewDrafts.ts +++ b/packages/studio/src/components/editor/previewDrafts.ts @@ -6,6 +6,7 @@ import { MAX_DESCRIBE_HANDLES, type EditingDraft, + type EditingDraftEnd, type EditingDraftRotate, } from "@hyperframes/core/runtime/editing-port"; import { previewRequest } from "../../player/lib/previewChannel"; @@ -16,9 +17,12 @@ type Drawn = { rotate?: EditingDraftRotate | null; }; +/** One gesture's draft: `draft` is the frame's number for it, `saving` the selector its save will patch. */ +type Entry = Drawn & { gesture: object; draft?: number; saving?: string }; + interface Queue { ops: EditingDraft[]; - drawn: Map; + drawn: Map; sending: boolean; } @@ -51,14 +55,24 @@ function queueFor(iframe: HTMLIFrameElement): Queue { return queue; } +const opGesture = new WeakMap(); + function send(iframe: HTMLIFrameElement, queue: Queue): void { if (queue.sending || !queue.ops.length) return; const drafts = queue.ops.splice(0, MAX_DESCRIBE_HANDLES); queue.sending = true; - void previewRequest(iframe, "draft", { drafts }).finally(() => { - queue.sending = false; - send(iframe, queue); - }); + void previewRequest(iframe, "draft", { drafts }) + .then((reply) => { + for (const op of drafts) { + const entry = queue.drawn.get(op.handle); + const draft = reply?.drafts?.[op.handle]; + if (draft && entry && entry.gesture === opGesture.get(op)) entry.draft = draft; + } + }) + .finally(() => { + queue.sending = false; + send(iframe, queue); + }); } /** Draws `part` of the stand-in's draft on its frame element; any other element is left alone. */ @@ -66,9 +80,17 @@ export function drawPreviewDraft(element: Element, part: Partial): void { const target = standIns.get(element); if (!target) return; const queue = queueFor(target.iframe); - const drawn = { translate: null, size: null, ...queue.drawn.get(target.handle), ...part }; - queue.drawn.set(target.handle, drawn); - const op = { handle: target.handle, ...drawn }; + const entry: Entry = { + translate: null, + size: null, + gesture: {}, + ...queue.drawn.get(target.handle), + ...part, + }; + queue.drawn.set(target.handle, entry); + const { translate, size, rotate } = entry; + const op = { handle: target.handle, translate, size, ...("rotate" in entry && { rotate }) }; + opGesture.set(op, entry.gesture); const last = queue.ops.map((queued) => queued.handle).lastIndexOf(target.handle); const waiting = queue.ops[last]; if (waiting && !("end" in waiting)) queue.ops[last] = op; @@ -76,19 +98,62 @@ export function drawPreviewDraft(element: Element, part: Partial): void { send(target.iframe, queue); } +/** A gesture's commit started: the save that patches `selector` may carry this draft's end. */ +export function armPreviewDraftEnd(element: Element, selector: string | null): void { + const target = standIns.get(element); + const entry = target && queueFor(target.iframe).drawn.get(target.handle); + if (entry && selector) entry.saving = selector; +} + +/** Ends a save patching `selectors` carries; one with draws waiting or no number ends alone. */ +export function takePreviewDraftEnds( + iframe: HTMLIFrameElement, + selectors: readonly string[], +): EditingDraftEnd[] { + const queue = queueFor(iframe); + const ends: EditingDraftEnd[] = []; + for (const [handle, entry] of queue.drawn) { + const waiting = queue.ops.some((op) => op.handle === handle); + if (!entry.draft || !entry.saving || !selectors.includes(entry.saving) || waiting) continue; + queue.drawn.delete(handle); + ends.push({ handle, draft: entry.draft, end: "keep-size" }); + } + return ends; +} + +export function sendPreviewDraftEnds(iframe: HTMLIFrameElement, ends: readonly EditingDraftEnd[]) { + if (!ends.length) return; + const queue = queueFor(iframe); + queue.ops.push(...ends); + send(iframe, queue); +} + export function endPreviewDraftKeepingSizeOnly(element: Element): void { const target = standIns.get(element); - if (!target || !queueFor(target.iframe).drawn.has(target.handle)) return; + const entry = target && queueFor(target.iframe).drawn.get(target.handle); + if (!entry) return; + if (entry.draft) return endDraft(element, "keep-size"); drawPreviewDraft(element, { translate: null }); - endPreviewDraft(element, "keep"); + endDraft(element, "keep"); } /** Ends the stand-in's draft on its frame: "keep" once saved or regrabbed mid-save, else "restore". */ export function endPreviewDraft(element: Element, end: "keep" | "restore"): void { + endDraft(element, end); +} + +function endDraft(element: Element, end: EditingDraftEnd["end"]): void { const target = standIns.get(element); if (!target) return; const queue = queueFor(target.iframe); - if (!queue.drawn.delete(target.handle)) return; - queue.ops.push({ handle: target.handle, end }); + const entry = queue.drawn.get(target.handle); + if (!entry) return; + queue.drawn.delete(target.handle); + const { handle } = target; + queue.ops.push( + entry.draft + ? { handle, draft: entry.draft, end } + : { handle, end: end === "restore" ? "restore" : "keep" }, + ); send(target.iframe, queue); } diff --git a/packages/studio/src/hooks/sealedTweenPatch.ts b/packages/studio/src/hooks/sealedTweenPatch.ts index 9bf2af9c64..87ba139b12 100644 --- a/packages/studio/src/hooks/sealedTweenPatch.ts +++ b/packages/studio/src/hooks/sealedTweenPatch.ts @@ -1,5 +1,6 @@ import type { RuntimeTweenChange } from "./gsapRuntimePatch"; import { sendPreviewWrite, type PreviewTicket } from "../utils/sealedPreviewLedger"; +import { sendPreviewDraftEnds, takePreviewDraftEnds } from "../components/editor/previewDrafts"; const definedChannels = (props: T): T => Object.fromEntries(Object.entries(props).filter(([, v]) => v !== undefined)) as T; @@ -22,6 +23,16 @@ const wirePatch = ({ selector, change }: { selector: string; change: RuntimeTwee const sealedGroupPatched = new WeakMap>(); +const channelsOf = (change: RuntimeTweenChange) => + change.kind === "keyframes" ? change.keyframes.flatMap(Object.keys) : Object.keys(change.props); + +const selectorsNotWritingScale = ( + patches: ReadonlyArray<{ selector: string; change: RuntimeTweenChange }>, +) => + patches + .filter(({ change }) => !channelsOf(change).some((channel) => channel.startsWith("scale"))) + .map(({ selector }) => selector); + /** A sealed preview patches its own tweens; a refusal or no answer runs `fallback` after the group's last write. */ export function patchSealedPreview( ticket: PreviewTicket, @@ -29,11 +40,18 @@ export function patchSealedPreview( lastWrite: boolean, fallback: () => void, ): void { - const request = { patches: patches.map(wirePatch), seek: lastWrite }; const { iframe } = ticket; - const patched = sendPreviewWrite(ticket, "patch-tweens", request).then( - (r) => typeof r === "object" && r?.patched === true, - ); + const endsDrafts = takePreviewDraftEnds(iframe, selectorsNotWritingScale(patches)); + const request = { + patches: patches.map(wirePatch), + seek: lastWrite, + ...(endsDrafts.length && { endsDrafts }), + }; + const patched = sendPreviewWrite(ticket, "patch-tweens", request).then((r) => { + const landed = typeof r === "object" && r?.patched === true; + if (!landed) sendPreviewDraftEnds(iframe, endsDrafts); + return landed; + }); const earlier = sealedGroupPatched.get(iframe) ?? Promise.resolve(true); const group = Promise.all([earlier, patched]).then(([a, b]) => a && b); if (!lastWrite) { From 8f7e59742f700119875eba1d08d265eae3bd83d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:05:26 +0000 Subject: [PATCH 099/367] fix(ci): a rerun of the captures check reads the PR's current body (#8479) --- scripts/ci/resolve-workflow-pr.mjs | 37 ++++++++++++------------ scripts/ci/resolve-workflow-pr.test.mjs | 38 ++++++++++++++++++++++++- 2 files changed, 56 insertions(+), 19 deletions(-) diff --git a/scripts/ci/resolve-workflow-pr.mjs b/scripts/ci/resolve-workflow-pr.mjs index 59e237c738..2065871332 100644 --- a/scripts/ci/resolve-workflow-pr.mjs +++ b/scripts/ci/resolve-workflow-pr.mjs @@ -15,28 +15,29 @@ export function dispatchedPullRequest(pulls, repository, branch, sha) { return pr; } -function main() { - const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8")); - if (process.env.GITHUB_EVENT_NAME === "workflow_dispatch") { - const repository = process.env.GITHUB_REPOSITORY; - const branch = process.env.GITHUB_REF_NAME; +/** The PR a check runs for. A PR event carries the body it had when it fired, and a rerun replays that event, so the + * body is read now; the head stays the one the run checks out. */ +export function resolvedPullRequest(event, env, api) { + const repository = env.GITHUB_REPOSITORY; + if (env.GITHUB_EVENT_NAME === "workflow_dispatch") { + const branch = env.GITHUB_REF_NAME; const owner = repository.split("/")[0]; - const raw = execFileSync( - "gh", - [ - "api", - `repos/${repository}/pulls?state=open&head=${encodeURIComponent(`${owner}:${branch}`)}&per_page=100`, - ], - { encoding: "utf8", timeout: 60_000 }, - ); - event.pull_request = dispatchedPullRequest( - JSON.parse(raw), - repository, - branch, - process.env.GITHUB_SHA, + const pulls = api( + `repos/${repository}/pulls?state=open&head=${encodeURIComponent(`${owner}:${branch}`)}&per_page=100`, ); + return dispatchedPullRequest(pulls, repository, branch, env.GITHUB_SHA); } if (!event.pull_request) throw new Error("This check requires an open pull request."); + const live = api(`repos/${repository}/pulls/${event.pull_request.number}`); + return { ...event.pull_request, body: live.body }; +} + +const ghApi = (path) => + JSON.parse(execFileSync("gh", ["api", path], { encoding: "utf8", timeout: 60_000 })); + +function main() { + const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8")); + event.pull_request = resolvedPullRequest(event, process.env, ghApi); const path = join(process.env.RUNNER_TEMP, "workflow-pr-event.json"); writeFileSync(path, JSON.stringify(event)); appendFileSync( diff --git a/scripts/ci/resolve-workflow-pr.test.mjs b/scripts/ci/resolve-workflow-pr.test.mjs index 953289493a..f22a6c7572 100644 --- a/scripts/ci/resolve-workflow-pr.test.mjs +++ b/scripts/ci/resolve-workflow-pr.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { dispatchedPullRequest } from "./resolve-workflow-pr.mjs"; +import { dispatchedPullRequest, resolvedPullRequest } from "./resolve-workflow-pr.mjs"; const pr = { state: "open", @@ -25,3 +25,39 @@ test("refuses ambiguous PRs", () => { test("refuses a PR which advanced after dispatch", () => { assert.throws(() => resolve([pr], "b".repeat(40)), /head changed/); }); + +// fails without the fix: a rerun of a PR's first check run replayed the body the PR opened with, so a body fixed +// since (Before/After captures added) still failed the captures check on every rerun. +test("a PR event takes the PR's current body, and keeps the head the run is for", () => { + const opened = { ...pr, body: "as opened" }; + const asked = []; + const api = (path) => { + asked.push(path); + return { ...pr, body: "as edited", head: { ...pr.head, sha: "b".repeat(40) } }; + }; + const event = { pull_request: opened }; + const env = { GITHUB_EVENT_NAME: "pull_request", GITHUB_REPOSITORY: "owner/repo" }; + const resolved = resolvedPullRequest(event, env, api); + assert.deepEqual(asked, ["repos/owner/repo/pulls/7"]); + assert.equal(resolved.body, "as edited"); + assert.equal(resolved.head.sha, pr.head.sha); +}); +test("a dispatch finds its PR by branch and exact head", () => { + const env = { + GITHUB_EVENT_NAME: "workflow_dispatch", + GITHUB_REPOSITORY: "owner/repo", + GITHUB_REF_NAME: pr.head.ref, + GITHUB_SHA: pr.head.sha, + }; + const api = (path) => { + assert.match(path, /^repos\/owner\/repo\/pulls\?state=open&head=owner%3Abot%2Fcatalog-publish/); + return [pr]; + }; + assert.equal(resolvedPullRequest({}, env, api), pr); +}); +test("refuses an event without a PR", () => { + assert.throws( + () => resolvedPullRequest({}, { GITHUB_EVENT_NAME: "push" }, () => null), + /open pull request/, + ); +}); From f57552da49c3426e3af641c086fa5cdd25fd595a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:07:51 +0000 Subject: [PATCH 100/367] fix(studio): a sealed Layers pick of a cropped layer puts its resize corners on the whole layer (#8468) * fix(studio): a sealed Layers pick of a cropped layer puts its resize corners on the whole layer * test(studio): keep the crop-lift test's comment within the line limit --- .../components/editor/domEditOverlayCrop.ts | 28 ++++-- .../studio/src/hooks/useCropOverlay.test.ts | 86 +++++++++++++++++++ packages/studio/src/hooks/useCropOverlay.ts | 4 + 3 files changed, 113 insertions(+), 5 deletions(-) create mode 100644 packages/studio/src/hooks/useCropOverlay.test.ts diff --git a/packages/studio/src/components/editor/domEditOverlayCrop.ts b/packages/studio/src/components/editor/domEditOverlayCrop.ts index 9ea143dd11..846044a9b0 100644 --- a/packages/studio/src/components/editor/domEditOverlayCrop.ts +++ b/packages/studio/src/components/editor/domEditOverlayCrop.ts @@ -45,6 +45,23 @@ export function cropRectFromInsets( // A frame lift is kept until the frame says it is gone, so a lost reply never leaves the crop hidden there. type CropLift = { rule: HTMLStyleElement | null; sheetClip?: string; dropped?: boolean }; const cropLifts = new WeakMap(); +const liftListeners = new Set<() => void>(); +let liftVersion = 0; +function liftsChanged() { + liftVersion += 1; + for (const listener of liftListeners) listener(); +} +function setLift(element: HTMLElement, lift: CropLift | null) { + if (lift) cropLifts.set(element, lift); + else cropLifts.delete(element); + liftsChanged(); +} +/** For `useSyncExternalStore`: the overlay redraws its crop hug when a lift starts, lands, is refused or drops. */ +export function subscribeCropLifts(listener: () => void): () => void { + liftListeners.add(listener); + return () => liftListeners.delete(listener); +} +export const cropLiftsVersion = () => liftVersion; const UNLIFT_TRIES = 3; function liftSelector(element: HTMLElement): string | null { @@ -60,7 +77,7 @@ function unliftInFrame(element: HTMLElement, record: CropLift, tries = UNLIFT_TR void previewRequest(target.iframe, "crop-lift", { handle: target.handle, lift: false }).then( (reply) => { if (cropLifts.get(element) !== record) return; - if (reply?.lifted === false) cropLifts.delete(element); + if (reply?.lifted === false) setLift(element, null); else if (tries > 1) unliftInFrame(element, record, tries - 1); }, ); @@ -71,11 +88,11 @@ function liftInFrame(element: HTMLElement): boolean { if (!target) return false; // Until the frame answers, the clip it last reported is the one under the lift. const record: CropLift = { rule: null, sheetClip: frameClipPaths.get(element)?.computed ?? "" }; - cropLifts.set(element, record); + setLift(element, record); void previewRequest(target.iframe, "crop-lift", { handle: target.handle, lift: true }).then( (reply) => { if (cropLifts.get(element) !== record || !reply) return; - if (!reply.lifted) cropLifts.delete(element); + if (!reply.lifted) setLift(element, null); else if (typeof reply.clipPath === "string" && reply.clipPath.length <= MAX_ELEMENT_VALUE) record.sheetClip = reply.clipPath.trim(); }, @@ -92,7 +109,7 @@ export function liftElementCrop(element: HTMLElement): void { const rule = doc.createElement("style"); rule.textContent = `${selector}{clip-path:none!important}`; (doc.head ?? doc.documentElement).append(rule); - cropLifts.set(element, { rule }); + setLift(element, { rule }); } export function dropElementCropLift(element: HTMLElement): void { @@ -100,10 +117,11 @@ export function dropElementCropLift(element: HTMLElement): void { if (!lift || lift.dropped) return; if (lift.rule) { lift.rule.remove(); - cropLifts.delete(element); + setLift(element, null); return; } lift.dropped = true; + liftsChanged(); unliftInFrame(element, lift); } diff --git a/packages/studio/src/hooks/useCropOverlay.test.ts b/packages/studio/src/hooks/useCropOverlay.test.ts new file mode 100644 index 0000000000..0cbd928bc3 --- /dev/null +++ b/packages/studio/src/hooks/useCropOverlay.test.ts @@ -0,0 +1,86 @@ +// @vitest-environment happy-dom +import { act, createElement } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { + dropElementCropLift, + liftElementCrop, + rememberFrameClipPath, +} from "../components/editor/domEditOverlayCrop"; +import type { DomEditSelection } from "../components/editor/domEditing"; +import type { OverlayRect } from "../components/editor/domEditOverlayGeometry"; +import { useCropOverlay } from "./useCropOverlay"; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const sent: Array<(reply: unknown) => void> = []; +let sealed = true; +vi.mock("../player/lib/previewChannel", () => ({ + previewRequest: () => new Promise((answer) => sent.push(answer)), +})); +vi.mock("../components/editor/previewDrafts", () => ({ + previewStandIn: () => (sealed ? { iframe: {}, handle: "hf-1" } : undefined), +})); + +let host: HTMLDivElement; +let root: Root; +beforeEach(() => { + host = document.body.appendChild(document.createElement("div")); + root = createRoot(host); +}); +afterEach(() => { + act(() => root.unmount()); + host.remove(); + sent.length = 0; +}); + +const rect: OverlayRect = { + left: 0, + top: 0, + width: 400, + height: 200, + editScaleX: 1, + editScaleY: 1, +}; + +/** The selection box's crop hug as the overlay last drew it. */ +function drawn(element: HTMLElement) { + const seen: Array = []; + function Probe() { + const { cropOutlineInsetPx } = useCropOverlay({ + selection: { element } as DomEditSelection, + overlayRect: rect, + }); + seen.push(cropOutlineInsetPx?.right ?? null); + return null; + } + act(() => root.render(createElement(Probe))); + return () => seen.at(-1); +} + +// fails without the fix: the lift lives outside React, so the box kept hugging the crop once the handles lifted it. +it("a sealed layer picked with no press drops its crop hug once the crop handles lift it, and gets it back when the frame refuses", async () => { + sealed = true; + const element = document.createElement("div"); + rememberFrameClipPath(element, "inset(0px 150px 0px 0px)", "inset(0px 150px 0px 0px)"); + const hug = drawn(element); + expect(hug()).toBe(150); + act(() => liftElementCrop(element)); + expect(hug(), "the box shows the whole layer while it is lifted").toBe(null); + await act(async () => sent[0]!({ lifted: false, clipPath: null })); + expect(hug(), "a lift the frame refused leaves the crop showing").toBe(150); +}); + +it("an unsealed layer's crop hug follows its lift and its drop", () => { + sealed = false; + const element = document.body.appendChild(document.createElement("div")); + element.id = "target"; + element.style.setProperty("clip-path", "inset(0px 150px 0px 0px)"); + const hug = drawn(element); + expect(hug()).toBe(150); + act(() => liftElementCrop(element)); + expect(hug()).toBe(null); + act(() => dropElementCropLift(element)); + expect(hug()).toBe(150); + element.remove(); +}); diff --git a/packages/studio/src/hooks/useCropOverlay.ts b/packages/studio/src/hooks/useCropOverlay.ts index 2563b33ce5..0d0eec6b1e 100644 --- a/packages/studio/src/hooks/useCropOverlay.ts +++ b/packages/studio/src/hooks/useCropOverlay.ts @@ -1,8 +1,11 @@ +import { useSyncExternalStore } from "react"; import type { OverlayRect } from "../components/editor/domEditOverlayGeometry"; import type { DomEditSelection } from "../components/editor/domEditing"; import { + cropLiftsVersion, isElementCropLifted, readElementCropInsets, + subscribeCropLifts, } from "../components/editor/domEditOverlayCrop"; /** Selection-box crop hug: the outline that makes the selection box hug the @@ -15,6 +18,7 @@ export function useCropOverlay(params: { overlayRect: OverlayRect | null; }) { const { selection, overlayRect } = params; + useSyncExternalStore(subscribeCropLifts, cropLiftsVersion); const cropInsets = selection && !isElementCropLifted(selection.element) From c99cbbe44d92deca1345aac73729fa29828757c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:07:54 +0000 Subject: [PATCH 101/367] fix(studio): a drag behind a refused edit is refused only when it would land on a clip (#8456) * fix(studio): a refused delete no longer brings back another delete still saving A refused delete, or a ripple shift that fails after its delete, now moves back only the clips that delete shifted, on the timeline as it is now, instead of restoring the timeline from before it. * fix(studio): a refused delete also refuses the ripple shifts queued behind it A delete's ripple shift saves absolute starts worked out with every earlier pending delete applied. When one of those is refused, the shifts queued behind it are refused too and leave their gap, so the saved file never puts a clip on top of the restored one. * fix(studio): a ripple shift queued behind a refused edit is refused before it writes The timeline's edit queue now has one owner. It knows when an edit still pending is refused, and a ripple shift (after a delete or a trim) queued behind it is refused instead of saving starts that assumed that edit. The trim ripple's rollback moves clips back by its own shift only. Drags, single-clip timing and link edits are unchanged. * fix(studio): a drag queued behind a refused edit is refused only if it would overlap A drop is where the user put it, so a drag queued behind an edit that is then refused still saves, unless it would now land on a clip in its lane, such as the one a refused delete puts back. Then it is refused with the same "Clips on the same track can't overlap." notice a refused drop shows, and the clip returns to where it was. The lane overlap check is shared with the insert-on-drop partner check. * fix(studio): a trim behind a refused edit follows the drag rule, and both notices show as info A trim queued behind an edit that is then refused is kept unless it now overlaps a clip in its lane, the same rule as a drag. A refused drag or trim shows "Clips on the same track can't overlap." in the same info tone as a refused drop: the notice's owner now holds its words and its tone. * fix(studio): a refused edit refuses trims behind it, per project, until every save settles - A queued save stays tracked until it settles, so a later failure still refuses the ripple queued behind it. - A trim's own resize is refused behind a refused edit too: its start and duration were read from the timeline that edit left. - Each project gets its own queue. - A refused trim shift reloads the preview, as a refused delete does. * test(studio): the project-switch case keeps the old project's save pending * fix(studio): a single-clip SDK timing save waits its turn in the edit queue The SDK move and resize now run inside the queued edit, with the file-write fallback in the same entry, so the earlier-refusal check guards both paths and later edits see these saves. * test(studio): give the clip-timing tests a 10 s timeline so every case can use the SDK path * fix(studio): a single-clip drag behind a refused edit is refused only when it lands on a clip * fix(studio): a queued timeline edit reads and writes only the project it was queued in Each edit queue now carries the project it was made for and hands that id to every queued edit, so the SDK readers, the file writes and the tween rewrite never follow a project switch that happens while an edit waits. * test(studio): hold the old project's save from the start in the project-switch case * revert(studio): leave project isolation of queued edits to its own change Takes out the per-project queue and the project binding of queued edits. Main already lets a queued edit follow a project switch, through more handles than the project id (preview, timeline store, history), so that fix moves to one change that covers every handle. * fix(studio): a queued single-clip SDK save reads the project it was made in Main read the project as the save started, right away; queued, it read it when its turn came. The move and resize now take the project when the gesture queues them, for the SDK reader and the tween rewrite. * fix(studio): a refused edit refuses only later edits of its own project Each queued edit carries the project it was queued in, and the queue tracks refusals per project, so a refusal left behind by a project the editor has moved away from never refuses an edit in the one now open. * test(studio): the switch matrix's stand-in SDK session finds no element, like an unknown target * fix(studio): a refused drag takes back only its own shift With Ripple on, a drag behind a refused delete was rolled back to its rippled start, on top of the clip the delete put back. Both drag rollbacks now move the clip from where it is by this drag's own shift, the rule the delete and trim rollbacks follow. The overlap check no longer takes a lane it never reads. * test(studio): the drag-overlap test's earlier refused edit belongs to the hook's project * refactor(studio): track-insert edits live beside the track-insert layout buildTrackInsertEdits moves unchanged from the drag commit into timelineDragLanding, next to layoutAfterTrackInsert, whose layout it turns into edits. Both the drag and the canvas z-order mirror still call it. * fix(studio): a drag behind a refusal in a project no longer shown is refused The drag's overlap check reads the timeline on screen. Once the editor shows another project, that timeline is not the drag's own, so the check could keep a drag that lands on the clip its refused delete put back. A queue whose project is not shown now refuses an edit behind a refusal outright, before any policy reads live state. * test(studio): the group-drag row carries the policy the move adapter gives it --- .../studio/src/hooks/timelineEditQueue.ts | 25 ++++- .../src/hooks/timelineMoveAdapter.test.ts | 31 +++--- .../studio/src/hooks/timelineMoveAdapter.ts | 28 +++--- .../useTimelineClipTimingEditing.test.tsx | 45 ++++++++- .../src/hooks/useTimelineClipTimingEditing.ts | 12 ++- .../src/hooks/useTimelineDeleteOps.test.tsx | 67 +++++++++++-- .../useTimelineEditing.projectSwitch.test.tsx | 67 +++++++++++++ .../hooks/useTimelineGroupEditing.test.tsx | 26 ++++- .../src/hooks/useTimelineGroupEditing.ts | 6 +- .../player/components/TimelineProvider.tsx | 3 +- .../components/timelineClipDragCommit.test.ts | 47 ++++++++- .../components/timelineClipDragCommit.ts | 95 ++++--------------- .../player/components/timelineCollision.ts | 34 +++++++ .../player/components/timelineDragLanding.ts | 74 ++++++++++++++- .../components/timelineMainTrackInsert.ts | 19 +--- .../studio/src/utils/studioSaveDiagnostics.ts | 4 + 16 files changed, 437 insertions(+), 146 deletions(-) diff --git a/packages/studio/src/hooks/timelineEditQueue.ts b/packages/studio/src/hooks/timelineEditQueue.ts index c185900ef2..e990fd8b6c 100644 --- a/packages/studio/src/hooks/timelineEditQueue.ts +++ b/packages/studio/src/hooks/timelineEditQueue.ts @@ -1,6 +1,12 @@ import { useLayoutEffect, useRef, type MutableRefObject, type RefObject } from "react"; import type { PublishSdkSession } from "../utils/sdkCutover"; import { forgetTimelineOptimisticGestures } from "../player/components/timelineOptimisticRevision"; +import { usePlayerStore } from "../player"; +import { + landsOnLaneClip, + laneOverlapRefusal, + type LaneLanding, +} from "../player/components/timelineCollision"; /** The editor's one timeline edit queue. `placed` holds, per project, a promise that rejects * when an edit of that project still pending is refused. */ @@ -55,8 +61,20 @@ export const refuseWithEarlier = (error: unknown): never => { throw error; }; -/** Runs `run` after every edit queued before it. When one of those, in the same project, was - * refused, `ifEarlierRefused` runs first, and throwing refuses this edit too. */ +/** For an edit the user placed, such as a drop: kept unless it now overlaps a lane clip. */ +export const keepUnlessItOverlaps = + (changes: ReadonlyArray>) => () => { + const { elements } = usePlayerStore.getState(); + const shown = new Map(elements.map((e) => [e.key ?? e.id, e])); + const placed = changes.map(({ element, start }) => ({ + element: shown.get(element.key ?? element.id) ?? element, + start, + })); + if (landsOnLaneClip(elements, placed)) throw laneOverlapRefusal(); + }; + +/** Runs `run` after every edit queued before it. When one in its project was refused, `ifEarlierRefused` + * decides (throw to refuse too); with that project no longer shown, the edit is refused outright. */ export function enqueueTimelineEdit( queue: TimelineEditQueue, run: (projectId: string) => Promise, @@ -73,7 +91,8 @@ export function enqueueTimelineEdit( const byProject = (queue.placed ??= new Map()); const earlier = byProject.get(projectId) ?? Promise.resolve(); const task = queue.current.then(async () => { - if (ifEarlierRefused) await earlier.catch(ifEarlierRefused); + if (ifEarlierRefused) + await earlier.catch(isClosed(queue) ? refuseWithEarlier : ifEarlierRefused); if (!projectId) throw new Error("No project to save this edit to"); return run(projectId); }); diff --git a/packages/studio/src/hooks/timelineMoveAdapter.test.ts b/packages/studio/src/hooks/timelineMoveAdapter.test.ts index 74ea16ee94..497883c4e8 100644 --- a/packages/studio/src/hooks/timelineMoveAdapter.test.ts +++ b/packages/studio/src/hooks/timelineMoveAdapter.test.ts @@ -23,6 +23,12 @@ const movedPair = (edits: MoveArgs[0]) => [ { element: edits[1].element, start: 3, track: 2 }, ]; +// Every drag carries its policy for an earlier refused edit. +const commitOptions = (coalesceKey: string | undefined) => ({ + coalesceKey, + ifEarlierRefused: expect.any(Function), +}); + const runMove = async (edits: MoveArgs[0], coalesceKey: MoveArgs[1], intent: MoveArgs[2]) => { const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined); await persistTimelineMoveEditsAtomically(edits, coalesceKey, intent, { @@ -36,17 +42,19 @@ describe("persistTimelineMoveEditsAtomically", () => { const edits = twoLaneEdits(1); const handleTimelineGroupMove = await runMove(edits, "clip-lane-move:7", "track-insert"); expect(handleTimelineGroupMove).toHaveBeenCalledTimes(1); - expect(handleTimelineGroupMove).toHaveBeenCalledWith(movedPair(edits), { - coalesceKey: "clip-lane-move:7", - }); + expect(handleTimelineGroupMove).toHaveBeenCalledWith( + movedPair(edits), + commitOptions("clip-lane-move:7"), + ); }); it("omits track attrs for plain timing moves (keeps the SDK fast path eligible)", async () => { const edit = { element: element("a", 0), updates: { start: 1, track: 0 } }; const handleTimelineGroupMove = await runMove([edit], undefined, "timing"); - expect(handleTimelineGroupMove).toHaveBeenCalledWith([{ element: edit.element, start: 1 }], { - coalesceKey: undefined, - }); + expect(handleTimelineGroupMove).toHaveBeenCalledWith( + [{ element: edit.element, start: 1 }], + commitOptions(undefined), + ); }); it("persists the track attr for a single lane reorder (stable track lanes)", async () => { @@ -56,16 +64,17 @@ describe("persistTimelineMoveEditsAtomically", () => { const handleTimelineGroupMove = await runMove([edit], "clip-lane-move:7", "lane-reorder"); expect(handleTimelineGroupMove).toHaveBeenCalledWith( [{ element: edit.element, start: 1, track: 1 }], - { coalesceKey: "clip-lane-move:7" }, + commitOptions("clip-lane-move:7"), ); }); it("persists track attrs for a multi-selection lane drag (stable track lanes)", async () => { const edits = twoLaneEdits(2); const handleTimelineGroupMove = await runMove(edits, "clip-lane-move:7", "lane-reorder"); - expect(handleTimelineGroupMove).toHaveBeenCalledWith(movedPair(edits), { - coalesceKey: "clip-lane-move:7", - }); + expect(handleTimelineGroupMove).toHaveBeenCalledWith( + movedPair(edits), + commitOptions("clip-lane-move:7"), + ); }); it("carries explicit detachment through the atomic move", async () => { @@ -76,7 +85,7 @@ describe("persistTimelineMoveEditsAtomically", () => { const handle = await runMove([edit], "move", "track-insert"); expect(handle).toHaveBeenCalledWith( [{ element: edit.element, start: 1, track: 0, audioGroup: null }], - { coalesceKey: "move" }, + commitOptions("move"), ); }); diff --git a/packages/studio/src/hooks/timelineMoveAdapter.ts b/packages/studio/src/hooks/timelineMoveAdapter.ts index 30e1ec860d..a31b4eff51 100644 --- a/packages/studio/src/hooks/timelineMoveAdapter.ts +++ b/packages/studio/src/hooks/timelineMoveAdapter.ts @@ -1,5 +1,6 @@ import { useCallback } from "react"; import type { TimelineElement } from "../player"; +import { keepUnlessItOverlaps } from "./timelineEditQueue"; import type { TimelineGroupCommitOptions, TimelineGroupMoveChange, @@ -35,19 +36,20 @@ export function persistTimelineMoveEditsAtomically( operation: TimelineMoveOperation, deps: AtomicMoveDeps, ): Promise { - return deps.handleTimelineGroupMove( - edits.map(({ element, updates }) => ({ - element, - start: updates.start, - audioGroup: updates.audioGroup, - // Stable track lanes: a lane is the authored data-track-index, so every - // vertical gesture (lane-reorder AND track-insert) must persist the track; - // z is paint order only and is synced separately. Plain horizontal moves - // ("timing") omit it so they stay eligible for the SDK fast path. - track: operation === "timing" ? undefined : updates.track, - })), - { coalesceKey }, - ); + const changes = edits.map(({ element, updates }) => ({ + element, + start: updates.start, + audioGroup: updates.audioGroup, + // Stable track lanes: a lane is the authored data-track-index, so every + // vertical gesture (lane-reorder AND track-insert) must persist the track; + // z is paint order only and is synced separately. Plain horizontal moves + // ("timing") omit it so they stay eligible for the SDK fast path. + track: operation === "timing" ? undefined : updates.track, + })); + return deps.handleTimelineGroupMove(changes, { + coalesceKey, + ifEarlierRefused: keepUnlessItOverlaps(changes), + }); } export function useTimelineMoveEditsHandler( diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx index 6323627b78..c8ae538cc3 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx @@ -11,6 +11,7 @@ import { useTimelineEditQueue, type TimelineEditQueue, } from "./timelineEditQueue"; +import { LANE_OVERLAP_NOTICE } from "../player/components/timelineCollision"; import { useTimelineClipTimingEditing } from "./useTimelineClipTimingEditing"; import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness"; @@ -37,12 +38,13 @@ const gsapSyncs = vi.mocked(finishClipTimingFallback); function mountClipTiming() { usePlayerStore.getState().setDuration(10); const queue: TimelineEditQueue = { current: Promise.resolve(), projectId: "project" }; + const showToast = vi.fn(); let hook: ReturnType | null = null; function Harness() { hook = useTimelineClipTimingEditing({ activeCompPath: "index.html", timelineElements: [], - showToast: vi.fn(), + showToast, writeProjectFile: vi.fn(), recordEdit: vi.fn(), reloadPreview: vi.fn(), @@ -54,7 +56,7 @@ function mountClipTiming() { return null; } const root = mountReactHarness(); - return { queue, getHook: () => hook!, unmount: () => act(() => root.unmount()) }; + return { queue, showToast, getHook: () => hook!, unmount: () => act(() => root.unmount()) }; } const clipB: TimelineElement = { @@ -69,7 +71,7 @@ const clipB: TimelineElement = { describe.each<[string, CutoverResult]>([ ["the SDK path", { status: "committed", version: "1", before: "

", after: "

" }], ["the file-write fallback", { status: "declined", reason: "feature_disabled" }], -])("a single-clip trim saved through %s", (_path, sdkResult) => { +])("a single-clip edit saved through %s", (_path, sdkResult) => { afterEach(() => vi.clearAllMocks()); it("saves when nothing queued before it was refused", async () => { @@ -98,6 +100,43 @@ describe.each<[string, CutoverResult]>([ expect(fileWrites).not.toHaveBeenCalled(); unmount(); }); + + // Moves B to `to` while a move queued before it is held, then refuses that move with A back at 0-2. + async function dragBehindRefusedMove(to: number) { + usePlayerStore.getState().setElements([{ ...clipB, id: "a", hfId: "hf-a", start: 0 }, clipB]); + sdkWrites.mockResolvedValue(sdkResult); + const h = mountClipTiming(); + let refuseMove: (error: Error) => void = () => {}; + const moveSave = new Promise((_, fail) => (refuseMove = fail)); + const move = enqueueTimelineEdit(h.queue, () => moveSave, { projectId: "project" }); + const onlyTheMove = h.queue.current; + let drag: Promise = Promise.resolve(); + await act(async () => { + drag = h.getHook().handleTimelineElementMove(clipB, { start: to, track: 0 }) ?? drag; + await vi.waitFor(() => expect(h.queue.current).not.toBe(onlyTheMove)); + refuseMove(new Error("move refused")); + await expect(move).rejects.toThrow("move refused"); + await drag.catch(() => undefined); + }); + h.unmount(); + usePlayerStore.getState().setElements([]); + return { drag, showToast: h.showToast }; + } + + // fails without the fix: a single-clip drag saved B at 1 s over the restored A. + it("refuses a single-clip drag that would land on a restored clip, with the refused-drop notice", async () => { + const { drag, showToast } = await dragBehindRefusedMove(1); + await expect(drag).rejects.toThrow(LANE_OVERLAP_NOTICE); + expect(sdkWrites).not.toHaveBeenCalled(); + expect(fileWrites).not.toHaveBeenCalled(); + expect(showToast.mock.calls).toEqual([[LANE_OVERLAP_NOTICE, "info"]]); + }); + + it("keeps a single-clip drag that stays clear of a restored clip", async () => { + const { drag } = await dragBehindRefusedMove(6); + await expect(drag).resolves.toBeUndefined(); + expect(sdkWrites).toHaveBeenCalledOnce(); + }); }); describe("a single-clip trim queued before a project switch", () => { diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts index 3de067741b..da84705dcd 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts @@ -26,9 +26,10 @@ import { cutoverCommittedOrThrow, sdkTimingPersist, type CutoverResult } from ". type SdkCommit = Extract; import type { TimelineMoveUpdates, UseTimelineEditingOptions } from "./useTimelineEditingTypes"; -import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics"; +import { getStudioSaveErrorMessage, getStudioSaveErrorTone } from "../utils/studioSaveDiagnostics"; import { enqueueTimelineEdit, + keepUnlessItOverlaps, refuseWithEarlier, isClosed, shownPreview, @@ -225,13 +226,16 @@ export function useTimelineClipTimingEditing({ : undefined; return reorderDone .then(() => - enqueueEdit(element, "Move timeline clip", buildMovePatches, step, { trySdk: sdkMove }), + enqueueEdit(element, "Move timeline clip", buildMovePatches, step, { + ifEarlierRefused: keepUnlessItOverlaps([{ element, start: updates.start }]), + trySdk: sdkMove, + }), ) .then((sdk) => finishMoveGsapSync(sdk && sdkTimingGsapSync(sdk))) .catch((error) => { // Failed persist: revert the optimistic duration readout + live root. whileShown(editQueueRef, rollbackDuration); - showToast(getStudioSaveErrorMessage(error), "error"); + showToast(getStudioSaveErrorMessage(error), getStudioSaveErrorTone(error)); throw error; }); }; @@ -341,7 +345,7 @@ export function useTimelineClipTimingEditing({ return persistDone.catch((error) => { // Failed persist: revert the optimistic duration readout + live root. whileShown(editQueueRef, rollbackDuration); - showToast(getStudioSaveErrorMessage(error), "error"); + showToast(getStudioSaveErrorMessage(error), getStudioSaveErrorTone(error)); throw error; }); }, diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx index f92f40f8c1..b0c6161089 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -11,6 +11,9 @@ import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordin import { enqueueTimelineEdit, type TimelineEditQueue } from "./timelineEditQueue"; import type { TimelineGroupCommitOptions } from "./useTimelineGroupEditing"; import { useTimelineTrimRipple } from "./useTimelineTrimRipple"; +import { persistTimelineMoveEditsAtomically } from "./timelineMoveAdapter"; +import { persistMoveEdits, type DragCommitDeps } from "../player/components/timelineClipDragCommit"; +import { LANE_OVERLAP_NOTICE } from "../player/components/timelineCollision"; installReactActEnvironment(); @@ -285,17 +288,63 @@ describe("useTimelineDeleteOps: ripple undo label", () => { ]); }); - // A drag's start is where the user dropped it, so it saves as before; it does not opt in. - it("a plain move queued behind a refused delete still saves", async () => { - const { writes, elements, getHook, handleTimelineGroupMove } = mountQueuedEdits("delete hf-a"); + // Deletes hf-b with Ripple off, then drags hf-a to `to` while the delete is still saving. + async function dragBehindRefusedDelete(to: number) { + usePlayerStore.setState({ rippleEditEnabled: false }); + const queued = mountQueuedEdits("delete hf-b"); + const [a, b] = queued.elements; + let refusal: Promise = Promise.resolve(); + const onMoveElements: DragCommitDeps["onMoveElements"] = (edits, coalesceKey) => { + const moved = persistTimelineMoveEditsAtomically(edits, coalesceKey, "timing", { + handleTimelineGroupMove: queued.handleTimelineGroupMove, + }); + refusal = moved.then( + () => null, + (error: Error) => error.message, + ); + return moved; + }; + try { + await act(async () => { + const deleting = queued.getHook().handleTimelineElementDelete(b); + const { elements, updateElement } = usePlayerStore.getState(); + const drag = persistMoveEdits([{ element: a, updates: { start: to, track: 0 } }], { + elements, + trackOrder: [0], + updateElement, + onMoveElements, + }); + await Promise.all([deleting, drag]); + }); + } finally { + usePlayerStore.setState({ rippleEditEnabled: true }); + } + return { writes: queued.writes, refused: await refusal }; + } - await act(async () => { - const deleting = getHook().handleTimelineElementDelete(elements[0]); - const c = usePlayerStore.getState().elements.find((e) => e.id === "hf-c")!; - await Promise.all([deleting, handleTimelineGroupMove([{ element: c, start: 8 }])]); - }); + it("a drag queued behind a refused delete that stays clear of the restored clip still saves", async () => { + const { writes, refused } = await dragBehindRefusedDelete(6.5); - expect(writes).toEqual(["delete hf-a", "move hf-c@8"]); + expect(refused).toBeNull(); + expect(writes).toEqual(["delete hf-b", "move hf-a@6.5"]); + expect(usePlayerStore.getState().elements).toEqual([ + el("hf-a", 6.5, 2), + el("hf-c", 4, 2), + el("hf-b", 2, 2), + ]); + }); + + // fails without the fix: the drag saved hf-a at 2.5, on top of hf-b, which the refused delete put back. + it("a drag queued behind a refused delete that would land on the restored clip is refused and rolls back", async () => { + const { writes, refused } = await dragBehindRefusedDelete(2.5); + + expect(refused).toBe(LANE_OVERLAP_NOTICE); + expect(writes).toEqual(["delete hf-b"]); + expect(usePlayerStore.getState().elements).toEqual([ + el("hf-a", 0, 2), + el("hf-c", 4, 2), + el("hf-b", 2, 2), + ]); }); it("removes a multi-clip selection with one request, however many clips it holds", async () => { diff --git a/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx b/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx index f42b07a729..a824944f5d 100644 --- a/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx +++ b/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx @@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client"; import { afterEach, describe, expect, it, vi } from "vitest"; import { usePlayerStore, type TimelineElement } from "../player"; import { jsonResponse, requestUrl } from "./fetchStubTestUtils"; +import { keepUnlessItOverlaps } from "./timelineEditQueue"; import { useTimelineEditing } from "./useTimelineEditing"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -168,3 +169,69 @@ describe.each(["lands", "is refused"])( }); }, ); + +describe.each< + [string, (hook: ReturnType, c: TimelineElement) => unknown] +>([ + ["a single-clip drag", (hook, c) => hook.handleTimelineElementMove(c, { start: 2.5, track: 0 })], + [ + "a group drag, with the policy the move adapter gives it", + (hook, c) => { + const changes = [{ element: c, start: 2.5 }]; + return hook.handleTimelineGroupMove(changes, { + ifEarlierRefused: keepUnlessItOverlaps(changes), + }); + }, + ], +])("%s queued behind a delete that is refused after a project switch", (_kind, drag) => { + // fails without the fix: the drag was checked against the shown project's clips, kept, and saved + // on top of the restored clip in its own project. + it("is refused with the delete, since its own project's timeline is not shown", async () => { + stubFetch([]); + usePlayerStore.getState().setDuration(10); + usePlayerStore.getState().setElements([clip("a", 0), clip("b", 2), clip("c", 4)]); + let refuseDelete: (error: Error) => void = () => {}; + const deleteSave = new Promise((_, fail) => (refuseDelete = fail)); + const oldWrite = vi.fn().mockReturnValueOnce(deleteSave).mockResolvedValue(undefined); + let hook: ReturnType | null = null; + function Harness({ projectId }: { projectId: "old" | "new" }) { + hook = useTimelineEditing({ + projectId, + activeCompPath: "index.html", + timelineElements: usePlayerStore.getState().elements, + showToast: vi.fn(), + writeProjectFile: projectId === "old" ? oldWrite : vi.fn(), + recordEdit: vi.fn(), + reloadPreview: vi.fn(), + previewIframeRef: { current: null }, + pendingTimelineEditPathRef: { current: new Set() }, + uploadProjectFiles: vi.fn(), + }); + return null; + } + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + act(() => root.render()); + const [, b, c] = usePlayerStore.getState().elements; + let deleted: Promise = Promise.resolve(); + let dragged: Promise = Promise.resolve(); + act(() => { + deleted = Promise.resolve(hook!.handleTimelineElementsDelete([b!])); + dragged = Promise.resolve(drag(hook!, c!)); + }); + act(() => { + usePlayerStore.getState().setElements([clip("a", 0)]); + root.render(); + }); + + await act(async () => { + refuseDelete(new Error("refused")); + await Promise.allSettled([deleted, dragged]); + }); + + await expect(dragged).rejects.toThrow("refused"); + expect(oldWrite).toHaveBeenCalledOnce(); + act(() => root.unmount()); + }); +}); diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx index 83e197d66d..e360107e25 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx @@ -11,7 +11,8 @@ import { } from "@hyperframes/studio-server"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { Root } from "react-dom/client"; -import type { TimelineElement } from "../player"; +import { usePlayerStore, type TimelineElement } from "../player"; +import { LANE_OVERLAP_NOTICE } from "../player/components/timelineCollision"; import { persistTimelineMoveEditsAtomically } from "./timelineMoveAdapter"; import { useTimelineGroupEditing } from "./useTimelineGroupEditing"; import { @@ -210,6 +211,29 @@ it("refuses a ripple shift before it writes when an edit queued before it is ref } }); +// fails without the fix: the refused drag said the same words as a refused drop, but as an error. +it("a drag refused for landing on a restored clip shows the refused-drop notice, as info", async () => { + usePlayerStore.getState().setElements([el("restored", 0, 2)]); + const showToast = vi.fn(); + const { earlier, getHook, unmount } = mountBehindRefusedEdit(showToast); + try { + await act(async () => { + const drag = persistTimelineMoveEditsAtomically( + [{ element: el("a", 4, 2), updates: { start: 1, track: 0 } }], + undefined, + "timing", + { handleTimelineGroupMove: getHook().handleTimelineGroupMove }, + ); + await expect(earlier).rejects.toThrow("delete refused"); + await expect(drag).rejects.toThrow(LANE_OVERLAP_NOTICE); + }); + expect(showToast.mock.calls).toEqual([[LANE_OVERLAP_NOTICE, "info"]]); + } finally { + unmount(); + usePlayerStore.getState().setElements([]); + } +}); + // fails without the fix: a trim of B, shifted to 0 by a delete that was then refused, wrote B at 0. it("refuses a trim before it writes when an edit queued before it is refused, so the clip keeps its start", async () => { const { earlier, fetchMock, getHook, unmount } = mountBehindRefusedEdit(); diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts index 79cc622c90..378cb1dd39 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.ts +++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts @@ -32,7 +32,7 @@ import { syncPreviewContentDuration, } from "./timelineTimingSync"; import type { GsapMutationStatus } from "./gsapMutationClient"; -import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics"; +import { getStudioSaveErrorMessage, getStudioSaveErrorTone } from "../utils/studioSaveDiagnostics"; import { enqueueTimelineEdit, refuseWithEarlier, @@ -368,7 +368,7 @@ export function useTimelineGroupEditing({ if (options?.suppressFailureToast) { console.error("[Timeline] group move failed to persist", error); } else { - showToast(getStudioSaveErrorMessage(error), "error"); + showToast(getStudioSaveErrorMessage(error), getStudioSaveErrorTone(error)); } throw error; }); @@ -483,7 +483,7 @@ export function useTimelineGroupEditing({ // Failed persist: revert the optimistic duration readout + live root // alongside the gesture owner's store rollback. whileShown(editQueueRef, rollbackDuration); - showToast(getStudioSaveErrorMessage(error), "error"); + showToast(getStudioSaveErrorMessage(error), getStudioSaveErrorTone(error)); throw error; }); }, diff --git a/packages/studio/src/player/components/TimelineProvider.tsx b/packages/studio/src/player/components/TimelineProvider.tsx index 476e585c75..396a63b460 100644 --- a/packages/studio/src/player/components/TimelineProvider.tsx +++ b/packages/studio/src/player/components/TimelineProvider.tsx @@ -30,6 +30,7 @@ import type { TimelineEditCallbacks } from "./timelineCallbacks"; import type { KeyframeDiamondContextMenuState } from "./KeyframeDiamondContextMenu"; import { useTimelineProviderState } from "./useTimelineProviderState"; import { TimelineReadOnlyContext } from "./timelineReadOnly"; +import { LANE_OVERLAP_NOTICE, LANE_OVERLAP_TONE } from "./timelineCollision"; import { TimelineEditProvider, useTimelineEditContextOptional, @@ -217,7 +218,7 @@ function TimelineProviderState({ children, ...props }: TimelineProps & { childre const shell = useStudioShellContextOptional(); const { onNotice } = useTimelineEditContextOptional(); const notice = shell?.showToast ?? onNotice; - const onDropRefused = notice && (() => notice("Clips on the same track can't overlap.", "info")); + const onDropRefused = notice && (() => notice(LANE_OVERLAP_NOTICE, LANE_OVERLAP_TONE)); const value = useTimelineProviderState({ ...props, onDropRefused }); return {children}; } diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.ts index 9ec5d8437e..a776d45dbb 100644 --- a/packages/studio/src/player/components/timelineClipDragCommit.test.ts +++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi, type Mock } from "vitest"; -import type { TimelineElement } from "../store/playerStore"; +import { usePlayerStore, type TimelineElement } from "../store/playerStore"; import type { DraggedClipState } from "./useTimelineClipDrag"; import { commitDraggedClipMove, @@ -1669,3 +1669,48 @@ describe("commitDraggedClipMove: drop onto main-track clips", () => { expect(onDropRefused).not.toHaveBeenCalled(); }); }); + +// A delete still saving rippled C from 4 to 2; C is dragged to 2.5; the refused delete's rollback moves C +// back by its ripple to 4.5, and then the drag is refused too. +describe("a refused drag after an earlier edit's rollback moved its clip", () => { + const startOf = (id: string) => + usePlayerStore.getState().elements.find((e) => e.id === id)?.start; + function setUp() { + const store = usePlayerStore.getState(); + store.setElements([el("a", 0, 0, 2), el("c", 0, 2, 2)]); + let refuse: (error: Error) => void = () => {}; + const save = new Promise((_, fail) => (refuse = fail)); + const deps = { + elements: usePlayerStore.getState().elements, + trackOrder: [0], + updateElement: store.updateElement, + }; + const rollBackRipple = () => store.updateElement("c", { start: startOf("c")! + 2 }); + return { c: deps.elements[1]!, save, refuse, deps, rollBackRipple }; + } + + // fails without the fix: C went back to its rippled 2, on top of the restored B. + it("takes back only its own shift on the single-clip path", async () => { + const { c, save, refuse, deps, rollBackRipple } = setUp(); + commitDraggedClipMove(drag(c, { previewStart: 2.5, previewTrack: 0 }), { + ...deps, + onMoveElement: () => save, + }); + rollBackRipple(); + refuse(new Error("lands on B")); + await flushMicrotasks(); + expect(startOf("c")).toBe(4); + }); + + it("takes back only its own shift on the multi-clip path", async () => { + const { c, save, refuse, deps, rollBackRipple } = setUp(); + const moved = persistMoveEdits([{ element: c, updates: { start: 2.5, track: 0 } }], { + ...deps, + onMoveElements: () => save, + }); + rollBackRipple(); + refuse(new Error("lands on B")); + await expect(moved).resolves.toBe(false); + expect(startOf("c")).toBe(4); + }); +}); diff --git a/packages/studio/src/player/components/timelineClipDragCommit.ts b/packages/studio/src/player/components/timelineClipDragCommit.ts index bb800edb98..37e30d3e96 100644 --- a/packages/studio/src/player/components/timelineClipDragCommit.ts +++ b/packages/studio/src/player/components/timelineClipDragCommit.ts @@ -1,17 +1,14 @@ -import type { TimelineElement } from "../store/playerStore"; +import { usePlayerStore, type TimelineElement } from "../store/playerStore"; import { clampToHostStart } from "../store/timelineElement"; import type { DraggedClipState } from "./useTimelineClipDrag"; // Type-only: erased at runtime, so the timelineZMirror → timelineClipDragCommit // value-import edge stays acyclic. import type { ZMirrorLaneMove } from "./timelineZMirror"; import { classifyZone } from "./timelineZones"; -import { layoutAfterTrackInsert } from "./timelineDragLanding"; +import { buildTrackInsertEdits } from "./timelineDragLanding"; import type { TimelineTrackInsertLayout } from "./timelineTrackInsertLayout"; import { computeStackingPatches, type StackingPatch } from "./timelineStackingSync"; -import { - canMoveTimelineElement as canMoveElement, - resolveExpandedHostAlias, -} from "./timelineAuthoredMoveTarget"; +import { resolveExpandedHostAlias } from "./timelineAuthoredMoveTarget"; import type { TimelineMoveOperation, TimelineAtomicMoveUpdates, @@ -89,6 +86,12 @@ export interface DragCommitDeps { } const keyOf = (e: TimelineElement) => e.key ?? e.id; + +/** Where `key` sits now, minus this drag's own shift: an earlier edit's rollback may have moved it since. */ +function startBeforeDrag(key: string, from: number, to: number): number { + const now = usePlayerStore.getState().elements.find((e) => keyOf(e) === key)?.start ?? to; + return now - (to - from); +} const round3 = (v: number) => Math.round(v * 1000) / 1000; // One deterministic coalesce key shared by both records in a lane-change gesture. let laneChangeGestureSeq = 0; @@ -191,13 +194,15 @@ export function persistMoveEdits( ? e : { element: e.element, updates: { ...e.updates, track: e.persistTrack } }, ); + const movedTo = new Map(edits.map((e) => [keyOf(e.element), e.updates.start])); const restorePrev = () => batchElementUpdates(() => { for (const p of prev) { const { audioGroup, ...timing } = p.updates; const updates: Partial = {}; if (isLatestTimelineOptimisticGesture(updateElement, revision, p.key)) { - Object.assign(updates, timing); + const to = movedTo.get(p.key) ?? timing.start; + Object.assign(updates, timing, { start: startBeforeDrag(p.key, timing.start, to) }); } if ( isLatestTimelineOptimisticGesture(updateElement, membershipRevision, p.key, "membership") @@ -312,7 +317,10 @@ export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDe updateElement(dragKey, updates); Promise.resolve(onMoveElement?.(drag.element, updates)).catch((error) => { if (isLatestTimelineOptimisticGesture(updateElement, revision, dragKey)) { - updateElement(dragKey, prev); + updateElement(dragKey, { + ...prev, + start: startBeforeDrag(dragKey, prev.start, updates.start), + }); } console.error("[Timeline] Failed to persist clip edit", error); }); @@ -378,77 +386,6 @@ export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDe ).catch(() => undefined); } -/** Build the one sanctioned multi-clip write: atomically insert and compact a - * source-file zone, then let the caller sync the deliberate vertical stacking. */ -// fallow-ignore-next-line complexity -function buildTrackInsertEdits( - element: TimelineElement, - previewStart: number, - insertRow: number, - multi: { - keys: ReadonlySet; - movedStart: (e: TimelineElement) => number; - } | null, - deps: DragCommitDeps, -): { candidate: TimelineElement[]; edits: TimelineMoveEdit[] } | null { - const { elements } = deps; - const editKey = keyOf(element); - const layout = layoutAfterTrackInsert(element, previewStart, insertRow, multi, deps); - if (!layout) return null; - const { normalized, targetTrack, writable } = layout; - const bySrc = new Map(elements.map((e) => [keyOf(e), e])); - // A partial zone renumber creates collisions; refuse a shifted locked row. - for (const norm of normalized) { - const src = bySrc.get(keyOf(norm)); - if ( - src && - writable(src) && - !canMoveElement(src) && - norm.track !== (src.authoredTrack ?? src.track) - ) { - console.warn( - `[Timeline] Track insert refused: locked clip ${keyOf(src)} would need renumbering`, - ); - return null; - } - } - const candidate = elements.map((e) => { - if (keyOf(e) === editKey) return { ...e, start: previewStart, track: targetTrack }; - if (multi?.keys.has(keyOf(e))) return { ...e, start: multi.movedStart(e) }; - return e; - }); - const edits: TimelineMoveEdit[] = []; - if (multi) { - for (const src of elements) { - const srcKey = keyOf(src); - if (srcKey !== editKey && multi.keys.has(srcKey) && !writable(src) && canMoveElement(src)) { - edits.push({ - element: src, - updates: { start: multi.movedStart(src), track: src.track }, - persistTrack: src.authoredTrack, - }); - } - } - } - for (const norm of normalized) { - const src = bySrc.get(keyOf(norm)); - if (!src || !canMoveElement(src)) continue; - const normKey = keyOf(norm); - let start = src.start; - if (normKey === editKey) start = previewStart; - else if (multi?.keys.has(normKey)) start = multi.movedStart(src); - edits.push({ - element: src, - updates: { - start, - track: norm.track, - ...(normKey === editKey && src.audioGroup ? { audioGroup: null } : {}), - }, - }); - } - return { candidate, edits }; -} - function commitTrackInsert( drag: DraggedClipState, deps: DragCommitDeps, diff --git a/packages/studio/src/player/components/timelineCollision.ts b/packages/studio/src/player/components/timelineCollision.ts index 62c995abe2..ef77612241 100644 --- a/packages/studio/src/player/components/timelineCollision.ts +++ b/packages/studio/src/player/components/timelineCollision.ts @@ -217,6 +217,40 @@ export function timeRangesOverlap( return aStart < bEnd && bStart < aEnd; } +export const LANE_OVERLAP_NOTICE = "Clips on the same track can't overlap."; +export const LANE_OVERLAP_TONE = "info"; + +export const laneOverlapRefusal = () => + Object.assign(new Error(LANE_OVERLAP_NOTICE), { tone: LANE_OVERLAP_TONE }); + +export type LaneLanding = { element: TimelineElement; start: number; track?: number }; + +/** True when one of `checked` overlaps another clip in its lane, each clip placed where `moves` puts it. */ +export function landsOnLaneClip( + elements: readonly TimelineElement[], + moves: readonly LaneLanding[], + checked: readonly LaneLanding[] = moves, +): boolean { + const keyOf = (e: TimelineElement) => e.key ?? e.id; + const landed = new Map(moves.map((m) => [keyOf(m.element), m])); + const place = (e: TimelineElement) => { + const move = landed.get(keyOf(e)); + const start = move?.start ?? e.start; + return { start, end: start + e.duration, track: move?.track ?? e.track }; + }; + return checked.some(({ element }) => { + const self = place(element); + return elements.some((other) => { + const at = place(other); + return ( + keyOf(other) !== keyOf(element) && + at.track === self.track && + timeRangesOverlap(self.start, self.end, at.start, at.end) + ); + }); + }); +} + /** * True when no clip on `track` overlaps [start, end) — excluding the clip * identified by `excludeKey` (the one being dragged). diff --git a/packages/studio/src/player/components/timelineDragLanding.ts b/packages/studio/src/player/components/timelineDragLanding.ts index 1fcc243c2e..aa96a34349 100644 --- a/packages/studio/src/player/components/timelineDragLanding.ts +++ b/packages/studio/src/player/components/timelineDragLanding.ts @@ -1,5 +1,6 @@ import type { TimelineElement } from "../store/playerStore"; -import type { DragCommitDeps } from "./timelineClipDragCommit"; +import type { DragCommitDeps, TimelineMoveEdit } from "./timelineClipDragCommit"; +import { canMoveTimelineElement as canMoveElement } from "./timelineAuthoredMoveTarget"; import { classifyZone, normalizeToZones } from "./timelineZones"; import { sameSourceFile } from "./timelineAuthoredTrack"; @@ -67,3 +68,74 @@ export function layoutAfterTrackInsert( ); return { normalized, targetTrack, writable }; } + +/** Build the one sanctioned multi-clip write: atomically insert and compact a + * source-file zone, then let the caller sync the deliberate vertical stacking. */ +// fallow-ignore-next-line complexity +export function buildTrackInsertEdits( + element: TimelineElement, + previewStart: number, + insertRow: number, + multi: { + keys: ReadonlySet; + movedStart: (e: TimelineElement) => number; + } | null, + deps: DragCommitDeps, +): { candidate: TimelineElement[]; edits: TimelineMoveEdit[] } | null { + const { elements } = deps; + const editKey = keyOf(element); + const layout = layoutAfterTrackInsert(element, previewStart, insertRow, multi, deps); + if (!layout) return null; + const { normalized, targetTrack, writable } = layout; + const bySrc = new Map(elements.map((e) => [keyOf(e), e])); + // A partial zone renumber creates collisions; refuse a shifted locked row. + for (const norm of normalized) { + const src = bySrc.get(keyOf(norm)); + if ( + src && + writable(src) && + !canMoveElement(src) && + norm.track !== (src.authoredTrack ?? src.track) + ) { + console.warn( + `[Timeline] Track insert refused: locked clip ${keyOf(src)} would need renumbering`, + ); + return null; + } + } + const candidate = elements.map((e) => { + if (keyOf(e) === editKey) return { ...e, start: previewStart, track: targetTrack }; + if (multi?.keys.has(keyOf(e))) return { ...e, start: multi.movedStart(e) }; + return e; + }); + const edits: TimelineMoveEdit[] = []; + if (multi) { + for (const src of elements) { + const srcKey = keyOf(src); + if (srcKey !== editKey && multi.keys.has(srcKey) && !writable(src) && canMoveElement(src)) { + edits.push({ + element: src, + updates: { start: multi.movedStart(src), track: src.track }, + persistTrack: src.authoredTrack, + }); + } + } + } + for (const norm of normalized) { + const src = bySrc.get(keyOf(norm)); + if (!src || !canMoveElement(src)) continue; + const normKey = keyOf(norm); + let start = src.start; + if (normKey === editKey) start = previewStart; + else if (multi?.keys.has(normKey)) start = multi.movedStart(src); + edits.push({ + element: src, + updates: { + start, + track: norm.track, + ...(normKey === editKey && src.audioGroup ? { audioGroup: null } : {}), + }, + }); + } + return { candidate, edits }; +} diff --git a/packages/studio/src/player/components/timelineMainTrackInsert.ts b/packages/studio/src/player/components/timelineMainTrackInsert.ts index 0f22a1a404..0062c5d0f3 100644 --- a/packages/studio/src/player/components/timelineMainTrackInsert.ts +++ b/packages/studio/src/player/components/timelineMainTrackInsert.ts @@ -3,7 +3,7 @@ import type { DragCommitDeps, TimelineMoveEdit } from "./timelineClipDragCommit" import type { DraggedClipState } from "./timelineClipDragTypes"; import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences"; import { sharesLinkGroup } from "./audioClipLink"; -import { timeRangesOverlap } from "./timelineCollision"; +import { landsOnLaneClip, timeRangesOverlap } from "./timelineCollision"; import { getTimelineEditCapabilities } from "./timelineEditing"; import { round3, TRACK_GAP_EPSILON_S } from "./timelineGaps"; import { isMainTrackElement } from "./timelineZones"; @@ -47,23 +47,8 @@ export function resolveMainTrackInsert( return [{ element: partner, start: round3(partner.start + lead.start - lead.element.start) }]; }); const moves = [...main, ...partners]; - const landed = new Map(moves.map((m) => [keyOf(m.element), m.start])); - const startAfter = (e: TimelineElement) => landed.get(keyOf(e)) ?? e.start; // A partner may not land on a clip in its lane, moved or not, nor start before 0; main-track moves only reorder. - const lands = partners.some(({ element, start }) => - elements.some( - (other) => - other.track === element.track && - keyOf(other) !== keyOf(element) && - timeRangesOverlap( - start, - start + element.duration, - startAfter(other), - startAfter(other) + other.duration, - ), - ), - ); - if (lands || partners.some((p) => p.start < 0)) return null; + if (landsOnLaneClip(elements, moves, partners) || partners.some((p) => p.start < 0)) return null; return moves.every((m) => getTimelineEditCapabilities(m.element).canMove) ? moves : null; } diff --git a/packages/studio/src/utils/studioSaveDiagnostics.ts b/packages/studio/src/utils/studioSaveDiagnostics.ts index bf0d4086fe..0a1e85e429 100644 --- a/packages/studio/src/utils/studioSaveDiagnostics.ts +++ b/packages/studio/src/utils/studioSaveDiagnostics.ts @@ -113,6 +113,10 @@ function attachStudioSaveAttempt(error: unknown, attempt: number): unknown { return error; } +export function getStudioSaveErrorTone(error: unknown): "info" | "error" { + return error instanceof Error && "tone" in error && error.tone === "info" ? "info" : "error"; +} + export function getStudioSaveErrorMessage(error: unknown): string { if (error instanceof Error && error.message) return error.message; if (typeof error === "string" && error.trim()) return error; From 61008a40dd91ca41b70b78757ced98ecf3daa31d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:15:02 +0000 Subject: [PATCH 102/367] fix(studio): a sealed preview shows paused video frames from Studio's decoder (#8466) * fix(studio): a sealed preview shows paused video frames from Studio's decoder * fix(studio): an aborted paused-frame decode holds its slot until it settles --- .../src/runtime/editing/pausedFrames.test.ts | 42 ++++ .../core/src/runtime/editing/pausedFrames.ts | 206 ++++++++++++++++++ .../core/src/runtime/editingAgent.test.ts | 1 + packages/core/src/runtime/editingAgent.ts | 10 + packages/core/src/runtime/editingPort.test.ts | 1 + packages/core/src/runtime/editingPort.ts | 24 +- .../core/src/runtime/pausedVideoFrames.ts | 2 +- .../player/hooks/playbackAdapterResolution.ts | 4 +- packages/studio/src/player/lib/frameToken.ts | 2 +- .../src/player/lib/pausedVideoDecoder.test.ts | 28 +-- .../src/player/lib/pausedVideoDecoder.ts | 46 ++-- .../lib/pausedVideoProvider.sealed.test.ts | 65 ++++++ .../player/lib/pausedVideoProvider.test.ts | 146 +++++++++---- .../src/player/lib/pausedVideoProvider.ts | 193 +++++++++++----- 14 files changed, 632 insertions(+), 138 deletions(-) create mode 100644 packages/core/src/runtime/editing/pausedFrames.test.ts create mode 100644 packages/core/src/runtime/editing/pausedFrames.ts create mode 100644 packages/studio/src/player/lib/pausedVideoProvider.sealed.test.ts diff --git a/packages/core/src/runtime/editing/pausedFrames.test.ts b/packages/core/src/runtime/editing/pausedFrames.test.ts new file mode 100644 index 0000000000..f2dc050f28 --- /dev/null +++ b/packages/core/src/runtime/editing/pausedFrames.test.ts @@ -0,0 +1,42 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from "vitest"; +import { pausedFrameAsk, portPausedVideoProvider } from "./pausedFrames"; + +const closers: Array<() => void> = []; +afterEach(() => closers.splice(0).forEach((close) => close())); +const video = () => document.createElement("video"); + +it("asks by path and the proxy's own options only, and never for another server's media", () => { + const own = `${location.origin}/api/projects/p/preview/a.mp4?hf-proxy=h264&hf-proxy-box=640x360&token=x`; + expect(pausedFrameAsk({ video: video(), source: own, time: 1 })).toEqual({ + path: "/api/projects/p/preview/a.mp4", + params: { "hf-proxy": "h264", "hf-proxy-box": "640x360" }, + time: 1, + }); + expect( + pausedFrameAsk({ video: video(), source: "https://cdn.example/a.mp4", time: 1 }), + ).toBeNull(); +}); + +it("tells Studio when a decode is aborted, and rejects what is pending on dispose", async () => { + const { port1, port2 } = new MessageChannel(); + closers.push(() => port2.close()); + const asked: Array> = []; + port2.onmessage = (event) => asked.push(event.data); + const provider = portPausedVideoProvider(port1); + const control = new AbortController(); + const source = `${location.origin}/api/projects/p/preview/a.mp4`; + const first = provider.decode([{ video: video(), source, time: 0 }], control.signal); + await vi.waitFor(() => expect(asked).toHaveLength(1)); + control.abort(); + await expect(first).rejects.toThrow("Preview cancelled"); + await vi.waitFor(() => expect(asked[1]).toEqual({ type: "abort", id: 1 })); + const second = provider.decode( + [{ video: video(), source, time: 0 }], + new AbortController().signal, + ); + await vi.waitFor(() => expect(asked).toHaveLength(3)); + provider.dispose(); + await expect(second).rejects.toThrow("Preview cancelled"); + await vi.waitFor(() => expect(asked.at(-1)).toEqual({ type: "close" })); +}); diff --git a/packages/core/src/runtime/editing/pausedFrames.ts b/packages/core/src/runtime/editing/pausedFrames.ts new file mode 100644 index 0000000000..673f33aedd --- /dev/null +++ b/packages/core/src/runtime/editing/pausedFrames.ts @@ -0,0 +1,206 @@ +// Paused video frames for a frame Studio cannot script: the runtime asks over a port Studio handed it, and Studio +// decodes. An ask names a path on the frame's own server and the proxy options it played, never a URL: Studio +// resolves it against its own project before reading anything. +import { sourceFactsOfSrc } from "../mediaSourceLookup"; +import type { + PausedVideoFrame, + PausedVideoFrameProvider, + PausedVideoFrameRequest, +} from "../pausedVideoFrames"; + +/** The query options the runtime's media proxy adds to a src; any other key never leaves the frame. */ +export const PAUSED_FRAME_PARAMS = [ + "hf-proxy", + "hf-proxy-box", + "hf-proxy-light", + "hf-proxy-retry", +] as const; +const PARAM_VALUE = /^[\w.:-]{1,64}$/; +/** The most image bytes one decode may hand back; the runtime presents no more at once either. */ +export const PAUSED_FRAME_BYTES = 128 * 1024 * 1024; +/** The most sources one decode may name. */ +export const PAUSED_FRAME_SOURCES = 4; + +export interface PausedFrameAsk { + path: string; + params: Record; + time: number; + /** Hints from the frame: they shape decode timing, never what is read. */ + frameRate?: number; + variableFrameRate?: boolean; +} + +export interface PausedFrameImage { + image: ImageBitmap; + timestamp: number; + duration: number; + width: number; + height: number; +} + +export type PausedFrameAskMessage = + | { type: "decode"; id: number; asks: PausedFrameAsk[] } + | { type: "abort"; id: number } + | { type: "suspend"; id: number } + | { type: "close" }; + +export type PausedFrameReply = + | { type: "frames"; id: number; frames: PausedFrameImage[] } + | { type: "failed"; id: number; message: string } + | { type: "suspended"; id: number }; + +const isRecord = (value: unknown): value is Record => + Object.prototype.toString.call(value) === "[object Object]"; +const isId = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; +const finite = (value: unknown): value is number => + typeof value === "number" && Number.isFinite(value); + +function parseParams(value: unknown): Record | null { + if (!isRecord(value)) return null; + const known = PAUSED_FRAME_PARAMS as readonly string[]; + const entries = Object.entries(value); + const valid = entries.every( + ([key, param]) => known.includes(key) && typeof param === "string" && PARAM_VALUE.test(param), + ); + return valid ? (Object.fromEntries(entries) as Record) : null; +} + +function withHints(target: T, from: Record): T { + const hinted: T & { frameRate?: number; variableFrameRate?: boolean } = target; + if (finite(from.frameRate) && from.frameRate > 0) hinted.frameRate = from.frameRate; + if (typeof from.variableFrameRate === "boolean") + hinted.variableFrameRate = from.variableFrameRate; + return hinted; +} + +function parseAsk(value: unknown): PausedFrameAsk | null { + if (!isRecord(value) || typeof value.path !== "string" || !finite(value.time)) return null; + const params = parseParams(value.params); + return params ? withHints({ path: value.path, params, time: value.time }, value) : null; +} + +/** One message from the frame, or null for anything off-shape. Paths are checked by the host, not here. */ +export function parsePausedFrameAsk(data: unknown): PausedFrameAskMessage | null { + if (!isRecord(data)) return null; + if (data.type === "close") return { type: "close" }; + if (!isId(data.id)) return null; + if (data.type === "abort" || data.type === "suspend") return { type: data.type, id: data.id }; + if (data.type !== "decode" || !Array.isArray(data.asks)) return null; + const asks = data.asks.map(parseAsk); + return asks.every((ask): ask is PausedFrameAsk => ask !== null) + ? { type: "decode", id: data.id, asks } + : null; +} + +/** The ask for one request: only a src on the document's own server, by path and proxy options. */ +export function pausedFrameAsk(request: PausedVideoFrameRequest): PausedFrameAsk | null { + let url: URL; + try { + url = new URL(request.source, document.baseURI); + } catch { + return null; + } + if (url.origin !== new URL(document.baseURI).origin) return null; + const params: Record = {}; + for (const key of PAUSED_FRAME_PARAMS) { + const value = url.searchParams.get(key); + if (value !== null) params[key] = value; + } + const facts = sourceFactsOfSrc(request.source); + const ask: PausedFrameAsk = { path: url.pathname, params, time: request.time }; + if (facts?.frameRate) ask.frameRate = facts.frameRate; + if (facts?.variableFrameRate !== undefined) ask.variableFrameRate = facts.variableFrameRate; + return ask; +} + +const aborted = () => new DOMException("Preview cancelled", "AbortError"); + +/** The runtime's provider over `port`: each decode is one ask, answered by Studio with transferred images. */ +export function portPausedVideoProvider(port: MessagePort): PausedVideoFrameProvider { + const pending = new Map< + number, + { resolve: (reply: PausedFrameReply) => void; reject: (e: unknown) => void } + >(); + let lastId = 0; + let disposed = false; + const closeImages = (reply: unknown) => { + if (!isRecord(reply) || !Array.isArray(reply.frames)) return; + for (const frame of reply.frames) + if (isRecord(frame)) (frame.image as ImageBitmap | undefined)?.close?.(); + }; + port.onmessage = (event: MessageEvent) => { + const reply = event.data; + const entry = isRecord(reply) && isId(reply.id) ? pending.get(reply.id) : undefined; + if (!entry) return closeImages(reply); + pending.delete((reply as { id: number }).id); + entry.resolve(reply as PausedFrameReply); + }; + const ask = (message: Exclude, signal?: AbortSignal) => + new Promise((resolve, reject) => { + if (disposed) return reject(aborted()); + const onAbort = () => { + if (!pending.delete(message.id)) return; + port.postMessage({ type: "abort", id: message.id }); + reject(aborted()); + }; + pending.set(message.id, { + resolve: (reply) => { + signal?.removeEventListener("abort", onAbort); + resolve(reply); + }, + reject, + }); + signal?.addEventListener("abort", onAbort, { once: true }); + port.postMessage(message); + }); + const provider: PausedVideoFrameProvider = { + async decode(requests, signal) { + signal.throwIfAborted(); + const asks = requests.map(pausedFrameAsk); + if (asks.some((a) => a === null)) + throw new Error("Preview source is not on the preview server"); + const reply = await ask( + { type: "decode", id: ++lastId, asks: asks as PausedFrameAsk[] }, + signal, + ); + if (reply.type === "failed") throw new Error(reply.message); + if (reply.type !== "frames") throw new Error("Preview frames malformed"); + if (signal.aborted || disposed) { + closeImages(reply); + throw aborted(); + } + return reply.frames.map((frame): PausedVideoFrame => { + let released = false; + return { + source: frame.image, + timestamp: frame.timestamp, + duration: frame.duration, + width: frame.width, + height: frame.height, + release() { + if (released) return; + released = true; + frame.image.close(); + }, + }; + }); + }, + async suspend() { + await ask({ type: "suspend", id: ++lastId }).catch(() => {}); + }, + dispose() { + if (disposed) return; + disposed = true; + for (const entry of pending.values()) entry.reject(aborted()); + pending.clear(); + try { + port.postMessage({ type: "close" }); + } catch {} + port.close(); + window.removeEventListener("pagehide", onPageHide); + }, + }; + const onPageHide = () => provider.dispose(); + window.addEventListener("pagehide", onPageHide, { once: true }); + return provider; +} diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index f9b8195f7f..ce7761e1c1 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -210,6 +210,7 @@ describe("installEditingAgent", () => { "live-retime", "assets-unloaded", "text-edit", + "serve-paused-frames", ], }, }); diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts index dcbbc25fbe..56649f9c4f 100644 --- a/packages/core/src/runtime/editingAgent.ts +++ b/packages/core/src/runtime/editingAgent.ts @@ -65,6 +65,7 @@ import { documentMarkup } from "./editing/documentMarkup"; import { setAudioGroupAttribute } from "./editing/setAudioGroupAttribute"; import { editElement } from "./editing/editElement"; import { endTextEdit, textEdit } from "./editing/textEdit"; +import { portPausedVideoProvider } from "./editing/pausedFrames"; type Handlers = { [K in EditingRequestKind]: ( @@ -236,6 +237,15 @@ const HANDLERS: Handlers = { "swap-scenes": swapScenes, "live-retime": liveRetime, "assets-unloaded": () => ({ unloaded: previewAssetsUnloaded(document, window.__hfLottie) }), + "serve-paused-frames": ({ channel }) => { + const install = window.__hf?.setPausedVideoFrameProvider; + if (!install) { + channel.close(); + return { served: false }; + } + install(portPausedVideoProvider(channel)); + return { served: true }; + }, "text-edit": (params, port) => textEdit(params, port, EDITING_PROTOCOL_VERSION), }; diff --git a/packages/core/src/runtime/editingPort.test.ts b/packages/core/src/runtime/editingPort.test.ts index 212e2a7816..82e58dc796 100644 --- a/packages/core/src/runtime/editingPort.test.ts +++ b/packages/core/src/runtime/editingPort.test.ts @@ -113,6 +113,7 @@ describe("createEditingPortClient", () => { "live-retime", "assets-unloaded", "text-edit", + "serve-paused-frames", ], }); } finally { diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index d9e327f4c8..a7224090ff 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -222,6 +222,7 @@ export const EDITING_REQUEST_KINDS = [ "live-retime", "assets-unloaded", "text-edit", + "serve-paused-frames", ] as const; export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number]; @@ -377,6 +378,8 @@ export interface EditingRequests { "live-retime": { params: LiveRetimeParams; result: { result: LiveRetimeResult } }; "assets-unloaded": { params: NoParams; result: { unloaded: boolean } }; "text-edit": { params: TextEditParams; result: TextEditResult }; + /** Studio's paused-frame decoding port (`editing/pausedFrames.ts`); false when no runtime can use it. */ + "serve-paused-frames": { params: { channel: MessagePort }; result: { served: boolean } }; } export type EditingParams = EditingRequests[K]["params"]; export type EditingResult = EditingRequests[K]["result"]; @@ -610,6 +613,10 @@ const PARAM_PARSERS: { "live-retime": parseLiveRetime, "assets-unloaded": noParams, "text-edit": parseTextEdit, + "serve-paused-frames": (params) => + hasKeys(params, "channel") && params.channel instanceof MessagePort + ? { channel: params.channel } + : null, }; /** Validates one request off the wire. Never throws: anything unusable becomes a typed error. */ @@ -645,7 +652,7 @@ export interface EditingPortClient { request( kind: K, params: EditingParams, - options?: { timeoutMs?: number }, + options?: { timeoutMs?: number; transfer?: Transferable[] }, ): Promise>; /** Calls `listener` with each key the frame forwards for `watch-keys`; returns the unsubscribe. */ onKey(listener: (key: EditingKeyEvent) => void): () => void; @@ -786,7 +793,10 @@ export function createEditingPortClient(options: { const send = () => { if (!pending.has(id)) return; try { - port?.postMessage({ v: EDITING_PROTOCOL_VERSION, id, kind, params }); + port?.postMessage( + { v: EDITING_PROTOCOL_VERSION, id, kind, params }, + requestOptions?.transfer ?? [], + ); } catch (err) { settle(id, { error: new EditingPortError("failed", String(err)) }); } @@ -829,3 +839,13 @@ export function createEditingPortClient(options: { export { elementHome, transformWDivisor, type MotionPathHome } from "./editing/motionPathHome"; export type { TextEditEndedEvent } from "./editing/textEdit"; +export { + parsePausedFrameAsk, + PAUSED_FRAME_BYTES, + PAUSED_FRAME_PARAMS, + PAUSED_FRAME_SOURCES, + type PausedFrameAsk, + type PausedFrameAskMessage, + type PausedFrameImage, + type PausedFrameReply, +} from "./editing/pausedFrames"; diff --git a/packages/core/src/runtime/pausedVideoFrames.ts b/packages/core/src/runtime/pausedVideoFrames.ts index 511dd3158e..a1c292c9ec 100644 --- a/packages/core/src/runtime/pausedVideoFrames.ts +++ b/packages/core/src/runtime/pausedVideoFrames.ts @@ -13,6 +13,7 @@ import { PREVIEW_VIDEO_SOURCE_ATTR, PREVIEW_VIDEO_CANVAS_ATTR, } from "../studioPreviewMark"; +import { PAUSED_FRAME_BYTES as SURFACE_BUDGET } from "./editing/pausedFrames"; export interface PausedVideoFrameRequest { video: HTMLVideoElement; @@ -44,7 +45,6 @@ export interface PreparedPausedVideoFrames { release(): void; } -const SURFACE_BUDGET = 128 * 1024 * 1024; type Presented = { video: HTMLVideoElement; canvas: HTMLCanvasElement; diff --git a/packages/studio/src/player/hooks/playbackAdapterResolution.ts b/packages/studio/src/player/hooks/playbackAdapterResolution.ts index c338bce496..534c13bdc0 100644 --- a/packages/studio/src/player/hooks/playbackAdapterResolution.ts +++ b/packages/studio/src/player/hooks/playbackAdapterResolution.ts @@ -11,7 +11,7 @@ import { type StaticSeekCacheEntry, } from "../lib/playbackAdapter"; import { readTimelineDurationFromDocument } from "../lib/timelineDOM"; -import { attachPausedVideoProvider } from "../lib/pausedVideoProvider"; +import { servePausedVideoFrames } from "../lib/pausedVideoProvider"; import { previewFrameOpaque } from "../lib/previewChannel"; import { bridgePlaybackAdapter } from "../lib/bridgePlayback"; @@ -105,9 +105,9 @@ export function resolveFramePlaybackAdapter( iframe: HTMLIFrameElement, refs: StaticSeekRefs, ): PlaybackAdapter | null { + servePausedVideoFrames(iframe); if (previewFrameOpaque(iframe)) return bridgePlaybackAdapter(iframe); const win = iframe.contentWindow as IframeWindow | null; if (!win) return null; - attachPausedVideoProvider(iframe, win); return resolvePlaybackAdapter(iframe, win, refs); } diff --git a/packages/studio/src/player/lib/frameToken.ts b/packages/studio/src/player/lib/frameToken.ts index d7e4cb1d58..c47b7bd8d4 100644 --- a/packages/studio/src/player/lib/frameToken.ts +++ b/packages/studio/src/player/lib/frameToken.ts @@ -1,6 +1,6 @@ import { studioApiFetch } from "../../utils/studioApiFetch"; -const PREVIEW_PATH = /^(\/api\/projects\/[^/?#]+)\/preview(?:\/~[\w-]{43})?(?=[/?#]|$)/; +export const PREVIEW_PATH = /^(\/api\/projects\/[^/?#]+)\/preview(?:\/~[\w-]{43})?(?=[/?#]|$)/; export function fetchFrameToken(frameTokenPath: string): Promise { return studioApiFetch(frameTokenPath) diff --git a/packages/studio/src/player/lib/pausedVideoDecoder.test.ts b/packages/studio/src/player/lib/pausedVideoDecoder.test.ts index d0e21c62a8..a3c7e0dd0f 100644 --- a/packages/studio/src/player/lib/pausedVideoDecoder.test.ts +++ b/packages/studio/src/player/lib/pausedVideoDecoder.test.ts @@ -1,6 +1,6 @@ // @vitest-environment happy-dom import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import { createPausedVideoDecoder } from "./pausedVideoDecoder"; +import { createPausedVideoDecoder, type PausedVideoDecodeAsk } from "./pausedVideoDecoder"; const inputs: { source: string; dispose: ReturnType }[] = []; const rebuilt: { @@ -64,24 +64,26 @@ vi.mock("../store/playerStore", () => ({ vi.mock("@hyperframes/core/runtime/protocol", () => ({ frameDisplayScale: () => displayScale })); const providers: ReturnType[] = []; +/** A decoder whose asks carry `facts`' timing hints, as the frame's runtime sends them. */ function provider( facts?: Record< string, { width: number; height: number; frameRate?: number; variableFrameRate?: boolean } >, - rootSize?: { width: number; height: number }, ) { - const iframe = document.createElement("iframe"); - document.body.append(iframe); - if (facts) Object.assign(iframe.contentWindow, { __HF_MEDIA_SOURCE_FACTS__: facts }); - if (rootSize) - Object.defineProperties(iframe.contentDocument!.documentElement, { - clientWidth: { value: rootSize.width, configurable: true }, - clientHeight: { value: rootSize.height, configurable: true }, - }); - const result = createPausedVideoDecoder(iframe); - providers.push(result); - return result; + const decoder = createPausedVideoDecoder(); + providers.push(decoder); + const hinted = (ask: PausedVideoDecodeAsk): PausedVideoDecodeAsk => { + const fact = Object.entries(facts ?? {}).find(([suffix]) => ask.source.endsWith(suffix))?.[1]; + return fact + ? { ...ask, frameRate: fact.frameRate, variableFrameRate: fact.variableFrameRate } + : ask; + }; + return { + ...decoder, + decode: (asks: PausedVideoDecodeAsk[], signal: AbortSignal) => + decoder.decode(asks.map(hinted), signal), + }; } const request = (source: string) => ({ source: `http://localhost/${source}.webm`, diff --git a/packages/studio/src/player/lib/pausedVideoDecoder.ts b/packages/studio/src/player/lib/pausedVideoDecoder.ts index b50f44307d..fff60e5653 100644 --- a/packages/studio/src/player/lib/pausedVideoDecoder.ts +++ b/packages/studio/src/player/lib/pausedVideoDecoder.ts @@ -6,14 +6,10 @@ import { VideoSampleSink, type Rotation, } from "mediabunny"; -import type { - PausedVideoFrame, - PausedVideoFrameProvider, - PausedVideoFrameRequest, -} from "@hyperframes/core"; +import type { PausedVideoFrame } from "@hyperframes/core"; +import { PAUSED_FRAME_SOURCES } from "@hyperframes/core/runtime/editing-port"; import { untaggedVideoMatrix } from "@hyperframes/parsers/media-streams"; import { mediaUrlSourceOptions } from "./mediaFetch"; -import type { IframeWindow } from "./playbackTypes"; import { previewDecodeTime, previewPresentationTime, @@ -21,7 +17,7 @@ import { } from "./previewVideoTime"; const FRAME_BUDGET = 64 * 1024 * 1024; -const MAX_READERS = 4; +const MAX_READERS = PAUSED_FRAME_SOURCES; const NEARBY_FORWARD_SECONDS = 0.5; const ALPHA_DRAIN_WAIT_MS = 2000; @@ -89,7 +85,20 @@ async function asBt601(sample: VideoSample): Promise { }); } -export function createPausedVideoDecoder(iframe: HTMLIFrameElement): PausedVideoFrameProvider { +export interface PausedVideoDecodeAsk { + source: string; + time: number; + frameRate?: number; + variableFrameRate?: boolean; +} + +export interface PausedVideoDecoder { + decode(asks: PausedVideoDecodeAsk[], signal: AbortSignal): Promise; + suspend(): Promise; + dispose(): void; +} + +export function createPausedVideoDecoder(): PausedVideoDecoder { const readers = new Map>(); const opened = new Map(); const opening = new Map void>(); @@ -98,18 +107,6 @@ export function createPausedVideoDecoder(iframe: HTMLIFrameElement): PausedVideo let bytes = 0; let disposed = false; - const sourceFacts = (source: string) => { - let path = new URL(source, location.href).pathname; - try { - path = decodeURIComponent(path); - } catch {} - return Object.entries( - (iframe.contentWindow as IframeWindow | null)?.__HF_MEDIA_SOURCE_FACTS__ ?? {}, - ) - .filter(([suffix]) => path.endsWith(suffix)) - .sort(([a], [b]) => b.length - a.length)[0]?.[1]; - }; - const trim = (budget = FRAME_BUDGET) => { for (const [entry, reader] of cacheOrder) { if (bytes <= budget) break; @@ -379,18 +376,17 @@ export function createPausedVideoDecoder(iframe: HTMLIFrameElement): PausedVideo if (signal.aborted || disposed) await closeIterator(reader).catch(() => {}); } }; - const sourceTiming = (request: PausedVideoFrameRequest, reader: Reader) => { - const facts = sourceFacts(request.source); + const sourceTiming = (request: PausedVideoDecodeAsk, reader: Reader) => { return { - frameRate: facts?.frameRate, - variableFrameRate: facts?.variableFrameRate, + frameRate: request.frameRate, + variableFrameRate: request.variableFrameRate, sourceLead: reader.lead, inputLead: reader.lead, timeResolution: reader.ticks, }; }; const decodeOne = async ( - request: PausedVideoFrameRequest, + request: PausedVideoDecodeAsk, signal: AbortSignal, ): Promise => { signal.throwIfAborted(); diff --git a/packages/studio/src/player/lib/pausedVideoProvider.sealed.test.ts b/packages/studio/src/player/lib/pausedVideoProvider.sealed.test.ts new file mode 100644 index 0000000000..833a515456 --- /dev/null +++ b/packages/studio/src/player/lib/pausedVideoProvider.sealed.test.ts @@ -0,0 +1,65 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from "vitest"; +import type { PausedVideoFrameProvider } from "@hyperframes/core"; +import { resolveFramePlaybackAdapter } from "../hooks/playbackAdapterResolution"; +import { sealedPreviewFrame } from "./sealedPreviewFrame.test-helpers"; + +const decoder = vi.hoisted(() => ({ + decode: vi.fn(), + suspend: vi.fn(async () => {}), + dispose: vi.fn(), +})); +vi.mock("./pausedVideoDecoder", () => ({ createPausedVideoDecoder: () => decoder })); +vi.mock("../../utils/studioApiFetch", () => ({ + studioApiFetch: vi.fn(async () => Response.json({ files: ["index.html", "assets/a.mp4"] })), +})); + +const TOKEN = "t".repeat(43); +const refs = () => ({ cache: { current: null }, warned: { current: false } }); +const runtime = window as unknown as { __hf?: { setPausedVideoFrameProvider?: unknown } }; +afterEach(() => { + delete runtime.__hf; + vi.unstubAllGlobals(); +}); + +// Node has no ImageBitmap; a MessagePort crosses a port by transfer and closes like one. +const bitmap = () => new MessageChannel().port1; + +it("a sealed frame's runtime decodes paused frames through Studio, which reads only the project file", async () => { + vi.stubGlobal( + "createImageBitmap", + vi.fn(async () => bitmap()), + ); + // happy-dom's MessagePort global is not the class its MessageChannel makes, as a browser's is. + vi.stubGlobal("MessagePort", bitmap().constructor); + const install = vi.fn<(provider: PausedVideoFrameProvider) => void>(); + runtime.__hf = { setPausedVideoFrameProvider: install }; + const { iframe } = sealedPreviewFrame(); + Object.defineProperty(iframe, "src", { + value: `${location.origin}/api/projects/p1/preview/~${TOKEN}/index.html`, + }); + + resolveFramePlaybackAdapter(iframe, refs()); + await vi.waitFor(() => expect(install).toHaveBeenCalledOnce()); + + const release = vi.fn(); + decoder.decode.mockResolvedValueOnce([ + { source: bitmap(), timestamp: 0.5, duration: 1 / 30, width: 4, height: 2, release }, + ]); + const provider = install.mock.calls[0]![0]; + const source = `${location.origin}/api/projects/p1/preview/~${TOKEN}/assets/a.mp4?hf-proxy=h264&other=1`; + const video = document.createElement("video"); + const frames = await provider.decode( + [{ video, source, time: 0.5 }], + new AbortController().signal, + ); + + expect(decoder.decode).toHaveBeenCalledWith( + [{ source: "/api/projects/p1/preview/assets/a.mp4?hf-proxy=h264", time: 0.5 }], + expect.any(AbortSignal), + ); + expect(frames).toMatchObject([{ timestamp: 0.5, duration: 1 / 30, width: 4, height: 2 }]); + expect(release).toHaveBeenCalledOnce(); + frames[0]!.release(); + provider.dispose(); +}); diff --git a/packages/studio/src/player/lib/pausedVideoProvider.test.ts b/packages/studio/src/player/lib/pausedVideoProvider.test.ts index 80c78969a9..a798214ee7 100644 --- a/packages/studio/src/player/lib/pausedVideoProvider.test.ts +++ b/packages/studio/src/player/lib/pausedVideoProvider.test.ts @@ -1,53 +1,109 @@ // @vitest-environment happy-dom -import { expect, it, vi } from "vitest"; -import type { PausedVideoFrameProvider } from "@hyperframes/core"; -import { attachPausedVideoProvider } from "./pausedVideoProvider"; +import { afterEach, expect, it, vi } from "vitest"; +import type { PausedFrameAsk } from "@hyperframes/core/runtime/editing-port"; +import { pausedFrameHost } from "./pausedVideoProvider"; +import type { PausedVideoDecoder } from "./pausedVideoDecoder"; -const decoder = vi.hoisted(() => ({ - decode: vi.fn(async () => []), - suspend: vi.fn(async () => {}), - dispose: vi.fn(), -})); -vi.mock("./pausedVideoDecoder", () => ({ createPausedVideoDecoder: () => decoder })); +const decoder = { decode: vi.fn(), suspend: vi.fn(async () => {}), dispose: vi.fn() }; +const closers: Array<() => void> = []; +afterEach(() => { + closers.splice(0).forEach((close) => close()); + vi.resetAllMocks(); + vi.unstubAllGlobals(); +}); -it("forwards native-play suspension through the lazy provider facade", async () => { - const iframe = document.createElement("iframe"); - document.body.append(iframe); - const install = vi.fn<(provider: PausedVideoFrameProvider) => void>(); - const win = iframe.contentWindow!; - Object.assign(win, { - __hf: { - setPausedVideoFrameProvider: install, - }, +let lastId = 0; +function host() { + const { port1, port2 } = new MessageChannel(); + const studio = pausedFrameHost(port1, "/api/projects/p1", { + decoder: async () => decoder as unknown as PausedVideoDecoder, + files: async () => new Set(["assets/a.mp4"]), }); - attachPausedVideoProvider(iframe, win); - const provider = install.mock.calls[0]![0]; - await provider.decode([], new AbortController().signal); - await provider.suspend?.(); - expect(decoder.suspend).toHaveBeenCalledOnce(); - await provider.decode([], new AbortController().signal); + const replies: Array> = []; + port2.onmessage = (event) => replies.push(event.data); + closers.push(() => { + studio.close(); + port2.close(); + }); + const decode = (asks: unknown[]) => port2.postMessage({ type: "decode", id: ++lastId, asks }); + return { replies, decode, port2 }; +} +const at = (path: string, params: Record = {}): PausedFrameAsk => ({ + path, + params, + time: 0, +}); +const A = "/api/projects/p1/preview/assets/a.mp4"; + +it.each([ + ["a URL the frame names", "http://evil.test/api/projects/p1/preview/assets/a.mp4"], + ["a host-relative URL", "//evil.test/api/projects/p1/preview/assets/a.mp4"], + ["another project's file", "/api/projects/p2/preview/assets/a.mp4"], + ["a path that climbs out", "/api/projects/p1/preview/assets/../../secret.mp4"], + ["an encoded climb", "/api/projects/p1/preview/assets/%2e%2e/%2e%2e/secret.mp4"], + ["a file the project does not have", "/api/projects/p1/preview/assets/b.mp4"], +])("refuses %s without reading anything", async (_, path) => { + const { replies, decode } = host(); + decode([at(path)]); + await vi.waitFor(() => expect(replies).toHaveLength(1)); + expect(replies[0]).toMatchObject({ type: "failed" }); + expect(decoder.decode).not.toHaveBeenCalled(); +}); + +it("ignores an ask carrying any option but the proxy's", async () => { + const { replies, decode, port2 } = host(); + decode([at(A, { url: "http://evil.test/x.mp4" })]); + port2.postMessage({ type: "suspend", id: ++lastId }); + await vi.waitFor(() => expect(replies).toEqual([{ type: "suspended", id: lastId }])); + expect(decoder.decode).not.toHaveBeenCalled(); +}); + +it("refuses more sources than one decode may name, and a second decode while one runs", async () => { + const { replies, decode } = host(); + decode([at(A), at(A), at(A), at(A), at(A)]); + await vi.waitFor(() => expect(replies).toHaveLength(1)); + expect(replies[0]).toMatchObject({ type: "failed", message: "Preview decode over budget" }); + + decoder.decode.mockReturnValue(new Promise(() => {})); + decode([at(A)]); + await vi.waitFor(() => expect(decoder.decode).toHaveBeenCalledOnce()); + decode([at(A)]); + await vi.waitFor(() => expect(replies).toHaveLength(2)); + expect(replies[1]).toMatchObject({ type: "failed", message: "Preview decoder busy" }); + expect(decoder.decode).toHaveBeenCalledOnce(); +}); + +it("keeps an aborted decode's slot until that decode settles", async () => { + let settle = (_frames: unknown[]) => {}; + decoder.decode.mockReturnValueOnce(new Promise((resolve) => (settle = resolve))); + const { replies, decode, port2 } = host(); + decode([at(A)]); + const first = lastId; + await vi.waitFor(() => expect(decoder.decode).toHaveBeenCalledOnce()); + port2.postMessage({ type: "abort", id: first }); + decode([at(A)]); + await vi.waitFor(() => expect(replies).toHaveLength(1)); + expect(replies[0]).toMatchObject({ type: "failed", message: "Preview decoder busy" }); + + settle([]); + port2.postMessage({ type: "suspend", id: ++lastId }); + await vi.waitFor(() => expect(replies.at(-1)).toEqual({ type: "suspended", id: lastId })); + decoder.decode.mockResolvedValueOnce([]); + decode([at(A)]); + await vi.waitFor(() => expect(replies.at(-1)).toMatchObject({ type: "frames", frames: [] })); expect(decoder.decode).toHaveBeenCalledTimes(2); - win.dispatchEvent(new Event("pagehide")); - await Promise.resolve(); - expect(decoder.dispose).toHaveBeenCalledOnce(); - iframe.remove(); }); -it("allows native-play suspension after the lazy decoder chunk rejects", async () => { - vi.resetModules(); - vi.doMock("./pausedVideoDecoder", () => { - throw new Error("decoder chunk unavailable"); - }); - const { attachPausedVideoProvider: attach } = await import("./pausedVideoProvider"); - const iframe = document.createElement("iframe"); - document.body.append(iframe); - const install = vi.fn<(provider: PausedVideoFrameProvider) => void>(); - const win = iframe.contentWindow!; - Object.assign(win, { __hf: { setPausedVideoFrameProvider: install } }); - attach(iframe, win); - const provider = install.mock.calls[0]![0]; - await expect(provider.decode([], new AbortController().signal)).rejects.toThrow(); - await expect(provider.suspend!()).resolves.toBeUndefined(); - win.dispatchEvent(new Event("pagehide")); - iframe.remove(); +it("refuses frames over the byte budget and releases them", async () => { + vi.stubGlobal("createImageBitmap", vi.fn()); + const release = vi.fn(); + decoder.decode.mockResolvedValue([ + { source: {}, timestamp: 0, duration: 1, width: 8192, height: 8192, release }, + ]); + const { replies, decode } = host(); + decode([at(A)]); + await vi.waitFor(() => expect(replies).toHaveLength(1)); + expect(replies[0]).toMatchObject({ type: "failed", message: "Preview decode over budget" }); + expect(release).toHaveBeenCalledOnce(); + expect(createImageBitmap).not.toHaveBeenCalled(); }); diff --git a/packages/studio/src/player/lib/pausedVideoProvider.ts b/packages/studio/src/player/lib/pausedVideoProvider.ts index ec747c7fed..362be8f3c6 100644 --- a/packages/studio/src/player/lib/pausedVideoProvider.ts +++ b/packages/studio/src/player/lib/pausedVideoProvider.ts @@ -1,54 +1,149 @@ -import type { PausedVideoFrameProvider } from "@hyperframes/core"; -import type { IframeWindow } from "./playbackTypes"; +// Studio decodes only its project's files, at URLs it builds: the film can load those through the preview route. +import { encodeUrlPath } from "@hyperframes/parsers"; +import { + PAUSED_FRAME_BYTES, + PAUSED_FRAME_SOURCES, + parsePausedFrameAsk, + type PausedFrameAsk, +} from "@hyperframes/core/runtime/editing-port"; +import { studioApiFetch } from "../../utils/studioApiFetch"; +import { PREVIEW_PATH } from "./frameToken"; +import { previewEditingClient } from "./previewChannel"; +import type { PausedVideoFrame } from "@hyperframes/core"; +import type { PausedVideoDecodeAsk, PausedVideoDecoder } from "./pausedVideoDecoder"; -const installed = new WeakMap< - HTMLIFrameElement, - { - document: Document; - provider: PausedVideoFrameProvider; - setter: (provider: PausedVideoFrameProvider | null) => void; - } ->(); +const served = new WeakMap(); -/** A lazy facade also installs in Studio's hidden reload frame before its first seek. */ -export function attachPausedVideoProvider(iframe: HTMLIFrameElement, win: IframeWindow): void { - if (!win.__hf?.setPausedVideoFrameProvider || !iframe.contentDocument) return; - const previous = installed.get(iframe); - const setter = win.__hf.setPausedVideoFrameProvider; - if (previous?.document === iframe.contentDocument && previous.setter === setter) return; - previous?.provider.dispose(); - let disposed = false; - let decoder: Promise | null = null; - const provider: PausedVideoFrameProvider = { - async decode(requests, signal) { - signal.throwIfAborted(); - if (disposed) throw new DOMException("Preview disposed", "AbortError"); - decoder ??= import("./pausedVideoDecoder").then(({ createPausedVideoDecoder }) => - createPausedVideoDecoder(iframe), - ); - const actual = await decoder; - if (disposed) { - actual.dispose(); - throw new DOMException("Preview disposed", "AbortError"); - } - return actual.decode(requests, signal); - }, - async suspend() { - const actual = await decoder?.catch(() => null); - await actual?.suspend?.(); - }, - dispose() { - if (disposed) return; - disposed = true; - void decoder?.then((actual) => actual.dispose()).catch(() => {}); - win.removeEventListener("pagehide", onPageHide); - }, +export function servePausedVideoFrames(iframe: HTMLIFrameElement): void { + const project = PREVIEW_PATH.exec(new URL(iframe.src, location.href).pathname)?.[1]; + if (!project) return; + const client = previewEditingClient(iframe); + if (served.get(iframe) === client) return; + served.set(iframe, client); + const { port1, port2 } = new MessageChannel(); + const host = pausedFrameHost(port1, project); + iframe.addEventListener("load", host.close, { once: true }); + client + .request("serve-paused-frames", { channel: port2 }, { transfer: [port2] }) + .then(({ served: on }) => on || host.close(), host.close); +} + +async function projectFiles(project: string): Promise> { + const res = await studioApiFetch(project); + if (!res.ok) throw new Error(`Project files unavailable: ${res.status}`); + const body = (await res.json()) as { files?: unknown }; + return new Set(Array.isArray(body.files) ? body.files.filter((f) => typeof f === "string") : []); +} + +/** The project file `path` names on this project's preview route, or null for anything else. */ +function projectFileOf(path: string, project: string): string | null { + const route = PREVIEW_PATH.exec(path); + const rest = route ? path.slice(route[0].length) : ""; + if (!route || route[1] !== project || !rest.startsWith("/")) return null; + let relative: string; + try { + relative = decodeURIComponent(rest.slice(1)); + } catch { + return null; + } + const parts = relative.split("/"); + return parts.some((part) => part === "" || part === "." || part === "..") ? null : relative; +} + +const loadDecoder = () => + import("./pausedVideoDecoder").then(({ createPausedVideoDecoder }) => createPausedVideoDecoder()); + +export function pausedFrameHost( + port: MessagePort, + project: string, + deps: { + decoder?: () => Promise; + files?: (project: string) => Promise>; + } = {}, +) { + let decoder: Promise | null = null; + let files: Promise> | null = null; + const inFlight = new Map(); + let closed = false; + const reply = (message: unknown, transfer: Transferable[] = []) => { + if (!closed) port.postMessage(message, transfer); }; - const onPageHide = () => { - provider.dispose(); - installed.delete(iframe); + + const resolveAsk = async (ask: PausedFrameAsk): Promise => { + const relative = projectFileOf(ask.path, project); + if (relative === null) throw new Error("Preview source is not this project's"); + files ??= (deps.files ?? projectFiles)(project); + if (!(await files).has(relative)) throw new Error("Preview source is not a project file"); + const url = new URL(`${project}/preview/${encodeUrlPath(relative)}`, location.origin); + for (const [key, value] of Object.entries(ask.params)) url.searchParams.set(key, value); + const { frameRate, variableFrameRate } = ask; + return { source: url.pathname + url.search, time: ask.time, frameRate, variableFrameRate }; }; - win.addEventListener("pagehide", onPageHide, { once: true }); - installed.set(iframe, { document: iframe.contentDocument, provider, setter }); - setter(provider); + + const send = async (id: number, frames: PausedVideoFrame[], signal: AbortSignal) => { + if (frames.reduce((sum, f) => sum + f.width * f.height * 4, 0) > PAUSED_FRAME_BYTES) + throw new Error("Preview decode over budget"); + const images = await Promise.all(frames.map((frame) => createImageBitmap(frame.source))); + if (signal.aborted || closed) return images.forEach((image) => image.close()); + const wire = frames.map(({ timestamp, duration, width, height }, i) => ({ + image: images[i], + timestamp, + duration, + width, + height, + })); + reply({ type: "frames", id, frames: wire }, images); + }; + + const refusal = (asks: PausedFrameAsk[]) => { + if (inFlight.size > 0) return "Preview decoder busy"; + return asks.length === 0 || asks.length > PAUSED_FRAME_SOURCES + ? "Preview decode over budget" + : null; + }; + + const decode = async (id: number, asks: PausedFrameAsk[]) => { + const refused = refusal(asks); + if (refused) return reply({ type: "failed", id, message: refused }); + const control = new AbortController(); + inFlight.set(id, control); + try { + const resolved = await Promise.all(asks.map(resolveAsk)); + decoder ??= (deps.decoder ?? loadDecoder)(); + const frames = await (await decoder).decode(resolved, control.signal); + await send(id, frames, control.signal).finally(() => frames.forEach((f) => f.release())); + } catch (error) { + if (!control.signal.aborted) + reply({ type: "failed", id, message: String((error as Error)?.message ?? error) }); + } finally { + if (inFlight.get(id) === control) inFlight.delete(id); + } + }; + + const close = () => { + if (closed) return; + closed = true; + for (const control of inFlight.values()) control.abort(); + inFlight.clear(); + void decoder?.then((actual) => actual.dispose()).catch(() => {}); + port.close(); + }; + + port.onmessage = (event: MessageEvent) => { + const message = parsePausedFrameAsk(event.data); + if (!message || closed) return; + if (message.type === "close") return close(); + if (message.type === "abort") return inFlight.get(message.id)?.abort(); + if (message.type === "suspend") { + void (decoder ?? Promise.resolve(null)) + .catch(() => null) + .then((actual) => actual?.suspend()) + .catch(() => {}) + .then(() => reply({ type: "suspended", id: message.id })); + return; + } + void decode(message.id, message.asks); + }; + + return { close }; } From 835e660e0e3ec98893ef3ace94385d045f790e14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:16:07 +0000 Subject: [PATCH 103/367] fix(player): a sealed film no longer shows failed to load while its runtime starts (#8472) * fix(player): a sealed film is ready from its document before its runtime boots * test(core): the static composition post reaches a parent frame while the page parses * refactor(core): keep the static read's bounds inside their file --- .../core/src/runtime/compositionDimension.ts | 13 +++ .../core/src/runtime/compositionLength.ts | 48 +++++++++- packages/core/src/runtime/entry.ts | 3 + .../src/runtime/staticCompositionPost.test.ts | 58 +++++++++++ .../core/src/runtime/staticCompositionPost.ts | 43 +++++++++ packages/core/src/runtime/types.ts | 10 ++ packages/player/src/composition-probe.ts | 17 +--- packages/player/src/hyperframes-player.ts | 24 ++++- .../player/src/runtime-message-handler.ts | 13 +++ .../src/sealedStaticComposition.test.ts | 95 +++++++++++++++++++ 10 files changed, 308 insertions(+), 16 deletions(-) create mode 100644 packages/core/src/runtime/staticCompositionPost.test.ts create mode 100644 packages/core/src/runtime/staticCompositionPost.ts create mode 100644 packages/player/src/sealedStaticComposition.test.ts diff --git a/packages/core/src/runtime/compositionDimension.ts b/packages/core/src/runtime/compositionDimension.ts index 1fbcb5bffc..278c9c358e 100644 --- a/packages/core/src/runtime/compositionDimension.ts +++ b/packages/core/src/runtime/compositionDimension.ts @@ -14,6 +14,19 @@ export function parseCompositionDimension(value: string | null | undefined): num return Number.isFinite(parsed) && parsed > 0 ? parsed : null; } +/** The composition's size as a document alone gives it: the composition root's, else any element that declares both. */ +export function readCompositionSizeFromDocument( + doc: ParentNode | null | undefined, +): { width: number; height: number } | null { + const root = + doc?.querySelector("[data-composition-id][data-width][data-height]") ?? + doc?.querySelector("[data-width][data-height]"); + if (!root) return null; + const width = parseCompositionDimension(root.getAttribute("data-width")); + const height = parseCompositionDimension(root.getAttribute("data-height")); + return width !== null && height !== null ? { width, height } : null; +} + export function findRootCompositionElement(doc: ParentNode = document): HTMLElement | null { const explicitRoot = doc.querySelector('[data-composition-id][data-root="true"]'); if (isHtmlElement(explicitRoot)) return explicitRoot; diff --git a/packages/core/src/runtime/compositionLength.ts b/packages/core/src/runtime/compositionLength.ts index 975829c3d8..4542a327a4 100644 --- a/packages/core/src/runtime/compositionLength.ts +++ b/packages/core/src/runtime/compositionLength.ts @@ -2,13 +2,17 @@ import { resolveCompositionDuration, type CompositionDurationResult, } from "@hyperframes/parsers/composition-duration"; -import { findRootCompositionElement, parseCompositionDimension } from "./compositionDimension"; +import { + findRootCompositionElement, + parseCompositionDimension, + readCompositionSizeFromDocument, +} from "./compositionDimension"; import { isMediaElement } from "./domRealm"; import { parseStrictFiniteTimingNumber, resolveMediaElementDurationSeconds } from "./playbackRate"; import { createRuntimeStartTimeResolver } from "./startResolver"; import { createRuntimeState } from "./state"; -export { findRootCompositionElement }; +export { findRootCompositionElement, readCompositionSizeFromDocument }; export const LOOP_INFLATED_TIMELINE_SECONDS = 7200; @@ -204,3 +208,43 @@ export function readStaticCompositionMeta( }); return { ...readCompositionSize(root), fps: createRuntimeState().canonicalFps, durationSeconds }; } + +export const STATIC_COMPOSITION = "static-composition"; +const MAX_STATIC_DURATION_SECONDS = 86_400; +const MAX_STATIC_DIMENSION = 16_384; + +export type StaticComposition = { + durationSeconds: number; + compositionSize: { width: number; height: number } | null; +}; + +/** What the document alone says of its composition: the probe reads it, a sealed frame's runtime posts it. */ +export function readStaticComposition(doc: Document): StaticComposition | null { + const durationSeconds = readStaticCompositionMeta(doc)?.durationSeconds ?? 0; + if (!(durationSeconds > 0)) return null; + return { durationSeconds, compositionSize: readCompositionSizeFromDocument(doc) }; +} + +const boundedDimension = (value: unknown): number | null => + typeof value === "number" && Number.isInteger(value) && value > 0 && value <= MAX_STATIC_DIMENSION + ? value + : null; + +/** A posted read with a finite length in (0, a day] and no size or a whole bounded one, else null. */ +export function parseStaticComposition(data: Record): StaticComposition | null { + const seconds = data["durationSeconds"]; + if ( + typeof seconds !== "number" || + !Number.isFinite(seconds) || + seconds <= 0 || + seconds > MAX_STATIC_DURATION_SECONDS + ) + return null; + const { width, height } = data; + if (width == null && height == null) return { durationSeconds: seconds, compositionSize: null }; + const w = boundedDimension(width); + const h = boundedDimension(height); + return w !== null && h !== null + ? { durationSeconds: seconds, compositionSize: { width: w, height: h } } + : null; +} diff --git a/packages/core/src/runtime/entry.ts b/packages/core/src/runtime/entry.ts index 7b00153df0..2ea8f84339 100644 --- a/packages/core/src/runtime/entry.ts +++ b/packages/core/src/runtime/entry.ts @@ -21,6 +21,7 @@ import { trackAcceleratedCanvases } from "./captureMotionBlur"; import { parkFarScenesAtBoot } from "./sceneWindow"; import { installPausedVideoCallbacks } from "./pausedVideoCallbacks"; import { corsForSealedMedia } from "./sealedMediaCors"; +import { postStaticCompositionWhenParsed } from "./staticCompositionPost"; type HyperframeWindow = Window & { __hyperframeRuntimeBootstrapped?: boolean; @@ -101,6 +102,8 @@ function startAfterCompositionScripts(): void { } } +postStaticCompositionWhenParsed(); + if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", startAfterCompositionScripts, { once: true }); } else { diff --git a/packages/core/src/runtime/staticCompositionPost.test.ts b/packages/core/src/runtime/staticCompositionPost.test.ts new file mode 100644 index 0000000000..b7f5dd9a02 --- /dev/null +++ b/packages/core/src/runtime/staticCompositionPost.test.ts @@ -0,0 +1,58 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { postStaticCompositionWhenParsed } from "./staticCompositionPost"; + +const ROOT = + '
'; + +/** A frame's view of its parent: a window that only records posts. */ +function framed() { + const posts: unknown[] = []; + const parent = { postMessage: (message: unknown) => posts.push(message) }; + vi.spyOn(window, "parent", "get").mockReturnValue(parent as unknown as Window); + return posts; +} + +const sent = (posts: unknown[]) => + posts.map((post) => { + const { type, durationSeconds, width, height } = post as Record; + return { type, durationSeconds, width, height }; + }); + +describe("postStaticCompositionWhenParsed", () => { + afterEach(() => { + vi.restoreAllMocks(); + document.body.innerHTML = ""; + }); + + it("tells a parent frame the document's length and size, once", () => { + const posts = framed(); + document.body.innerHTML = ROOT; + postStaticCompositionWhenParsed(); + expect(sent(posts)).toEqual([ + { type: "static-composition", durationSeconds: 10, width: 1920, height: 1080 }, + ]); + }); + + it("posts nothing from a top-level page", () => { + const post = vi.spyOn(window, "postMessage"); + document.body.innerHTML = ROOT; + postStaticCompositionWhenParsed(); + expect(post).not.toHaveBeenCalled(); + }); + + it("posts while the page still parses, once the root declares its length", async () => { + const posts = framed(); + vi.spyOn(document, "readyState", "get").mockReturnValue("loading"); + postStaticCompositionWhenParsed(); + document.body.innerHTML = '
'; + await Promise.resolve(); + expect(posts).toEqual([]); + document.body.innerHTML = ROOT; + await Promise.resolve(); + expect(sent(posts)).toEqual([ + { type: "static-composition", durationSeconds: 10, width: 1920, height: 1080 }, + ]); + document.dispatchEvent(new Event("DOMContentLoaded")); + expect(posts).toHaveLength(1); + }); +}); diff --git a/packages/core/src/runtime/staticCompositionPost.ts b/packages/core/src/runtime/staticCompositionPost.ts new file mode 100644 index 0000000000..b7da0b0fc6 --- /dev/null +++ b/packages/core/src/runtime/staticCompositionPost.ts @@ -0,0 +1,43 @@ +import { postRuntimeMessage } from "./bridge"; +import { + findRootCompositionElement, + readStaticComposition, + STATIC_COMPOSITION, +} from "./compositionLength"; + +/** Posts the document's static read once, as soon as it is whole: when the root is parsed if it declares its length, + * else at DOMContentLoaded. A parent that can't read the frame is then ready when one that can would be. */ +export function postStaticCompositionWhenParsed(doc: Document = document): void { + // A top-level page (a render) has no parent to tell, and the read walks every clip. + if (window.parent === window) return; + let posted = false; + const post = (): void => { + if (posted) return; + posted = true; + const read = readStaticComposition(doc); + if (!read) return; + postRuntimeMessage({ + source: "hf-preview", + type: STATIC_COMPOSITION, + durationSeconds: read.durationSeconds, + width: read.compositionSize?.width ?? null, + height: read.compositionSize?.height ?? null, + }); + }; + const declared = () => findRootCompositionElement(doc)?.hasAttribute("data-duration") === true; + if (doc.readyState !== "loading" || declared()) return post(); + const observer = new MutationObserver(() => { + if (!declared()) return; + observer.disconnect(); + post(); + }); + observer.observe(doc, { childList: true, subtree: true }); + doc.addEventListener( + "DOMContentLoaded", + () => { + observer.disconnect(); + post(); + }, + { once: true }, + ); +} diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.ts index c529a9a2d2..f962baf61e 100644 --- a/packages/core/src/runtime/types.ts +++ b/packages/core/src/runtime/types.ts @@ -166,6 +166,15 @@ export type RuntimePickerCancelledMessage = { type: "pick-mode-cancelled"; }; +/** The document's own length and size, posted before the runtime boots (`compositionLength.readStaticComposition`). */ +export type RuntimeStaticCompositionMessage = { + source: "hf-preview"; + type: "static-composition"; + durationSeconds: number; + width: number | null; + height: number | null; +}; + export type RuntimeStageSizeMessage = { source: "hf-preview"; type: "stage-size"; @@ -337,6 +346,7 @@ export type RuntimeOutboundMessage = | RuntimePickerPickedManyMessage | RuntimePickerCancelledMessage | RuntimeStageSizeMessage + | RuntimeStaticCompositionMessage | RuntimeMediaAutoplayBlockedMessage | RuntimeReadyMessage | RuntimeAssetsReadyMessage diff --git a/packages/player/src/composition-probe.ts b/packages/player/src/composition-probe.ts index 4d7148788c..b3b76a12cd 100644 --- a/packages/player/src/composition-probe.ts +++ b/packages/player/src/composition-probe.ts @@ -10,7 +10,10 @@ * `stop()` on disconnect or src change. */ -import { readStaticCompositionMeta } from "@hyperframes/core/runtime/composition-length"; +import { + readCompositionSizeFromDocument, + readStaticCompositionMeta, +} from "@hyperframes/core/runtime/composition-length"; import { STUDIO_PREVIEW_ERRORS } from "@hyperframes/core/studio-preview-mark"; import { shouldInjectRuntime } from "./shouldInjectRuntime.js"; import { @@ -55,17 +58,7 @@ export function readPositiveDimension(value: string | null): number | null { return Number.isFinite(parsed) && parsed > 0 ? parsed : null; } -export function readCompositionSizeFromDocument( - doc: Document | null | undefined, -): { width: number; height: number } | null { - const root = - doc?.querySelector("[data-composition-id][data-width][data-height]") ?? - doc?.querySelector("[data-width][data-height]"); - if (!root) return null; - const width = readPositiveDimension(root.getAttribute("data-width")); - const height = readPositiveDimension(root.getAttribute("data-height")); - return width !== null && height !== null ? { width, height } : null; -} +export { readCompositionSizeFromDocument }; type ProbeOutcome = | { kind: "ready"; result: ProbeResult } diff --git a/packages/player/src/hyperframes-player.ts b/packages/player/src/hyperframes-player.ts index b0c661f164..16e4e515b6 100644 --- a/packages/player/src/hyperframes-player.ts +++ b/packages/player/src/hyperframes-player.ts @@ -1,4 +1,5 @@ import { CompositionProbe, type ProbeResult, readPositiveDimension } from "./composition-probe.js"; +import type { StaticComposition } from "@hyperframes/core/runtime/composition-length"; import { isControlsClick, setupControls, setupPoster } from "./controls-setup.js"; import { adoptShadowStyles, createCompositionIframe, scaleIframeToFit } from "./iframe-dom.js"; import { DirectTimelineClock } from "./direct-timeline-clock.js"; @@ -131,6 +132,7 @@ class HyperframesPlayer extends HTMLElement { private probe: CompositionProbe; private _ready = false; + private _readyBeforeRuntime = false; private _readyDocument: Document | null = null; private _connected = false; private _assetsReady = false; @@ -1288,6 +1290,7 @@ class HyperframesPlayer extends HTMLElement { this._rejectRuntimeDataDelivery(channel, requestId, message), onRuntimeTimelineReady: (duration, assetsReady) => this._onRuntimeTimelineReady(duration, assetsReady), + onStaticComposition: (read) => this._onStaticComposition(read), setBuffering: (buffering) => this._setBuffering(buffering), setRuntimeFps: (fps) => { this._runtimeFps = fps; @@ -1312,13 +1315,15 @@ class HyperframesPlayer extends HTMLElement { } private _onRuntimeTimelineReady(duration: number, assetsReady: boolean | undefined) { - if (this._ready) return; + if (this._ready && !this._readyBeforeRuntime) return; + const alreadyReady = this._readyBeforeRuntime; + this._readyBeforeRuntime = false; this.probe.stop(); this._setDuration(duration); this._directTimelineAdapter = null; this._ready = true; this.controlsApi?.updateTime(this._currentTime, duration); - this._dispatchReady(); + if (!alreadyReady) this._dispatchReady(); const doc = this._getSameOriginIframeDocument(); if (doc) this._media.setupFromIframe(doc); @@ -1329,6 +1334,19 @@ class HyperframesPlayer extends HTMLElement { this._playWhenWanted(); } + /** A sealed frame's length and size from its document, as the probe reads them; play waits for the runtime. */ + private _onStaticComposition({ durationSeconds, compositionSize }: StaticComposition) { + // An open frame's own poll reads the same thing. + if (this._ready || this._getSameOriginIframeDocument()) return; + this.probe.stop(); + this._setDuration(durationSeconds); + if (compositionSize) this._setCompositionSize(compositionSize.width, compositionSize.height); + this._ready = true; + this._readyBeforeRuntime = true; + this.controlsApi?.updateTime(0, durationSeconds); + this._dispatchReady(); + } + private _onProbeReady(result: ProbeResult) { this._applyThenEmit(() => this._applyProbeResult(result)); } @@ -1464,6 +1482,7 @@ class HyperframesPlayer extends HTMLElement { this.probe.latchUntilNextLoad(); this.probe.stop(); this._ready = false; + this._readyBeforeRuntime = false; this._readyDocument = null; this._invalidateAssetsWait(); this._releaseDocument(); @@ -1616,6 +1635,7 @@ class HyperframesPlayer extends HTMLElement { } this._ready = false; + this._readyBeforeRuntime = false; // The runtime installs its bridge once its scripts ran and posts `ready`, which can come before // the iframe's load event. Do not erase that authoritative handshake here: doing so strands // retained data set after load until a second `ready` that never comes. Source setters and diff --git a/packages/player/src/runtime-message-handler.ts b/packages/player/src/runtime-message-handler.ts index 1ae13ac120..69152c63cd 100644 --- a/packages/player/src/runtime-message-handler.ts +++ b/packages/player/src/runtime-message-handler.ts @@ -13,6 +13,11 @@ import { import type { ShaderLoaderState } from "./shader-loader-state.js"; import type { ShaderTransitionState } from "./shader-options.js"; import { inspectRuntimeProtocol } from "@hyperframes/core/runtime/protocol"; +import { + parseStaticComposition, + STATIC_COMPOSITION, + type StaticComposition, +} from "@hyperframes/core/runtime/composition-length"; type SceneRecord = { id: string; start: number; duration: number }; @@ -48,6 +53,8 @@ export interface MessageHandlerCallbacks extends PlaybackStateCallbacks { * player uses this as the cross-origin readiness signal because the * same-origin composition probe cannot inspect CDN iframes. */ onRuntimeTimelineReady: (duration: number, assetsReady: boolean | undefined) => void; + /** The frame's own static read, posted before its runtime boots, for a player that can't read the frame. */ + onStaticComposition?: (read: StaticComposition) => void; setBuffering?: (buffering: boolean) => void; setRuntimeFps?: (fps: number) => void; setRuntimeOwnsPlayRange?: (owns: boolean) => void; @@ -96,6 +103,12 @@ export function handleRuntimeMessage( return; } + if (data["type"] === STATIC_COMPOSITION) { + const read = parseStaticComposition(data); + if (read) callbacks.onStaticComposition?.(read); + return; + } + if (data["type"] === "ready") { callbacks.onRuntimeReady(); return; diff --git a/packages/player/src/sealedStaticComposition.test.ts b/packages/player/src/sealedStaticComposition.test.ts new file mode 100644 index 0000000000..25f669d971 --- /dev/null +++ b/packages/player/src/sealedStaticComposition.test.ts @@ -0,0 +1,95 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +type Player = HTMLElement & { + ready: boolean; + duration: number; + iframeElement: HTMLIFrameElement; + _onIframeLoad(): void; +}; + +/** A player whose frame is sealed as the browser seals it: its window posts, its document can't be read. */ +function framedPlayer(sealed = true) { + const player = document.createElement("hyperframes-player") as Player; + player.setAttribute("sandbox-origin", ""); + document.body.appendChild(player); + const frame = player.iframeElement; + if (sealed) Object.defineProperty(frame, "contentDocument", { value: null, configurable: true }); + const events: string[] = []; + player.addEventListener("error", (event: Event) => + events.push(`error ${(event as CustomEvent<{ message?: string }>).detail?.message}`), + ); + player.addEventListener("ready", () => events.push("ready")); + player._onIframeLoad(); + const post = ( + data: Record, + source: MessageEventSource | null = frame.contentWindow, + ) => + window.dispatchEvent( + new MessageEvent("message", { source, data: { source: "hf-preview", ...data } }), + ); + const postStatic = (over: Record = {}, source?: MessageEventSource | null) => + post( + { type: "static-composition", durationSeconds: 4, width: 1080, height: 1920, ...over }, + source, + ); + const postTimeline = () => post({ type: "timeline", durationInFrames: 180, durationSeconds: 6 }); + return { player, events, postStatic, postTimeline }; +} + +describe("a sealed film whose runtime boots after the 8 s check", () => { + beforeEach(async () => { + vi.useFakeTimers(); + await import("./hyperframes-player.js"); + }); + afterEach(() => { + vi.useRealTimers(); + document.body.innerHTML = ""; + }); + + // fails without the fix: a sealed player could only wait for the runtime's timeline, so a film whose runtime booted + // at 10 s showed "Composition timeline not found after 8s" while the same film unsealed was ready from its document. + it("is ready from its document's static read, with no 8 s error, and the runtime's timeline still lands", () => { + const { player, events, postStatic, postTimeline } = framedPlayer(); + vi.advanceTimersByTime(1000); + postStatic(); + expect(events).toEqual(["ready"]); + expect(player.duration).toBe(4); + vi.advanceTimersByTime(9000); + expect(events).toEqual(["ready"]); + postTimeline(); + expect(events).toEqual(["ready"]); + expect(player.duration).toBe(6); + }); + + it.each([ + ["a duration that is not a number", { durationSeconds: Number.NaN }], + ["an infinite duration", { durationSeconds: Number.POSITIVE_INFINITY }], + ["a zero duration", { durationSeconds: 0 }], + ["a negative duration", { durationSeconds: -4 }], + ["a duration past the bound", { durationSeconds: 1e9 }], + ["a duration sent as text", { durationSeconds: "4" }], + ["a width that is not a whole positive number", { width: 0.5 }], + ["a height past the bound", { height: 1e7 }], + ])("ignores a static read with %s", (_name, over) => { + const { player, events, postStatic } = framedPlayer(); + postStatic(over); + vi.advanceTimersByTime(8000); + expect(events).toEqual(["error Composition timeline not found after 8s"]); + expect(player.ready).toBe(false); + }); + + it("ignores a static read posted by any window but its own frame", () => { + const { player, events, postStatic } = framedPlayer(); + postStatic({}, window); + vi.advanceTimersByTime(8000); + expect(events).toEqual(["error Composition timeline not found after 8s"]); + expect(player.ready).toBe(false); + }); + + it("a frame whose document the player reads keeps its own probe and ignores the post", () => { + const { player, events, postStatic } = framedPlayer(false); + postStatic(); + expect(events).toEqual([]); + expect(player.ready).toBe(false); + }); +}); From 5ae70826edba1babb96e57d99be9699c45f0c1d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:29:19 +0000 Subject: [PATCH 104/367] fix(core): a far clip the runtime lets go of keeps counting in the film's length (#8480) * fix(core): a far clip the player lets go of keeps its measured length * test(studio): a capture page keeps a far clip's length while the runtime lets go of it * fix(core): a far clip the runtime lets go of stays in Studio's clip list --- packages/core/src/runtime/clipTree.ts | 5 +- packages/core/src/runtime/init.ts | 6 +- packages/core/src/runtime/media.ts | 4 +- packages/core/src/runtime/playbackRate.ts | 5 +- packages/core/src/runtime/sourceLength.ts | 13 +++ packages/core/src/runtime/startResolver.ts | 3 +- packages/core/src/runtime/timeline.test.ts | 21 +++++ packages/core/src/runtime/timeline.ts | 5 +- .../utils/runtimeClipLength.browser.test.ts | 76 ++++++++++++++++++ packages/studio/tests/fixtures/clip-600s.webm | Bin 0 -> 14304 bytes 10 files changed, 128 insertions(+), 10 deletions(-) create mode 100644 packages/core/src/runtime/sourceLength.ts create mode 100644 packages/studio/src/utils/runtimeClipLength.browser.test.ts create mode 100644 packages/studio/tests/fixtures/clip-600s.webm diff --git a/packages/core/src/runtime/clipTree.ts b/packages/core/src/runtime/clipTree.ts index 47ad3575b9..bdb64234c5 100644 --- a/packages/core/src/runtime/clipTree.ts +++ b/packages/core/src/runtime/clipTree.ts @@ -10,6 +10,7 @@ * absolute start) when a caller needs them. */ +import { sourceLengthOf } from "./sourceLength"; import type { RuntimeTimelineLike } from "./types"; import { parseStrictFiniteTimingNumber, @@ -74,8 +75,8 @@ function durationFromTimeline( function durationFromMedia(el: Element): number | null { if (isMediaElement(el)) { - return Number.isFinite(el.duration) - ? resolveNaturalMediaTimelineDuration(el, el.duration) + return Number.isFinite(sourceLengthOf(el)) + ? resolveNaturalMediaTimelineDuration(el, sourceLengthOf(el)) : null; } return resolveTimedImageDurationSeconds(el); diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts index 935ee72999..f170ff4c86 100644 --- a/packages/core/src/runtime/init.ts +++ b/packages/core/src/runtime/init.ts @@ -1,4 +1,5 @@ // fallow-ignore-file code-duplication complexity +import { rememberSourceLength, sourceLengthOf } from "./sourceLength"; import { wallClearTimeout, wallSetTimeout } from "./wallClock"; import { setPreviewRasterScale } from "./previewRasterHints"; import { createFarSceneSkip } from "./farScenes"; @@ -1557,6 +1558,7 @@ export function initSandboxRuntimeModular(): void { const invalidateOnMediaTimingEvent = (event: Event) => { const target = event.target; + if (isMediaElement(target)) rememberSourceLength(target); if (isMediaElement(target) && lengthIsAuthored(target)) return; invalidateCompositionTimingCaches(); }; @@ -3655,8 +3657,8 @@ export function initSandboxRuntimeModular(): void { context.inheritedDuration > 0 ? Math.max(0, context.inheritedStart + context.inheritedDuration - start) : null; - const sourceDuration = Number.isFinite(element.duration) - ? resolveNaturalMediaTimelineDuration(element, element.duration) + const sourceDuration = Number.isFinite(sourceLengthOf(element)) + ? resolveNaturalMediaTimelineDuration(element, sourceLengthOf(element)) : null; // The element's own data-duration is an explicit clip-length trim // (the studio writes it when you drag the clip edge). It must bound diff --git a/packages/core/src/runtime/media.ts b/packages/core/src/runtime/media.ts index 5bc7a7e27f..dad72d5205 100644 --- a/packages/core/src/runtime/media.ts +++ b/packages/core/src/runtime/media.ts @@ -1,3 +1,4 @@ +import { sourceLengthOf } from "./sourceLength"; import { wallClearTimeout, wallSetTimeout } from "./wallClock"; import { swallow } from "./diagnostics"; import { isClipVisibleAt, isInClipWindow } from "./clipWindow"; @@ -149,7 +150,8 @@ export function refreshRuntimeMediaCache(params?: { const playbackRate = readElementPlaybackRate(el); const rate = readElementRateSpec(el); const loop = el.loop; - const sourceDuration = Number.isFinite(el.duration) && el.duration > 0 ? el.duration : null; + const length = sourceLengthOf(el); + const sourceDuration = Number.isFinite(length) && length > 0 ? length : null; let duration = params?.resolveDurationSeconds?.(el) ?? Number.parseFloat(el.dataset.duration ?? ""); if ((!Number.isFinite(duration) || duration < 0) && sourceDuration != null) { diff --git a/packages/core/src/runtime/playbackRate.ts b/packages/core/src/runtime/playbackRate.ts index d31bb1f956..6e28e1c7f3 100644 --- a/packages/core/src/runtime/playbackRate.ts +++ b/packages/core/src/runtime/playbackRate.ts @@ -1,3 +1,4 @@ +import { sourceLengthOf } from "./sourceLength"; import { clampPlaybackRate, readAuthoredDurationSeconds, @@ -62,12 +63,12 @@ export function resolveMediaElementDurationSeconds( const resolved = resolveMediaDuration({ tag: "video", // video and audio resolve identically authoredDurationSeconds: readDataDurationSeconds((name) => el.getAttribute(name)), - sourceDurationSeconds: Number.isFinite(el.duration) ? el.duration : null, + sourceDurationSeconds: Number.isFinite(sourceLengthOf(el)) ? sourceLengthOf(el) : null, mediaStartSeconds: readMediaStart(el), playbackRate: readElementPlaybackRate(el), }); return resolved.source === "media" - ? resolveNaturalMediaTimelineDuration(el, el.duration) + ? resolveNaturalMediaTimelineDuration(el, sourceLengthOf(el)) : resolved.seconds; } diff --git a/packages/core/src/runtime/sourceLength.ts b/packages/core/src/runtime/sourceLength.ts new file mode 100644 index 0000000000..174a7a3067 --- /dev/null +++ b/packages/core/src/runtime/sourceLength.ts @@ -0,0 +1,13 @@ +const measured = new WeakMap(); + +export function rememberSourceLength(media: HTMLMediaElement): void { + if (Number.isFinite(media.duration) && media.duration > 0) + measured.set(media, { src: media.src, seconds: media.duration }); +} + +/** The source length: the element's own, else the one measured for the same `src` before a reload emptied it; NaN. */ +export function sourceLengthOf(media: { duration: number; src?: string }): number { + if (Number.isFinite(media.duration)) return media.duration; + const kept = measured.get(media); + return kept !== undefined && kept.src === media.src ? kept.seconds : Number.NaN; +} diff --git a/packages/core/src/runtime/startResolver.ts b/packages/core/src/runtime/startResolver.ts index c1ef59a2c7..ed7699081a 100644 --- a/packages/core/src/runtime/startResolver.ts +++ b/packages/core/src/runtime/startResolver.ts @@ -1,3 +1,4 @@ +import { sourceLengthOf } from "./sourceLength"; import type { RuntimeTimelineLike } from "./types"; import { readTimelineDurationSeconds } from "./timelineDuration"; import { resolveAuthoredTimingWindow } from "./authoredTiming"; @@ -100,7 +101,7 @@ export function createRuntimeStartTimeResolver(params: { resolveAuthoredDuration(element) ?? positive( isMediaElement(element) - ? resolveNaturalMediaTimelineDuration(element, element.duration) + ? resolveNaturalMediaTimelineDuration(element, sourceLengthOf(element)) : null, ) ?? positive(resolveTimedImageDurationSeconds(element)) ?? diff --git a/packages/core/src/runtime/timeline.test.ts b/packages/core/src/runtime/timeline.test.ts index 7f4c0bf80e..d1f3227e46 100644 --- a/packages/core/src/runtime/timeline.test.ts +++ b/packages/core/src/runtime/timeline.test.ts @@ -6,6 +6,7 @@ import { runtimeElementWindow, } from "./timeline"; import { createRuntimeStartTimeResolver } from "./startResolver"; +import { rememberSourceLength } from "./sourceLength"; type TimelineTestWindow = Window & { __timelines?: Record number }>; @@ -309,6 +310,26 @@ describe("collectRuntimeTimelinePayload", () => { ); }); + // fails without the fix: a far clip the runtime let go of dropped out of the clip list. + it("keeps an untrimmed clip the runtime let go of, at its measured length", () => { + const root = document.createElement("div"); + root.setAttribute("data-composition-id", "main"); + document.body.appendChild(root); + const video = document.createElement("video"); + video.id = "far"; + video.src = "far.mp4"; + video.setAttribute("data-start", "300"); + root.appendChild(video); + Object.defineProperty(video, "duration", { value: 600, writable: true, configurable: true }); + rememberSourceLength(video); + video.duration = Number.NaN; + + const far = collectRuntimeTimelinePayload(defaultParams).clips.find( + (clip) => clip.id === "far", + ); + expect(far?.duration).toBe(600); + }); + it("identifies video clips by tag", () => { const root = document.createElement("div"); root.setAttribute("data-composition-id", "main"); diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.ts index 94757fc876..bc901f671e 100644 --- a/packages/core/src/runtime/timeline.ts +++ b/packages/core/src/runtime/timeline.ts @@ -1,3 +1,4 @@ +import { sourceLengthOf } from "./sourceLength"; import type { RuntimeTimelineClip, RuntimeTimelineMessage, @@ -447,8 +448,8 @@ export function collectRuntimeTimelinePayload(params: { duration = resolveTimelineDurationSeconds(nodeCompositionId); } if (duration == null && isMediaElement(node)) { - if (Number.isFinite(node.duration)) { - duration = resolveNaturalMediaTimelineDuration(node, node.duration); + if (Number.isFinite(sourceLengthOf(node))) { + duration = resolveNaturalMediaTimelineDuration(node, sourceLengthOf(node)); } } if (duration == null) duration = resolveTimedImageDurationSeconds(node, start); diff --git a/packages/studio/src/utils/runtimeClipLength.browser.test.ts b/packages/studio/src/utils/runtimeClipLength.browser.test.ts new file mode 100644 index 0000000000..6417171182 --- /dev/null +++ b/packages/studio/src/utils/runtimeClipLength.browser.test.ts @@ -0,0 +1,76 @@ +// Real Chrome: a capture page's film length while the runtime lets go of a far clip it has already measured. +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import type { Browser } from "puppeteer-core"; +import { afterAll, beforeAll, expect, it } from "vitest"; +import { + STUDIO_PREVIEW_CAPTURE_MODE, + STUDIO_PREVIEW_MARK_META, +} from "@hyperframes/core/studio-preview-mark"; +import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils"; + +const require = createRequire(import.meta.url); +const ORIGIN = "https://fixture.hyperframes.test"; +const CLIP = readFileSync(new URL("../../tests/fixtures/clip-600s.webm", import.meta.url)); + +/** The clip trimmed to 37.43 s at 0, and untrimmed (600 s) at 300 s: the film is 900 s long. */ +function filmHtml(): string { + const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8"); + const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); + return ` + + +
+ + +
+ + `; +} + +let browser: Browser; +beforeAll(async () => { + browser = await launchTestChrome(); +}); +afterAll(() => closeTestChrome(browser)); + +// fails without the fix: each time the runtime let go of the far clip, the film fell back to 37.43 s. +it("keeps a far clip's measured length while the runtime lets go of it", async () => { + const page = await browser.newPage(); + await page.setRequestInterception(true); + page.on("request", (request) => { + const url = request.url(); + if (url === `${ORIGIN}/index.html`) + return void request.respond({ status: 200, contentType: "text/html", body: filmHtml() }); + if (url === `${ORIGIN}/clip-600s.webm`) + return void request.respond({ status: 200, contentType: "video/webm", body: CLIP }); + void request.abort(); + }); + await page.goto(`${ORIGIN}/index.html`); + await page.waitForFunction( + () => (window as unknown as { __playerReady?: boolean }).__playerReady === true, + ); + // Asks the far clip to load as a length read does, and notes the film's length every 16 ms for 2 s. + const lengths = await page.evaluate( + () => + new Promise((resolve) => { + const far = document.getElementById("far") as HTMLVideoElement; + const player = (window as unknown as { __player: { getDuration(): number } }).__player; + const seen: number[] = []; + const started = performance.now(); + (function poll() { + if (far.readyState < 1 && far.networkState !== 2) { + far.preload = "metadata"; + far.load(); + } + seen.push(player.getDuration()); + if (performance.now() - started > 2000) return resolve(seen); + setTimeout(poll, 16); + })(); + }), + ); + await page.close(); + const measured = lengths.indexOf(900); + expect(measured).toBeGreaterThanOrEqual(0); + expect(lengths.slice(measured).filter((seconds) => seconds !== 900)).toEqual([]); +}, 30_000); diff --git a/packages/studio/tests/fixtures/clip-600s.webm b/packages/studio/tests/fixtures/clip-600s.webm new file mode 100644 index 0000000000000000000000000000000000000000..9b424a8d61fdf70fb40c281c2b14f77cac0e5e4d GIT binary patch literal 14304 zcmd7ZZD^Hc90u_F>^P?-x{69`*g@?}kUm=YT5vpW(WtqTTZV}2=+gCKbzu2IM4V?w z-OORj5#kGaWJ-uOPDw8~qSGtGPa{Hm6HoNP2&rQl_9=R9-OVol?SJtoGny#u+40)% zy6y*k7~5SnXL|N0w)m06rQr7;{;0$Se@von(}vZnUP!e2Wr@vx*~ErSOT^f>Ir&@a z_Pl(&u5VkzkxjSP9$wRM)IV_Ly*nCvpAX(US=ZMYeC*c7&s!RfwneJ0yj#`K7ksd7 z&f;@da?G;JaW~=*tIFSZ>fP*wM7%E3`S{B9Yi7@!9{lpWrxsrIZuQoVg;VM?7Gd$9 z_72+Sp7JBDUv@Oj9o;*A*5sG=`ew@ed$a3ae7eIoTQ)CkTAG}f^&?Y%&Td+;`-CZO z&HM4={0vpWb-?`t-b({sT2V9o0`RS=d-xzqq=++w_Nav2_nW1#uQ3z__D|N^8 zB0A8{9ZewC9d^!ejz^N{z;xXqTXF|x>U*pxpabo?4&6pzFn zojK>QEz!;$xVG+)-Sj;UR-yybxdX+zL!O}S=*yr3*VY}fC3m1$cYIw!NBBKZ%pI7i zJAO?$his|uA=l;(6f2JG*=!^-;2<)dLvU^#BFhoTq&PxQ&mp+C4zcBsOdwt!AsDYi zWKRykOagf{h7i>25P66kf-4h9Q5_@LI@77Lu5}5K{8on;{Za!FM?za!At__iaUtxsV`#h zCXDA0BooNnc?Xg49D;-E5Lu2uK8Ya&^&Ap@5hN4H$u5Loybh5)^+n{$1oE3f29D-y5Y4#8jei0;d2xbz(;|J@rN8;2eTv0@+dNATpjqaBv+W%Mr-o3_?)P zAvm}WvE`6VAcYb_FkXkqo*aUi3M6=rj((d$2yS|uafB>~uX5{Nx}tQHR)aNG6b1(+I(M9U^;j2xbyUcM&0|*CFx{ zIRsZGkRwS4kv%yC$s7`Lk&TIJcl4zhsZ-Dkn=f&;NUt$ z_T&&G>yYxXl?VyH2$DGjGYKS?aS+*4UqlYhAxI{WIVA^?@f?DK>kwIvKk!$KLoky-UW+3H^*TfzB8TA01oBqiL1a%3K{AJgT;!dYgV>&^ z=Maq7A+j7<25P66kf-4iqf-VPk!$KLy$}$yOIbAzX*~!1TzUFUvLoFQ(r_5&LK!vAi;BVMZf1DGJY7y zfAb9{6=!m2!Xm?%Zs0eVR9vcbkZU_7B=b`Wce{)kpK%a-N_ex6#3Hhsa=Qc%^keQV zAq4dtg5(idzyA*vceAFrGt@tV84>{u^R{F79;S8^?U};p@TA z-<@xZ>@WGzzBi9$BNyGJaX*y&8TL{@8hq8nsU?4zy%c;!Zt&97izUC@UJ8DIYw*&H Ihl0QO4~*EJG5`Po literal 0 HcmV?d00001 From 154842851acc143bdafa74707992103460369ae7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:49:32 +0000 Subject: [PATCH 105/367] test(studio): the preview regression counts decoded covers, not the macOS gamma filter (#8484) --- packages/studio/tests/e2e/preview-video-regression.mjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/studio/tests/e2e/preview-video-regression.mjs b/packages/studio/tests/e2e/preview-video-regression.mjs index 993e17707f..2ccf77ec03 100644 --- a/packages/studio/tests/e2e/preview-video-regression.mjs +++ b/packages/studio/tests/e2e/preview-video-regression.mjs @@ -235,7 +235,7 @@ async function nativeOnlyHandoff() { await host.frame.evaluate(() => window.__hf.setPausedVideoFrameProvider(null)); await seek(host, 0); await host.frame.waitForFunction( - () => !document.querySelector("[data-hf-preview-video-canvas]"), + () => !document.querySelector("canvas[data-hf-preview-video-canvas]"), ); const baseline = await picture(host, "native-only-paused"); assert.equal(baseline.scene, "A"); @@ -312,7 +312,7 @@ async function delayedNativeRecovery() { const deliveredAt = performance.now(); await release(); await host.frame.waitForFunction( - () => !document.querySelector("[data-hf-preview-video-canvas]"), + () => !document.querySelector("canvas[data-hf-preview-video-canvas]"), { timeout: 5000 }, ); const recovery = await host.frame.evaluate(() => ({ @@ -423,7 +423,7 @@ try { assert.equal(await host.frame.evaluate(() => window.__player.isPlaying()), false); await play(host); await host.frame.waitForFunction( - () => document.querySelectorAll("[data-hf-preview-video-canvas]").length === 0, + () => document.querySelectorAll("canvas[data-hf-preview-video-canvas]").length === 0, ); await collectGarbage(host); assert.deepEqual(errors, [], "Browser logged an error or unclosed VideoSample"); From 104eab37ad38f75336290655e54308d319a4d3e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:55:49 +0000 Subject: [PATCH 106/367] fix(core): a preview seek waits for each graded video to draw its new frame (#8488) * test(core): a preview seek waits for each graded video to draw its new frame * fix(core): a preview seek waits for each graded video to draw its new frame * test(core): a graded video that cannot draw never holds a preview seek * fix(core): a graded video that cannot draw never holds a preview seek --- .../core/src/runtime/colorGrading.test.ts | 96 +++++++++++++++++++ packages/core/src/runtime/colorGrading.ts | 46 ++++++++- .../src/runtime/init.gradeSeekHold.test.ts | 41 ++++++++ packages/core/src/runtime/init.ts | 1 + .../tests/e2e/graded-video-transitions.mjs | 1 + 5 files changed, 183 insertions(+), 2 deletions(-) create mode 100644 packages/core/src/runtime/init.gradeSeekHold.test.ts diff --git a/packages/core/src/runtime/colorGrading.test.ts b/packages/core/src/runtime/colorGrading.test.ts index 6e0e05d296..640aa50211 100644 --- a/packages/core/src/runtime/colorGrading.test.ts +++ b/packages/core/src/runtime/colorGrading.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { mediaElementTime } from "./mediaClock"; import { PREVIEW_SEEK_HOLD_ATTR } from "../studioPreviewMark"; +import { resetSeekDispatchState, waitForSeekCompletion } from "./adapters/seek-dispatch"; import { COLOR_GRADING_SOURCE_HIDDEN_ATTR, HF_COLOR_GRADING_ATTR, @@ -370,6 +371,101 @@ describe("createColorGradingRuntime", () => { expect(texImage2DCalls.length).toBeGreaterThan(drawsBefore); }); + it("holds a seek until each graded video draws the frame it landed on", async () => { + resetSeekDispatchState(); + vi.useFakeTimers(); + try { + const video = makeDrawableVideo(); + Object.defineProperty(video, "readyState", { + value: HTMLMediaElement.HAVE_METADATA, + configurable: true, + }); + startRuntimeWithVideo(video); + runtime!.holdSeekUntilDrawn(); + expect(runtime!.redraw()).toBe(0); + let settled = false; + void waitForSeekCompletion().then(() => (settled = true)); + await vi.advanceTimersByTimeAsync(0); + expect(settled).toBe(false); + + Object.defineProperty(video, "readyState", { + value: HTMLMediaElement.HAVE_CURRENT_DATA, + configurable: true, + }); + video.dispatchEvent(new Event("seeked")); + await vi.advanceTimersByTimeAsync(0); + expect(settled).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + + it("lets a seek go after a bounded wait when a graded video never draws", async () => { + resetSeekDispatchState(); + vi.useFakeTimers(); + try { + const video = makeDrawableVideo(); + Object.defineProperty(video, "readyState", { + value: HTMLMediaElement.HAVE_METADATA, + configurable: true, + }); + startRuntimeWithVideo(video); + runtime!.holdSeekUntilDrawn(); + let settled = false; + const seek = waitForSeekCompletion().then(() => (settled = true)); + await vi.advanceTimersByTimeAsync(1_000); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(2_000); + await seek; + expect(settled).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + + it("does not hold a seek for a graded video that has nothing to draw", async () => { + resetSeekDispatchState(); + vi.useFakeTimers(); + try { + const video = makeDrawableVideo(); + Object.defineProperty(video, "readyState", { + value: HTMLMediaElement.HAVE_NOTHING, + configurable: true, + }); + startRuntimeWithVideo(video); + runtime!.holdSeekUntilDrawn(); + let settled = false; + void waitForSeekCompletion().then(() => (settled = true)); + await vi.advanceTimersByTimeAsync(0); + expect(settled).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + + it("lets a held seek go as soon as its graded video fails", async () => { + resetSeekDispatchState(); + vi.useFakeTimers(); + try { + const video = makeDrawableVideo(); + Object.defineProperty(video, "readyState", { + value: HTMLMediaElement.HAVE_METADATA, + configurable: true, + }); + startRuntimeWithVideo(video); + runtime!.holdSeekUntilDrawn(); + let settled = false; + void waitForSeekCompletion().then(() => (settled = true)); + await vi.advanceTimersByTimeAsync(0); + expect(settled).toBe(false); + video.dispatchEvent(new Event("error")); + await vi.advanceTimersByTimeAsync(0); + expect(settled).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + it("does not redraw-loop on its own hide writes (opacity/visibility only)", async () => { const { video } = startRuntimeWithVideo(); await new Promise((resolve) => requestAnimationFrame(() => resolve(null))); diff --git a/packages/core/src/runtime/colorGrading.ts b/packages/core/src/runtime/colorGrading.ts index 8f0f470cb4..1430bfbfcc 100644 --- a/packages/core/src/runtime/colorGrading.ts +++ b/packages/core/src/runtime/colorGrading.ts @@ -1,4 +1,5 @@ import { wallClearTimeout, wallSetTimeout } from "./wallClock"; +import { registerSeekCompletion } from "./adapters/seek-dispatch"; import { PREVIEW_SEEK_HOLD_ATTR } from "../studioPreviewMark"; import { HF_COLOR_GRADING_ADJUST_KEYS, @@ -236,6 +237,7 @@ interface ColorGradingEntry extends ColorGradingRenderer { sourceOpacityForCanvas: string; sourceVisibleForCanvas: boolean; hasDrawn: boolean; + seeksAwaitingDraw: Array<() => void>; contextLost: boolean; grainSeed: number; destroyed: boolean; @@ -260,6 +262,7 @@ export interface RuntimeColorGradingApi { refresh: () => number; redraw: () => number; redrawAnimated: () => number; + holdSeekUntilDrawn: () => void; waitForActiveLuts: () => Promise; setGrading: ( target: HfColorGradingTarget | string | null | undefined, @@ -3525,6 +3528,12 @@ function placeCanvas( return { layout, uv }; } +function markDrawn(entry: ColorGradingEntry): void { + entry.hasDrawn = true; + entry.drawError = null; + releaseSeeks(entry); +} + function drawEntry(entry: ColorGradingEntry): boolean { if (entry.destroyed || entry.contextLost) return false; const frame = drawableFrame(entry); @@ -3540,8 +3549,7 @@ function drawEntry(entry: ColorGradingEntry): boolean { renderGradedFrame(entry, pixels, layout, uv); hideSourceElement(entry); if (injectedFrameSource) hideFrame(entry, source); - entry.hasDrawn = true; - entry.drawError = null; + markDrawn(entry); return true; } catch (err) { entry.drawError = err instanceof Error ? err.message : "Shader draw failed"; @@ -3782,6 +3790,8 @@ function installEntryListeners(entry: ColorGradingEntry): void { addListener(entry, entry.element, "loadedmetadata", redraw); addListener(entry, entry.element, "loadeddata", redrawOnPresentedFrame); addListener(entry, entry.element, "seeked", redrawOnPresentedFrame); + addListener(entry, entry.element, "error", () => releaseSeeks(entry)); + addListener(entry, entry.element, "emptied", () => releaseSeeks(entry)); addListener(entry, entry.element, "timeupdate", redraw); addListener(entry, window, "resize", redraw); if (isVideoElement(entry.element)) { @@ -3820,9 +3830,32 @@ function installEntryListeners(entry: ColorGradingEntry): void { } } +const SEEK_DRAW_LIMIT_MS = 2_000; + +function nextDraw(entry: ColorGradingEntry): Promise { + return new Promise((resolve) => { + const release = () => { + wallClearTimeout(timer); + const at = entry.seeksAwaitingDraw.indexOf(release); + if (at >= 0) entry.seeksAwaitingDraw.splice(at, 1); + resolve(); + }; + const timer = wallSetTimeout(release, SEEK_DRAW_LIMIT_MS); + entry.seeksAwaitingDraw.push(release); + }); +} + +const releaseSeeks = (entry: ColorGradingEntry) => { + for (const release of entry.seeksAwaitingDraw.splice(0)) release(); +}; + +const canDraw = (video: HTMLVideoElement) => + !video.error && video.readyState >= HTMLMediaElement.HAVE_METADATA && video.videoWidth > 0; + function detachEntry(entry: ColorGradingEntry): ColorGradingRenderer | null { if (entry.destroyed) return null; entry.destroyed = true; + releaseSeeks(entry); cancelScheduledFrame(entry); entry.resizeObserver?.disconnect(); for (const cleanup of entry.cleanup) cleanup(); @@ -4003,6 +4036,7 @@ export function createColorGradingRuntime(pausedMediaLease?: { sourceOpacityForCanvas: window.getComputedStyle(element).opacity || "1", sourceVisibleForCanvas: window.getComputedStyle(element).visibility !== "hidden", hasDrawn: false, + seeksAwaitingDraw: [], contextLost: false, grainSeed: seedForElement(element), destroyed: false, @@ -4111,6 +4145,13 @@ export function createColorGradingRuntime(pausedMediaLease?: { return drawn; }; + const holdSeekUntilDrawn = (): void => { + const videos = trackedEntries().filter( + (entry) => isVideoElement(entry.element) && canDraw(entry.element), + ); + if (videos.length) registerSeekCompletion(Promise.all(videos.map(nextDraw)), "video-frame"); + }; + const waitForActiveLuts = async (): Promise => { const pending = new Set>(); for (const element of trackedElements) { @@ -4302,6 +4343,7 @@ export function createColorGradingRuntime(pausedMediaLease?: { refresh, redraw, redrawAnimated, + holdSeekUntilDrawn, waitForActiveLuts, setGrading, setCompare, diff --git a/packages/core/src/runtime/init.gradeSeekHold.test.ts b/packages/core/src/runtime/init.gradeSeekHold.test.ts new file mode 100644 index 0000000000..ac24720c00 --- /dev/null +++ b/packages/core/src/runtime/init.gradeSeekHold.test.ts @@ -0,0 +1,41 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { initSandboxRuntimeModular } from "./init"; +import { createMockTimeline, resetRuntimeFixtureDom } from "./runtimeSeekFixture.test-helpers"; + +const calls = vi.hoisted(() => [] as string[]); + +vi.mock("./colorGrading", async (original) => { + const real = await original(); + return { + ...real, + createColorGradingRuntime: (...args: Parameters) => { + const api = real.createColorGradingRuntime(...args); + return { + ...api, + holdSeekUntilDrawn: () => void calls.push("hold"), + redraw: () => { + calls.push("redraw"); + return api.redraw(); + }, + }; + }, + }; +}); + +afterEach(() => { + calls.length = 0; + vi.restoreAllMocks(); +}); + +it("a paused seek holds for the graded videos' draw before it redraws them", () => { + resetRuntimeFixtureDom(); + document.body.innerHTML = + '
'; + window.__timelines = { main: createMockTimeline(60) }; + initSandboxRuntimeModular(); + calls.length = 0; + + window.__player!.seek(5); + + expect(calls.slice(0, 2)).toEqual(["hold", "redraw"]); +}); diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts index f170ff4c86..f6e13592f1 100644 --- a/packages/core/src/runtime/init.ts +++ b/packages/core/src/runtime/init.ts @@ -5063,6 +5063,7 @@ export function initSandboxRuntimeModular(): void { transport.play(); return; } + colorGrading.holdSeekUntilDrawn(); colorGrading.redraw(); paintVfx(state.currentTime); const blurred = paintCaptureMotionBlur(state.currentTime); diff --git a/packages/studio/tests/e2e/graded-video-transitions.mjs b/packages/studio/tests/e2e/graded-video-transitions.mjs index a2e9cb850b..0fcb9aba33 100644 --- a/packages/studio/tests/e2e/graded-video-transitions.mjs +++ b/packages/studio/tests/e2e/graded-video-transitions.mjs @@ -42,6 +42,7 @@ try { /** RGB at fractions of the film's width and height, read from a screenshot of the preview at `time`. */ const sample = async (name, time, points) => { await frame.evaluate((t) => window.__player.seek(t, { settled: true }), time); + await frame.evaluate(() => window.__hfWaitForSeekCompletion?.()); await frame.evaluate( () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))), ); From bfd6cb755f9ea4caface8532c865f9f1ddaa00e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:56:11 +0000 Subject: [PATCH 107/367] fix(studio): a pasted element lands after its own original, never inside a script (#8489) * fix(studio): a pasted element lands after its own original, never inside a script * fix(studio): a paste compares the anchor id instead of building a pattern from it --- .../core/src/compiler/htmlDocument.test.ts | 20 +++ packages/core/src/compiler/htmlDocument.ts | 21 +++ .../studio/src/hooks/useClipboard.test.ts | 3 +- packages/studio/src/hooks/useClipboard.ts | 20 +-- .../studio/src/utils/clipboardPayload.test.ts | 32 ++++ packages/studio/src/utils/clipboardPayload.ts | 161 ++++++------------ 6 files changed, 141 insertions(+), 116 deletions(-) diff --git a/packages/core/src/compiler/htmlDocument.test.ts b/packages/core/src/compiler/htmlDocument.test.ts index fa73321984..bbaacc22af 100644 --- a/packages/core/src/compiler/htmlDocument.test.ts +++ b/packages/core/src/compiler/htmlDocument.test.ts @@ -12,6 +12,7 @@ import { hasCompositionOutsideTemplates, isFullHtmlDocument, mapStartTagsAndStyles, + tagsOutsideCommentsAndRawText, parseHTMLContent, stripEmbeddedRuntimeScripts, } from "./htmlDocument.js"; @@ -524,3 +525,22 @@ describe("insertRuntimeTag", () => { } }); }); + +describe("tagsOutsideCommentsAndRawText", () => { + it("lists the real tags only, never tag text inside a script, style, title or comment", () => { + const html = `

x


`; + const tags = [...tagsOutsideCommentsAndRawText(html)].map( + ({ lowercaseName, closing, start, endAfterBracket }) => + `${closing ? "/" : ""}${lowercaseName}:${html.slice(start, endAfterBracket)}`, + ); + expect(tags).toEqual([ + 'p:

', + "/p:

", + "script:", + "style:", + "br:
", + ]); + }); +}); diff --git a/packages/core/src/compiler/htmlDocument.ts b/packages/core/src/compiler/htmlDocument.ts index 242034122c..2bca064612 100644 --- a/packages/core/src/compiler/htmlDocument.ts +++ b/packages/core/src/compiler/htmlDocument.ts @@ -308,6 +308,27 @@ export function mapStartTagsAndStyles( return out + html.slice(cursor); } +export interface SourceTag { + start: number; + endAfterBracket: number; + lowercaseName: string; + closing: boolean; +} + +export function* tagsOutsideCommentsAndRawText(html: string): Generator { + for (const open of markupStarts(html)) { + const closing = html.charAt(open + 1) === "/"; + const nameStart = open + (closing ? 2 : 1); + if (!/[a-z]/i.test(html.charAt(nameStart))) continue; + const end = findTagEnd(html, nameStart); + if (end === -1) return; + let nameEnd = nameStart; + while (nameEnd < end && !isTagBoundary(html.charAt(nameEnd))) nameEnd++; + const lowercaseName = lowerAscii(html.slice(nameStart, nameEnd)); + yield { start: open, endAfterBracket: end + 1, lowercaseName, closing }; + } +} + export function findStartTags(html: string, name: string): number[] { const token = `<${lowerAscii(name)}`; const starts: number[] = []; diff --git a/packages/studio/src/hooks/useClipboard.test.ts b/packages/studio/src/hooks/useClipboard.test.ts index 123721a574..b3d4e2087b 100644 --- a/packages/studio/src/hooks/useClipboard.test.ts +++ b/packages/studio/src/hooks/useClipboard.test.ts @@ -304,7 +304,8 @@ describe("pasteElementHtml", () => { ROOT.replace("", '

Hello there

'), ); const copied = stamped.match(/]*id="title"[^>]*>.*?<\/p>/)![0]; - const content = pasteElementHtml(stamped, { html: copied, originSelector: "#title" }); + const content = pasteElementHtml(stamped, { html: copied, saved: true }, true); + expect(content.indexOf("

") + 4).toBe(content.indexOf("\n export function pasteElementHtml( content: string, - payload: { html: string; saved?: boolean; originSelector?: string; originSelectorIndex?: number }, + payload: { html: string; saved?: boolean }, fromThisFile = false, ): string { - const reminted = remintHfIds(payload.html, new DOMParser(), hfIdsInFile(content), payload.saved); + const parser = new DOMParser(); + const reminted = remintHfIds(payload.html, parser, hfIdsInFile(content), payload.saved); const deduped = deduplicateIds(reminted, collectHtmlIds(content)); - const result = insertAsSibling( - content, - deduped, - payload.originSelector, - payload.originSelectorIndex, - ); + const anchorFromThisFile = + fromThisFile && payload.saved + ? parser + .parseFromString(payload.html, "text/html") + .body.firstElementChild?.getAttribute("data-hf-id") + : null; + const result = insertAsSibling(content, deduped, anchorFromThisFile ?? undefined); return fromThisFile ? carryLook(result, renamedIds(reminted, deduped), 0) : result; } @@ -376,8 +378,6 @@ export function useClipboard({ ...savedMarkupElseLive(parseSavedSource(content), live, sourceFile), sourceFile, projectId: pid ?? undefined, - originSelector: domSelection.selector, - originSelectorIndex: domSelection.selectorIndex, }; }); return copyFound(found, copy, showToast); diff --git a/packages/studio/src/utils/clipboardPayload.test.ts b/packages/studio/src/utils/clipboardPayload.test.ts index d677328bf7..8801b0ce31 100644 --- a/packages/studio/src/utils/clipboardPayload.test.ts +++ b/packages/studio/src/utils/clipboardPayload.test.ts @@ -4,6 +4,7 @@ import { deduplicateIds, serializeClipboardPayload, deserializeClipboardPayload, + insertAsSibling, type ClipboardPayload, } from "./clipboardPayload"; @@ -128,3 +129,34 @@ describe("serializeClipboardPayload / deserializeClipboardPayload", () => { expect(deserializeClipboardPayload(json)).toBeNull(); }); }); + +describe("insertAsSibling", () => { + const ROOT = '
'; + const PASTED = 'new'; + + it("places the paste right after the element the file names by that id", () => { + const source = `${ROOT}

one two

three

`; + expect(insertAsSibling(source, PASTED, "a1")).toBe( + `${ROOT}

one two

\n${PASTED}

three

`, + ); + }); + + it("never anchors on tag text inside a script, style or comment", () => { + const script = ``; + const style = + ''; + const source = `${script}${style}${ROOT}

one

`; + expect(insertAsSibling(source, PASTED, "w1")).toBe( + `${script}${style}${ROOT}${PASTED}

one

`, + ); + }); + + it("takes an anchor no element has, a pattern-like one too, as no anchor, at once", () => { + const source = `${ROOT}${"a".repeat(5000)}!`; + const started = performance.now(); + expect(insertAsSibling(source, PASTED, "(a+)+$")).toBe( + `${ROOT}${PASTED}${"a".repeat(5000)}!`, + ); + expect(performance.now() - started).toBeLessThan(500); + }); +}); diff --git a/packages/studio/src/utils/clipboardPayload.ts b/packages/studio/src/utils/clipboardPayload.ts index 227505d1ee..fef60cc4dd 100644 --- a/packages/studio/src/utils/clipboardPayload.ts +++ b/packages/studio/src/utils/clipboardPayload.ts @@ -1,4 +1,7 @@ -import { COMPOSITION_ROOT_OPEN_TAG_RE } from "./compositionPatterns"; +import { + tagsOutsideCommentsAndRawText, + type SourceTag, +} from "@hyperframes/core/compiler/html-document"; const CLIPBOARD_MARKER = "hyperframes-clipboard:v1"; @@ -26,8 +29,6 @@ export type ClipboardPayload = saved?: boolean; sourceFile: string; projectId?: string; - originSelector?: string; - originSelectorIndex?: number; }; type SerializedPayload = { _marker: string } & ClipboardPayload; @@ -85,119 +86,69 @@ export function deserializeClipboardPayload(json: string): ClipboardPayload | nu html: obj.html, sourceFile: obj.sourceFile, projectId: typeof obj.projectId === "string" ? obj.projectId : undefined, - originSelector: typeof obj.originSelector === "string" ? obj.originSelector : undefined, - originSelectorIndex: - typeof obj.originSelectorIndex === "number" ? obj.originSelectorIndex : undefined, }; } return null; } -/** - * Insert `newHtml` as a sibling immediately after the element matched by - * `selector` (at `selectorIndex`) in `source`. Falls back to inserting after - * the composition root if the selector doesn't match — so paste never silently - * drops the content. - */ -// fallow-ignore-next-line complexity -export function insertAsSibling( - source: string, - newHtml: string, - selector: string | undefined, - selectorIndex: number | undefined, -): string { - if (selector) { - const idx = selectorIndex ?? 0; - let matchCount = 0; +const VOID_TAGS = new Set([ + "area", + "base", + "br", + "col", + "embed", + "hr", + "img", + "input", + "link", + "meta", + "source", + "track", + "wbr", +]); +const HF_ID_ATTRIBUTE = /\sdata-hf-id\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/i; - // Find the element by searching for its opening tag pattern. - // For id selectors like #foo, search for id="foo". - // For class selectors like .name-text, search for class="...name-text...". - // For attribute selectors like [data-composition-id="x"], search literally. +const tagText = (source: string, tag: SourceTag) => source.slice(tag.start, tag.endAfterBracket); +const selfClosing = (source: string, tag: SourceTag) => + source.charAt(tag.endAfterBracket - 2) === "/"; - let searchPattern: RegExp | null = null; - if (selector.startsWith("#")) { - const id = selector.slice(1); - searchPattern = new RegExp(`<[a-z][^>]*\\bid="${id}"[^>]*>`, "gi"); - } else if (selector.startsWith(".")) { - const cls = selector.slice(1); - searchPattern = new RegExp(`<[a-z][^>]*\\bclass="[^"]*\\b${cls}\\b[^"]*"[^>]*>`, "gi"); - } else if (selector.startsWith("[")) { - const inner = selector.slice(1, -1); - searchPattern = new RegExp(`<[a-z][^>]*\\b${inner}[^>]*>`, "gi"); - } - - if (searchPattern) { - let match: RegExpExecArray | null; - while ((match = searchPattern.exec(source)) !== null) { - if (matchCount === idx) { - const insertPos = findClosingTagPosition(source, match.index); - if (insertPos > 0) { - return source.slice(0, insertPos) + "\n" + newHtml + source.slice(insertPos); - } - } - matchCount++; - } - } - } - - // Fallback: insert after composition root opening tag (same as timeline clips) - const rootMatch = COMPOSITION_ROOT_OPEN_TAG_RE.exec(source); - if (rootMatch && rootMatch.index != null) { - const insertAt = rootMatch.index + rootMatch[0].length; - return source.slice(0, insertAt) + newHtml + source.slice(insertAt); - } - - return source + newHtml; -} - -// fallow-ignore-next-line complexity -function findClosingTagPosition(html: string, openTagStart: number): number { - // Find the end of the opening tag - const openTagEnd = html.indexOf(">", openTagStart); - if (openTagEnd < 0) return -1; - - // Self-closing tag? - if (html[openTagEnd - 1] === "/") return openTagEnd + 1; - - // Extract the tag name - const tagNameMatch = html.slice(openTagStart).match(/^<([a-z][a-z0-9]*)/i); - if (!tagNameMatch) return -1; - const tagName = tagNameMatch[1]!; - - // Walk forward counting open/close tags of the same name - let depth = 1; - let pos = openTagEnd + 1; - const openRe = new RegExp(`<${tagName}(?:\\s|>|/>)`, "gi"); - const closeRe = new RegExp(``, "gi"); - - while (depth > 0 && pos < html.length) { - openRe.lastIndex = pos; - closeRe.lastIndex = pos; - - const nextOpen = openRe.exec(html); - const nextClose = closeRe.exec(html); - - if (!nextClose) return -1; - - if (nextOpen && nextOpen.index < nextClose.index) { - // Check if it's self-closing - const selfCloseCheck = html.lastIndexOf("/", html.indexOf(">", nextOpen.index)); - if (selfCloseCheck > nextOpen.index) { - pos = html.indexOf(">", nextOpen.index) + 1; - } else { - depth++; - pos = html.indexOf(">", nextOpen.index) + 1; - } - } else { - depth--; - if (depth === 0) return nextClose.index + nextClose[0].length; - pos = nextClose.index + nextClose[0].length; - } +/** Just past the end of the element whose start tag is `tags[at]`, or -1 when it never closes. */ +function elementEnd(source: string, tags: SourceTag[], at: number): number { + const open = tags[at]!; + if (VOID_TAGS.has(open.lowercaseName) || selfClosing(source, open)) return open.endAfterBracket; + let depth = 0; + for (const tag of tags.slice(at)) { + if (tag.lowercaseName !== open.lowercaseName || (!tag.closing && selfClosing(source, tag))) + continue; + depth += tag.closing ? -1 : 1; + if (depth === 0) return tag.endAfterBracket; } return -1; } +/** + * Insert `newHtml` right after the element whose `data-hf-id` is `anchorHfId`, else just inside the composition + * root, else at the end. Only real tags count: text inside a script, style or comment never anchors it. + */ +export function insertAsSibling(source: string, newHtml: string, anchorHfId?: string): string { + const tags = [...tagsOutsideCommentsAndRawText(source)]; + if (anchorHfId) { + const hfIdOf = (tag: SourceTag) => { + const match = HF_ID_ATTRIBUTE.exec(tagText(source, tag)); + return match && (match[1] ?? match[2] ?? match[3]); + }; + const at = tags.findIndex((tag) => !tag.closing && hfIdOf(tag) === anchorHfId); + const end = at < 0 ? -1 : elementEnd(source, tags, at); + if (end > 0) return source.slice(0, end) + "\n" + newHtml + source.slice(end); + } + const root = tags.find( + (tag) => !tag.closing && /\sdata-composition-id\s*=/i.test(tagText(source, tag)), + ); + return root + ? source.slice(0, root.endAfterBracket) + newHtml + source.slice(root.endAfterBracket) + : source + newHtml; +} + /** An `id="..."` attribute, not `data-id="..."` or similar — only matches * when preceded by whitespace, the way every generated attribute is. */ export const ID_ATTR_RE = /(?<=\s)id="([^"]+)"/; From bc3d7b43e852c694a5c465a69392dd35b46fe1cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:56:35 +0000 Subject: [PATCH 108/367] test(studio): the edit-accuracy bench reads what a person ends with after sealed saves and undos (#8475) * test(studio): the edit-accuracy bench reads a sequence's file once its last edit has saved A sealed press made while the previous save is out waits, then replays and saves. The sequence bench read the file once its write count was met, which one gesture writing twice can reach before the last gesture saves, so that edit looked lost. Studio now says on the page while an edit saves, and the bench also waits for that and for no waiting press, two frames in a row. * test(studio): a sequence's undo step waits until the undo is shown and records how long it took * test(studio): an undo step records when the box first moves apart from when Studio is idle * test(studio): the bench's rest wait takes its clock, so its times are exact in tests --- .../src/utils/studioPendingEdits.test.ts | 28 +++++++++++ .../studio/src/utils/studioPendingEdits.ts | 15 +++++- .../tests/e2e/edit-accuracy/sequences.mjs | 50 +++++++++++++++++-- .../tests/e2e/edit-accuracy/settle.test.mjs | 35 ++++++++++++- 4 files changed, 123 insertions(+), 5 deletions(-) diff --git a/packages/studio/src/utils/studioPendingEdits.test.ts b/packages/studio/src/utils/studioPendingEdits.test.ts index 834de7962e..40c9792941 100644 --- a/packages/studio/src/utils/studioPendingEdits.test.ts +++ b/packages/studio/src/utils/studioPendingEdits.test.ts @@ -5,6 +5,7 @@ import { addStudioPendingEditFlushListener, adoptingStudioPendingEdit, beginStudioPendingEdit, + beginStudioShownRestore, flushStudioPendingEdits, afterStudioPendingEdits, hasStudioPendingEdits, @@ -42,6 +43,33 @@ describe("a canvas press still waiting to run", () => { }); }); +// fails without the fix: nothing on the page said an edit was still saving, so the edit-accuracy bench read the file +// after a sealed press replayed and before that press's own save landed. +describe("the page's word that an edit is still saving", () => { + const saving = () => document.documentElement.hasAttribute("data-studio-edits-saving"); + + // Each ends its edit before asserting, so a failure leaves no edit pending for the tests after it. + it("holds from a pending edit's start until its save lands", async () => { + let save!: () => void; + const edit = beginStudioPendingEdit(null); + const atStart = saving(); + edit.settle(new Promise((resolve) => (save = resolve))); + await Promise.resolve(); + const whileSaving = saving(); + save(); + await vi.waitFor(() => expect(saving()).toBe(false)); + expect([atStart, whileSaving]).toEqual([true, true]); + }); + + it("holds while a shown undo or redo waits for its save", async () => { + const landed = beginStudioShownRestore(); + const whileWaiting = saving(); + landed(); + await vi.waitFor(() => expect(saving()).toBe(false)); + expect(whileWaiting).toBe(true); + }); +}); + describe("studio pending edit flush", () => { it("waits for mounted panels to persist pending local edits", async () => { const persist = vi.fn(async () => undefined); diff --git a/packages/studio/src/utils/studioPendingEdits.ts b/packages/studio/src/utils/studioPendingEdits.ts index 1e9ad6eeec..fe8cf62753 100644 --- a/packages/studio/src/utils/studioPendingEdits.ts +++ b/packages/studio/src/utils/studioPendingEdits.ts @@ -87,7 +87,11 @@ export function beginStudioShownRestore(): () => void { let end = () => {}; const landed = new Promise((resolve) => (end = resolve)); shownRestores.add(landed); - void landed.then(() => shownRestores.delete(landed)); + markEditsSavingOnPage(); + void landed.then(() => { + shownRestores.delete(landed); + markEditsSavingOnPage(); + }); return end; } @@ -95,6 +99,13 @@ export function isStudioEditSaving(): boolean { return pendingEdits.size > 0 || shownRestores.size > 0; } +function markEditsSavingOnPage(): void { + globalThis.document?.documentElement.toggleAttribute( + "data-studio-edits-saving", + isStudioEditSaving(), + ); +} + export function afterStudioPendingEdits(run: () => void): () => void { let waiting = true; const check = () => { @@ -125,8 +136,10 @@ export function trackStudioPendingEdit( showAgain: null, claimsAtBegin: historyClaims(), }); + markEditsSavingOnPage(); const done = () => { pendingEdits.delete(promise); + markEditsSavingOnPage(); if (!pendingEdits.size) allSettled?.(); }; promise.then(done, done); diff --git a/packages/studio/tests/e2e/edit-accuracy/sequences.mjs b/packages/studio/tests/e2e/edit-accuracy/sequences.mjs index b84fb83c60..bb58cc735b 100644 --- a/packages/studio/tests/e2e/edit-accuracy/sequences.mjs +++ b/packages/studio/tests/e2e/edit-accuracy/sequences.mjs @@ -243,13 +243,23 @@ async function driveStep(ctx, step, state) { const { page } = ctx.A; if (step.do === "undo") { await blurPreview(page); + const before = (await measure(ctx.A)).visible; + const pressedAt = Date.now(); await chord(page, "Control+z"); - // A key's DOM change reaches the CDP quads only after a frame; the next step reads from them. - await nextFrame(page); + // shownMs: the box first moved, what a person sees. restMs: Studio idle, so the next press lands on the shown box. + let shownMs = null; + const restMs = await restedFor( + async () => { + const moved = quadDistance((await measure(ctx.A)).visible, before) >= 0.5; + if (moved && shownMs === null) shownMs = Date.now() - pressedAt; + return studioBusy(page); + }, + () => nextFrame(page), + ); state.depth -= 1; // Undone back to the start, the box belongs where it began; any other undo leaves it unknown here. state.intended = state.depth === 0 ? state.start : null; - return { do: "undo" }; + return { do: "undo", shownMs, restMs }; } if (step.do === "nudge") { await recording(page, true); @@ -439,6 +449,35 @@ export function heldSize(sizeKeys, time) { const sizeError = (a, b) => a && b ? Math.max(Math.abs(a.width - b.width), Math.abs(a.height - b.height)) : 0; +/** + * Resolves once `busy()` has read false `frames` reads in a row, a `frame()` apart, with the ms until the first of + * those reads; throws at `timeout` ms. + */ +export async function restedFor( + busy, + frame, + { frames = 2, timeout = 20_000, now = Date.now } = {}, +) { + const start = now(); + let [clear, clearSince] = [0, 0]; + for (const deadline = start + timeout; now() < deadline; await frame()) { + const readAt = now(); + clear = (await busy()) ? 0 : clear + 1; + if (clear === 1) clearSince = readAt; + if (clear >= frames) return clearSince - start; + } + throw new Error("an edit was still waiting or saving"); +} + +// A sealed press waits for the previous save, then replays, and a sealed undo shows only once the preview applies it. +const studioBusy = (page) => + page.evaluate( + () => + Boolean(document.querySelector("[data-dom-edit-press-waiting]")) || + document.documentElement.hasAttribute("data-studio-edits-saving") || + document.documentElement.hasAttribute("data-preview-changing"), + ); + async function untilSaved(watcher, owed) { for (const deadline = Date.now() + 10_000; Date.now() < deadline; await sleep(50)) if (watcher.versions.length - 1 >= owed) return; @@ -517,6 +556,11 @@ async function measureSequence({ spec, dir, files, evidence }, session, control, backSince = back ? (backSince ?? Date.now()) : null; if (backSince !== null && Date.now() - backSince >= UNDONE_QUIET_MS) break; } + // The write count is a floor: one gesture may write twice, so it can be met before the last gesture saves. + await restedFor( + () => studioBusy(page), + () => nextFrame(page), + ); await page.waitForFunction( // Asked over each preview's editing port: a preview that cannot answer yet is not clear. async () => diff --git a/packages/studio/tests/e2e/edit-accuracy/settle.test.mjs b/packages/studio/tests/e2e/edit-accuracy/settle.test.mjs index d357b7d1d5..ee8d652f3a 100644 --- a/packages/studio/tests/e2e/edit-accuracy/settle.test.mjs +++ b/packages/studio/tests/e2e/edit-accuracy/settle.test.mjs @@ -13,7 +13,7 @@ import { swapPending, unsettledBy, } from "./case.mjs"; -import { heldSize, keyedBy } from "./sequences.mjs"; +import { heldSize, keyedBy, restedFor } from "./sequences.mjs"; describe("settling on the shown preview", () => { const read = (pending, x = 0, frames = "a") => ({ @@ -289,3 +289,36 @@ describe("the box a press is measured against", () => { expect(shown.m.visible[0][0]).toBe(0); }); }); + +// fails without the fix: the sequence read the file once its write count was met, while a sealed press that waited for +// the previous save was still saving, so the last gesture's edit looked lost. +describe("the end of a sequence", () => { + // Each frame advances a fake clock by 10 ms, so the times are exact. + const reads = (states) => { + let [at, ms] = [0, 0]; + return { + busy: async () => states[Math.min(at++, states.length - 1)], + frame: async () => void (ms += 10), + now: () => ms, + read: () => at, + }; + }; + + it("waits until no press waits and no edit saves, two reads in a row", async () => { + const { busy, frame, now, read } = reads([true, true, false, true, false, false, true]); + await restedFor(busy, frame, { now }); + expect(read()).toBe(6); + }); + + it("says how long until the first of the clear reads, the undo's time to show", async () => { + const { busy, frame, now } = reads([true, true, false, false]); + expect(await restedFor(busy, frame, { now })).toBe(20); + }); + + it("gives up with a reason when an edit never stops saving", async () => { + const { busy, frame, now } = reads([true]); + await expect(restedFor(busy, frame, { now, timeout: 30 })).rejects.toThrow( + /still waiting or saving/, + ); + }); +}); From 71588b0a73485efc66f00d7abb72e0328547de53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:57:59 +0000 Subject: [PATCH 109/367] fix(ci): a shard whose results never uploaded is re-run, and never read as an edit accuracy drop (#8477) * fix(ci): a shard whose results never uploaded is re-run, and never read as an edit accuracy drop * refactor(ci): the edit accuracy shard count lives in one place, and a test keeps the matrix on it --- .github/workflows/ci.yml | 18 ++++++++----- .../tests/e2e/edit-accuracy/ratchet.mjs | 12 ++++----- .../tests/e2e/edit-accuracy/ratchet.test.mjs | 16 +++++++++-- scripts/edit-accuracy-retry.test.mjs | 27 ++++++++++++++++--- 4 files changed, 55 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9faf8001d2..ebac9fb2bd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,8 @@ permissions: # External users' CI continues to emit telemetry unless they set this themselves. env: HYPERFRAMES_NO_TELEMETRY: "1" + # The edit accuracy shard count; studio-edit-accuracy's matrix lists the same shards (its strategy cannot read env). + EDIT_ACCURACY_SHARDS: ${{ github.event_name == 'merge_group' && 30 || 15 }} on: merge_group: @@ -1337,11 +1339,16 @@ jobs: with: pattern: edit-accuracy-shard-* path: /tmp/edit-accuracy-shards + # A shard whose evidence never uploaded (its upload failed, or the job died first) has nothing to mark, so it + # is re-run too. - name: List the shards marked for a re-run id: plan run: | - shards=$(find /tmp/edit-accuracy-shards -path '*/edit-accuracy-shard-*/retry' | - sed -E 's#.*/edit-accuracy-shard-([0-9]+)/retry$#\1#' | sort -n | paste -sd, -) + shards=$( { + find /tmp/edit-accuracy-shards -path '*/edit-accuracy-shard-*/retry' | + sed -E 's#.*/edit-accuracy-shard-([0-9]+)/retry$#\1#' + for n in $(seq 1 "$EDIT_ACCURACY_SHARDS"); do [ -d "/tmp/edit-accuracy-shards/edit-accuracy-shard-$n" ] || echo "$n"; done + } | sort -n | paste -sd, -) echo "shards=[${shards}]" >> "$GITHUB_OUTPUT" # Each marked shard runs once more on a fresh runner and replaces its evidence before the gate reads it. @@ -1357,7 +1364,6 @@ jobs: shard: ${{ fromJSON(needs.studio-edit-accuracy-retry-plan.outputs.shards) }} env: EDIT_ACCURACY_GRID: ${{ github.event_name == 'merge_group' && 'full' || 'pr' }} - SHARDS: ${{ github.event_name == 'merge_group' && 30 || 15 }} steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -1377,7 +1383,7 @@ jobs: bash scripts/ci/base-file.sh packages/studio/tests/e2e/edit-accuracy/baseline.json /tmp/base-edit-accuracy.json [ -f /tmp/base-edit-accuracy.json ] || echo '{"cases":{}}' > /tmp/base-edit-accuracy.json - name: Run the shard again - run: bash scripts/ci/edit-accuracy-shard.sh "${{ matrix.shard }}/${SHARDS}" + run: bash scripts/ci/edit-accuracy-shard.sh "${{ matrix.shard }}/${EDIT_ACCURACY_SHARDS}" - name: Replace the shard's evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 @@ -1412,12 +1418,10 @@ jobs: - name: Compare every run with the base branch id: gate # Smoothness and newly passing cases are reported, not gated; a case fails only if it fails 2 of its 3 runs. - env: - SHARDS: ${{ github.event_name == 'merge_group' && 30 || 15 }} run: | set +e mapfile -t RESULTS < <(find /tmp/edit-accuracy-shards -name results.json | sort) - node packages/studio/tests/e2e/edit-accuracy/ratchet.mjs gate --shards "$SHARDS" /tmp/base-edit-accuracy.json \ + node packages/studio/tests/e2e/edit-accuracy/ratchet.mjs gate --shards "$EDIT_ACCURACY_SHARDS" /tmp/base-edit-accuracy.json \ packages/studio/tests/e2e/edit-accuracy/baseline.json /tmp/edit-accuracy-gate "${RESULTS[@]}" echo "exit_code=$?" >> "$GITHUB_OUTPUT" cat /tmp/edit-accuracy-gate/comment.md >> "$GITHUB_STEP_SUMMARY" || true diff --git a/packages/studio/tests/e2e/edit-accuracy/ratchet.mjs b/packages/studio/tests/e2e/edit-accuracy/ratchet.mjs index 99ab1efe6f..b0af1fd37f 100644 --- a/packages/studio/tests/e2e/edit-accuracy/ratchet.mjs +++ b/packages/studio/tests/e2e/edit-accuracy/ratchet.mjs @@ -197,18 +197,18 @@ function main(argv) { } const cases = runs.flatMap((r) => r.cases); const full = gridOf(runs) === "full"; + // A shard that died uploads nothing, so the count of first runs is what shows it. + const firstRuns = runs.filter((r) => !r.meta.rerun).length; + const shortfall = + shards !== null && firstRuns !== shards && `${firstRuns} of ${shards} shards reported results`; + // A case that ran and fell is a drop; a shard that did not report is not one, so only the cases that ran count. const g = gate( base, readJson(headPath), cases, QUARANTINED, - full ? null : new Set(cases.map((c) => c.id)), + full && !shortfall ? null : new Set(cases.map((c) => c.id)), ); - // A shard that died uploads nothing, so the count of first runs is what shows it. - const firstRuns = runs.filter((r) => !r.meta.rerun).length; - const shortfall = - shards !== null && firstRuns !== shards && `${firstRuns} of ${shards} shards reported results`; - // A case that ran and fell is a drop; a shard that did not report is not one. const code = g.ok ? (shortfall ? 2 : 0) : 1; if (shortfall) g.reasons.push(shortfall); g.ok = code === 0; diff --git a/packages/studio/tests/e2e/edit-accuracy/ratchet.test.mjs b/packages/studio/tests/e2e/edit-accuracy/ratchet.test.mjs index a8aecf024b..6b5ba40691 100644 --- a/packages/studio/tests/e2e/edit-accuracy/ratchet.test.mjs +++ b/packages/studio/tests/e2e/edit-accuracy/ratchet.test.mjs @@ -199,13 +199,16 @@ describe("teleport in the gate", () => { describe("gate command, as CI runs it", () => { const script = fileURLToPath(new URL("./ratchet.mjs", import.meta.url)); /** Runs `gate --shards ` over the given shard results; returns its exit code, comment and verdict. */ - function runGate(shards, shardCases) { + function runGate(shards, shardCases, grid = "pr") { const dir = mkdtempSync(join(tmpdir(), "edit-accuracy-gate-")); const base = join(dir, "base.json"); writeFileSync(base, JSON.stringify(baseline({ a: good, b: good }))); const results = shardCases.map((cases, i) => { const path = join(dir, `shard-${i}.json`); - writeFileSync(path, JSON.stringify({ meta: { grid: `pr shard ${i + 1}/${shards}` }, cases })); + writeFileSync( + path, + JSON.stringify({ meta: { grid: `${grid} shard ${i + 1}/${shards}` }, cases }), + ); return path; }); const out = join(dir, "out"); @@ -242,6 +245,15 @@ describe("gate command, as CI runs it", () => { ); }); + it("says a full grid with a shard missing did not run, not that the missing cases fell", () => { + const g = runGate(2, [[run("a")]], "full"); + expect(g.code).toBe(2); + expect(g.verdict).toBe( + "Edit accuracy did not run: 1 of 2 shards reported results; see the shard jobs.", + ); + expect(g.comment).not.toMatch(/fell/); + }); + it("still says accuracy fell when a case that ran regressed, even with a shard missing", () => { const g = runGate(2, [[run("a", 9), run("a", 9), run("a", 9)]]); expect(g.code).toBe(1); diff --git a/scripts/edit-accuracy-retry.test.mjs b/scripts/edit-accuracy-retry.test.mjs index ed7f23b28a..a9ca1122c4 100644 --- a/scripts/edit-accuracy-retry.test.mjs +++ b/scripts/edit-accuracy-retry.test.mjs @@ -59,17 +59,29 @@ test("a shard is marked for a re-run when it timed out or its bench stopped on a test("the retry plan lists exactly the marked shards", () => { const plan = step("studio-edit-accuracy-retry-plan", "List the shards marked for a re-run").run; withTree((root) => { - for (const shard of [7, 12, 3]) + for (let shard = 1; shard <= 12; shard++) mkdirSync(join(root, `edit-accuracy-shards/edit-accuracy-shard-${shard}`), { recursive: true, }); writeFileSync(join(root, "edit-accuracy-shards/edit-accuracy-shard-7/retry"), ""); writeFileSync(join(root, "edit-accuracy-shards/edit-accuracy-shard-12/retry"), ""); - assert.equal(runStep(plan, root), "shards=[7,12]\n"); + assert.equal(runStep(plan, root, { EDIT_ACCURACY_SHARDS: "12" }), "shards=[7,12]\n"); }); withTree((root) => { mkdirSync(join(root, "edit-accuracy-shards/edit-accuracy-shard-1"), { recursive: true }); - assert.equal(runStep(plan, root), "shards=[]\n"); + assert.equal(runStep(plan, root, { EDIT_ACCURACY_SHARDS: "1" }), "shards=[]\n"); + }); +}); + +test("the retry plan also re-runs a shard whose evidence never uploaded", () => { + const plan = step("studio-edit-accuracy-retry-plan", "List the shards marked for a re-run").run; + withTree((root) => { + for (const shard of [1, 2, 4]) + mkdirSync(join(root, `edit-accuracy-shards/edit-accuracy-shard-${shard}`), { + recursive: true, + }); + writeFileSync(join(root, "edit-accuracy-shards/edit-accuracy-shard-2/retry"), ""); + assert.equal(runStep(plan, root, { EDIT_ACCURACY_SHARDS: "5" }), "shards=[2,3,5]\n"); }); }); @@ -94,6 +106,15 @@ test("each marked shard re-runs once and replaces its evidence before the gate r assert.match(jobs["studio-edit-accuracy-gate"].if, /!cancelled\(\)/); }); +test("the shard matrix runs exactly the shards the count names, for the merge queue and for pull requests", () => { + const [, queue, pr] = ci.env.EDIT_ACCURACY_SHARDS.match(/&& (\d+) \|\| (\d+)/); + const lists = [...jobs["studio-edit-accuracy"].strategy.matrix.shard.matchAll(/'(\[[^']*\])'/g)]; + assert.deepEqual( + lists.map((m) => JSON.parse(m[1])), + [Number(queue), Number(pr)].map((n) => Array.from({ length: n }, (_, k) => k + 1)), + ); +}); + test("a cancelled shard and its re-run both fit in the merge queue's 60 minute check wait", () => { const shard = jobs["studio-edit-accuracy"]["timeout-minutes"]; const plan = jobs["studio-edit-accuracy-retry-plan"]["timeout-minutes"]; From fccd00e719c5ab8d95baf531248a64ecc6a14a3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 11:09:31 +0000 Subject: [PATCH 110/367] fix(studio-server): a cut names its new half from the file's own id (#8481) --- packages/core/package-subpaths.json | 6 +++ packages/core/package.json | 10 +++++ .../src/helpers/sourceMutation.ts | 9 +++-- .../sourceMutationSplitAndGroup.test.ts | 8 ++++ .../studio-server/src/routes/files.test.ts | 38 +++++++++++++++++++ packages/studio-server/src/routes/files.ts | 8 ++-- .../studio/src/hooks/useRazorSplit.test.tsx | 2 +- .../src/utils/razorSplitTransaction.test.ts | 3 +- .../studio/src/utils/razorSplitTransaction.ts | 2 - 9 files changed, 74 insertions(+), 12 deletions(-) diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json index 36a0f34904..8697fafc43 100644 --- a/packages/core/package-subpaths.json +++ b/packages/core/package-subpaths.json @@ -548,6 +548,12 @@ "types": "./dist/compiler/htmlDocument.d.ts", "environments": ["browser", "bun", "node"] }, + "./compiler/selector-id-tokens": { + "source": "./src/compiler/selectorIdTokens.ts", + "runtime": "./dist/compiler/selectorIdTokens.js", + "types": "./dist/compiler/selectorIdTokens.d.ts", + "environments": ["browser", "bun", "node"] + }, "./compiler/png-colour-tags": { "source": "./src/compiler/pngColourTags.ts", "runtime": "./dist/compiler/pngColourTags.js", diff --git a/packages/core/package.json b/packages/core/package.json index cf4f62c724..6aa4a1c3e3 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -555,6 +555,12 @@ "import": "./src/compiler/htmlDocument.ts", "types": "./src/compiler/htmlDocument.ts" }, + "./compiler/selector-id-tokens": { + "bun": "./src/compiler/selectorIdTokens.ts", + "node": "./dist/compiler/selectorIdTokens.js", + "import": "./src/compiler/selectorIdTokens.ts", + "types": "./src/compiler/selectorIdTokens.ts" + }, "./compiler/png-colour-tags": { "bun": "./src/compiler/pngColourTags.ts", "node": "./dist/compiler/pngColourTags.js", @@ -1075,6 +1081,10 @@ "import": "./dist/compiler/htmlDocument.js", "types": "./dist/compiler/htmlDocument.d.ts" }, + "./compiler/selector-id-tokens": { + "import": "./dist/compiler/selectorIdTokens.js", + "types": "./dist/compiler/selectorIdTokens.d.ts" + }, "./compiler/png-colour-tags": { "import": "./dist/compiler/pngColourTags.js", "types": "./dist/compiler/pngColourTags.d.ts" diff --git a/packages/studio-server/src/helpers/sourceMutation.ts b/packages/studio-server/src/helpers/sourceMutation.ts index ce8c12fd4d..4c5321522d 100644 --- a/packages/studio-server/src/helpers/sourceMutation.ts +++ b/packages/studio-server/src/helpers/sourceMutation.ts @@ -4,6 +4,7 @@ import { removeElementWithGsapCascade } from "@hyperframes/parsers"; import { readMediaOffsetSeconds, readPlaybackRate } from "@hyperframes/parsers/media-duration"; import postcss from "postcss"; import selectorParser from "postcss-selector-parser"; +import { escapeCssIdentifier } from "@hyperframes/core/compiler/selector-id-tokens"; import { isAllowedHtmlAttribute, isSafeAttributeValue } from "@hyperframes/core/html-attr-safety"; import { sanitizeRichTextChildren } from "@hyperframes/core/rich-text-sanitize"; import { @@ -88,7 +89,7 @@ function duplicateCssRulesForId(document: Document, originalId: string, newId: s const idToken = `#${originalId}`; const transform = selectorParser((selectors) => { selectors.walkIds((node) => { - if (node.value === originalId) node.value = newId; + if (node.value === originalId) node.value = escapeCssIdentifier(newId); }); }); for (const styleEl of document.querySelectorAll("style")) { @@ -429,6 +430,7 @@ export interface SplitElementResult { html: string; matched: boolean; newId: string | null; + originalId?: string | null; refusal?: SplitRefusal; } @@ -477,7 +479,7 @@ export function splitElementInHtml( source: string, target: SourceMutationTarget, splitTime: number, - newId: string, + newId: string | null, fallbackTiming?: { start: number; duration: number; @@ -533,7 +535,7 @@ export function splitElementInHtml( return refused(source, "outside-clip"); } - newId = nextUniqueId(document, newId); + newId = nextUniqueId(document, newId ?? `${el.getAttribute("id") || "clip"}-split`); const firstDuration = splitTime - start; const secondDuration = duration - firstDuration; @@ -616,6 +618,7 @@ export function splitElementInHtml( html: ensureHfIds(html), matched: true, newId, + originalId, }; } diff --git a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts index e029c59102..41b703aa64 100644 --- a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts +++ b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts @@ -1,5 +1,6 @@ // fallow-ignore-file code-duplication import { parseHTML } from "linkedom"; +import postcss from "postcss"; import { describe, expect, it } from "vitest"; import { readMediaOffsetSeconds } from "@hyperframes/parsers/media-duration"; import { @@ -99,6 +100,13 @@ describe("splitElementInHtml", () => { expect(cssMatches?.length).toBeGreaterThanOrEqual(1); }); + it("writes a new id into the stylesheet only as one escaped id selector", () => { + const result = splitElementInHtml(source, { id: "box" }, 3, "x{} body { display: none } #q"); + const css = parseHTML(result.html).document.querySelector("style")!.textContent!; + const selectors = postcss.parse(css).nodes.map((rule) => (rule as postcss.Rule).selector); + expect(selectors).toEqual(["#box", String.raw`#x\{\}\ body\ \{\ display\:\ none\ \}\ \#q`]); + }); + it("deduplicates IDs when the requested newId already exists", () => { const withExisting = source.replace( "", diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.ts index bef56783a5..13b964091a 100644 --- a/packages/studio-server/src/routes/files.test.ts +++ b/packages/studio-server/src/routes/files.test.ts @@ -1197,6 +1197,44 @@ describe("registerFileRoutes", () => { expect(response.headers.get("etag")).toBe(payload.version); }); + it("names a cut's right half from the file's own id, whatever id the request carries", async () => { + const projectDir = createProjectDir(); + const before = ` +
A
+`; + writeFileSync(join(projectDir, "index.html"), before); + const app = new Hono(); + registerFileRoutes(app, createAdapter(projectDir)); + + const response = await postCutBatch(app, [ + { + path: "index.html", + expectedVersion: fileContentVersion(before), + targets: [ + { + target: { hfId: "h1", id: "t{} main { display: none } #t" }, + originalId: "x{} body { display: none } #q", + splitTime: 2, + elementStart: 0, + elementDuration: 4, + }, + ], + }, + ]); + const after = readFileSync(join(projectDir, "index.html"), "utf-8"); + + expect(response.status).toBe(200); + expect(after).not.toContain("display"); + expect(after.match(/", + ); + expect(after).toContain('id="a-split"'); + expect(after).toContain('"#a-split"'); + }); + it("folds multiple same-file cuts and writes one canonical file result", async () => { const projectDir = createProjectDir(); const before = diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts index 6b49d2413b..7877ce4aea 100644 --- a/packages/studio-server/src/routes/files.ts +++ b/packages/studio-server/src/routes/files.ts @@ -287,7 +287,6 @@ interface ElementPatchBatchFileResult { interface AtomicCutTarget { target: MutationTarget; - originalId?: string; splitTime: number; elementStart: number; elementDuration: number; @@ -2305,8 +2304,7 @@ async function foldAtomicCutFile( }) .map(({ cut }) => cut); for (const cut of orderedTargets) { - const baseId = cut.originalId || cut.target.id || "clip"; - const split = splitElementInHtml(after, cut.target, cut.splitTime, `${baseId}-split`, { + const split = splitElementInHtml(after, cut.target, cut.splitTime, null, { start: cut.elementStart, duration: cut.elementDuration, playbackStart: cut.playbackStart, @@ -2323,13 +2321,13 @@ async function foldAtomicCutFile( splitCount++; rightHalfIds.push(split.newId); - if (!cut.originalId) continue; + if (!split.originalId) continue; const block = extractGsapScriptBlock(after); if (!block) continue; const result = await executeGsapMutation( { type: "split-animations", - originalId: cut.originalId, + originalId: split.originalId, newId: split.newId, splitTime: cut.splitTime, elementStart: cut.elementStart, diff --git a/packages/studio/src/hooks/useRazorSplit.test.tsx b/packages/studio/src/hooks/useRazorSplit.test.tsx index d5475ec9f3..eeae1d8ea7 100644 --- a/packages/studio/src/hooks/useRazorSplit.test.tsx +++ b/packages/studio/src/hooks/useRazorSplit.test.tsx @@ -137,7 +137,7 @@ describe("useRazorSplit linked clips", () => { await split?.(video, 2); }); const targets = JSON.parse(bodies[0] ?? "{}").files[0].targets.map( - (cut: { originalId: string }) => cut.originalId, + (cut: { target: { id: string } }) => cut.target.id, ); expect(targets).toEqual(["talk", "talk-audio"]); act(() => root.unmount()); diff --git a/packages/studio/src/utils/razorSplitTransaction.test.ts b/packages/studio/src/utils/razorSplitTransaction.test.ts index 464b74a4f8..024bdb7747 100644 --- a/packages/studio/src/utils/razorSplitTransaction.test.ts +++ b/packages/studio/src/utils/razorSplitTransaction.test.ts @@ -33,7 +33,8 @@ describe("buildAtomicCutIntents", () => { expect(intents).toHaveLength(1); expect(intents[0].targets).toHaveLength(2); - expect(intents[0].targets.map((target) => target.originalId)).toEqual(["host-a", "host-b"]); + expect(intents[0].targets.map((cut) => cut.target.id)).toEqual(["host-a", "host-b"]); + expect(intents[0].targets.some((cut) => "originalId" in cut)).toBe(false); }); it("carries the element's authored track onto the cut target, so both split halves stay pinned to it server-side", () => { diff --git a/packages/studio/src/utils/razorSplitTransaction.ts b/packages/studio/src/utils/razorSplitTransaction.ts index 7f17d2f849..c7f5d0abf2 100644 --- a/packages/studio/src/utils/razorSplitTransaction.ts +++ b/packages/studio/src/utils/razorSplitTransaction.ts @@ -12,7 +12,6 @@ type ProjectFileWriter = (path: string, content: string, expectedContent?: strin interface CutTarget { target: NonNullable>; - originalId?: string; splitTime: number; elementStart: number; elementDuration: number; @@ -64,7 +63,6 @@ function buildCutTarget( ): CutTarget { return { target, - ...(element.domId ? { originalId: element.domId } : {}), splitTime: Math.max(0, toAuthoredStart(element, splitTime)), elementStart: toAuthoredStart(element, element.start), elementDuration: element.duration, From 3a68f7b3ca5c2ae99b8cf039b0576f3e457a66d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 11:35:42 +0000 Subject: [PATCH 111/367] test(studio): the preview regression runs green against a sealed preview (#8470) * test(studio): the preview regression waits for a sealed slider release to land before seeking * test(studio): the preview regression's held media answer carries the server's CORS grant * test(studio): the preview regression seeks only after Studio's posted seeks have landed * test(studio): the regression's barrier takes its message only from the Studio page --- .../tests/e2e/preview-video-regression.mjs | 43 +++++++++++++++++-- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/packages/studio/tests/e2e/preview-video-regression.mjs b/packages/studio/tests/e2e/preview-video-regression.mjs index 2ccf77ec03..5be74d67d1 100644 --- a/packages/studio/tests/e2e/preview-video-regression.mjs +++ b/packages/studio/tests/e2e/preview-video-regression.mjs @@ -75,6 +75,28 @@ async function open(beforeNavigate) { return { page, iframe, frame }; } +// A sealed frame gets Studio's seeks as posted messages, which an in-frame seek can overtake. Studio's own message +// queue to the frame is ordered: once a message posted after them arrives, they have all been applied. +async function afterStudioMessages(host) { + await host.frame.evaluate((studio) => { + window.__regressionBarrier = new Promise((resolve) => { + const isBarrier = (event) => + event.source === parent && event.data?.type === "preview-regression-barrier"; + const onMessage = (event) => { + if (event.origin !== studio || !isBarrier(event)) return; + removeEventListener("message", onMessage); + resolve(); + }; + addEventListener("message", onMessage); + }); + }, new URL(host.page.url()).origin); + const iframe = await host.frame.frameElement(); + await iframe.evaluate((el) => + el.contentWindow.postMessage({ type: "preview-regression-barrier" }, "*"), + ); + await host.frame.evaluate(() => window.__regressionBarrier); +} + async function seek(host, time) { const start = performance.now(); await host.frame.evaluate(async (time) => { @@ -153,6 +175,18 @@ async function collectGarbage(host) { await session.detach(); } +// The preview server's own CORS answer to `request`: a sealed frame plays its media only with that grant. +async function serverCorsFor(request) { + const origin = request.headers().origin; + if (!origin) return {}; + const res = await fetch(request.url(), { + headers: { origin, "sec-fetch-dest": "video", range: "bytes=0-0" }, + }); + await res.body?.cancel(); + const cors = /^(access-control-|vary$|x-content-type-options$)/; + return Object.fromEntries([...res.headers].filter(([header]) => cors.test(header))); +} + async function withBlockedNative(test) { const assets = new Map( await Promise.all( @@ -168,17 +202,18 @@ async function withBlockedNative(test) { const host = await open(async (page) => { await page.setRequestInterception(true); page.on("requestfailed", (request) => held.delete(request)); - const respondPrefix = (request, name, data) => { + const respondPrefix = async (request, name, data) => { if (prefixed.has(name)) { held.add(request); return; } prefixed.add(name); const prefix = data.subarray(0, 16 * 1024); - void request.respond({ + await request.respond({ status: 206, contentType: "video/mp4", headers: { + ...(await serverCorsFor(request)), "Content-Range": `bytes 0-${prefix.length - 1}/${data.length}`, "Content-Length": String(prefix.length), "Accept-Ranges": "bytes", @@ -189,7 +224,8 @@ async function withBlockedNative(test) { page.on("request", (request) => { const name = new URL(request.url()).pathname.split("/").at(-1); const data = assets.get(name); - if (request.resourceType() === "media" && data && blocked) respondPrefix(request, name, data); + if (request.resourceType() === "media" && data && blocked) + void respondPrefix(request, name, data); else void request.continue(); }); }); @@ -399,6 +435,7 @@ try { await picture(host, `drag-${fraction}`); } await host.page.mouse.up(); + await afterStudioMessages(host); await seek(host, 7); await picture(host, "paused-b"); await seek(host, 5.5); From 679a5a7e0b8d6ecc75ac79c3780d814b0d2bb40d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 11:49:32 +0000 Subject: [PATCH 112/367] fix(studio): a menu that does not fit below opens above, never over what opened it (#8406) * fix(studio): a menu that does not fit below opens above, never over what opened it * test(studio): the timeline parts fixture opens its clip menu from an anchor --- .../components/editor/CanvasContextMenu.tsx | 11 ++-- .../src/components/ui/menuPosition.test.ts | 52 +++++++++++++++++++ .../studio/src/components/ui/menuPosition.ts | 27 ++++++++++ .../components/AutomationSelectionMenu.tsx | 15 +++--- .../ClipContextMenu.groups.test.tsx | 4 +- .../components/ClipContextMenu.test.tsx | 25 +++++---- .../src/player/components/ClipContextMenu.tsx | 21 ++++---- .../components/KeyframeDiamondContextMenu.tsx | 14 ++--- .../components/TimelineOverlays.test.ts | 12 ++++- .../player/components/TimelineOverlays.tsx | 3 +- .../player/components/TimelineParts.test.tsx | 2 +- .../player/components/TimelineProvider.tsx | 4 +- .../player/components/TrackGapContextMenu.tsx | 9 ++-- .../components/useTimelineClipContextMenu.ts | 4 +- 14 files changed, 138 insertions(+), 65 deletions(-) create mode 100644 packages/studio/src/components/ui/menuPosition.test.ts create mode 100644 packages/studio/src/components/ui/menuPosition.ts diff --git a/packages/studio/src/components/editor/CanvasContextMenu.tsx b/packages/studio/src/components/editor/CanvasContextMenu.tsx index 1c13c50e45..7a02a19480 100644 --- a/packages/studio/src/components/editor/CanvasContextMenu.tsx +++ b/packages/studio/src/components/editor/CanvasContextMenu.tsx @@ -34,6 +34,7 @@ import { type ZOrderPatch, } from "./canvasContextMenuZOrder"; import { menuClasses } from "../ui/menuStyle"; +import { placeMenu, pointAnchor } from "../ui/menuPosition"; interface CanvasContextMenuProps { /** Viewport x of the right-click event. */ @@ -157,14 +158,10 @@ export const CanvasContextMenu = memo(function CanvasContextMenu({ const hasDelete = Boolean(onDelete); const hasDivider = hasZActions && hasDelete; - // Overflow correction — match ClipContextMenu approach. Only the rendered - // groups contribute height (keeps positioning correct when a group is hidden). - const menuWidth = 200; + // Only the rendered groups contribute height (keeps placement correct when a group is hidden). const menuHeight = 8 + (hasZActions ? Z_ACTIONS.length * 28 : 0) + (hasDivider ? 1 : 0) + (hasDelete ? 28 : 0) + 8; // padding + items + divider + delete + padding - const overflowY = y + menuHeight - window.innerHeight; - const adjustedX = x + menuWidth > window.innerWidth ? x - menuWidth : x; - const adjustedY = overflowY > 0 ? y - overflowY - 8 : y; + const { left, top } = placeMenu(pointAnchor(x, y), { width: 200, height: menuHeight }); const el = selection.element; @@ -211,7 +208,7 @@ export const CanvasContextMenu = memo(function CanvasContextMenu({
{ + it("opens below its anchor when it fits", () => { + expect(placeMenu({ left: 10, top: 100, bottom: 124 }, size, view)).toEqual({ + left: 10, + top: 124, + }); + }); + + it("opens above an anchor near the window's bottom, its bottom at the anchor's top", () => { + const anchor = { left: 10, top: 540, bottom: 564 }; + const { top } = placeMenu(anchor, size, view); + expect(top).toBe(390); + expect(top + size.height).toBeLessThanOrEqual(anchor.top); + }); + + it("flips above a pointer near the window's bottom instead of sliding over it", () => { + expect(placeMenu(pointAnchor(10, 550), size, view).top).toBe(400); + }); + + it("clamps inside the window only when it fits neither below nor above", () => { + expect(placeMenu(pointAnchor(10, 100), { width: 200, height: 550 }, view).top).toBe(42); + expect(placeMenu(pointAnchor(10, 100), { width: 200, height: 700 }, view).top).toBe(8); + }); + + it("opens leftward when it would cross the window's right edge", () => { + expect(placeMenu(pointAnchor(800, 10), size, view).left).toBe(600); + }); +}); + +describe("menuAnchor", () => { + it("is the box of the pressed element's data-menu-anchor ancestor", () => { + const button = document.createElement("button"); + button.setAttribute("data-menu-anchor", ""); + const icon = document.createElement("span"); + button.appendChild(icon); + const box = { left: 30, top: 540, bottom: 564 } as DOMRect; + button.getBoundingClientRect = () => box; + expect(menuAnchor(icon, 35, 550)).toBe(box); + }); + + it("is the pointer's point without one", () => { + expect(menuAnchor(document.createElement("div"), 35, 550)).toEqual(pointAnchor(35, 550)); + expect(menuAnchor(null, 35, 550)).toEqual(pointAnchor(35, 550)); + }); +}); diff --git a/packages/studio/src/components/ui/menuPosition.ts b/packages/studio/src/components/ui/menuPosition.ts new file mode 100644 index 0000000000..876d886af6 --- /dev/null +++ b/packages/studio/src/components/ui/menuPosition.ts @@ -0,0 +1,27 @@ +const MENU_MARGIN = 8; + +export interface MenuAnchor { + left: number; + top: number; + bottom: number; +} + +export const pointAnchor = (x: number, y: number): MenuAnchor => ({ left: x, top: y, bottom: y }); + +/** The pressed element's `[data-menu-anchor]` box, else the pointer's point. */ +export function menuAnchor(target: EventTarget | null, x: number, y: number): MenuAnchor { + const anchor = (target as Element | null)?.closest?.("[data-menu-anchor]"); + return anchor ? anchor.getBoundingClientRect() : pointAnchor(x, y); +} + +/** Below the anchor; above it when that does not fit; clamped inside the window only when neither fits. */ +export function placeMenu( + anchor: MenuAnchor, + size: { width: number; height: number }, + view = { width: window.innerWidth, height: window.innerHeight }, +): { left: number; top: number } { + const left = anchor.left + size.width > view.width ? anchor.left - size.width : anchor.left; + if (anchor.bottom + size.height <= view.height) return { left, top: anchor.bottom }; + if (anchor.top - size.height >= 0) return { left, top: anchor.top - size.height }; + return { left, top: Math.max(MENU_MARGIN, view.height - size.height - MENU_MARGIN) }; +} diff --git a/packages/studio/src/player/components/AutomationSelectionMenu.tsx b/packages/studio/src/player/components/AutomationSelectionMenu.tsx index fe79a28312..9bf0d40419 100644 --- a/packages/studio/src/player/components/AutomationSelectionMenu.tsx +++ b/packages/studio/src/player/components/AutomationSelectionMenu.tsx @@ -9,6 +9,7 @@ import { createPortal } from "react-dom"; import { useContextMenuDismiss } from "../../hooks/useContextMenuDismiss"; import { AUTOMATION_SHAPES, type AutomationShapeId } from "./automationShapes"; import { menuClasses } from "../../components/ui/menuStyle"; +import { placeMenu, pointAnchor } from "../../components/ui/menuPosition"; interface AutomationSelectionMenuProps { x: number; @@ -31,14 +32,10 @@ export const AutomationSelectionMenu = memo(function AutomationSelectionMenu({ const menuRef = useContextMenuDismiss(onClose); const row = "block w-full px-2 py-1 text-left text-[11px] text-panel-text-1 hover:bg-panel-hover disabled:opacity-40"; - // Same edge-clamping precedent as TrackGapContextMenu: without it a - // right-click near the bottom/right of the timeline renders this menu - // partially off-screen. - const menuWidth = 140; - const menuHeight = AUTOMATION_SHAPES.length * 24 + 32; - const overflowY = y + menuHeight - window.innerHeight; - const adjustedX = x + menuWidth > window.innerWidth ? x - menuWidth : x; - const adjustedY = overflowY > 0 ? y - overflowY - 8 : y; + const { left, top } = placeMenu(pointAnchor(x, y), { + width: 140, + height: AUTOMATION_SHAPES.length * 24 + 32, + }); return createPortal(
{AUTOMATION_SHAPES.map((shape) => (
', +]; + +describe("markupOutsideAllowlist", () => { + it("passes clip markup that parses to the same inert tree with scripting on as in the check", () => { + for (const html of ALLOWED) { + const checked = parse(html, false); + expect(markupOutsideAllowlist(checked.documentElement)).toEqual([]); + const run = parse(html, true); + expect(tagsOf(run)).toEqual(tagsOf(checked)); + expect(runsCode(run)).toBe(false); + } + }); + + it("refuses markup a scripting parser could read differently, or that loads or points elsewhere", () => { + for (const html of REFUSED) + expect(markupOutsideAllowlist(parse(html, false).documentElement), html).not.toEqual([]); + }); + + it("shows why: a noscript the check reads as inert runs a handler once scripting is on", () => { + const html = REFUSED[0]!; + expect(runsCode(parse(html, false))).toBe(false); + expect(runsCode(parse(html, true))).toBe(true); + }); +}); diff --git a/packages/core/src/utils/htmlAttrSafety.test.ts b/packages/core/src/utils/htmlAttrSafety.test.ts index a665d6cb05..ea935d0492 100644 --- a/packages/core/src/utils/htmlAttrSafety.test.ts +++ b/packages/core/src/utils/htmlAttrSafety.test.ts @@ -1,6 +1,6 @@ // @vitest-environment happy-dom import { describe, expect, it } from "vitest"; -import { isSafeAttributeValue, unsafeMarkup } from "./htmlAttrSafety"; +import { isSafeAttributeValue, markupOutsideAllowlist } from "./htmlAttrSafety"; const root = (html: string) => { const holder = document.createElement("template"); @@ -8,33 +8,51 @@ const root = (html: string) => { return holder.content.firstElementChild!; }; -describe("unsafeMarkup", () => { +describe("markupOutsideAllowlist", () => { it("names each handler and script link anywhere in the tree", () => { const tree = root( ``, ); - expect(unsafeMarkup(tree)).toEqual(["div[onclick]", "a[href]", "img[src]", "img[onerror]"]); + expect(markupOutsideAllowlist(tree)).toEqual([ + "div[onclick]", + "a[href]", + "img[src]", + "img[onerror]", + ]); }); it("names elements that carry code, wherever they sit, a template's content included", () => { const tree = root( `
`, ); - expect(unsafeMarkup(tree)).toEqual(["script", "iframe[srcdoc]", "object", "embed", "script"]); + expect(markupOutsideAllowlist(tree)).toEqual( + expect.arrayContaining(["script", "iframe", "iframe[srcdoc]", "object", "embed"]), + ); + expect(markupOutsideAllowlist(tree).filter((found) => found === "script")).toHaveLength(2); }); - it("names an SVG animation that sets a script link", () => { + it("names an SVG animation that sets a script link, and a script link in xlink:href", () => { const tree = root( - ``, + ``, ); - expect(unsafeMarkup(tree)).toEqual(["set[to]", "animate[values]"]); + expect(markupOutsideAllowlist(tree)).toEqual([ + "set", + "set[attributeName]", + "set[to]", + "use[xlink:href]", + ]); }); - it("names nothing in ordinary markup", () => { + it("names nothing in ordinary markup, inline SVG with its namespace declarations included", () => { const tree = root( - `
`, + `
`, ); - expect(unsafeMarkup(tree)).toEqual([]); + expect(markupOutsideAllowlist(tree)).toEqual([]); + }); + + it("names a namespace declaration that holds anything but its own namespace", () => { + const tree = root(``); + expect(markupOutsideAllowlist(tree)).toEqual(["svg[xmlns:xlink]"]); }); }); diff --git a/packages/core/src/utils/htmlAttrSafety.ts b/packages/core/src/utils/htmlAttrSafety.ts index 9166ede430..04fb423033 100644 --- a/packages/core/src/utils/htmlAttrSafety.ts +++ b/packages/core/src/utils/htmlAttrSafety.ts @@ -5,6 +5,8 @@ * used by sourceMutation (core), sdkCutover (studio), and mutate (sdk). */ +import { SVG_ATTRIBUTES, SVG_ELEMENTS } from "./svgAllowlist"; + export const ALLOWED_HTML_ATTRS = new Set([ "id", "class", @@ -105,54 +107,50 @@ export function isSafeAttributeValue(name: string, value: string): boolean { return true; } -const CODE_ELEMENTS = new Set(["script", "object", "embed"]); -const INLINE_DOCUMENT_FRAMES = new Set(["iframe", "frame"]); -const LINK_ANIMATIONS = new Set(["set", "animate"]); -const ANIMATED_LINKS = new Set(["href", "xlink:href"]); -const ANIMATED_VALUES = ["to", "from", "by", "values"]; - -function kindFindings(element: Element, tag: string): string[] { - if (CODE_ELEMENTS.has(tag)) return [tag]; - return INLINE_DOCUMENT_FRAMES.has(tag) && element.hasAttribute("srcdoc") - ? [`${tag}[srcdoc]`] - : []; -} - -const runsCode = (name: string, value: string) => - name.toLowerCase().startsWith("on") || !isSafeAttributeValue(name, value); - -function attributeFindings(element: Element, tag: string): string[] { - return Array.from(element.attributes) - .filter(({ name, value }) => runsCode(name, value)) - .map(({ name }) => `${tag}[${name}]`); -} - -const animatesLink = (element: Element, tag: string) => - LINK_ANIMATIONS.has(tag) && - ANIMATED_LINKS.has(element.getAttribute("attributeName")?.toLowerCase() ?? ""); - -function animationFindings(element: Element, tag: string): string[] { - if (!animatesLink(element, tag)) return []; - return ANIMATED_VALUES.filter((name) => - (element.getAttribute(name)?.split(";") ?? []).some((v) => !isSafeAttributeValue("href", v)), - ).map((name) => `${tag}[${name}]`); -} - function childrenOf(element: Element, tag: string): Element[] { const content = tag === "template" ? (element as HTMLTemplateElement).content : null; return [...Array.from(element.children), ...Array.from(content?.children ?? [])]; } -function unsafeIn(element: Element, found: string[]): void { - const tag = element.localName; - found.push(...kindFindings(element, tag)); - found.push(...attributeFindings(element, tag)); - found.push(...animationFindings(element, tag)); - for (const child of childrenOf(element, tag)) unsafeIn(child, found); +const ELEMENTS_PARSED_ALIKE_WITH_SCRIPTING_ON = new Set( + ( + "html head body div span p a abbr address article aside b bdi bdo blockquote br button caption cite code col " + + "colgroup data dd del details dfn dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hgroup hr i img " + + "ins kbd label li main mark nav ol picture pre q rp rt ruby s samp section small source strong sub summary sup " + + "table tbody td template tfoot th thead time tr track u ul var video audio canvas wbr" + ).split(" "), +); +const SVG_NS = "http://www.w3.org/2000/svg"; +const isSvg = (element: Element) => element.namespaceURI === SVG_NS; +const FIXED_NAMESPACES = new Map([ + ["xmlns", SVG_NS], + ["xmlns:xlink", "http://www.w3.org/1999/xlink"], +]); + +function elementAllowed(element: Element, tag: string): boolean { + if (isSvg(element)) return tag !== "style" && SVG_ELEMENTS.has(element.tagName); + return ELEMENTS_PARSED_ALIKE_WITH_SCRIPTING_ON.has(tag) || /^hf-[a-z0-9-]+$/.test(tag); } -export function unsafeMarkup(root: Element): string[] { +function attributeAllowed(element: Element, name: string, value: string): boolean { + if (!isSafeAttributeValue(name, value) || name.toLowerCase().startsWith("on")) return false; + if (isAllowedHtmlAttribute(name)) return true; + if (!isSvg(element)) return false; + const namespace = FIXED_NAMESPACES.get(name); + if (namespace) return value === namespace; + return name === "xlink:href" || SVG_ATTRIBUTES.has(name.replace(/^[^:]*:/, "")); +} + +function outsideIn(element: Element, found: string[]): void { + const tag = element.localName; + if (!elementAllowed(element, tag)) found.push(tag); + for (const { name, value } of Array.from(element.attributes)) + if (!attributeAllowed(element, name, value)) found.push(`${tag}[${name}]`); + for (const child of childrenOf(element, tag)) outsideIn(child, found); +} + +export function markupOutsideAllowlist(root: Element): string[] { const found: string[] = []; - unsafeIn(root, found); + outsideIn(root, found); return found; } diff --git a/packages/core/src/utils/svgAllowlist.ts b/packages/core/src/utils/svgAllowlist.ts new file mode 100644 index 0000000000..13423ea7e7 --- /dev/null +++ b/packages/core/src/utils/svgAllowlist.ts @@ -0,0 +1,205 @@ +/** The SVG elements and attributes sanitizeSvg keeps and the clipboard accepts; anything else is dropped or refused. */ +export const SVG_ELEMENTS = new Set([ + "svg", + "g", + "defs", + "symbol", + "use", + "image", + "a", + "switch", + "rect", + "circle", + "ellipse", + "line", + "polyline", + "polygon", + "path", + "text", + "tspan", + "textPath", + "linearGradient", + "radialGradient", + "stop", + "pattern", + "mask", + "clipPath", + "marker", + "filter", + "feBlend", + "feColorMatrix", + "feComponentTransfer", + "feComposite", + "feConvolveMatrix", + "feDiffuseLighting", + "feDisplacementMap", + "feDistantLight", + "feDropShadow", + "feFlood", + "feFuncA", + "feFuncB", + "feFuncG", + "feFuncR", + "feGaussianBlur", + "feImage", + "feMerge", + "feMergeNode", + "feMorphology", + "feOffset", + "fePointLight", + "feSpecularLighting", + "feSpotLight", + "feTile", + "feTurbulence", + "title", + "desc", + "metadata", + "style", +]); + +// Local names only — a namespace prefix (xlink:href, x:href, ...) is stripped before this +// lookup, so it doesn't matter which prefix an attacker aliases onto a real or fake namespace. +export const SVG_ATTRIBUTES = new Set([ + "id", + "class", + "style", + "transform", + "viewBox", + "width", + "height", + "x", + "y", + "x1", + "y1", + "x2", + "y2", + "cx", + "cy", + "r", + "rx", + "ry", + "fx", + "fy", + "points", + "d", + "offset", + "enable-background", + "gradientUnits", + "gradientTransform", + "spreadMethod", + "patternUnits", + "patternContentUnits", + "patternTransform", + "maskUnits", + "maskContentUnits", + "clipPathUnits", + "clip-rule", + "filterUnits", + "primitiveUnits", + "preserveAspectRatio", + "space", + "lang", + "role", + "focusable", + "tabindex", + "version", + "baseProfile", + "fill", + "fill-opacity", + "fill-rule", + "stroke", + "stroke-width", + "stroke-opacity", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-dasharray", + "stroke-dashoffset", + "opacity", + "color", + "stop-color", + "stop-opacity", + "font-family", + "font-size", + "font-weight", + "font-style", + "text-anchor", + "dominant-baseline", + "alignment-baseline", + "letter-spacing", + "word-spacing", + "text-decoration", + "clip-path", + "mask", + "filter", + "marker-start", + "marker-mid", + "marker-end", + "marker", + "cursor", + "pointer-events", + "visibility", + "display", + "overflow", + "vector-effect", + "paint-order", + "color-interpolation", + "color-interpolation-filters", + "isolation", + "mix-blend-mode", + "startOffset", + "method", + "spacing", + "side", + "textLength", + "lengthAdjust", + "in", + "in2", + "result", + "mode", + "type", + "values", + "dx", + "dy", + "stdDeviation", + "edgeMode", + "k1", + "k2", + "k3", + "k4", + "operator", + "radius", + "scale", + "xChannelSelector", + "yChannelSelector", + "baseFrequency", + "numOctaves", + "seed", + "stitchTiles", + "tableValues", + "slope", + "intercept", + "amplitude", + "exponent", + "order", + "divisor", + "bias", + "targetX", + "targetY", + "kernelMatrix", + "preserveAlpha", + "kernelUnitLength", + "surfaceScale", + "diffuseConstant", + "specularConstant", + "specularExponent", + "lighting-color", + "flood-color", + "flood-opacity", + "azimuth", + "elevation", + "pointsAtX", + "pointsAtY", + "pointsAtZ", + "limitingConeAngle", +]); diff --git a/packages/studio/src/hooks/useClipboard.sealed.test.ts b/packages/studio/src/hooks/useClipboard.sealed.test.ts index 3042ffd768..f243dbb13a 100644 --- a/packages/studio/src/hooks/useClipboard.sealed.test.ts +++ b/packages/studio/src/hooks/useClipboard.sealed.test.ts @@ -26,14 +26,24 @@ afterEach(() => { }); /** A sealed preview of SAVED, with the runtime's hide on the clip, and the saved file served. */ -function sealedClipboard(domSelection: DomEditSelection | null, scriptMade = "", saved = SAVED) { +function sealedClipboard( + domSelection: DomEditSelection | null, + scriptMade = "", + saved = SAVED, + otherFiles: Record = {}, +) { const preview = new DOMParser().parseFromString(ensureHfIds(saved), "text/html"); document.body.innerHTML = preview.body.innerHTML; document.querySelector("[data-composition-id]")!.insertAdjacentHTML("beforeend", scriptMade); document.getElementById("title")!.style.cssText = "visibility: hidden; display: none"; vi.stubGlobal( "fetch", - vi.fn(async () => new Response(JSON.stringify({ content: saved }))), + vi.fn(async (url: string) => { + const other = Object.keys(otherFiles).find((path) => + decodeURIComponent(String(url)).endsWith(`/files/${path}`), + ); + return new Response(JSON.stringify({ content: other ? otherFiles[other] : saved })); + }), ); const { iframe } = sealedPreviewFrame(); const writes: string[] = []; @@ -130,6 +140,18 @@ const SCRIPT_MADE = [ ['Made', true], ['
Made
', true], ['', true], + // fails without the fix: inert in the check's scripting-off parse, live in a preview that runs scripts. + [ + '
', + true, + ], + ['
', true], + ['
', true], + [ + '
', + true, + ], + ['

Made

', true], ['', false], ] as const; @@ -154,6 +176,28 @@ it("pastes a sealed preview's own element only when its markup runs no code", as } }); +// fails without the fix: markup the copy found in another file was taken as saved and pasted unchecked. +it("checks a saved element read from another file before pasting it into this one", async () => { + const received = `
+ +
`; + const selection = { + id: "go", + selector: "#go", + sourceFile: "compositions/recv.html", + } as DomEditSelection; + // The frame shows one of the person's own clips under the received element's file and id. + const relabelled = + '
'; + const { clipboard, writes, toasts } = sealedClipboard(selection, relabelled, SAVED, { + "compositions/recv.html": received, + }); + expect(clipboard().handleCopy()).toBe(true); + await clipboard().handlePaste(); + expect(writes).toEqual([]); + expect(toasts.at(-1)).toMatch(/^Couldn't paste/); +}); + it("pastes and duplicates a saved element with its own handler, as saved", async () => { const saved = SAVED.replace( "
", diff --git a/packages/studio/src/hooks/useClipboard.test.ts b/packages/studio/src/hooks/useClipboard.test.ts index b3d4e2087b..a165aa0d1b 100644 --- a/packages/studio/src/hooks/useClipboard.test.ts +++ b/packages/studio/src/hooks/useClipboard.test.ts @@ -229,14 +229,19 @@ describe("pasteTimelineClips", () => { it("still strips data-hf-id from a tag the HTML parser hoists out of body (e.g. title)", () => { // A never reaches DOMParser's body, so remintHfIds's DOM walk sees // no root element here -- this exercises the regex fallback, not the walk. + // Only an in-file copy gets that far: from anywhere else a <title> is refused. const hoisted: TimelineClipboardClip = { html: '<title data-hf-id="hf-leak">x', + readFrom: "index.html", start: 0, duration: 1, track: 0, }; - const { content } = pasteTimelineClips(ROOT, [hoisted], 0, []); + const { content } = pasteTimelineClips(ROOT, [hoisted], 0, [], true, "index.html"); expect(content).not.toContain("data-hf-id"); + expect(() => pasteTimelineClips(ROOT, [{ ...hoisted, readFrom: null }], 0, [])).toThrow( + /^Couldn't paste/, + ); }); it("captures the root's own id, not a data-id that happens to precede it", () => { @@ -293,10 +298,15 @@ describe("pasteTimelineClips + extendRootDurationInSource", () => { }); describe("pasteElementHtml", () => { - it("refuses code the parser hoists out of the body unless the markup came from the saved file", () => { + it("refuses code the parser hoists out of the body unless Studio read it from the file it writes to", () => { const html = ""; expect(() => pasteElementHtml(ROOT, { html })).toThrow(/^Couldn't paste/); - expect(pasteElementHtml(ROOT, { html, saved: true })).toContain(html); + expect(() => + pasteElementHtml(ROOT, { html, readFrom: "other.html" }, false, "index.html"), + ).toThrow(/^Couldn't paste/); + expect(pasteElementHtml(ROOT, { html, readFrom: "index.html" }, false, "index.html")).toContain( + html, + ); }); it("gives a pasted element and its children ids of their own, so an edit to the copy stays on it", () => { @@ -304,7 +314,12 @@ describe("pasteElementHtml", () => { ROOT.replace("", '

Hello there

'), ); const copied = stamped.match(/]*id="title"[^>]*>.*?<\/p>/)![0]; - const content = pasteElementHtml(stamped, { html: copied, saved: true }, true); + const content = pasteElementHtml( + stamped, + { html: copied, readFrom: "index.html" }, + true, + "index.html", + ); expect(content.indexOf("

") + 4).toBe(content.indexOf("\n 0) { - throw new Error( - "Couldn't paste: the copied element runs code (a script, an event handler or a script link)", - ); - } -} - /** Gives a clone's root and every descendant a fresh data-hf-id, clear of `taken`. Minted here, * inside the edit, or the server stamps them on the next preview load, behind undo's back. * DOMParser, not a regex, so a `>` inside an attribute value can't defeat it. */ -function remintHfIds(html: string, parser: DOMParser, taken: Set, saved = false): string { +function remintHfIds( + html: string, + parser: DOMParser, + taken: Set, + check: (doc: Document) => void, +): string { const doc = parser.parseFromString(html, "text/html"); - refuseRunningCode(doc, saved); + check(doc); const root = doc.body.firstElementChild; if (!root) { // A tag the HTML parser hoists out of (title/meta/style/base/link) @@ -195,14 +192,16 @@ const hfIdsInFile = (content: string) => export function pasteElementHtml( content: string, - payload: { html: string; saved?: boolean }, + payload: { html: string; readFrom?: string | null }, fromThisFile = false, + writeTo: string | null = null, ): string { const parser = new DOMParser(); - const reminted = remintHfIds(payload.html, parser, hfIdsInFile(content), payload.saved); + const check = (doc: Document) => refuseUnlistedMarkup(doc, payload.readFrom, writeTo); + const reminted = remintHfIds(payload.html, parser, hfIdsInFile(content), check); const deduped = deduplicateIds(reminted, collectHtmlIds(content)); const anchorFromThisFile = - fromThisFile && payload.saved + fromThisFile && !!payload.readFrom && payload.readFrom === writeTo ? parser .parseFromString(payload.html, "text/html") .body.firstElementChild?.getAttribute("data-hf-id") @@ -221,6 +220,7 @@ export function pasteTimelineClips( anchorTime: number, liveElements: readonly TimelineElement[], fromThisFile = false, + writeTo: string | null = null, ): { content: string; ids: string[]; requiredEnd: number } { const groupMinStart = Math.min(...clips.map((c) => c.start)); let existingIds = collectHtmlIds(content); @@ -235,7 +235,8 @@ export function pasteTimelineClips( const domParser = new DOMParser(); const takenHfIds = hfIdsInFile(content); for (const clip of clips) { - const reminted = remintHfIds(clip.html, domParser, takenHfIds, clip.saved); + const check = (doc: Document) => refuseUnlistedMarkup(doc, clip.readFrom, writeTo); + const reminted = remintHfIds(clip.html, domParser, takenHfIds, check); const deduped = deduplicateIds(reminted, existingIds); existingIds = existingIds.concat(collectHtmlIds(deduped)); const newStart = anchorTime + (clip.start - groupMinStart); @@ -255,7 +256,7 @@ export function pasteTimelineClips( .replace(/data-start="[^"]*"/, `data-start="${formatTimelineAttributeNumber(newStart)}"`) .replace(/data-track-index="[^"]*"/, `data-track-index="${newTrack}"`); const withPatched = patchedRootTag + deduped.slice(rootTagEnd + 1); - refuseRunningCode(domParser.parseFromString(withPatched, "text/html"), clip.saved); + check(domParser.parseFromString(withPatched, "text/html")); result = insertTimelineAssetIntoSource(result, withPatched); if (fromThisFile) { const authored = Number(rootTag.match(/data-start="([^"]*)"/)?.[1]); @@ -428,9 +429,10 @@ export function useClipboard({ try { let pastedIds: string[] = []; const fromThisFile = payload.sourceFile === targetPath && payload.projectId === pid; + const writeTo = payload.projectId === pid ? targetPath : null; const paste = (originalContent: string) => { if (payload.kind !== "timeline-clip") - return pasteElementHtml(originalContent, payload, fromThisFile); + return pasteElementHtml(originalContent, payload, fromThisFile, writeTo); const { currentTime, elements } = usePlayerStore.getState(); const pasted = pasteTimelineClips( originalContent, @@ -438,6 +440,7 @@ export function useClipboard({ pasteStart(payload, targetPath, currentTime, options), elements, fromThisFile, + writeTo, ); pastedIds = pasted.ids; // A clip pasted past the current composition end would exist in the @@ -507,7 +510,14 @@ export function useClipboard({ .getState() .elements.filter((el) => pathOf(el) === targetPath) .map((el) => ({ ...el, start: toAuthoredStart(el, el.start) })); - const pasted = pasteTimelineClips(originalContent, clips, anchorTime, liveElements, true); + const pasted = pasteTimelineClips( + originalContent, + clips, + anchorTime, + liveElements, + true, + targetPath, + ); ids = pasted.ids; return extendRootDurationInSource(pasted.content, pasted.requiredEnd); }; diff --git a/packages/studio/src/hooks/useClipboard.unsafeMarkup.test.ts b/packages/studio/src/hooks/useClipboard.unsafeMarkup.test.ts index b51066240b..240ee7bb89 100644 --- a/packages/studio/src/hooks/useClipboard.unsafeMarkup.test.ts +++ b/packages/studio/src/hooks/useClipboard.unsafeMarkup.test.ts @@ -7,9 +7,9 @@ vi.mock("@hyperframes/core/html-attr-safety", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - unsafeMarkup: (root: Element) => { + markupOutsideAllowlist: (root: Element) => { checked.push(root.outerHTML); - return actual.unsafeMarkup(root); + return actual.markupOutsideAllowlist(root); }, }; }); diff --git a/packages/studio/src/utils/authoredSource.ts b/packages/studio/src/utils/authoredSource.ts index eb89f1b815..b309abb512 100644 --- a/packages/studio/src/utils/authoredSource.ts +++ b/packages/studio/src/utils/authoredSource.ts @@ -150,7 +150,7 @@ export function liveMarkupWithoutPreviewMarks(live: Element): string { return copy.outerHTML; } -export type MarkedMarkup = { html: string; saved: boolean }; +export type MarkedMarkup = { html: string; readFrom: string | null }; export function savedMarkupElseLive( saved: Document, @@ -159,8 +159,8 @@ export function savedMarkupElseLive( ): MarkedMarkup { const authored = findAuthoredElement(saved, live) ?? findAuthoredElementById(saved, live); return authored - ? { html: authoredMarkup(authored, live, sourceFile), saved: true } - : { html: liveMarkupWithoutPreviewMarks(live), saved: false }; + ? { html: authoredMarkup(authored, live, sourceFile), readFrom: sourceFile } + : { html: liveMarkupWithoutPreviewMarks(live), readFrom: null }; } export async function readSavedMarkup( diff --git a/packages/studio/src/utils/clipboardMarkup.ts b/packages/studio/src/utils/clipboardMarkup.ts new file mode 100644 index 0000000000..b22157ec4f --- /dev/null +++ b/packages/studio/src/utils/clipboardMarkup.ts @@ -0,0 +1,13 @@ +import { markupOutsideAllowlist } from "@hyperframes/core/html-attr-safety"; + +/** Every clipboard write: only markup Studio itself read from the file it writes to skips the allowlist. */ +export function refuseUnlistedMarkup( + doc: Document, + readFrom: string | null | undefined, + writeTo: string | null, +): void { + if (readFrom && readFrom === writeTo) return; + if (markupOutsideAllowlist(doc.documentElement).length > 0) { + throw new Error("Couldn't paste: the copied element holds markup that can't be pasted here."); + } +} diff --git a/packages/studio/src/utils/clipboardPayload.test.ts b/packages/studio/src/utils/clipboardPayload.test.ts index 8801b0ce31..65e7114d48 100644 --- a/packages/studio/src/utils/clipboardPayload.test.ts +++ b/packages/studio/src/utils/clipboardPayload.test.ts @@ -87,12 +87,12 @@ describe("serializeClipboardPayload / deserializeClipboardPayload", () => { expect(parsed).toEqual(payload); }); - it("drops a 'saved' mark that arrives in clipboard text, for an element and for each clip", () => { + it("drops a 'readFrom' mark that arrives in clipboard text, for an element and for each clip", () => { const element = deserializeClipboardPayload( serializeClipboardPayload({ kind: "dom-element", html: '
', - saved: true, + readFrom: "index.html", sourceFile: "index.html", }), ); @@ -100,13 +100,19 @@ describe("serializeClipboardPayload / deserializeClipboardPayload", () => { serializeClipboardPayload({ kind: "timeline-clip", clips: [ - { html: '
', saved: true, start: 0, duration: 1, track: 0 }, + { + html: '
', + readFrom: "index.html", + start: 0, + duration: 1, + track: 0, + }, ], sourceFile: "index.html", }), ); expect(element).toMatchObject({ kind: "dom-element", html: '
' }); - expect(element).not.toHaveProperty("saved"); + expect(element).not.toHaveProperty("readFrom"); expect(clips?.kind === "timeline-clip" && clips.clips[0]).toEqual({ html: '
', start: 0, diff --git a/packages/studio/src/utils/clipboardPayload.ts b/packages/studio/src/utils/clipboardPayload.ts index fef60cc4dd..7506054c85 100644 --- a/packages/studio/src/utils/clipboardPayload.ts +++ b/packages/studio/src/utils/clipboardPayload.ts @@ -9,7 +9,7 @@ const CLIPBOARD_MARKER = "hyperframes-clipboard:v1"; * relative offsets and tracks across a group paste. */ export interface TimelineClipboardClip { html: string; - saved?: boolean; + readFrom?: string | null; start: number; duration: number; track: number; @@ -26,7 +26,7 @@ export type ClipboardPayload = | { kind: "dom-element"; html: string; - saved?: boolean; + readFrom?: string | null; sourceFile: string; projectId?: string; }; From a770f4b85dd73e60d7880c630fc3514877d0c611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 12:39:39 +0000 Subject: [PATCH 116/367] fix(studio): a sealed press held across a frame swap starts on the frame shown (#8492) * fix(studio): a sealed press held across a frame swap starts on the frame shown A press made while a sealed preview changes waits, then reads where its element is over the frame's channel. It read over the frame it was pressed on; when the change swapped frames, that frame was gone, no answer came, and the drag was dropped. It now reads over the frame shown once the change ends, asks again once if that frame changes, and starts from the box Studio drew when the frame never answers. A frame that answers the element is gone still drops the press, as a scriptable preview does. * refactor(studio): the held press's frame ask and start choice are their own steps * fix(studio): a held press with no answer starts from its box as pressed, not as redrawn * fix(studio): a press held across a sealed frame swap draws on the frame shown --- .../editor/previewGestureStartRead.ts | 27 ++++- .../components/editor/previewGestureStarts.ts | 61 ++++++---- .../editor/previewOverlayRects.test.ts | 113 +++++++++++++++++- 3 files changed, 170 insertions(+), 31 deletions(-) diff --git a/packages/studio/src/components/editor/previewGestureStartRead.ts b/packages/studio/src/components/editor/previewGestureStartRead.ts index 844903f505..c451a32091 100644 --- a/packages/studio/src/components/editor/previewGestureStartRead.ts +++ b/packages/studio/src/components/editor/previewGestureStartRead.ts @@ -7,7 +7,7 @@ import type { CropFrameStart } from "./domEditOverlayCrop"; import type { OverlayRect } from "./domEditOverlayGeometry"; import { invertManualOffsetDragMatrix, type ManualOffsetDragMatrix } from "./manualOffsetDrag"; import { flatVisibleRect, groupAwareRect } from "./previewOverlayRects"; -import { findPreviewElementForSelection } from "./previewSelection"; +import { findPreviewElementForSelection, standInFor } from "./previewSelection"; import { snapContextFromRects, type SnapContext } from "./snapTargetCollection"; export interface PreviewGestureStart { @@ -93,7 +93,7 @@ export async function measurePreviewGestureStart( } export type Shown = { selection: DomEditSelection; rect: OverlayRect; start?: PreviewGestureStart }; -export type OverChannel = { shown: Shown[]; snap: SnapContext }; +export type OverChannel = { shown: Shown[]; snap?: SnapContext }; /** An opaque frame's `selections` on the page it shows now and what a gesture on them starts from. */ export async function readShownGestureStarts( @@ -102,17 +102,34 @@ export async function readShownGestureStarts( path: string | null, selections: DomEditSelection[], ): Promise { + const answer = await askShownGestureStarts(iframe, overlay, path, selections); + return answer === UNANSWERED ? null : answer; +} + +export const UNANSWERED = "unanswered"; + +export async function askShownGestureStarts( + iframe: HTMLIFrameElement, + overlay: HTMLDivElement | null, + path: string | null, + selections: DomEditSelection[], +): Promise { const found = await Promise.all( selections.map((selection) => findPreviewElementForSelection(iframe, selection, path)), ); + if (found.includes(undefined)) return UNANSWERED; const handles = found.map((element) => element?.handle); if (!overlay || !handles.length || !handles.every(Boolean)) return null; const read = await measurePreviewGestureStart(iframe, overlay, handles as string[]); + if (!read) return UNANSWERED; const shown = selections.flatMap((selection, i) => { - const element = read?.elements[i]; - return element ? [{ selection: { ...selection, handle: handles[i] }, ...element }] : []; + const start = read.elements[i]; + const onFrame = found[i]; + if (!start || !onFrame) return []; + const element = standInFor(iframe, onFrame); + return [{ selection: { ...selection, handle: onFrame.handle, element }, ...start }]; }); - return read && shown.length === selections.length ? { shown, snap: read.snap } : null; + return shown.length === selections.length ? { shown, snap: read.snap } : null; } export async function readCropFrameStart( diff --git a/packages/studio/src/components/editor/previewGestureStarts.ts b/packages/studio/src/components/editor/previewGestureStarts.ts index 59d8c64719..fa96b3bf0c 100644 --- a/packages/studio/src/components/editor/previewGestureStarts.ts +++ b/packages/studio/src/components/editor/previewGestureStarts.ts @@ -22,7 +22,12 @@ import { setStudioWaitingPressCancel } from "../../utils/studioPendingEdits"; import { playheadMoment } from "../../hooks/editMoment"; import type { EditMoment } from "./manualEditsTypes"; import { previewFrameOpaque } from "../../player/lib/previewChannel"; -import { readShownGestureStarts, type OverChannel, type Shown } from "./previewGestureStartRead"; +import { + askShownGestureStarts, + UNANSWERED, + type OverChannel, + type Shown, +} from "./previewGestureStartRead"; type ShownStart = ( e: React.PointerEvent, @@ -144,6 +149,7 @@ export function createPreviewGestureStarts( start: ShownStart, draw: WaitingPressState["draw"] = null, targets: () => DomEditSelection[] = () => [], + drawn: () => OverChannel | null = () => null, ): boolean => { const at = playheadMoment(); const iframe = opts.iframeRef.current; @@ -183,28 +189,33 @@ export function createPreviewGestureStarts( settledFrames = settled ? settledFrames + 1 : 0; return elements.length; }; - // An opaque frame's pressed elements are found over its channel, once the preview settles. - let overChannel: OverChannel | null | undefined; - let asked = false; - const channelStep = (frame: HTMLIFrameElement): "wait" | "lost" | "run" => { + // An opaque frame's pressed elements are found over the channel of the frame shown once the preview settles. + let overChannel: OverChannel | null | typeof UNANSWERED | undefined; + let askedOf: HTMLIFrameElement | null = null; + let asks = 0; + const askShownFrame = () => { + const frame = opts.iframeRef.current ?? channel!; + if (askedOf === frame || asks >= 2) return; + [askedOf, asks, overChannel] = [frame, asks + 1, undefined]; + void askShownGestureStarts( + frame, + opts.overlayRef.current, + opts.activeCompositionPathRef.current, + targets(), + ).then((answer) => askedOf === frame && (overChannel = answer)); + }; + const channelStep = (): "wait" | "lost" | "run" | "drawn" => { const overdue = performance.now() - since > PRESS_WAIT_MAX_MS; if (overdue) giveUpOnPreviewChange(); if (isPreviewChanging() && !overdue) return "wait"; - if (!asked) { - asked = true; - void readShownGestureStarts( - frame, - opts.overlayRef.current, - opts.activeCompositionPathRef.current, - targets(), - ).then((shown) => (overChannel = shown)); - } + askShownFrame(); if (overChannel === undefined) return "wait"; + if (overChannel === UNANSWERED) return "drawn"; return overChannel ? "run" : "lost"; }; - const waitStep = (): "wait" | "lost" | "run" => { + const waitStep = (): "wait" | "lost" | "run" | "drawn" => { if (press.after && !press.after.ended) return "wait"; - if (channel) return channelStep(channel); + if (channel) return channelStep(); const found = countFrame(); // A change that never ends (a save with no reply) would hold every press: run on the page shown. const overdue = performance.now() - since > PRESS_WAIT_MAX_MS; @@ -213,6 +224,11 @@ export function createPreviewGestureStarts( if (found === 0 || settledFrames > MAX_SETTLED_WAIT_FRAMES) return "lost"; return overdue || shownFrames >= 2 ? "run" : "wait"; }; + const startsFrom = (step: "lost" | "run" | "drawn"): OverChannel | undefined | false => { + if (step === "lost") return false; + if (step === "drawn") return drawn() ?? false; + return typeof overChannel === "object" && overChannel ? overChannel : undefined; + }; const poll = () => { if (press.ended) return; const step = waitStep(); @@ -222,7 +238,8 @@ export function createPreviewGestureStarts( } endWaitingPress(press); const pointerDown = down as unknown as React.PointerEvent; - if (step === "lost" || !start(pointerDown, at, true, overChannel ?? undefined)) return; + const read = startsFrom(step); + if (read === false || !start(pointerDown, at, true, read)) return; if (press.moved) moveActiveGesture(press.moved); if (press.released) releaseActiveGesture(press.released); }; @@ -291,6 +308,7 @@ export function createPreviewGestureStarts( items.map((item) => ({ ...item, rect: shiftedOverlayRect(item.rect, dx, dy) })), ), () => items.map((item) => item.selection), + () => ({ shown: items.map(({ selection, rect }) => ({ selection, rect })) }), ); }; const startGesture = ( @@ -305,13 +323,11 @@ export function createPreviewGestureStarts( ) => { // A replay edits what was pressed, though another element may be selected by then. const target = options?.selection ?? opts.selectionRef.current; + const pressedRect = opts.overlayRectRef.current; let draw: WaitingPressState["draw"] = null; - if (kind === "drag") draw = drawPressedBox(opts.overlayRectRef.current); + if (kind === "drag") draw = drawPressedBox(pressedRect); if (kind === "resize") - draw = drawResizedBox( - opts.overlayRectRef.current, - options?.resizeCorner ?? { x: e.clientX, y: e.clientY }, - ); + draw = drawResizedBox(pressedRect, options?.resizeCorner ?? { x: e.clientX, y: e.clientY }); return startOnShownPreview( e, () => { @@ -336,6 +352,7 @@ export function createPreviewGestureStarts( }, draw, () => (target ? [target] : []), + () => (target && pressedRect ? { shown: [{ selection: target, rect: pressedRect }] } : null), ); }; diff --git a/packages/studio/src/components/editor/previewOverlayRects.test.ts b/packages/studio/src/components/editor/previewOverlayRects.test.ts index 9407b77b4a..0be5ac8022 100644 --- a/packages/studio/src/components/editor/previewOverlayRects.test.ts +++ b/packages/studio/src/components/editor/previewOverlayRects.test.ts @@ -11,6 +11,7 @@ import type { DomEditSelection } from "./domEditing"; import { orientedGroupAwareOverlayRect, type OverlayRect } from "./domEditOverlayGeometry"; import type { UseDomEditOverlayGesturesOptions } from "./domEditOverlayGestures"; import { createPreviewGestureStarts } from "./previewGestureStarts"; +import { standInHandle } from "./previewSelection"; import { useDomEditOverlayRects } from "./useDomEditOverlayRects"; import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; @@ -238,11 +239,34 @@ describe("overlay rects on an opaque frame match a scriptable one", () => { }); }); +/** A sealed frame whose runtime never answers, as a frame the page has dropped. */ +function silentFrame() { + const frameWindow = new Proxy({ postMessage() {} } as Record, { + get: (target, key) => { + if (key === "postMessage") return target.postMessage; + throw new DOMException("blocked", "SecurityError"); + }, + }); + const iframe = detachedFakeIframe(frameWindow); + Object.defineProperty(iframe, "contentDocument", { value: null }); + return sized(iframe, [100, 50, 960, 540]) as HTMLIFrameElement; +} + describe("a press held across a preview change on an opaque frame", () => { - async function pressDuringChange(selection: DomEditSelection) { + async function pressDuringChange( + selection: DomEditSelection, + { + iframe = opaqueFrame(), + overlayRect = null, + whileWaiting = () => {}, + }: { + iframe?: HTMLIFrameElement; + overlayRect?: OverlayRect | null; + whileWaiting?: (opts: UseDomEditOverlayGesturesOptions) => void; + } = {}, + ) { press.changing = true; press.start.mockClear(); - const iframe = opaqueFrame(); const overlay = sized(document.createElement("div"), [20, 10, 1200, 800]) as HTMLDivElement; const opts = { waitingPressRef: { current: null }, @@ -252,8 +276,8 @@ describe("a press held across a preview change on an opaque frame", () => { overlayRef: { current: overlay }, activeCompositionPathRef: { current: "index.html" }, selectionRef: { current: selection }, - overlayRectRef: { current: null }, - setOverlayRect: vi.fn(), + overlayRectRef: { current: overlayRect }, + setOverlayRect: vi.fn((rect: OverlayRect | null) => (opts.overlayRectRef.current = rect)), } as unknown as UseDomEditOverlayGesturesOptions; const { startGesture } = createPreviewGestureStarts(opts, vi.fn(), vi.fn()); const down = { @@ -267,6 +291,7 @@ describe("a press held across a preview change on an opaque frame", () => { startGesture("drag", down as unknown as React.PointerEvent); await new Promise((resolve) => setTimeout(resolve, 50)); expect(press.start).not.toHaveBeenCalled(); + whileWaiting(opts); press.changing = false; return { opts, overlay }; } @@ -289,6 +314,86 @@ describe("a press held across a preview change on an opaque frame", () => { expect(started.rect.angle).toBeCloseTo(36.87, 2); }); + // fails without the fix: the press read over the frame it was pressed on, which the change had removed, so no + // answer came and the drag was dropped. + it("reads over the frame shown once the change ends, when the change swapped frames", async () => { + const turned = document.getElementById("turned")!; + const pressedOn = opaqueFrame(); + await pressDuringChange(makeSelection("turned", turned), { + iframe: pressedOn, + whileWaiting: (opts) => { + opts.iframeRef.current = opaqueFrame(); + Object.defineProperty(pressedOn, "contentWindow", { value: null }); + }, + }); + await vi.waitFor(() => expect(press.start).toHaveBeenCalledOnce(), { timeout: 3000 }); + const [, , , started] = press.start.mock.calls[0] as [ + unknown, + unknown, + unknown, + { selection: DomEditSelection }, + ]; + expect(started.selection.id).toBe("turned"); + // fails without the fix: the gesture drew through the stand-in of the frame it was pressed on, now removed. + expect(started.selection.element).not.toBe(turned); + expect(standInHandle(started.selection.element)).toBe(started.selection.handle); + }); + + it("starts from the box Studio drew when the frame shown never answers", async () => { + const turned = makeSelection("turned", document.getElementById("turned")!); + const drawn = { left: 1, top: 2, width: 3, height: 4 } as OverlayRect; + await pressDuringChange(turned, { iframe: silentFrame(), overlayRect: drawn }); + await vi.waitFor(() => expect(press.start).toHaveBeenCalledOnce(), { timeout: 3000 }); + const [, , , started] = press.start.mock.calls[0] as [ + unknown, + unknown, + unknown, + { selection: DomEditSelection; rect: OverlayRect }, + ]; + expect(started).toMatchObject({ selection: turned, rect: drawn }); + expect(started.selection.element).toBe(turned.element); + }); + + // fails without the fix: the waiting box's redraws had already moved the box the drag started from. + it("starts from the box as it was at the press, though the pointer moved while it waited", async () => { + const turned = makeSelection("turned", document.getElementById("turned")!); + const drawn = { left: 1, top: 2, width: 3, height: 4 } as OverlayRect; + await pressDuringChange(turned, { + iframe: silentFrame(), + overlayRect: drawn, + whileWaiting: (opts) => opts.waitingPressRef.current!.draw!(30, 0), + }); + await vi.waitFor(() => expect(press.start).toHaveBeenCalledOnce(), { timeout: 3000 }); + const [, , , started] = press.start.mock.calls[0] as [ + unknown, + unknown, + unknown, + { rect: OverlayRect }, + ]; + expect(started.rect).toEqual(drawn); + }); + + it("asks the frame shown again when a swap comes after its first ask", async () => { + const turned = document.getElementById("turned")!; + const drawn = { left: 1, top: 2, width: 3, height: 4 } as OverlayRect; + const { opts, overlay } = await pressDuringChange(makeSelection("turned", turned), { + iframe: silentFrame(), + overlayRect: drawn, + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + opts.iframeRef.current = opaqueFrame(); + await vi.waitFor(() => expect(press.start).toHaveBeenCalledOnce(), { timeout: 3000 }); + const [, , , started] = press.start.mock.calls[0] as [ + unknown, + unknown, + unknown, + { rect: OverlayRect }, + ]; + expect(close(started.rect)).toEqual( + close(orientedGroupAwareOverlayRect(overlay, liveFrame(), turned)), + ); + }); + it("drops the press when the page shown no longer has the element", async () => { const turned = document.getElementById("turned")!; const { opts } = await pressDuringChange(makeSelection("turned", turned)); From 97b90d8fa2b9e7c475e30e0e9a91f49418d1aedb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 12:40:37 +0000 Subject: [PATCH 117/367] fix(studio): a sealed preview's clips keep their GSAP transition label (#8499) * test: a sealed preview's clips name their GSAP transition * fix(studio): a sealed preview's clips keep their GSAP transition label * fix(studio): GSAP scene and overlay clips carry their transition label too --- packages/core/src/runtime/timeline.test.ts | 24 +++++++++++++ packages/core/src/runtime/timeline.ts | 5 +++ .../src/runtime/transitionLabels.ts} | 12 +++---- packages/core/src/runtime/types.ts | 1 + packages/core/src/studioPreviewMark.ts | 5 +++ .../src/player/lib/manifestClips.test.ts | 36 +++++++++++++++++++ .../studio/src/player/lib/manifestClips.ts | 15 +++++++- .../studio/src/player/lib/playbackTypes.ts | 1 + .../studio/src/player/lib/timelineDOM.test.ts | 24 +++++++++++++ packages/studio/src/player/lib/timelineDOM.ts | 9 ++--- .../src/player/lib/timelineIframeHelpers.ts | 2 +- 11 files changed, 118 insertions(+), 16 deletions(-) rename packages/{studio/src/player/lib/timelineTransitionMetadata.ts => core/src/runtime/transitionLabels.ts} (79%) create mode 100644 packages/studio/src/player/lib/manifestClips.test.ts diff --git a/packages/core/src/runtime/timeline.test.ts b/packages/core/src/runtime/timeline.test.ts index d1f3227e46..e6d003eaf2 100644 --- a/packages/core/src/runtime/timeline.test.ts +++ b/packages/core/src/runtime/timeline.test.ts @@ -115,6 +115,30 @@ describe("collectRuntimeTimelinePayload", () => { expect(trackOf("clip-other")).toBe(2); }); + it("names both clips of a GSAP transition on the clip message, for a preview that cannot read the page", () => { + const root = document.createElement("div"); + root.setAttribute("data-composition-id", "main"); + root.setAttribute("data-duration", "10"); + root.innerHTML = ` +
+
+
`; + document.body.appendChild(root); + (window as TimelineTestWindow).__timelines = { + main: { duration: () => 10, labels: { "hf:transition:a:b:fade": 2 } } as never, + }; + + const labels = collectRuntimeTimelinePayload(defaultParams).clips.map((clip) => [ + clip.id, + clip.transitionLabel, + ]); + expect(labels).toEqual([ + ["a", "hf:transition:a:b:fade"], + ["b", "hf:transition:a:b:fade"], + ["c", null], + ]); + }); + it("collects clips from elements with data-start and data-duration", () => { const root = document.createElement("div"); root.setAttribute("data-composition-id", "main"); diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.ts index bc901f671e..c248d2ed47 100644 --- a/packages/core/src/runtime/timeline.ts +++ b/packages/core/src/runtime/timeline.ts @@ -5,6 +5,7 @@ import type { RuntimeTimelineScene, RuntimeTimelineLike, } from "./types"; +import { transitionLabelsForDocument } from "./transitionLabels"; import { unproxiedSrc } from "./proxySrc"; import { stableClipId } from "./clipTree"; import { findRootCompositionElement, parseCompositionDimension } from "./compositionDimension"; @@ -270,6 +271,7 @@ export function collectRuntimeTimelinePayload(params: { __timelines?: Record; }; const timelineRegistry = runtimeWindow.__timelines ?? {}; + const transitionLabels = transitionLabelsForDocument(document, timelineRegistry); const startResolver = createRuntimeStartTimeResolver({ timelineRegistry, includeAuthoredTimingAttrs: true, @@ -505,6 +507,7 @@ export function collectRuntimeTimelinePayload(params: { timelineGroup: node.getAttribute("data-timeline-group"), timelinePriority: parseNum(node.getAttribute("data-timeline-priority")), text: readSentTextLayer(node), + transitionLabel: transitionLabels.get(node) ?? null, }; }; const addClip = (clip: RuntimeTimelineClip) => { @@ -636,6 +639,7 @@ export function collectRuntimeTimelinePayload(params: { timelineGroup: el.getAttribute("data-timeline-group"), timelinePriority: parseNum(el.getAttribute("data-timeline-priority")), text: readSentTextLayer(el), + transitionLabel: transitionLabels.get(el) ?? null, }); gsapClipIds.add(el.id); } @@ -694,6 +698,7 @@ export function collectRuntimeTimelinePayload(params: { timelineGroup: el.getAttribute("data-timeline-group"), timelinePriority: parseNum(el.getAttribute("data-timeline-priority")), text: readSentTextLayer(el), + transitionLabel: transitionLabels.get(el) ?? null, }); gsapClipIds.add(el.id); } diff --git a/packages/studio/src/player/lib/timelineTransitionMetadata.ts b/packages/core/src/runtime/transitionLabels.ts similarity index 79% rename from packages/studio/src/player/lib/timelineTransitionMetadata.ts rename to packages/core/src/runtime/transitionLabels.ts index 713637e440..13c9e21bb0 100644 --- a/packages/studio/src/player/lib/timelineTransitionMetadata.ts +++ b/packages/core/src/runtime/transitionLabels.ts @@ -1,8 +1,6 @@ -import type { TimelineLike } from "./playbackTypes"; +export const TRANSITION_LABEL_PREFIX = "hf:transition:"; -const TRANSITION_LABEL_PREFIX = "hf:transition:"; - -type TimelineWithLabels = TimelineLike & { +type TimelineWithLabels = { labels?: Record; getLabels?: () => Record; }; @@ -30,13 +28,13 @@ function findTimedElement(doc: Document, markerId: string): Element | null { export function transitionLabelsForDocument( doc: Document, - timelines: Readonly> | undefined, + timelines: Readonly> | undefined, ): ReadonlyMap { const labels = new Map(); if (!timelines) return labels; - for (const timeline of Object.values(timelines) as TimelineWithLabels[]) { - const timelineLabels = timeline.getLabels?.() ?? timeline.labels ?? {}; + for (const timeline of Object.values(timelines) as Array) { + const timelineLabels = timeline?.getLabels?.() ?? timeline?.labels ?? {}; for (const label of Object.keys(timelineLabels)) { const pair = transitionParts(label); if (!pair) continue; diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.ts index f962baf61e..d08ec4cbab 100644 --- a/packages/core/src/runtime/types.ts +++ b/packages/core/src/runtime/types.ts @@ -99,6 +99,7 @@ export type RuntimeTimelineClip = RuntimeTimelineClipIdentity & { timelineGroup: string | null; timelinePriority: number | null; text: TextLayerRead | null; + transitionLabel: string | null; }; export type RuntimeTimelineScene = { diff --git a/packages/core/src/studioPreviewMark.ts b/packages/core/src/studioPreviewMark.ts index c826576f5e..5e53e837ad 100644 --- a/packages/core/src/studioPreviewMark.ts +++ b/packages/core/src/studioPreviewMark.ts @@ -1,5 +1,10 @@ import { isWebKit } from "./runtime/mediaClock.js"; +export { + TRANSITION_LABEL_PREFIX, + transitionLabelsForDocument, +} from "./runtime/transitionLabels.js"; + export const STUDIO_PREVIEW_MARK_META = "hyperframes-studio-preview"; export const PREVIEW_SEEK_HOLD_ATTR = "data-hf-preview-seek-hold"; export const PREVIEW_VIDEO_FRAME_ATTR = "data-hf-preview-video-frame"; diff --git a/packages/studio/src/player/lib/manifestClips.test.ts b/packages/studio/src/player/lib/manifestClips.test.ts new file mode 100644 index 0000000000..e7b2a5b41d --- /dev/null +++ b/packages/studio/src/player/lib/manifestClips.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { wellFormedClips } from "./manifestClips"; + +const clip = (transitionLabel: unknown) => ({ + id: "a", + label: "A", + kind: "element", + tagName: "div", + start: 0, + duration: 3, + track: 0, + compositionId: null, + parentCompositionId: null, + compositionSrc: null, + assetUrl: null, + transitionLabel, +}); + +describe("wellFormedClips", () => { + it("keeps a transition label only as the runtime writes one, and the clip either way", () => { + const clips = wellFormedClips([ + clip("hf:transition:a:b:fade"), + clip(`hf:transition:a:b:${"x".repeat(200)}`), + clip("javascript:alert(1)"), + clip(5), + clip(null), + ]); + expect(clips.map((kept) => kept.transitionLabel)).toEqual([ + "hf:transition:a:b:fade", + undefined, + undefined, + undefined, + undefined, + ]); + }); +}); diff --git a/packages/studio/src/player/lib/manifestClips.ts b/packages/studio/src/player/lib/manifestClips.ts index 55816f0958..97518db6e9 100644 --- a/packages/studio/src/player/lib/manifestClips.ts +++ b/packages/studio/src/player/lib/manifestClips.ts @@ -1,5 +1,8 @@ +import { TRANSITION_LABEL_PREFIX } from "@hyperframes/core/studio-preview-mark"; import type { ClipManifestClip } from "./playbackTypes"; +const MAX_TRANSITION_LABEL = 200; + const OPTIONAL_NUMBERS = ["zIndex", "playbackStart", "playbackRate"] as const; export const clipNumber = (value: unknown): number | null => @@ -18,7 +21,17 @@ function wellFormedClip(clip: unknown): clip is ClipManifestClip { ); } +const transitionLabelOf = (value: unknown): string | undefined => + typeof value === "string" && + value.length <= MAX_TRANSITION_LABEL && + value.startsWith(TRANSITION_LABEL_PREFIX) + ? value + : undefined; + /** A preview frame's clip list, keeping only clips whose timing and track are numbers. */ export function wellFormedClips(clips: readonly unknown[]): ClipManifestClip[] { - return clips.filter(wellFormedClip); + return clips.filter(wellFormedClip).map(({ transitionLabel, ...clip }) => { + const label = transitionLabelOf(transitionLabel); + return label ? { ...clip, transitionLabel: label } : clip; + }); } diff --git a/packages/studio/src/player/lib/playbackTypes.ts b/packages/studio/src/player/lib/playbackTypes.ts index d42916cbb5..b7bd51ad2f 100644 --- a/packages/studio/src/player/lib/playbackTypes.ts +++ b/packages/studio/src/player/lib/playbackTypes.ts @@ -47,6 +47,7 @@ export interface ClipManifestClip extends RuntimeTimelineClipIdentity { compositionAncestors?: string[]; playbackStart?: number; playbackRate?: number; + transitionLabel?: string; } export interface ClipManifest { diff --git a/packages/studio/src/player/lib/timelineDOM.test.ts b/packages/studio/src/player/lib/timelineDOM.test.ts index 011efe4530..7f74011801 100644 --- a/packages/studio/src/player/lib/timelineDOM.test.ts +++ b/packages/studio/src/player/lib/timelineDOM.test.ts @@ -428,6 +428,30 @@ describe("a sealed preview's text rows", () => { }); }); +describe("a sealed preview's transition labels", () => { + it("names a clip's transition from the runtime's clip message, with no page timelines to read", () => { + const row = createTimelineElementFromManifestClip({ + clip: { + id: "a", + label: "A", + kind: "element", + tagName: "div", + start: 0, + duration: 3, + track: 0, + compositionId: null, + parentCompositionId: null, + compositionSrc: null, + assetUrl: null, + transitionLabel: "hf:transition:a:b:fade", + }, + fallbackIndex: 0, + doc: makeDoc(`
`), + }); + expect(row.transitionLabel).toBe("hf:transition:a:b:fade"); + }); +}); + describe("group info cache", () => { const parseMember = (doc: Document) => createTimelineElementFromManifestClip({ diff --git a/packages/studio/src/player/lib/timelineDOM.ts b/packages/studio/src/player/lib/timelineDOM.ts index 6f985de87a..e3657ca674 100644 --- a/packages/studio/src/player/lib/timelineDOM.ts +++ b/packages/studio/src/player/lib/timelineDOM.ts @@ -20,7 +20,7 @@ import { previewWithoutFrameToken } from "./frameToken"; import { clipNumber, clipTrack } from "./manifestClips"; import { groupInfoFor } from "./timelineGroupInfo"; import { receivedTimelineText } from "./timelineText"; -import { transitionLabelsForDocument } from "./timelineTransitionMetadata"; +import { transitionLabelsForDocument } from "@hyperframes/core/studio-preview-mark"; import { resolveMediaElement, applyMediaMetadataFromElement, @@ -84,9 +84,6 @@ export function createTimelineElementFromManifestClip(params: { const { clip, fallbackIndex, doc } = params; const numericTrack = clipTrack(clip.track) ?? 0; let hostEl = params.hostEl ?? null; - const transitionLabels = doc - ? transitionLabelsForDocument(doc, (doc.defaultView as IframeWindow | null)?.__timelines) - : new Map(); const label = getTimelineElementDisplayLabel({ id: clip.id, label: clip.label, @@ -121,9 +118,7 @@ export function createTimelineElementFromManifestClip(params: { id: identity.id, label, transitionLabel: - (hostEl && transitionLabels.get(hostEl)) || - hostEl?.getAttribute("data-transition-label") || - undefined, + clip.transitionLabel || hostEl?.getAttribute("data-transition-label") || undefined, key: identity.key, kind: clip.kind, tag: resolveClipTag(clip), diff --git a/packages/studio/src/player/lib/timelineIframeHelpers.ts b/packages/studio/src/player/lib/timelineIframeHelpers.ts index 59d9292c56..befddaaab4 100644 --- a/packages/studio/src/player/lib/timelineIframeHelpers.ts +++ b/packages/studio/src/player/lib/timelineIframeHelpers.ts @@ -25,7 +25,7 @@ import { type PreviewTarget, } from "./timelineElementHelpers"; import { postRuntimeControlMessage } from "./runtimeProtocol"; -import { transitionLabelsForDocument } from "./timelineTransitionMetadata"; +import { transitionLabelsForDocument } from "@hyperframes/core/studio-preview-mark"; // --------------------------------------------------------------------------- // Viewport / DOM normalisation From 680c9a5402c5524137763d7ce7ff33dc32589d4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 12:43:29 +0000 Subject: [PATCH 118/367] test(cli): run the PowerShell round-trip names in one shell so slow Windows runners stay in time (#8498) --- packages/cli/src/utils/shellArg.test.ts | 29 ++++++++++++++++--------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/packages/cli/src/utils/shellArg.test.ts b/packages/cli/src/utils/shellArg.test.ts index f479a13cd2..e794f60176 100644 --- a/packages/cli/src/utils/shellArg.test.ts +++ b/packages/cli/src/utils/shellArg.test.ts @@ -129,7 +129,7 @@ describe("shellArg", () => { ); const argvScript = join(root, "argv.cjs"); - writeFileSync(argvScript, "process.stdout.write(JSON.stringify(process.argv.slice(2)));"); + writeFileSync(argvScript, 'process.stdout.write(JSON.stringify(process.argv.slice(2)) + "\\n");'); const readArgv = (output: string): string[] => JSON.parse(output) as string[]; it.runIf(process.platform === "win32")( @@ -150,19 +150,28 @@ describe("shellArg", () => { it.runIf(process.platform === "win32")( "prints a Windows word that PowerShell reads as written", () => { - for (const name of WINDOWS_ROUND_TRIP) { - const line = `& '${process.execPath}' '${argvScript}' ${shellArg(name, "win32")}`; - const output = execFileSync( - "powershell.exe", - ["-NoProfile", "-EncodedCommand", Buffer.from(line, "utf16le").toString("base64")], - { encoding: "utf8" }, - ); + // One Windows PowerShell for every name: a cold start each pushed a slow runner past the timeout. + const lines = WINDOWS_ROUND_TRIP.map( + (name) => `& '${process.execPath}' '${argvScript}' ${shellArg(name, "win32")}`, + ); + const output = execFileSync( + "powershell.exe", + [ + "-NoProfile", + "-EncodedCommand", + Buffer.from(lines.join("\n"), "utf16le").toString("base64"), + ], + { encoding: "utf8" }, + ); + const runs = output.split(/\r?\n/).filter(Boolean); + expect(runs).toHaveLength(WINDOWS_ROUND_TRIP.length); + WINDOWS_ROUND_TRIP.forEach((name, index) => { // Windows PowerShell hands a space-free word to a program unquoted, so a doubled trailing backslash stays doubled. expect( - readArgv(output).map((arg) => win32.normalize(arg)), + readArgv(runs[index]!).map((arg) => win32.normalize(arg)), name, ).toEqual([win32.normalize(name)]); - } + }); }, ); }); From 45674e840f6a3155ba761f7b31330910eba556cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 12:54:49 +0000 Subject: [PATCH 119/367] fix(studio): copy and duplicate refuse a file that is not one of the project's compositions (#8490) * refactor(core): keep the SVG element and attribute allowlist in its own module * test(studio): clipboard writes refuse markup a scripting preview reads differently * fix(studio): paste and duplicate write only allowed markup unless it comes from the same file * test(studio): copy and duplicate use only files Studio knows in the project * fix(studio): copy and duplicate refuse a file that is not one of the project's compositions * test(core): inline SVG with its namespace declarations pastes from another file * fix(core): paste keeps SVG namespace declarations and checks xlink:href as a link * chore(cli): regenerate the media-use SVG sanitizer from its moved allowlist --- .../src/components/editor/domEditingDom.ts | 12 +++++++ .../src/hooks/useClipboard.sealed.test.ts | 30 +++++++++++++++- .../src/hooks/useClipboard.source.test.ts | 6 +++- packages/studio/src/hooks/useClipboard.ts | 34 +++++++++---------- packages/studio/src/utils/clipboardMarkup.ts | 10 ++++++ 5 files changed, 73 insertions(+), 19 deletions(-) diff --git a/packages/studio/src/components/editor/domEditingDom.ts b/packages/studio/src/components/editor/domEditingDom.ts index b6a9775cec..77663712cb 100644 --- a/packages/studio/src/components/editor/domEditingDom.ts +++ b/packages/studio/src/components/editor/domEditingDom.ts @@ -102,6 +102,18 @@ export function getCompositionSourceMapRevision(): number { return compositionSourceMapRevision; } +export function knownCompositionFile( + claimed: string | undefined, + activeCompositionPath: string | null, +): string | null { + const file = claimed || activeCompositionPath || "index.html"; + const known = + file === "index.html" || + file === activeCompositionPath || + [...compositionSourceMap.values()].includes(file); + return known ? file : null; +} + /** The source file `source` names (see `EditingElementSource`), with this project's composition map. */ export function resolveElementSourceFile( source: EditingElementSource, diff --git a/packages/studio/src/hooks/useClipboard.sealed.test.ts b/packages/studio/src/hooks/useClipboard.sealed.test.ts index f243dbb13a..4023cad5c5 100644 --- a/packages/studio/src/hooks/useClipboard.sealed.test.ts +++ b/packages/studio/src/hooks/useClipboard.sealed.test.ts @@ -7,6 +7,7 @@ import { useClipboard } from "./useClipboard"; import { usePlayerStore, type TimelineElement } from "../player"; import type { DomEditSelection } from "../components/editor/domEditing"; import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers"; +import { setCompositionSourceMap } from "../components/editor/domEditingDom"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -21,6 +22,7 @@ afterEach(() => { act(() => root?.unmount()); root = null; vi.unstubAllGlobals(); + setCompositionSourceMap(new Map()); usePlayerStore.getState().reset(); document.body.innerHTML = ""; }); @@ -186,7 +188,8 @@ it("checks a saved element read from another file before pasting it into this on selector: "#go", sourceFile: "compositions/recv.html", } as DomEditSelection; - // The frame shows one of the person's own clips under the received element's file and id. + // A received sub-composition of this project, and one of the person's own clips shown under its file and id. + setCompositionSourceMap(new Map([["recv", "compositions/recv.html"]])); const relabelled = '
'; const { clipboard, writes, toasts } = sealedClipboard(selection, relabelled, SAVED, { @@ -198,6 +201,31 @@ it("checks a saved element read from another file before pasting it into this on expect(toasts.at(-1)).toMatch(/^Couldn't paste/); }); +// fails without the fix: the file the frame named for a clip or a selection was read and written as given. +it("copies and duplicates nothing from a file Studio does not know as one of this project's compositions", async () => { + const elsewhere = { ...clipOf("go", "button", 1, 2), sourceFile: "compositions/elsewhere.html" }; + const shown = + '
'; + usePlayerStore.setState({ elements: [elsewhere] }); + selectClip("go"); + const duplicated = sealedClipboard(null, shown); + expect(await duplicated.clipboard().handleDuplicate()).toBe(false); + expect(duplicated.writes).toEqual([]); + act(() => root?.unmount()); + root = null; + + usePlayerStore.setState({ selectedElementId: null, selectedElementIds: new Set() }); + const selection = { + id: "go", + selector: "#go", + sourceFile: "compositions/elsewhere.html", + } as DomEditSelection; + const copied = sealedClipboard(selection, shown); + copied.clipboard().handleCopy(); + await copied.clipboard().handlePaste(); + expect(copied.writes).toEqual([]); +}); + it("pastes and duplicates a saved element with its own handler, as saved", async () => { const saved = SAVED.replace( "", diff --git a/packages/studio/src/hooks/useClipboard.source.test.ts b/packages/studio/src/hooks/useClipboard.source.test.ts index b67a5e5032..11ecc08447 100644 --- a/packages/studio/src/hooks/useClipboard.source.test.ts +++ b/packages/studio/src/hooks/useClipboard.source.test.ts @@ -2,11 +2,12 @@ import React, { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { ensureHfIds } from "@hyperframes/parsers/hf-ids"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useClipboard } from "./useClipboard"; import { usePlayerStore, type TimelineElement } from "../player"; import type { DomEditSelection } from "../components/editor/domEditing"; import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator"; +import { setCompositionSourceMap } from "../components/editor/domEditingDom"; // Saved without hf-ids and with no element id: the preview stamps ids only in memory. const SAVED = ` @@ -43,9 +44,12 @@ const TITLE: TimelineElement = { }; let root: Root | null = null; +// What Studio reads from the project's index.html before any copy. +beforeEach(() => setCompositionSourceMap(new Map([["sub", "compositions/sub.html"]]))); afterEach(() => { act(() => root?.unmount()); root = null; + setCompositionSourceMap(new Map()); vi.unstubAllGlobals(); document.body.innerHTML = ""; }); diff --git a/packages/studio/src/hooks/useClipboard.ts b/packages/studio/src/hooks/useClipboard.ts index 82fc3a5d31..443d803ec2 100644 --- a/packages/studio/src/hooks/useClipboard.ts +++ b/packages/studio/src/hooks/useClipboard.ts @@ -29,7 +29,8 @@ import { savedMarkupElseLive, } from "../utils/authoredSource"; import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator"; -import { refuseUnlistedMarkup } from "../utils/clipboardMarkup"; +import { copiedFile, refuseUnlistedMarkup } from "../utils/clipboardMarkup"; +import { knownCompositionFile } from "../components/editor/domEditingDom"; type InPlace = { inPlace?: boolean }; @@ -325,7 +326,7 @@ export function useClipboard({ targets: { elements: TimelineElement[]; lives: Element[] }, pid: string | null, ): Promise => { - const paths = targets.elements.map((el) => el.sourceFile || activeCompPath || "index.html"); + const paths = targets.elements.map((el) => copiedFile(el.sourceFile, activeCompPath)); const markup = await readSavedMarkup((path) => readSaved(path, pid), paths, targets.lives); return targets.elements.map((element, index) => ({ ...(markup[index] as MarkedMarkup), @@ -348,13 +349,12 @@ export function useClipboard({ findSelectedClips(selected, doc), ); const copy = (targets: { elements: TimelineElement[]; lives: Element[] }) => { - const sourceFile = targets.elements[0]?.sourceFile || activeCompPath || "index.html"; return readClips(targets, pid).then((clips): ClipboardPayload => { showToast(clips.length > 1 ? `Copied ${clips.length} clips` : "Copied clip", "info"); return { kind: "timeline-clip", clips, - sourceFile, + sourceFile: copiedFile(targets.elements[0]?.sourceFile, activeCompPath), projectId: pid ?? undefined, copiedInComposition: activeCompPath || "index.html", }; @@ -370,17 +370,17 @@ export function useClipboard({ const live = doc && findElementForSelection(doc, domSelection, activeCompPath); return live ?? { refused: "Unable to copy this element." }; }); - const sourceFile = domSelection.sourceFile || activeCompPath || "index.html"; - const copy = (live: Element) => - readSaved(sourceFile, pid).then((content): ClipboardPayload => { - showToast("Copied element", "info"); - return { - kind: "dom-element", - ...savedMarkupElseLive(parseSavedSource(content), live, sourceFile), - sourceFile, - projectId: pid ?? undefined, - }; - }); + const copy = async (live: Element): Promise => { + const sourceFile = copiedFile(domSelection.sourceFile, activeCompPath); + const content = await readSaved(sourceFile, pid); + showToast("Copied element", "info"); + return { + kind: "dom-element", + ...savedMarkupElseLive(parseSavedSource(content), live, sourceFile), + sourceFile, + projectId: pid ?? undefined, + }; + }; return copyFound(found, copy, showToast); }, [activeCompPath, previewIframeRef, readSaved, showToast], @@ -492,8 +492,7 @@ export function useClipboard({ if (!targets || !pid || projectIdRef.current !== pid) return false; const { elements } = targets; - const pathOf = (el: TimelineElement) => el.sourceFile || activeCompPath || "index.html"; - const targetPath = pathOf(elements[0]!); + const pathOf = (el: TimelineElement) => knownCompositionFile(el.sourceFile, activeCompPath); // The copy lands in targetPath's own clock, so anchor and lane check are local to it. const anchorTime = toAuthoredStart( elements[0]!, @@ -504,6 +503,7 @@ export function useClipboard({ try { const clips = await readClips(targets, pid); + const targetPath = copiedFile(elements[0]!.sourceFile, activeCompPath); let ids: string[] = []; const duplicate = (originalContent: string) => { const liveElements = usePlayerStore diff --git a/packages/studio/src/utils/clipboardMarkup.ts b/packages/studio/src/utils/clipboardMarkup.ts index b22157ec4f..4513ce21d3 100644 --- a/packages/studio/src/utils/clipboardMarkup.ts +++ b/packages/studio/src/utils/clipboardMarkup.ts @@ -1,4 +1,14 @@ import { markupOutsideAllowlist } from "@hyperframes/core/html-attr-safety"; +import { knownCompositionFile } from "../components/editor/domEditingDom"; + +export function copiedFile( + claimed: string | undefined, + activeCompositionPath: string | null, +): string { + const file = knownCompositionFile(claimed, activeCompositionPath); + if (file) return file; + throw new Error("Couldn't use this element: its file isn't one of this project's compositions."); +} /** Every clipboard write: only markup Studio itself read from the file it writes to skips the allowlist. */ export function refuseUnlistedMarkup( From 0e6879b8efea57f588ed835fab56f9211e0cfcde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 13:13:47 +0000 Subject: [PATCH 120/367] fix(studio): scrubbing across a cut shows the newest frame, not black (#8501) * test(studio): a scrub's newest paused frame is decoded, never refused while an older one settles * fix(studio): scrubbing across a cut shows the newest frame, not black * test(studio): a flood of paused-frame asks decodes only the newest; a throw never stalls --- .../player/lib/pausedVideoProvider.test.ts | 71 ++++++++++++++++--- .../src/player/lib/pausedVideoProvider.ts | 39 +++++++--- 2 files changed, 88 insertions(+), 22 deletions(-) diff --git a/packages/studio/src/player/lib/pausedVideoProvider.test.ts b/packages/studio/src/player/lib/pausedVideoProvider.test.ts index a798214ee7..571b809912 100644 --- a/packages/studio/src/player/lib/pausedVideoProvider.test.ts +++ b/packages/studio/src/player/lib/pausedVideoProvider.test.ts @@ -58,7 +58,7 @@ it("ignores an ask carrying any option but the proxy's", async () => { expect(decoder.decode).not.toHaveBeenCalled(); }); -it("refuses more sources than one decode may name, and a second decode while one runs", async () => { +it("refuses more sources than one decode may name, and replaces a decode a newer one overtakes", async () => { const { replies, decode } = host(); decode([at(A), at(A), at(A), at(A), at(A)]); await vi.waitFor(() => expect(replies).toHaveLength(1)); @@ -66,14 +66,17 @@ it("refuses more sources than one decode may name, and a second decode while one decoder.decode.mockReturnValue(new Promise(() => {})); decode([at(A)]); + const overtaken = lastId; await vi.waitFor(() => expect(decoder.decode).toHaveBeenCalledOnce()); decode([at(A)]); await vi.waitFor(() => expect(replies).toHaveLength(2)); - expect(replies[1]).toMatchObject({ type: "failed", message: "Preview decoder busy" }); + expect(replies[1]).toEqual({ type: "failed", id: overtaken, message: "Preview decode replaced" }); + expect(decoder.decode.mock.calls[0]![1].aborted).toBe(true); expect(decoder.decode).toHaveBeenCalledOnce(); }); -it("keeps an aborted decode's slot until that decode settles", async () => { +// fails without the fix: a scrub's newest frame was refused while the aborted one settled, so the preview showed black. +it("decodes the newest ask once an aborted decode settles, never two at once", async () => { let settle = (_frames: unknown[]) => {}; decoder.decode.mockReturnValueOnce(new Promise((resolve) => (settle = resolve))); const { replies, decode, port2 } = host(); @@ -81,17 +84,63 @@ it("keeps an aborted decode's slot until that decode settles", async () => { const first = lastId; await vi.waitFor(() => expect(decoder.decode).toHaveBeenCalledOnce()); port2.postMessage({ type: "abort", id: first }); - decode([at(A)]); - await vi.waitFor(() => expect(replies).toHaveLength(1)); - expect(replies[0]).toMatchObject({ type: "failed", message: "Preview decoder busy" }); - - settle([]); - port2.postMessage({ type: "suspend", id: ++lastId }); - await vi.waitFor(() => expect(replies.at(-1)).toEqual({ type: "suspended", id: lastId })); decoder.decode.mockResolvedValueOnce([]); decode([at(A)]); - await vi.waitFor(() => expect(replies.at(-1)).toMatchObject({ type: "frames", frames: [] })); + const newest = lastId; + port2.postMessage({ type: "suspend", id: ++lastId }); + await vi.waitFor(() => expect(replies).toEqual([{ type: "suspended", id: lastId }])); + expect(decoder.decode).toHaveBeenCalledOnce(); + + settle([]); + await vi.waitFor(() => + expect(replies.at(-1)).toEqual({ type: "frames", id: newest, frames: [] }), + ); expect(decoder.decode).toHaveBeenCalledTimes(2); + expect(replies.filter((reply) => reply.id === first)).toEqual([]); +}); + +it("answers a flood of 20 asks with 19 replaced and decodes only the newest, one call at a time", async () => { + const held: Array<() => void> = []; + let running = 0; + let most = 0; + decoder.decode.mockImplementation(() => { + most = Math.max(most, ++running); + return new Promise((resolve) => + held.push(() => { + running -= 1; + resolve([]); + }), + ); + }); + const { replies, decode } = host(); + for (let i = 0; i < 20; i += 1) decode([at(A)]); + const newest = lastId; + await vi.waitFor(() => expect(replies).toHaveLength(19)); + expect(replies.every((reply) => reply.message === "Preview decode replaced")).toBe(true); + await vi.waitFor(() => expect(held).toHaveLength(1)); + held.shift()!(); + await vi.waitFor(() => expect(held).toHaveLength(1)); + held.shift()!(); + await vi.waitFor(() => + expect(replies.at(-1)).toEqual({ type: "frames", id: newest, frames: [] }), + ); + expect(replies).toHaveLength(20); + expect(decoder.decode).toHaveBeenCalledTimes(2); + expect(most).toBe(1); +}); + +it("decodes the next ask after one whose decoder throws", async () => { + decoder.decode.mockRejectedValueOnce(new Error("decoder broke")); + const { replies, decode } = host(); + decode([at(A)]); + const broken = lastId; + await vi.waitFor(() => expect(replies).toHaveLength(1)); + expect(replies[0]).toEqual({ type: "failed", id: broken, message: "decoder broke" }); + decoder.decode.mockResolvedValueOnce([]); + decode([at(A)]); + await vi.waitFor(() => + expect(replies.at(-1)).toEqual({ type: "frames", id: lastId, frames: [] }), + ); }); it("refuses frames over the byte budget and releases them", async () => { diff --git a/packages/studio/src/player/lib/pausedVideoProvider.ts b/packages/studio/src/player/lib/pausedVideoProvider.ts index 362be8f3c6..f2f900b45f 100644 --- a/packages/studio/src/player/lib/pausedVideoProvider.ts +++ b/packages/studio/src/player/lib/pausedVideoProvider.ts @@ -64,6 +64,7 @@ export function pausedFrameHost( let decoder: Promise | null = null; let files: Promise> | null = null; const inFlight = new Map(); + let lastSettled = Promise.resolve(); let closed = false; const reply = (message: unknown, transfer: Transferable[] = []) => { if (!closed) port.postMessage(message, transfer); @@ -95,28 +96,44 @@ export function pausedFrameHost( reply({ type: "frames", id, frames: wire }, images); }; - const refusal = (asks: PausedFrameAsk[]) => { - if (inFlight.size > 0) return "Preview decoder busy"; - return asks.length === 0 || asks.length > PAUSED_FRAME_SOURCES - ? "Preview decode over budget" - : null; + const replaceOlder = () => { + for (const [older, control] of inFlight) { + if (control.signal.aborted) continue; + control.abort(); + reply({ type: "failed", id: older, message: "Preview decode replaced" }); + } + }; + + const nextTurn = () => { + const previous = lastSettled; + let settled = () => {}; + lastSettled = new Promise((resolve) => (settled = resolve)); + return { previous, settled }; + }; + + const decodeAndSend = async (id: number, asks: PausedFrameAsk[], signal: AbortSignal) => { + const resolved = await Promise.all(asks.map(resolveAsk)); + decoder ??= (deps.decoder ?? loadDecoder)(); + const frames = await (await decoder).decode(resolved, signal); + await send(id, frames, signal).finally(() => frames.forEach((f) => f.release())); }; const decode = async (id: number, asks: PausedFrameAsk[]) => { - const refused = refusal(asks); - if (refused) return reply({ type: "failed", id, message: refused }); + if (asks.length === 0 || asks.length > PAUSED_FRAME_SOURCES) + return reply({ type: "failed", id, message: "Preview decode over budget" }); + replaceOlder(); const control = new AbortController(); inFlight.set(id, control); + const { previous, settled } = nextTurn(); try { - const resolved = await Promise.all(asks.map(resolveAsk)); - decoder ??= (deps.decoder ?? loadDecoder)(); - const frames = await (await decoder).decode(resolved, control.signal); - await send(id, frames, control.signal).finally(() => frames.forEach((f) => f.release())); + await previous; + if (!control.signal.aborted) await decodeAndSend(id, asks, control.signal); } catch (error) { if (!control.signal.aborted) reply({ type: "failed", id, message: String((error as Error)?.message ?? error) }); } finally { if (inFlight.get(id) === control) inFlight.delete(id); + settled(); } }; From d4e8d6f983aa03ae88dfe99d2ffad1f35cb1d373 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 13:18:31 +0000 Subject: [PATCH 121/367] fix(core): a preview of hundreds of clips with no set length no longer loads them all (#8303) * test(core): a preview's far clip with no set length loads only its length and gives its decoder back * fix(core): a preview frees a far clip with no set length once it knows its length * fix(core): every timeline read of a clip's length keeps the one it reported before a release * test(core): the released clip's length is read through the runtime's own resolver * refactor(core): an animated element's clip reads its own attributes in one place * test(core): a far clip with no set length is held to its length, now that armed clips prefetch * refactor(core): the far-clip load handler keeps its own comment --- packages/core/src/runtime/entry.test.ts | 38 +++++++++++++++++++++++-- packages/core/src/runtime/init.ts | 26 +++++++++++++++-- 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/packages/core/src/runtime/entry.test.ts b/packages/core/src/runtime/entry.test.ts index 78f1b31fc8..bc027bdb3c 100644 --- a/packages/core/src/runtime/entry.test.ts +++ b/packages/core/src/runtime/entry.test.ts @@ -533,6 +533,39 @@ describe("runtime entry", () => { expect(loadsOf(now!)).toEqual([1]); }); + // fails without the fix: a preview loaded every clip with no authored length in full, so a film of hundreds ran + // the page out of memory. + it("in a preview a far clip with no authored length loads only its length, then gives its decoder back and keeps the length", async () => { + spyLoad(); + servePreview(); + const clips = videos(mountRoot(), "0", "1.5", "6"); + for (const clip of clips) clip.removeAttribute("data-duration"); + const [now, soon, later] = clips as [HTMLVideoElement, HTMLVideoElement, HTMLVideoElement]; + later.setAttribute("src", "later.mp4"); + + await evaluateRuntime(); + expect(armed(now, soon)).toEqual([true, true]); + // A clip the window arms loads whole ("auto"); this one only its length. + expect(later.preload).toBe("metadata"); + expect(loadsOf(later)).toEqual([1]); + + Object.defineProperty(later, "readyState", { value: 1, configurable: true }); + Object.defineProperty(later, "duration", { value: 2, configurable: true }); + later.dispatchEvent(new Event("loadedmetadata")); + // Freed by a reload with its src dropped and put back, as a clip the playhead left is. + expect(later.preload).toBe("none"); + expect(loadsOf(later)).toEqual([2]); + expect(later.getAttribute("src")).toBe("later.mp4"); + + // The released clip reports no length again; the timeline keeps the one it reported, for that src only. + Object.defineProperty(later, "readyState", { value: 0, configurable: true }); + Object.defineProperty(later, "duration", { value: Number.NaN, configurable: true }); + const { resolveMediaElementDurationSeconds } = await import("./playbackRate"); + expect(resolveMediaElementDurationSeconds(later)).toBe(2); + later.setAttribute("src", "other.mp4"); + expect(resolveMediaElementDurationSeconds(later)).toBeNull(); + }); + // Three takes of one file, each a picture and a sound, as an edit cut from a single source is. const takesOfOneFile = () => { const root = mountRoot(); @@ -639,7 +672,7 @@ describe("runtime entry", () => { expect(armed(now, soon)).toEqual([true, false]); }); - it("loads a clip with no authored length as a render does, so no reload drops its duration", async () => { + it("loads a due clip with no authored length whole and a far one's length only, so no reload drops a duration", async () => { spyLoad(); servePreview(); const [untrimmed, later] = videos(mountRoot(), "0", "8"); @@ -652,7 +685,8 @@ describe("runtime entry", () => { window.__player?.seek(3.6); window.__player?.seek(0.5); window.__player?.seek(7.5); - expect(armed(untrimmed, later)).toEqual([true, true]); + expect(untrimmed.preload).toBe("auto"); + expect(later.preload).toBe("metadata"); expect(loadsOf(untrimmed, later)).toEqual([1, 1]); }); diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts index f6e13592f1..4762558005 100644 --- a/packages/core/src/runtime/init.ts +++ b/packages/core/src/runtime/init.ts @@ -2754,9 +2754,23 @@ export function initSandboxRuntimeModular(): void { // Chromium's software decoders cost threads per loaded video; WebKit's reload of a shared file stalls audio. const freesBufferedVideo = (el: unknown): el is HTMLVideoElement => isVideoElement(el) && !isWebKit(); + // A preview's video with no set length loads its length first; once known, the window decides it. + const learnsLength = (el: unknown): el is HTMLVideoElement => + mediaDeferred && + loadsAhead && + freesBufferedVideo(el) && + el.hasAttribute("data-start") && + !lengthIsAuthored(el); + // Clips that loaded their length; the document's timing listener (sourceLength.ts) keeps it, and runs first. + const learned = new WeakSet(); // A far clip can finish a load the parser started before its window was decided. const onMediaLoadedWhileFar = (event: Event) => { const el = event.currentTarget; + if (learnsLength(el) && !learned.has(el)) { + learned.add(el); + syncTimedElementVisibility(state.currentTime, [el]); + return; + } if (!freesBufferedVideo(el) || mediaNearPlayhead.get(el) !== false || el.readyState === 0) return; el.preload = "none"; @@ -2861,7 +2875,13 @@ export function initSandboxRuntimeModular(): void { // Studio's preview loads a timed clip only near the playhead; the visibility pass decides. if (inPreloadWindow(mediaEl)) nearPlayheadPending.push(mediaEl); - else preloadMedia(mediaEl); + else if ( + learnsLength(mediaEl) && + resolveAbsoluteMediaStartSeconds(mediaEl) > state.currentTime + LOOKAHEAD_SECONDS + ) { + mediaEl.preload = "metadata"; + mediaEl.load(); + } else preloadMedia(mediaEl); // Probe volume automation from the GSAP timeline — same approach as the // renderer (see discoverAudioVolumeAutomationFromTimeline / audioMixer). @@ -3134,7 +3154,9 @@ export function initSandboxRuntimeModular(): void { const inPreloadWindow = (el: HTMLMediaElement) => mediaDeferred && el.hasAttribute("data-start") && - (lengthIsAuthored(el) || (!loadsAhead && el.readyState === HTMLMediaElement.HAVE_NOTHING)); + (lengthIsAuthored(el) || + (learnsLength(el) && learned.has(el) && Number.isFinite(sourceLengthOf(el))) || + (!loadsAhead && el.readyState === HTMLMediaElement.HAVE_NOTHING)); // Media on screen or due within the look-ahead loads; the rest stops holding a connection to // the origin that also serves Studio's thumbnails. From 3ac5265aac9fc495244ab077c6b2dc425488c84d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 13:24:12 +0000 Subject: [PATCH 122/367] fix(studio): Studio acts on a sealed preview's key report only after a real press or click (#8503) * test(studio): a sealed preview's key reports act only after a real press * fix(studio): Studio acts on a sealed preview's key report only after a real press or click --- .../useAppHotkeys.previewForwarding.test.tsx | 126 ++++++++++++++++-- packages/studio/src/hooks/useAppHotkeys.ts | 9 +- 2 files changed, 121 insertions(+), 14 deletions(-) diff --git a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx index d2ed775cd1..a79f1bbc5c 100644 --- a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx +++ b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx @@ -17,6 +17,7 @@ import { serveEditingRequests, } from "../player/hooks/timelinePlayerTestHarness"; import { previewRequest } from "../player/lib/previewChannel"; +import { parseCombo } from "@hyperframes/core/key-combo"; vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); @@ -26,6 +27,21 @@ const domDelete = vi.fn(async () => undefined); const historyUndo = vi.fn(async () => ({ ok: false })); const historyRedo = vi.fn(async () => ({ ok: false })); const settle = vi.fn(async () => undefined); +const changes = { + timelineDelete: vi.fn(async () => undefined), + split: vi.fn(async () => undefined), + write: vi.fn(async () => undefined), + copy: vi.fn(() => false), + paste: vi.fn(() => false), + cut: vi.fn(() => false), + duplicate: vi.fn(async () => false), + group: vi.fn(), + ungroup: vi.fn(), + record: vi.fn(), + resetKeyframes: vi.fn(() => false), + deleteKeyframes: vi.fn(), +}; +let readOnlyPreview = false; let root: Root | null = null; let sync: ((iframe: HTMLIFrameElement | null) => void) | null = null; @@ -44,8 +60,8 @@ function selection(): DomEditSelection { function Harness() { const selectionRef = useRef(selection()); const hotkeys = useAppHotkeys({ - handleTimelineElementsDelete: vi.fn(async () => undefined), - handleTimelineElementSplit: vi.fn(async () => undefined), + handleTimelineElementsDelete: changes.timelineDelete, + handleTimelineElementSplit: changes.split, handleDomEditElementDelete: domDelete, domEditSelectionRef: selectionRef, clearDomSelectionRef: useRef<() => void>(() => undefined), @@ -56,15 +72,20 @@ function Harness() { }, readOptionalProjectFile: vi.fn(async () => ""), readProjectFile: vi.fn(async () => ""), - writeProjectFile: vi.fn(async () => undefined), + writeProjectFile: changes.write, showToast: vi.fn(), syncHistoryPreviewAfterApply: vi.fn(async () => undefined), settlePendingEdits: settle, - handleCopy: vi.fn(() => false), - handlePaste: vi.fn(() => false), - handleCut: vi.fn(() => false), - onResetKeyframes: vi.fn(() => false), - onDeleteSelectedKeyframes: vi.fn(), + handleCopy: changes.copy, + handlePaste: changes.paste, + handleCut: changes.cut, + handleDuplicate: changes.duplicate, + onGroupSelection: changes.group, + onUngroupSelection: changes.ungroup, + onToggleRecording: changes.record, + onResetKeyframes: changes.resetKeyframes, + onDeleteSelectedKeyframes: changes.deleteKeyframes, + readOnlyPreview, onAfterUndoRedo: vi.fn(), } as unknown as Parameters[0]); sync = hotkeys.syncPreviewHotkeys; @@ -77,6 +98,8 @@ afterEach(() => { document.body.innerHTML = ""; usePlayerStore.getState().reset(); domDelete.mockClear(); + for (const change of Object.values(changes)) change.mockClear(); + readOnlyPreview = false; historyUndo.mockClear(); historyRedo.mockClear(); settle.mockReset(); @@ -182,7 +205,13 @@ describe("preview iframe hotkey forwarding", () => { afterEach(() => closers.splice(0).forEach((close) => close())); // A frame whose document refuses Studio, reached only over the editing port it hands out per connect. - async function sealedFrame(focus = { inPreview: true }, { inPlayer = false } = {}) { + async function sealedFrame( + focus = { inPreview: true }, + { + inPlayer = false, + activation = { queued: [] as boolean[], otherwise: true, reads: 0 }, + } = {}, + ) { const frame: Record = {}; const iframe = detachedFakeIframe(frame); const loaded = new Promise((resolve) => @@ -203,7 +232,17 @@ describe("preview iframe hotkey forwarding", () => { configurable: true, get: () => (!focus.inPreview ? document.body : inPlayer ? player : iframe), }); + // Studio's own window: active only after a real press or click, in the frame or out of it. + Object.defineProperty(window.navigator, "userActivation", { + configurable: true, + get: () => { + activation.reads += 1; + const isActive = activation.queued.shift() ?? activation.otherwise; + return { isActive, hasBeenActive: isActive }; + }, + }); closers.push(() => { + delete (window.navigator as { userActivation?: unknown }).userActivation; hasFocus.mockRestore(); delete (document as { activeElement?: unknown }).activeElement; player.remove(); @@ -229,6 +268,23 @@ describe("preview iframe hotkey forwarding", () => { (port) => ports.push(port), ), ); + const report = (combo: string) => { + const { mod, meta, ctrl, shift, alt, key } = parseCombo(combo)!; + ports.at(-1)!.postMessage({ + v: 1, + event: "key", + key: { + type: "keydown", + key, + code: "", + altKey: alt, + ctrlKey: ctrl, + metaKey: mod || meta, + shiftKey: shift, + repeat: false, + }, + }); + }; const keyDown = (key: string, code: string) => ports.at(-1)!.postMessage({ v: 1, @@ -245,7 +301,7 @@ describe("preview iframe hotkey forwarding", () => { }, }); await loaded; - return { iframe, watched, ports, keyDown, hasFocus }; + return { iframe, watched, ports, keyDown, report, hasFocus }; } it("leaves Studio's own reads of the preview answered while it forwards keys", async () => { @@ -298,6 +354,56 @@ describe("preview iframe hotkey forwarding", () => { expect(hasFocus).toHaveBeenCalledTimes(2); }); + const changesMade = () => + [domDelete, historyUndo, historyRedo, ...Object.values(changes)].reduce( + (n, spy) => n + spy.mock.calls.length, + 0, + ); + + // fails without the fix: focus in the frame was taken as a person's press, so every report below acted. + it.each([false, true])( + "acts on no app shortcut the frame reports with no real press (read-only preview: %s)", + async (readOnly) => { + readOnlyPreview = readOnly; + usePlayerStore.setState({ + selectedElementIds: new Set(["clip-a"]), + selectedElementId: "clip-a", + }); + root = mountReactHarness(); + // Each report Studio reads is unpressed, then the real Delete after them is pressed. + const activation = { + queued: APP_HOTKEY_ACTIONS.map(() => false), + otherwise: true, + reads: 0, + }; + const { iframe, watched, report, keyDown } = await sealedFrame( + { inPreview: true }, + { inPlayer: true, activation }, + ); + act(() => sync?.(iframe)); + await vi.waitFor(() => expect(watched).toHaveLength(1)); + for (const action of APP_HOTKEY_ACTIONS) report(DEFAULT_STUDIO_KEYS[action]); + keyDown("Delete", "Delete"); + await vi.waitFor(() => expect(activation.reads).toBe(APP_HOTKEY_ACTIONS.length + 1)); + await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(readOnly ? 0 : 1)); + expect(changesMade()).toBe(readOnly ? 0 : 1); + expect(usePlayerStore.getState().selectedElementId).toBe("clip-a"); + }, + ); + + // Known gap, by decision: a report forged within a real press's activation window (about 5 s) still acts. + it("still acts on a forged report while a real press's activation lasts", async () => { + root = mountReactHarness(); + const { iframe, watched, report } = await sealedFrame( + { inPreview: true }, + { inPlayer: true }, + ); + act(() => sync?.(iframe)); + await vi.waitFor(() => expect(watched).toHaveLength(1)); + report(DEFAULT_STUDIO_KEYS.undo); + await vi.waitFor(() => expect(historyUndo).toHaveBeenCalledTimes(1)); + }); + it("stops watching on the preview's next load, from a new port", async () => { root = mountReactHarness(); const { iframe, watched, ports } = await sealedFrame(); diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts index 015f13cc1f..185fe6ded4 100644 --- a/packages/studio/src/hooks/useAppHotkeys.ts +++ b/packages/studio/src/hooks/useAppHotkeys.ts @@ -39,12 +39,13 @@ function forwardSealedFrameKeys(iframe: HTMLIFrameElement, onKeyDown: (e: Keyboa const watchApp = () => watch(APP_HOTKEY_ACTIONS.map(getStudioKey)); watchApp(); const stopRebinds = subscribeStudioKeys(watchApp); - // The frame can report keys nobody pressed: act only while the person is in the preview. - const focused = () => + // The frame can report keys and take focus, but only a real press or click activates Studio's own window. + const pressedByPerson = () => iframe.ownerDocument.hasFocus() && - (iframe.getRootNode() as Document | ShadowRoot).activeElement === iframe; + (iframe.getRootNode() as Document | ShadowRoot).activeElement === iframe && + iframe.ownerDocument.defaultView?.navigator.userActivation?.isActive === true; const stopKeys = client.onKey((key) => { - if (key.type === "keydown" && focused()) onKeyDown(new KeyboardEvent(key.type, key)); + if (key.type === "keydown" && pressedByPerson()) onKeyDown(new KeyboardEvent(key.type, key)); }); return () => { stopRebinds(); From 479081658b011b09a173bc45bf3564dbff5ee091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 13:56:25 +0000 Subject: [PATCH 123/367] chore: release v0.9.81 (#8493) * chore: release v0.9.81 * chore: release v0.9.81 notes list the changes merged since the draft * chore: release v0.9.81 notes list the changes merged since the draft --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- docs/changelog.mdx | 77 ++++++++++++++++++++++++ gemini-extension.json | 2 +- 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/inspector/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/share/package.json | 2 +- packages/studio-server/package.json | 2 +- packages/studio/package.json | 2 +- plugin.json | 2 +- releases/v0.9.81.md | 76 +++++++++++++++++++++++ 22 files changed, 173 insertions(+), 20 deletions(-) create mode 100644 releases/v0.9.81.md diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index eee92e764d..4439acdde4 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 capture for HyperFrames.", - "version": "0.9.80", + "version": "0.9.81", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index cffa7c67b0..54195a93ad 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "hyperframes", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.", - "version": "0.9.80", + "version": "0.9.81", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index d7ed6d6d79..33c0a0f0be 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -3,7 +3,7 @@ "name": "hyperframes", "displayName": "HyperFrames by HeyGen", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.", - "version": "0.9.80", + "version": "0.9.81", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com" diff --git a/docs/changelog.mdx b/docs/changelog.mdx index c90ace5759..01fea7f766 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -8,6 +8,83 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio {/* New release entries are prepended by `bun run changelog:draft --write`. */} + +A heavy page now renders without running out of memory: a render starts only as many browsers as fit. Sealed previews take more edits in place, from moves and crops to undo and hotkeys. + +## Fixes + +- **Studio:** Studio acts on a sealed preview's key report only after a real press or click ([3ac5265aac](https://github.com/heygen-com/hyperframes/commit/3ac5265aac9fc495244ab077c6b2dc425488c84d), [#8503](https://github.com/heygen-com/hyperframes/pull/8503)). +- **Core:** A preview of hundreds of clips with no set length no longer loads them all ([d4e8d6f983](https://github.com/heygen-com/hyperframes/commit/d4e8d6f983aa03ae88dfe99d2ffad1f35cb1d373), [#8303](https://github.com/heygen-com/hyperframes/pull/8303)). +- **Studio:** Scrubbing across a cut shows the newest frame, not black ([0e6879b8ef](https://github.com/heygen-com/hyperframes/commit/0e6879b8efea57f588ed835fab56f9211e0cfcde), [#8501](https://github.com/heygen-com/hyperframes/pull/8501)). +- **Studio:** Copy and duplicate refuse a file that is not one of the project's compositions ([45674e840f](https://github.com/heygen-com/hyperframes/commit/45674e840f6a3155ba761f7b31330910eba556cc), [#8490](https://github.com/heygen-com/hyperframes/pull/8490)). +- **Studio:** A sealed preview's clips keep their GSAP transition label ([97b90d8fa2](https://github.com/heygen-com/hyperframes/commit/97b90d8fa2b9e7c475e30e0e9a91f49418d1aedb), [#8499](https://github.com/heygen-com/hyperframes/pull/8499)). +- **Studio:** A sealed press held across a frame swap starts on the frame shown ([a770f4b85d](https://github.com/heygen-com/hyperframes/commit/a770f4b85dd73e60d7880c630fc3514877d0c611), [#8492](https://github.com/heygen-com/hyperframes/pull/8492)). +- **Studio:** Paste and duplicate write only allowed markup unless it comes from the same file ([0b73069201](https://github.com/heygen-com/hyperframes/commit/0b73069201b7771078c63c92db0e5b73d99e4dd7), [#8483](https://github.com/heygen-com/hyperframes/pull/8483)). +- **Studio:** Rotating a layer in a sealed preview turns it from the angle its stylesheet shows ([039eca4f0f](https://github.com/heygen-com/hyperframes/commit/039eca4f0fa9e12e3a6e1a20386f655f319d89ea), [#8469](https://github.com/heygen-com/hyperframes/pull/8469)). +- **Studio:** A menu that does not fit below opens above, never over what opened it ([679a5a7e0b](https://github.com/heygen-com/hyperframes/commit/679a5a7e0b8d6ecc75ac79c3780d814b0d2bb40d), [#8406](https://github.com/heygen-com/hyperframes/pull/8406)). +- **Studio Server:** A cut names its new half from the file's own id ([fccd00e719](https://github.com/heygen-com/hyperframes/commit/fccd00e719c5ab8d95baf531248a64ecc6a14a3f), [#8481](https://github.com/heygen-com/hyperframes/pull/8481)). +- **Ci:** A shard whose results never uploaded is re-run, and never read as an edit accuracy drop ([71588b0a73](https://github.com/heygen-com/hyperframes/commit/71588b0a73485efc66f00d7abb72e0328547de53), [#8477](https://github.com/heygen-com/hyperframes/pull/8477)). +- **Studio:** A pasted element lands after its own original, never inside a script ([bfd6cb755f](https://github.com/heygen-com/hyperframes/commit/bfd6cb755f9ea4caface8532c865f9f1ddaa00e6), [#8489](https://github.com/heygen-com/hyperframes/pull/8489)). +- **Core:** A preview seek waits for each graded video to draw its new frame ([104eab37ad](https://github.com/heygen-com/hyperframes/commit/104eab37ad38f75336290655e54308d319a4d3e9), [#8488](https://github.com/heygen-com/hyperframes/pull/8488)). +- **Core:** A far clip the runtime lets go of keeps counting in the film's length ([5ae70826ed](https://github.com/heygen-com/hyperframes/commit/5ae70826edba1babb96e57d99be9699c45f0c1d9), [#8480](https://github.com/heygen-com/hyperframes/pull/8480)). +- **Player:** A sealed film no longer shows failed to load while its runtime starts ([835e660e0e](https://github.com/heygen-com/hyperframes/commit/835e660e0e3ec98893ef3ace94385d045f790e14), [#8472](https://github.com/heygen-com/hyperframes/pull/8472)). +- **Studio:** A sealed preview shows paused video frames from Studio's decoder ([61008a40dd](https://github.com/heygen-com/hyperframes/commit/61008a40dd91ca41b70b78757ced98ecf3daa31d), [#8466](https://github.com/heygen-com/hyperframes/pull/8466)). +- **Studio:** A drag behind a refused edit is refused only when it would land on a clip ([c99cbbe44d](https://github.com/heygen-com/hyperframes/commit/c99cbbe44d92deca1345aac73729fa29828757c9), [#8456](https://github.com/heygen-com/hyperframes/pull/8456)). +- **Studio:** A sealed Layers pick of a cropped layer puts its resize corners on the whole layer ([f57552da49](https://github.com/heygen-com/hyperframes/commit/f57552da49c3426e3af641c086fa5cdd25fd595a), [#8468](https://github.com/heygen-com/hyperframes/pull/8468)). +- **Ci:** A rerun of the captures check reads the PR's current body ([8f7e59742f](https://github.com/heygen-com/hyperframes/commit/8f7e59742f700119875eba1d08d265eae3bd83d0), [#8479](https://github.com/heygen-com/hyperframes/pull/8479)). +- **Studio:** A sealed move or resize ends its draft in the save's own frame message ([7e26a6d3c0](https://github.com/heygen-com/hyperframes/commit/7e26a6d3c0ac6df0e9cc881b8e3009046ff47015), [#8473](https://github.com/heygen-com/hyperframes/pull/8473)). +- **Core:** Load the motion path plugin only for a page that tweens along a path ([4157992664](https://github.com/heygen-com/hyperframes/commit/4157992664d3a9bd456594252fb7a5061ff45c27), [#8449](https://github.com/heygen-com/hyperframes/pull/8449)). +- **Studio:** A thrown value whose name getter throws still falls back to a reload ([f51e57b26e](https://github.com/heygen-com/hyperframes/commit/f51e57b26ea1526ee3f5a3ce6b3838243b801087), [#8474](https://github.com/heygen-com/hyperframes/pull/8474)). +- **Engine:** A heavy page starts only as many capture browsers as the machine's memory holds ([969eeba6ee](https://github.com/heygen-com/hyperframes/commit/969eeba6eea5d04daa50586a62871d2861130513), [#8452](https://github.com/heygen-com/hyperframes/pull/8452)). +- **Studio:** A timeline edit queued before a project switch stays in its own project ([3e101f9654](https://github.com/heygen-com/hyperframes/commit/3e101f9654033d73d47ac8a791d0f98c80755226), [#8458](https://github.com/heygen-com/hyperframes/pull/8458)). +- **Studio:** A sealed crop draws a layer's insets at its own scale and follows a seek ([05d1bc8b1c](https://github.com/heygen-com/hyperframes/commit/05d1bc8b1c1cbff2fcb447a36da5b5db4e7bad79), [#8451](https://github.com/heygen-com/hyperframes/pull/8451)). +- **Studio:** An in-place tween patch that throws says why it fell back to a reload ([e98ca56c4a](https://github.com/heygen-com/hyperframes/commit/e98ca56c4abe575b88ca76566e85773cf378438b), [#8454](https://github.com/heygen-com/hyperframes/pull/8454)). +- **Studio:** A sealed resize keeps a self-centring layer where it is ([926e1b5601](https://github.com/heygen-com/hyperframes/commit/926e1b560178651346b18c0dfb105589d61a1419), [#8467](https://github.com/heygen-com/hyperframes/pull/8467)). +- **Studio:** An undo or redo that adds a sealed page's first edit stays in place ([2d72e523ff](https://github.com/heygen-com/hyperframes/commit/2d72e523ff3e82e2e840be0daa954480a0bcfe14), [#8462](https://github.com/heygen-com/hyperframes/pull/8462)). +- **Studio:** Hiding an element hides it in the preview, sealed or not ([d37563e35b](https://github.com/heygen-com/hyperframes/commit/d37563e35be60098c0c87be831ae0ebc921f0b0f), [#8461](https://github.com/heygen-com/hyperframes/pull/8461)). +- **Studio:** A ripple shift queued behind a refused edit is refused before it writes ([56e0d6fbd7](https://github.com/heygen-com/hyperframes/commit/56e0d6fbd7fbaa4f668ac940b95089347d1f274e), [#8443](https://github.com/heygen-com/hyperframes/pull/8443)). +- **Studio:** A reloaded preview shows the saved grade, not one an undo took back ([5e6068e94a](https://github.com/heygen-com/hyperframes/commit/5e6068e94a82d35815611cbecfa8830c3441a348), [#8455](https://github.com/heygen-com/hyperframes/pull/8455)). +- **Studio:** A sealed canvas pick selects the timeline clip it belongs to ([ff01d81be1](https://github.com/heygen-com/hyperframes/commit/ff01d81be1691c8b97803c6d49d0109367928d20), [#8459](https://github.com/heygen-com/hyperframes/pull/8459)). +- **Studio:** A key pressed in a sealed preview reaches Studio's hotkeys ([34d5c4678d](https://github.com/heygen-com/hyperframes/commit/34d5c4678d4fcfdbe21d9185984b6d97577dadce), [#8444](https://github.com/heygen-com/hyperframes/pull/8444)). +- **CLI:** A crashed or encoder-failed render tells Desktop its code ([678fda62cd](https://github.com/heygen-com/hyperframes/commit/678fda62cda998f5b117271d8a542f901100cfd1), [#8434](https://github.com/heygen-com/hyperframes/pull/8434)). +- **Studio:** A preview clip's track is taken only as a whole number ([bf21bf9f78](https://github.com/heygen-com/hyperframes/commit/bf21bf9f78fca5220fee2e7f4025322efb0c304d), [#8447](https://github.com/heygen-com/hyperframes/pull/8447)). +- **Studio:** A colour grade made in the property panel saves to the file ([77f3b55fd3](https://github.com/heygen-com/hyperframes/commit/77f3b55fd3adf09c1579a582eae216c73c6d15be), [#8450](https://github.com/heygen-com/hyperframes/pull/8450)). +- **Studio:** Moving and nudging an element works in a sealed preview ([eea73b3107](https://github.com/heygen-com/hyperframes/commit/eea73b3107466de54cd79e4e973e1e5a3c83c2d4), [#8263](https://github.com/heygen-com/hyperframes/pull/8263)). +- **Share:** Names print as plain text in the terminal, and a saved owner address must be a real address ([d09a1809c1](https://github.com/heygen-com/hyperframes/commit/d09a1809c1eaca2b7da08eb84b47e49eeae95bd2), [#8341](https://github.com/heygen-com/hyperframes/pull/8341)). +- **Studio:** Timeline clips from the preview keep numeric fields, and drops write them as numbers ([59ea053f10](https://github.com/heygen-com/hyperframes/commit/59ea053f1004f730714488b485fe7c98c443adb1), [#8438](https://github.com/heygen-com/hyperframes/pull/8438)). +- **Studio:** Caption edits save through the project's file writer ([0774d96462](https://github.com/heygen-com/hyperframes/commit/0774d96462ab3e1145ac5186a3cbba98426f75f0), [#8445](https://github.com/heygen-com/hyperframes/pull/8445)). +- **Studio:** A preview clip's track, start and length enter the timeline only as numbers ([e1845e5dec](https://github.com/heygen-com/hyperframes/commit/e1845e5dec6409633cac00937fdd77650ff08085), [#8446](https://github.com/heygen-com/hyperframes/pull/8446)). +- **Studio:** The topology lens shows in a sealed preview ([79e43a33a8](https://github.com/heygen-com/hyperframes/commit/79e43a33a87dc3b178c7969c6ceaae7efd33b8b4), [#8420](https://github.com/heygen-com/hyperframes/pull/8420)). +- **Media Use:** A manifest path naming a share or another root is refused without looking at it ([2a24357338](https://github.com/heygen-com/hyperframes/commit/2a243573389f4410794689d2db526dbf24ba2720), [#8437](https://github.com/heygen-com/hyperframes/pull/8437)). +- **Studio:** A refused delete also refuses the ripple shifts queued behind it ([925cea1f1f](https://github.com/heygen-com/hyperframes/commit/925cea1f1f59bfde0d507c3575791f77a775939f), [#8421](https://github.com/heygen-com/hyperframes/pull/8421)). +- **Studio:** A reload that gives up says whether its frame was missing, blank or unreadable ([8ad7cbae24](https://github.com/heygen-com/hyperframes/commit/8ad7cbae247661d38638e0b4ae0569288ab1ffa5), [#8419](https://github.com/heygen-com/hyperframes/pull/8419)). +- **Studio:** Show a sealed composition's clip on the timeline ([28502224a5](https://github.com/heygen-com/hyperframes/commit/28502224a57631af0894d9a6e2bb6cd9aa9449cd), [#8408](https://github.com/heygen-com/hyperframes/pull/8408)). +- **Media Use:** Refuse links under .media before reserving, writing or recording ([0495a57f76](https://github.com/heygen-com/hyperframes/commit/0495a57f764c8b67460db711cf34e509c2860c1d), [#8327](https://github.com/heygen-com/hyperframes/pull/8327)). + +## Docs & Examples + +- **README:** Lead with what HyperFrames makes, keep every developer section ([84ff7d71c2](https://github.com/heygen-com/hyperframes/commit/84ff7d71c28798538f33be2009d51dc22fae9794), [#8442](https://github.com/heygen-com/hyperframes/pull/8442)). + +## Internal + +- **CLI:** Run the PowerShell round-trip names in one shell so slow Windows runners stay in time ([680c9a5402](https://github.com/heygen-com/hyperframes/commit/680c9a5402c5524137763d7ce7ff33dc32589d4e), [#8498](https://github.com/heygen-com/hyperframes/pull/8498)). +- **CLI:** The doctor output test no longer runs every machine check ([aa262c244d](https://github.com/heygen-com/hyperframes/commit/aa262c244dbe1250356f36fc08d25cfa6c2d15ad), [#8497](https://github.com/heygen-com/hyperframes/pull/8497)). +- **Studio:** The preview regression runs green against a sealed preview ([3a68f7b3ca](https://github.com/heygen-com/hyperframes/commit/3a68f7b3ca5c2ae99b8cf039b0576f3e457a66d9), [#8470](https://github.com/heygen-com/hyperframes/pull/8470)). +- **Studio:** The edit-accuracy bench reads what a person ends with after sealed saves and undos ([bc3d7b43e8](https://github.com/heygen-com/hyperframes/commit/bc3d7b43e852c694a5c465a69392dd35b46fe1cd), [#8475](https://github.com/heygen-com/hyperframes/pull/8475)). +- **Studio:** The preview regression counts decoded covers, not the macOS gamma filter ([154842851a](https://github.com/heygen-com/hyperframes/commit/154842851acc143bdafa74707992103460369ae7), [#8484](https://github.com/heygen-com/hyperframes/pull/8484)). +- **Windows:** Run the engine and CLI tests in three shards, not two, to stay under the step deadline ([a638c31aa1](https://github.com/heygen-com/hyperframes/commit/a638c31aa1a0cd44a02019930a0cf506f28bef72), [#8476](https://github.com/heygen-com/hyperframes/pull/8476)). +- **Studio:** A preview clip's number and track rules live in one place ([deb478a3f6](https://github.com/heygen-com/hyperframes/commit/deb478a3f630aaf4ba5eeb77b497c7e4be9e8656), [#8471](https://github.com/heygen-com/hyperframes/pull/8471)). +- **Studio:** Chrome-driven tests run alone after the unit tests ([c731046c77](https://github.com/heygen-com/hyperframes/commit/c731046c775f484959f33859488bbf98ccbd5dc6), [#8440](https://github.com/heygen-com/hyperframes/pull/8440)). +- A studio change with no visible effect can say so at any size ([a0b76d20fb](https://github.com/heygen-com/hyperframes/commit/a0b76d20fb687eff5c1036134006a1a618895ea3), [#8439](https://github.com/heygen-com/hyperframes/pull/8439)). +- **CLI:** A missed late SVG image in snapshot says which wait came up short ([826b4fcc69](https://github.com/heygen-com/hyperframes/commit/826b4fcc69f3adf33c068e095504f496f13e48af), [#8435](https://github.com/heygen-com/hyperframes/pull/8435)). + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.9.80...v0.9.81). + + Date: Sun, 22 Nov 2026 14:17:09 +0000 Subject: [PATCH 124/367] test(cli): the sign-in return test waits for each window's navigation instead of one second (#8507) --- .../cli/src/commands/oauthReturn.browser.test.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/commands/oauthReturn.browser.test.ts b/packages/cli/src/commands/oauthReturn.browser.test.ts index 039954ff66..8b2e6412a4 100644 --- a/packages/cli/src/commands/oauthReturn.browser.test.ts +++ b/packages/cli/src/commands/oauthReturn.browser.test.ts @@ -49,7 +49,6 @@ async function readReturnAddress(origin: string): Promise expect(await page.evaluate(() => location.origin)).toBe(origin); return await page.evaluate( async (back, viaAuthorize) => { - const settle = () => new Promise((done) => setTimeout(done, 1000)); const read = (w: Window | null) => { if (!w) return "no window"; if (w.closed) return "severed"; @@ -69,13 +68,19 @@ async function readReturnAddress(origin: string): Promise const frameViaAuthorize = framed(viaAuthorize); const popup = open(back); const popupViaAuthorize = open(viaAuthorize); - await settle(); - const seen = { + const readAll = () => ({ frame: read(frame.contentWindow), frameViaAuthorize: read(frameViaAuthorize.contentWindow), popup: read(popup), popupViaAuthorize: read(popupViaAuthorize), - }; + }); + // Each window starts on about:blank, which this page can read; wait until every navigation has landed. + const deadline = Date.now() + 20_000; + let seen = readAll(); + while (Object.values(seen).includes("about:blank") && Date.now() < deadline) { + await new Promise((done) => setTimeout(done, 50)); + seen = readAll(); + } popup?.close(); popupViaAuthorize?.close(); return seen; From 85261137849f8e050c904e508810e7d8292b00d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 14:21:42 +0000 Subject: [PATCH 125/367] fix(producer): a render that stops while preparing names the step it stopped in (#8506) --- .../services/render/stages/probeStage.test.ts | 23 +++++++- .../src/services/render/stages/probeStage.ts | 53 +++++++++++++------ 2 files changed, 59 insertions(+), 17 deletions(-) diff --git a/packages/producer/src/services/render/stages/probeStage.test.ts b/packages/producer/src/services/render/stages/probeStage.test.ts index 7bc573e83e..dad0f6ec24 100644 --- a/packages/producer/src/services/render/stages/probeStage.test.ts +++ b/packages/producer/src/services/render/stages/probeStage.test.ts @@ -36,6 +36,7 @@ let mediaPreflightComposition: unknown; let afterMediaPreflight: (() => void) | null = null; let fileServerCloseCallCount = 0; let browserMediaResults: unknown[] = []; +let browserMediaError: Error | null = null; type MockSession = { id: number; @@ -207,7 +208,10 @@ mock.module("../../fileServer.js", () => ({ })); mock.module("../../htmlCompiler.js", () => ({ - discoverMediaFromBrowser: async () => browserMediaResults, + discoverMediaFromBrowser: async () => { + if (browserMediaError) throw browserMediaError; + return browserMediaResults; + }, discoverAudioVolumeAutomationFromTimeline: async () => [], discoverVideoVisibilityFromTimeline: async () => [], recompileWithResolutions: async (c: unknown) => c, @@ -1870,3 +1874,20 @@ describe("reportedLengthSource", () => { expect(reportedLengthSource(null)).toBeNull(); }); }); + +describe("runProbeStage — a page call that never answers", () => { + it("says which probe step stopped, keeping the browser's own words", async () => { + resetRetryMocks(); + browserMediaError = new Error( + "Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.", + ); + const { runProbeStage } = await import("./probeStage.js"); + try { + await expect(runProbeStage(makeProbeInput({}))).rejects.toThrow( + "Preparing the render stopped while listing the film's videos, audio and images: Runtime.callFunctionOn timed out.", + ); + } finally { + browserMediaError = null; + } + }); +}); diff --git a/packages/producer/src/services/render/stages/probeStage.ts b/packages/producer/src/services/render/stages/probeStage.ts index 8679108c3c..f79567fed6 100644 --- a/packages/producer/src/services/render/stages/probeStage.ts +++ b/packages/producer/src/services/render/stages/probeStage.ts @@ -489,6 +489,19 @@ export function reportedLengthSource( return { from: "media", tag: source.tag, trimmed: source.trimmed, srcHash }; } +const STOPPED = "Preparing the render stopped while "; + +/** A failed page call says which probe step it was, so a hung one is named in the render's error. */ +async function probeStep(step: string, call: () => Promise): Promise { + try { + return await call(); + } catch (error) { + if (error instanceof Error && !error.message.startsWith(STOPPED)) + error.message = `${STOPPED}${step}: ${error.message}`; + throw error; + } +} + export async function runProbeStage(input: ProbeStageInput): Promise { const { projectDir, @@ -616,7 +629,8 @@ export async function runProbeStage(input: ProbeStageInput): Promise initializeSession(opening)); } finally { clearInterval(heartbeat); } @@ -710,7 +724,8 @@ export async function runProbeStage(input: ProbeStageInput): Promise initializeSession(reopening)); assertNotAborted(); lastBrowserConsole = probeSession.browserConsoleBuffer; } @@ -725,8 +740,12 @@ export async function runProbeStage(input: ProbeStageInput): Promise + getCompositionDuration(session), + ); + lengthSource = reportedLengthSource( + await probeStep("reading the film's length", () => getCompositionLengthSource(session)), + ); assertNotAborted(); log.info("Probed composition duration from browser", { discoveredDuration, @@ -742,9 +761,8 @@ export async function runProbeStage(input: ProbeStageInput): Promise 0) { - const resolutions = await resolveCompositionDurations( - session.page, - compiled.unresolvedCompositions, + const resolutions = await probeStep("reading each scene's length", () => + resolveCompositionDurations(session.page, compiled.unresolvedCompositions), ); assertNotAborted(); if (resolutions.length > 0) { @@ -767,7 +785,9 @@ export async function runProbeStage(input: ProbeStageInput): Promise + discoverMediaFromBrowser(session.page), + ); assertNotAborted(); if (browserMedia.length > 0) { const existingVideoIds = new Set(composition.videos.map((v) => v.id)); @@ -921,11 +941,13 @@ export async function runProbeStage(input: ProbeStageInput): Promise audio.id), - composition.duration, - fpsToNumber(job.config.fps), + const automation = await probeStep("reading the audio's volume changes", () => + discoverAudioVolumeAutomationFromTimeline( + session.page, + composition.audios.map((audio) => audio.id), + composition.duration, + fpsToNumber(job.config.fps), + ), ); assertNotAborted(); if (automation.length > 0) { @@ -947,9 +969,8 @@ export async function runProbeStage(input: ProbeStageInput): Promise + discoverVideoVisibilityFromTimeline(session.page, composition.duration), ); assertNotAborted(); From f03233ab4d1efcaaa677fd82fcad3a96bb46f9ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 14:23:33 +0000 Subject: [PATCH 126/367] fix(studio-server): previewing a page with thousands of media files no longer stalls the app (#8505) * fix(studio-server): previewing a page with thousands of media files no longer stalls the app Building a preview recorded each file the build read, and each file the page names, by walking its path with blocking link reads, one file at a time. A page naming 20,000 media files held the server's event loop for over a second, and the app froze while the preview loaded. The build now collects those paths and records them off the event loop in one batch per step, reading each shared folder once per batch. * fix(studio-server): a preview still loads when its project folder cannot be resolved Recording a build's reads resolved the project folder with a reader that fails on a folder it cannot resolve (a link loop, no permission), so a finished bundle turned into a failed build and the sub-composition route answered a server error. The folder now resolves the way the per-read recorder resolves it, and recording never fails its caller. --- .../studio-server/src/helpers/previewReads.ts | 40 ++++-- .../src/routes/preview.readsOffLoop.test.ts | 125 ++++++++++++++++++ .../src/routes/preview.recordClosed.test.ts | 2 +- packages/studio-server/src/routes/preview.ts | 24 ++-- 4 files changed, 170 insertions(+), 21 deletions(-) create mode 100644 packages/studio-server/src/routes/preview.readsOffLoop.test.ts diff --git a/packages/studio-server/src/helpers/previewReads.ts b/packages/studio-server/src/helpers/previewReads.ts index 52de4eedc2..d75c9b56bd 100644 --- a/packages/studio-server/src/helpers/previewReads.ts +++ b/packages/studio-server/src/helpers/previewReads.ts @@ -75,9 +75,12 @@ function walkNow(walk: LinkWalk): string[] { return step.value; } -async function walkOff(walk: LinkWalk): Promise { +async function walkOff( + walk: LinkWalk, + readLink: (path: string) => Promise, +): Promise { let step = walk.next(); - while (!step.done) step = walk.next(await readLinkOff(step.value)); + while (!step.done) step = walk.next(await readLink(step.value)); return step.value; } @@ -99,13 +102,32 @@ export function recordPreviewRead(projectDir: string, filePath: string): void { remember(realProject, read, walkNow(linksOnTheWay(read))); } -/** `recordPreviewRead` for a route that reads its project off the event loop. */ -export async function recordPreviewReadOff(projectDir: string, filePath: string): Promise { - if (filePath.length > MAX_PREVIEW_PATH_LENGTH) return; - const realProject = await realFilePathOff(resolve(projectDir)); - const read = inReal(realProject, projectDir, filePath); - if (read.length > MAX_PREVIEW_PATH_LENGTH) return; - remember(realProject, read, await walkOff(linksOnTheWay(read))); +/** `recordPreviewRead` for each of `filePaths`, off the event loop; a folder they share is read once per call. */ +export async function recordPreviewReadsOff( + projectDir: string, + filePaths: Iterable, +): Promise { + const realProject = await realFilePathOff(resolve(projectDir)).catch(() => + realFilePath(resolve(projectDir)), + ); + const links = new Map>(); + const readLinkOnce = (path: string) => { + let target = links.get(path); + if (!target) links.set(path, (target = readLinkOff(path))); + return target; + }; + const pending = filePaths[Symbol.iterator](); + const recordNext = async () => { + for (let next = pending.next(); !next.done; next = pending.next()) { + const filePath = next.value; + if (filePath.length > MAX_PREVIEW_PATH_LENGTH) continue; + const read = inReal(realProject, projectDir, filePath); + if (read.length > MAX_PREVIEW_PATH_LENGTH) continue; + remember(realProject, read, await walkOff(linksOnTheWay(read), readLinkOnce)); + } + }; + // Enough walks in flight to keep the fs thread pool (4 threads by default) busy. + await Promise.all(Array.from({ length: 16 }, recordNext)); } export function previewReferences(html: string): Set { diff --git a/packages/studio-server/src/routes/preview.readsOffLoop.test.ts b/packages/studio-server/src/routes/preview.readsOffLoop.test.ts new file mode 100644 index 0000000000..fc28400f1a --- /dev/null +++ b/packages/studio-server/src/routes/preview.readsOffLoop.test.ts @@ -0,0 +1,125 @@ +// @vitest-environment node +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { monitorEventLoopDelay } from "node:perf_hooks"; +import { Hono } from "hono"; +import { afterEach, expect, it } from "vitest"; +import { affectsPreview } from "../helpers/previewReads"; +import type { StudioApiAdapter } from "../types"; +import { registerPreviewRoutes } from "./preview"; + +const FILES = 20_000; +let root = ""; +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const adapter = (dir: string, bundle: StudioApiAdapter["bundle"]): StudioApiAdapter => ({ + listProjects: () => [], + resolveProject: async (id: string) => ({ id, dir }), + bundle, + lint: async () => ({ findings: [] }), + runtimeUrl: "/api/runtime.js", + rendersDir: () => "/tmp/renders", + startRender: () => ({ + id: "job-1", + status: "rendering", + progress: 0, + outputPath: "/tmp/out.mp4", + }), +}); + +// The histogram has no sample for work that starts in the tick it was enabled in, so wait for one first. +async function longestHoldMs(work: () => Promise): Promise { + const delay = monitorEventLoopDelay({ resolution: 10 }); + delay.enable(); + while (delay.count === 0) await new Promise(setImmediate); + await work(); + const seen = delay.count; + while (delay.count === seen) await new Promise(setImmediate); + delay.disable(); + return delay.max / 1e6; +} + +const pageNaming = (files: string[]) => + `${files.map((file) => ``).join("")}`; + +// fails without the fix: the build walked each of its 40,000 reads with blocking readlinks (a 1.7 s hold). +it("builds a preview of a page naming 20,000 media files without holding the event loop", async () => { + root = mkdtempSync(join(tmpdir(), "preview-reads-")); + // In a linked library, which the project's signature does not list, so the build's own reads are what is timed. + const library = join(root, "library"); + const projectDir = join(root, "project"); + mkdirSync(library); + mkdirSync(projectDir); + symlinkSync(library, join(projectDir, "media"), "junction"); + const files = Array.from({ length: FILES }, (_, i) => `media/clip-${i}.png`); + for (let i = 0; i < FILES; i++) writeFileSync(join(library, `clip-${i}.png`), ""); + const html = pageNaming(files); + writeFileSync(join(projectDir, "index.html"), html); + const app = new Hono(); + registerPreviewRoutes( + app, + adapter(projectDir, async (dir, options) => { + for (const file of files) options?.onRead?.(join(dir, file)); + return html; + }), + ); + + let status = 0; + const hold = await longestHoldMs(async () => { + status = (await app.request("http://localhost/projects/demo/preview")).status; + }); + + expect(status).toBe(200); + expect(hold).toBeLessThan(200); + expect(affectsPreview(projectDir, join(library, `clip-${FILES - 1}.png`))).toBe(true); +}); + +// fails without the fix: the build failed and the sub-composition route answered a server error. +it.skipIf(process.platform === "win32")( + "still answers when the project folder's real path cannot be resolved", + async () => { + root = mkdtempSync(join(tmpdir(), "preview-reads-")); + const projectDir = join(root, "loop"); + symlinkSync("loop", projectDir); + const html = pageNaming(["media/a.png"]); + const app = new Hono(); + registerPreviewRoutes( + app, + adapter(projectDir, async () => html), + ); + + expect((await app.request("http://localhost/projects/demo/preview")).status).toBe(200); + expect( + (await app.request("http://localhost/projects/demo/preview/comp/scene.html")).status, + ).toBe(404); + }, +); + +it.skipIf(process.platform === "win32")( + "counts a change behind a symlinked folder the build read through", + async () => { + const projectDir = (root = realpathSync(mkdtempSync(join(tmpdir(), "preview-reads-")))); + mkdirSync(join(projectDir, "shared", "clips"), { recursive: true }); + writeFileSync(join(projectDir, "shared", "clips", "a.png"), ""); + writeFileSync(join(projectDir, "shared", "clips", "b.png"), ""); + symlinkSync("shared/clips", join(projectDir, "media")); + const html = pageNaming(["media/a.png"]); + writeFileSync(join(projectDir, "index.html"), html); + const app = new Hono(); + registerPreviewRoutes( + app, + adapter(projectDir, async (dir, options) => { + options?.onRead?.(join(dir, "media", "b.png")); + return html; + }), + ); + + expect((await app.request("http://localhost/projects/demo/preview")).status).toBe(200); + + expect(affectsPreview(projectDir, "media")).toBe(true); + expect(affectsPreview(projectDir, "shared/clips/a.png")).toBe(true); + expect(affectsPreview(projectDir, "shared/clips/b.png")).toBe(true); + expect(affectsPreview(projectDir, "shared/clips/c.png")).toBe(false); + }, +); diff --git a/packages/studio-server/src/routes/preview.recordClosed.test.ts b/packages/studio-server/src/routes/preview.recordClosed.test.ts index 46c1671ca0..d7b00575f8 100644 --- a/packages/studio-server/src/routes/preview.recordClosed.test.ts +++ b/packages/studio-server/src/routes/preview.recordClosed.test.ts @@ -8,7 +8,7 @@ import type { StudioApiAdapter } from "../types"; // A path that stops resolving between the private-file check and the read's record (a link swapped for a loop). vi.mock("../helpers/previewReads.js", async (importOriginal) => ({ ...(await importOriginal()), - recordPreviewReadOff: () => Promise.reject(Object.assign(new Error("ELOOP"), { code: "ELOOP" })), + recordPreviewReadsOff: () => Promise.reject(Object.assign(new Error("ELOOP"), { code: "ELOOP" })), })); const { createStudioApi } = await import("../createStudioApi"); diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index de6f8aa71f..ae93aca6e4 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -86,7 +86,7 @@ import { settledFileTag } from "../helpers/fileVersion.js"; import { recordPreviewBuilt, recordPreviewRead, - recordPreviewReadOff, + recordPreviewReadsOff, } from "../helpers/previewReads.js"; import { isVariablesPayload, VARIABLES_PAYLOAD_ERROR } from "../helpers/variablesPayload.js"; import { injectPreviewVariables } from "../helpers/previewVariables.js"; @@ -631,11 +631,14 @@ export function registerPreviewRoutes( const diskMain = resolveProjectMainHtml(project.dir, project.id); try { - let bundled = await adapter.bundle(project.dir, { - stampHfIds: true, - onRead: (filePath) => recordPreviewRead(project.dir, filePath), - privateFiles: "studio", - }); + const reads: string[] = []; + let bundled = await adapter + .bundle(project.dir, { + stampHfIds: true, + onRead: (filePath) => reads.push(filePath), + privateFiles: "studio", + }) + .finally(() => recordPreviewReadsOff(project.dir, reads)); let mainCompositionPath = "index.html"; if (!bundled) { if (!diskMain) return null; @@ -650,7 +653,7 @@ export function registerPreviewRoutes( mainCompositionPath, ); bundled = based.html; - for (const path of based.references) recordPreviewRead(project.dir, path); + await recordPreviewReadsOff(project.dir, based.references); recordPreviewBuilt(project.dir); // The passes that parse the page run on the build worker (a capture page builds while a film plays); the @@ -802,9 +805,8 @@ export function registerPreviewRoutes( project.dir, requestSubPath(c.req.url, "projects/:id/preview/comp"), ); - if (compFile) recordPreviewRead(project.dir, compFile); // The sub-composition document takes its head from the root. - recordPreviewRead(project.dir, "index.html"); + await recordPreviewReadsOff(project.dir, compFile ? [compFile, "index.html"] : ["index.html"]); if (!compFile || !existsSync(compFile) || !statSync(compFile).isFile()) { return c.text("not found", 404); } @@ -837,7 +839,7 @@ export function registerPreviewRoutes( ); if (!built) return c.text("not found", 404); if ("refused" in built) return c.html(previewRefusalPage(built.refused), 200); - for (const path of built.references) recordPreviewRead(project.dir, path); + await recordPreviewReadsOff(project.dir, built.references); const transformed = await withinDeadline( transformPreviewHtml(built.html, adapter, project, compPath), deadline, @@ -888,7 +890,7 @@ export function registerPreviewRoutes( if (!file || (await isPrivateProjectFileOff(project.dir, file))) { return c.text("not found", 404); } - const recorded = await recordPreviewReadOff(project.dir, file).then( + const recorded = await recordPreviewReadsOff(project.dir, [file]).then( () => true, () => false, ); From 4a47c33ea36970ac288662ac40ec7790590ce9d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 14:58:03 +0000 Subject: [PATCH 127/367] fix(core): a far clip whose source is swapped learns its new length (#8509) * fix(core): a far clip whose source is swapped learns its new length * test(core): the swapped-source case names a freed clip, not the proxy fallback --- packages/core/src/runtime/entry.test.ts | 32 +++++++++++++++++++ packages/core/src/runtime/init.ts | 41 ++++++++++++++----------- 2 files changed, 55 insertions(+), 18 deletions(-) diff --git a/packages/core/src/runtime/entry.test.ts b/packages/core/src/runtime/entry.test.ts index bc027bdb3c..5627792cfd 100644 --- a/packages/core/src/runtime/entry.test.ts +++ b/packages/core/src/runtime/entry.test.ts @@ -672,6 +672,38 @@ describe("runtime entry", () => { expect(armed(now, soon)).toEqual([true, false]); }); + // A src set on a clip already freed left it at preload="none" with no length for the new src: out of its window, + // the timeline lost its length until the playhead reached it. + it("a far clip whose src is swapped after its length was learned learns the new length, then is freed again", async () => { + spyLoad(); + servePreview(); + const clips = videos(mountRoot(), "0", "6"); + for (const clip of clips) clip.removeAttribute("data-duration"); + const later = clips[1] as HTMLVideoElement; + later.setAttribute("src", "later.mp4"); + await evaluateRuntime(); + const metadata = (seconds: number) => { + Object.defineProperty(later, "readyState", { value: 1, configurable: true }); + Object.defineProperty(later, "duration", { value: seconds, configurable: true }); + later.dispatchEvent(new Event("loadedmetadata")); + }; + metadata(2); + expect([later.preload, loadsOf(later)[0]]).toEqual(["none", 2]); + + Object.defineProperty(later, "readyState", { value: 0, configurable: true }); + Object.defineProperty(later, "duration", { value: Number.NaN, configurable: true }); + later.setAttribute("src", "other.mp4"); + window.__player?.seek(0.5); + expect([later.preload, loadsOf(later)[0]]).toEqual(["metadata", 3]); + + metadata(3); + expect([later.preload, loadsOf(later)[0]]).toEqual(["none", 4]); + expect(later.getAttribute("src")).toBe("other.mp4"); + const { resolveMediaElementDurationSeconds } = await import("./playbackRate"); + Object.defineProperty(later, "duration", { value: Number.NaN, configurable: true }); + expect(resolveMediaElementDurationSeconds(later)).toBe(3); + }); + it("loads a due clip with no authored length whole and a far one's length only, so no reload drops a duration", async () => { spyLoad(); servePreview(); diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts index 4762558005..d56d008752 100644 --- a/packages/core/src/runtime/init.ts +++ b/packages/core/src/runtime/init.ts @@ -2761,13 +2761,25 @@ export function initSandboxRuntimeModular(): void { freesBufferedVideo(el) && el.hasAttribute("data-start") && !lengthIsAuthored(el); - // Clips that loaded their length; the document's timing listener (sourceLength.ts) keeps it, and runs first. - const learned = new WeakSet(); + // The src each clip loaded its length for; the document's timing listener (sourceLength.ts) keeps it, and runs first. + const learned = new WeakMap(); + const knowsLength = (el: HTMLMediaElement) => learned.get(el) === el.src; + const armLength = (el: HTMLMediaElement) => { + if ( + learnsLength(el) && + resolveAbsoluteMediaStartSeconds(el) > state.currentTime + LOOKAHEAD_SECONDS + ) { + el.preload = "metadata"; + el.load(); + } else preloadMedia(el); + }; + const swappedAfterLearning = (el: HTMLMediaElement) => + learnsLength(el) && learned.has(el) && !knowsLength(el) && el.preload === "none"; // A far clip can finish a load the parser started before its window was decided. const onMediaLoadedWhileFar = (event: Event) => { const el = event.currentTarget; - if (learnsLength(el) && !learned.has(el)) { - learned.add(el); + if (learnsLength(el) && !knowsLength(el)) { + learned.set(el, el.src); syncTimedElementVisibility(state.currentTime, [el]); return; } @@ -2875,13 +2887,7 @@ export function initSandboxRuntimeModular(): void { // Studio's preview loads a timed clip only near the playhead; the visibility pass decides. if (inPreloadWindow(mediaEl)) nearPlayheadPending.push(mediaEl); - else if ( - learnsLength(mediaEl) && - resolveAbsoluteMediaStartSeconds(mediaEl) > state.currentTime + LOOKAHEAD_SECONDS - ) { - mediaEl.preload = "metadata"; - mediaEl.load(); - } else preloadMedia(mediaEl); + else armLength(mediaEl); // Probe volume automation from the GSAP timeline — same approach as the // renderer (see discoverAudioVolumeAutomationFromTimeline / audioMixer). @@ -3155,7 +3161,7 @@ export function initSandboxRuntimeModular(): void { mediaDeferred && el.hasAttribute("data-start") && (lengthIsAuthored(el) || - (learnsLength(el) && learned.has(el) && Number.isFinite(sourceLengthOf(el))) || + (learnsLength(el) && knowsLength(el) && Number.isFinite(sourceLengthOf(el))) || (!loadsAhead && el.readyState === HTMLMediaElement.HAVE_NOTHING)); // Media on screen or due within the look-ahead loads; the rest stops holding a connection to @@ -3547,12 +3553,11 @@ export function initSandboxRuntimeModular(): void { if (upcoming && !rawNode.hasAttribute(STUDIO_PREVIEW_UPCOMING_ATTR)) loadPreviewImagesIn(rawNode); rawNode.toggleAttribute(STUDIO_PREVIEW_UPCOMING_ATTR, upcoming); - if ( - !seekOwnsMedia && - isMediaElement(rawNode) && - metadataBoundMedia.has(rawNode) && - inPreloadWindow(rawNode) - ) + const managed = !seekOwnsMedia && isMediaElement(rawNode) && metadataBoundMedia.has(rawNode); + if (managed && swappedAfterLearning(rawNode)) { + mediaNearPlayhead.delete(rawNode); + armLength(rawNode); + } else if (managed && inPreloadWindow(rawNode)) preloadNearPlayhead( rawNode, isVisibleNow, From 2b1495f7aff642e23a571217ad7f8bdc7d5533fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 14:59:34 +0000 Subject: [PATCH 128/367] fix(studio): a cropped layer's outline is cut at the layer's own scale, sealed or not (#8496) * fix(studio): a cropped layer's outline is cut at the layer's own scale, sealed or not * fix(core): the geometry stream keeps an element whose geometry now carries its layout size * fix(studio): a turned layer's crop is cut at its own scale, not its upright box's --- .../src/runtime/editing/watchGeometry.test.ts | 5 ++ .../core/src/runtime/editing/watchGeometry.ts | 7 ++- packages/core/src/runtime/editingElement.ts | 1 + packages/core/src/runtime/editingGeometry.ts | 7 +++ .../core/src/runtime/editingGestureStart.ts | 7 +-- packages/core/src/runtime/editingPort.ts | 3 +- .../components/editor/domEditOverlayCrop.ts | 52 ++++++++++++++---- .../editor/domEditOverlayGeometry.ts | 4 ++ .../editor/previewOverlayRects.test.ts | 53 ++++++++++++++++++- .../components/editor/previewOverlayRects.ts | 17 +++++- .../studio/src/hooks/useCropOverlay.test.ts | 22 +++++++- packages/studio/src/hooks/useCropOverlay.ts | 33 ++++-------- .../studio/src/player/lib/previewElements.ts | 18 +++---- 13 files changed, 175 insertions(+), 54 deletions(-) diff --git a/packages/core/src/runtime/editing/watchGeometry.test.ts b/packages/core/src/runtime/editing/watchGeometry.test.ts index 5da70c89b0..dcd8e3658d 100644 --- a/packages/core/src/runtime/editing/watchGeometry.test.ts +++ b/packages/core/src/runtime/editing/watchGeometry.test.ts @@ -67,6 +67,11 @@ describe("geometryEvent", () => { push({}, { ...element, members: [{ ...element.rect, z: 0 }] }), push({}, { ...element, corners: { nw: { x: 0, y: 0 } } }), push({}, { ...element, source: { width: 1, height: 1, declaredWidth: null } }), + push({}, { ...element, layout: { width: -1, height: 1 } }), + push({}, { ...element, layout: { width: 1, height: 100_001 } }), + push({}, { ...element, layout: { width: "1", height: 1 } }), + push({}, { ...element, layout: { width: 1, height: 1, depth: 1 } }), + push({}, { ...element, layout: undefined }), ]) expect(geometryEvent(bad, 1)).toBeNull(); }); diff --git a/packages/core/src/runtime/editing/watchGeometry.ts b/packages/core/src/runtime/editing/watchGeometry.ts index 2c5a10fd53..2e958f1af2 100644 --- a/packages/core/src/runtime/editing/watchGeometry.ts +++ b/packages/core/src/runtime/editing/watchGeometry.ts @@ -2,6 +2,7 @@ // stamped on the clock both windows share, until an empty list, the page hiding, or the parent's release. import { EDITING_ELEMENT_HANDLE, + MAX_DRAFT_PX, MAX_ELEMENT_ENTRIES, MAX_ELEMENT_VALUE, type EditingElementHandle, @@ -47,14 +48,18 @@ const isSource = (value: unknown) => finiteOrNull(value.declaredHeight)); const isClipPath = (value: unknown) => value === null || (typeof value === "string" && value.length <= MAX_ELEMENT_VALUE); +const isLayout = (value: unknown) => + keysAre(value, "height,width") && + [value.width, value.height].every((side) => finite(side) && side >= 0 && side <= MAX_DRAFT_PX); const isMembers = (value: unknown) => value === null || (Array.isArray(value) && value.length <= MAX_ELEMENT_ENTRIES && value.every(isRect)); function isGeometry(value: unknown): value is EditingElementGeometry { - if (!keysAre(value, "angle,clipPath,corners,members,rect,source,visible")) return false; + if (!keysAre(value, "angle,clipPath,corners,layout,members,rect,source,visible")) return false; return ( isRect(value.rect) && + isLayout(value.layout) && finite(value.angle) && isCorners(value.corners) && isSource(value.source) && diff --git a/packages/core/src/runtime/editingElement.ts b/packages/core/src/runtime/editingElement.ts index 9b6e9ca7a2..87339c17a7 100644 --- a/packages/core/src/runtime/editingElement.ts +++ b/packages/core/src/runtime/editingElement.ts @@ -62,6 +62,7 @@ export interface EditingElementMatch { export const MAX_ELEMENT_ENTRIES = 256; export const MAX_ELEMENT_TEXT = 10_000; export const MAX_ELEMENT_VALUE = 2_000; +export const MAX_DRAFT_PX = 100_000; export const MAX_SOURCE_GROUPS = 64; export const MAX_DESCRIBE_HANDLES = 256; export const MAX_POINT_STACK = 64; diff --git a/packages/core/src/runtime/editingGeometry.ts b/packages/core/src/runtime/editingGeometry.ts index 7536d2a83e..5244b0c970 100644 --- a/packages/core/src/runtime/editingGeometry.ts +++ b/packages/core/src/runtime/editingGeometry.ts @@ -32,6 +32,7 @@ export interface EditingElementBox { } | null; /** Inline `clip-path`, else the computed one; null when longer than MAX_ELEMENT_VALUE. */ clipPath: string | null; + layout: { width: number; height: number }; } export interface EditingElementGeometry extends EditingElementBox { @@ -201,6 +202,11 @@ function clipPathOf(element: HTMLElement): string | null { return value.length <= MAX_ELEMENT_VALUE ? value : null; } +function layoutOf(element: Element): EditingElementBox["layout"] { + const { offsetWidth = 0, offsetHeight = 0 } = element as Partial; + return { width: offsetWidth, height: offsetHeight }; +} + const finiteCorners = (corners: EditingCorners | null) => corners && Object.values(corners).every((p) => Number.isFinite(p.x) && Number.isFinite(p.y)) ? corners @@ -220,6 +226,7 @@ export function boxOf( corners: finiteCorners(corners), source: sourceOf(element), clipPath: clipPathOf(element), + layout: layoutOf(element), }; } diff --git a/packages/core/src/runtime/editingGestureStart.ts b/packages/core/src/runtime/editingGestureStart.ts index 5842df302f..3634c9c6d7 100644 --- a/packages/core/src/runtime/editingGestureStart.ts +++ b/packages/core/src/runtime/editingGestureStart.ts @@ -25,8 +25,6 @@ import { import { elementForHandle } from "./editingHandles"; export interface EditingGestureStart extends EditingElementGeometry { - /** The transform-free border box a resize grows from. */ - layout: { width: number; height: number }; /** Frame px its centre moves per px of translate, columns `a, b` (x) and `c, d` (y); null when it does not move measurably. */ move: { a: number; b: number; c: number; d: number } | null; /** Frame px its centre moves per px of drawn width, `a, b`, and height, `c, d`; null when it has no box. */ @@ -193,14 +191,11 @@ export function gestureStart(handles: readonly EditingElementHandle[]): { const starts = elements.map((geometry, i) => { const element = pressed[i]; if (!geometry || !isStylableElement(element)) return null; - const { offsetWidth = 0, offsetHeight = 0 } = element as Partial; - const layout = { width: offsetWidth, height: offsetHeight }; const rotation = gsapRotation(element); return { ...geometry, - layout, move: measureMoveResponse(element), - grow: measureGrowResponse(element, layout), + grow: measureGrowResponse(element, geometry.layout), gsap: gsapPosition(element), gsapRotation: rotation, cssRotation: rotation === null ? readCssRotationStart(element as HTMLElement) : null, diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index 7f66d5bbb3..a8a7d3b27a 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -19,6 +19,7 @@ import { import { EDITING_ELEMENT_HANDLE, MAX_DESCRIBE_HANDLES, + MAX_DRAFT_PX, type EditingElementDescription, type EditingElementHandle, type EditingElementHit, @@ -237,7 +238,7 @@ export interface EditingRuntimeSnapshot { clipParents: Array<[string, string]>; } -export const MAX_DRAFT_PX = 100_000; +export { MAX_DRAFT_PX }; export const MAX_DRAFT_DEG = 36_000; export const MAX_WATCHED_KEYS = 32; diff --git a/packages/studio/src/components/editor/domEditOverlayCrop.ts b/packages/studio/src/components/editor/domEditOverlayCrop.ts index 846044a9b0..8bd3b74ec9 100644 --- a/packages/studio/src/components/editor/domEditOverlayCrop.ts +++ b/packages/studio/src/components/editor/domEditOverlayCrop.ts @@ -1,5 +1,7 @@ import { composeElementTransform, + elementCornerPoints, + readElementTransformSnapshot, type PlanarTransformOps, } from "@hyperframes/core/runtime/editing-port"; import { @@ -247,26 +249,58 @@ export function resolveCropInsetFromMoveDrag(input: { /** Display-only hug: shrink a projected rect by the element's inset crop. * For rects nothing writes back to (e.g. the hover ring). */ -export function hugRectForElement( - rect: CropScreenRect & { editScaleX: number; editScaleY: number }, - element: HTMLElement, -): CropScreenRect { +export function hugRectForElement(rect: HugRect, element: HTMLElement): CropScreenRect { // A lifted clip shows the full element rect. - return isElementCropLifted(element) - ? rect - : hugRectForClipPath(rect, readElementClipPath(element)); + if (isElementCropLifted(element)) return rect; + return hugRectForClipPath( + rect, + readElementClipPath(element), + () => rect.ownScale ?? (previewStandIn(element) ? undefined : liveOwnScale(rect, element)), + ); } +type HugRect = CropScreenRect & { + editScaleX: number; + editScaleY: number; + ownScale?: { x: number; y: number }; + angle?: number; +}; + +/** A live element's own-axis scale: an oriented rect's edges, or its turned corners' edges over its upright box. */ +function liveOwnScale(rect: HugRect, element: HTMLElement): HugRect["ownScale"] { + const { offsetWidth: w, offsetHeight: h } = element; + if (!(w > 0 && h > 0)) return undefined; + const upright = { x: rect.width / w, y: rect.height / h }; + if (rect.angle !== undefined) return upright; + const win = element.ownerDocument.defaultView; + const transform = win && readElementTransformSnapshot(win, element); + const corners = transform && elementCornerPoints(win, element, transform); + const box = element.getBoundingClientRect(); + if (!corners || !(box.width > 0 && box.height > 0)) return upright; + const edge = (a: { x: number; y: number }, b: { x: number; y: number }) => + Math.hypot(b.x - a.x, b.y - a.y); + return { + x: (edge(corners.nw, corners.ne) / box.width) * upright.x, + y: (edge(corners.nw, corners.sw) / box.height) * upright.y, + }; +} + +const ownScaleXY = (own: HugRect["ownScale"], rect: HugRect): [number, number] => [ + own?.x ?? rect.editScaleX, + own?.y ?? rect.editScaleY, +]; + /** `hugRectForElement` for a clip-path read elsewhere; null is one that could not be read. */ export function hugRectForClipPath( - rect: CropScreenRect & { editScaleX: number; editScaleY: number }, + rect: HugRect, clipPath: string | null, + ownScaleOf: () => HugRect["ownScale"] = () => rect.ownScale, ): CropScreenRect { const insets = clipPath === null ? null : parseCropClipPath(clipPath); // Uneditable clip — show the full element rect. if (!insets || (insets.top <= 0 && insets.right <= 0 && insets.bottom <= 0 && insets.left <= 0)) return rect; - return cropRectFromInsets(rect, insets, rect.editScaleX, rect.editScaleY); + return cropRectFromInsets(rect, insets, ...ownScaleXY(ownScaleOf(), rect)); } /** diff --git a/packages/studio/src/components/editor/domEditOverlayGeometry.ts b/packages/studio/src/components/editor/domEditOverlayGeometry.ts index e75b0b9fda..5eb9b9e36a 100644 --- a/packages/studio/src/components/editor/domEditOverlayGeometry.ts +++ b/packages/studio/src/components/editor/domEditOverlayGeometry.ts @@ -26,6 +26,7 @@ export interface OverlayRect { height: number; editScaleX: number; editScaleY: number; + ownScale?: { x: number; y: number }; /** Live screen-space rotation; omitted for axis-aligned group bounds. */ angle?: number; } @@ -184,6 +185,7 @@ export function frameRectToOverlay( scale: OverlayRootScale, elementRect: { left: number; top: number; width: number; height: number }, source: FrameSource, + ownScale?: { x: number; y: number }, ): OverlayRect { const { iframeRect, overlayRect, rootScaleX, rootScaleY } = scale; const editScale = resolveDomEditCoordinateScale({ @@ -202,6 +204,7 @@ export function frameRectToOverlay( height: elementRect.height * rootScaleY, editScaleX: editScale.scaleX, editScaleY: editScale.scaleY, + ...(ownScale && { ownScale }), }; } @@ -345,6 +348,7 @@ export function orientOverlayRect( height, editScaleX: base.editScaleX, editScaleY: base.editScaleY, + ...(base.ownScale && { ownScale: base.ownScale }), angle, }; } diff --git a/packages/studio/src/components/editor/previewOverlayRects.test.ts b/packages/studio/src/components/editor/previewOverlayRects.test.ts index 0be5ac8022..6efdf0b3d4 100644 --- a/packages/studio/src/components/editor/previewOverlayRects.test.ts +++ b/packages/studio/src/components/editor/previewOverlayRects.test.ts @@ -179,8 +179,18 @@ const settled = async (overlay: Awaited>) => { return { overlayRect, childRects, group: groupOverlayItems.map((item) => item.rect), hoverRect }; }; -const close = (rect: OverlayRect | null) => - rect && Object.fromEntries(Object.entries(rect).map(([key, value]) => [key, +value.toFixed(9)])); +const rounded = (value: unknown): unknown => + typeof value === "number" + ? +value.toFixed(9) + : value && typeof value === "object" + ? Object.fromEntries(Object.entries(value).map(([key, v]) => [key, rounded(v)])) + : value; +// Drawn fields only: a live rect works out its own scale when it cuts a crop, a frame's arrives with it. +const close = (rect: OverlayRect | null) => { + if (!rect) return rect; + const { ownScale: _ownScale, ...drawn } = rect; + return rounded(drawn); +}; const closeAll = (shown: Awaited>) => ({ overlayRect: close(shown.overlayRect), childRects: shown.childRects.map(close), @@ -204,6 +214,45 @@ describe("overlay rects on an opaque frame match a scriptable one", () => { else expect(live.overlayRect).not.toBeNull(); }); + // fails without the fix: the hug cut the crop at the editor zoom alone, 175 px wide in both frames. + it("cuts a scaled layer's crop at its own scale, the same in both", async () => { + const grown = sized(document.createElement("div"), [1000, 100, 400, 200]); + grown.id = "grown"; + grown.style.setProperty("clip-path", "inset(0px 50px 0px 0px)"); + grown.style.setProperty("transform", "matrix(2, 0, 0, 2, 0, 0)"); + Object.defineProperty(grown, "offsetWidth", { value: 200, configurable: true }); + Object.defineProperty(grown, "offsetHeight", { value: 100, configurable: true }); + document.querySelector("[data-composition-id]")!.append(grown); + for (const frame of [liveFrame, opaqueFrame]) { + const { group } = await settled( + await overlayOn(frame(), { selection: null, group: ["grp", "grown"] }), + ); + expect(group[1]).toMatchObject({ width: 150, height: 100 }); + } + }); + + // fails without the fix: the cut took the turned layer's wider upright box as its scale, 167.4 px, not 173.2. + it("cuts a turned, scaled layer's crop at its own scale, not its upright box's, the same in both", async () => { + const [cos, sin] = [Math.cos(Math.PI / 6), Math.sin(Math.PI / 6)]; + const [width, height] = [2 * (200 * cos + 100 * sin), 2 * (200 * sin + 100 * cos)]; + const spun = sized(document.createElement("div"), [1000, 100, width, height]); + spun.id = "spun"; + spun.style.setProperty("clip-path", "inset(0px 50px 0px 0px)"); + spun.style.setProperty( + "transform", + `matrix(${2 * cos}, ${2 * sin}, ${-2 * sin}, ${2 * cos}, 0, 0)`, + ); + Object.defineProperty(spun, "offsetWidth", { value: 200, configurable: true }); + Object.defineProperty(spun, "offsetHeight", { value: 100, configurable: true }); + document.querySelector("[data-composition-id]")!.append(spun); + for (const frame of [liveFrame, opaqueFrame]) { + const { group } = await settled( + await overlayOn(frame(), { selection: null, group: ["grp", "spun"] }), + ); + expect(group[1]!.width).toBeCloseTo((width - 100) / 2, 6); + } + }); + it("covers what each case decides", async () => { const host = await settled( await overlayOn(opaqueFrame(), { diff --git a/packages/studio/src/components/editor/previewOverlayRects.ts b/packages/studio/src/components/editor/previewOverlayRects.ts index d832394427..e00ebe75cf 100644 --- a/packages/studio/src/components/editor/previewOverlayRects.ts +++ b/packages/studio/src/components/editor/previewOverlayRects.ts @@ -14,6 +14,7 @@ import { previewGeometry } from "../../player/lib/previewElements"; import { computeOverlayRootScale, type OverlayRootScale } from "./domEditOverlayBasis"; import { hugRectForClipPath } from "./domEditOverlayCrop"; import { + cornerEdgeLength, frameCornersToOverlay, frameRectToOverlay, orientOverlayRect, @@ -23,9 +24,23 @@ import { const clientRect = ({ x, y, width, height }: EditingRect) => ({ left: x, top: y, width, height }); +/** Overlay px per CSS px along the element's own edges, which a turn does not lengthen; undefined without a size. */ +function ownScaleOf(scale: OverlayRootScale, box: EditingElementBox) { + const { layout } = box; + if (!(layout.width > 0 && layout.height > 0)) return undefined; + const corners = box.corners && frameCornersToOverlay(scale, box.corners); + const width = corners + ? cornerEdgeLength(corners.nw, corners.ne) + : box.rect.width * scale.rootScaleX; + const height = corners + ? cornerEdgeLength(corners.nw, corners.sw) + : box.rect.height * scale.rootScaleY; + return { x: width / layout.width, y: height / layout.height }; +} + /** `toOverlayRect`. */ const baseRect = (scale: OverlayRootScale, box: EditingElementBox) => - frameRectToOverlay(scale, clientRect(box.rect), box.source); + frameRectToOverlay(scale, clientRect(box.rect), box.source, ownScaleOf(scale, box)); /** `orientedOverlayRect`. */ function orientedRect(scale: OverlayRootScale, box: EditingElementBox): OverlayRect { diff --git a/packages/studio/src/hooks/useCropOverlay.test.ts b/packages/studio/src/hooks/useCropOverlay.test.ts index 0cbd928bc3..0be03365ae 100644 --- a/packages/studio/src/hooks/useCropOverlay.test.ts +++ b/packages/studio/src/hooks/useCropOverlay.test.ts @@ -44,12 +44,12 @@ const rect: OverlayRect = { }; /** The selection box's crop hug as the overlay last drew it. */ -function drawn(element: HTMLElement) { +function drawn(element: HTMLElement, overlayRect: OverlayRect = rect) { const seen: Array = []; function Probe() { const { cropOutlineInsetPx } = useCropOverlay({ selection: { element } as DomEditSelection, - overlayRect: rect, + overlayRect, }); seen.push(cropOutlineInsetPx?.right ?? null); return null; @@ -71,6 +71,24 @@ it("a sealed layer picked with no press drops its crop hug once the crop handles expect(hug(), "a lift the frame refused leaves the crop showing").toBe(150); }); +// fails without the fix: the hug used the editor zoom alone, 150 where the layer's own 2x makes 300. +it.each([true, false])( + "a layer shown at twice its own size hugs its crop at that scale (sealed %s)", + (s) => { + sealed = s; + const element = document.body.appendChild(document.createElement("div")); + element.id = "grown"; + Object.defineProperty(element, "offsetWidth", { value: 200, configurable: true }); + Object.defineProperty(element, "offsetHeight", { value: 100, configurable: true }); + if (s) rememberFrameClipPath(element, "inset(0px 150px 0px 0px)", "inset(0px 150px 0px 0px)"); + else element.style.setProperty("clip-path", "inset(0px 150px 0px 0px)"); + // A frame's rect arrives with its own scale; a live element's is read off the element. + const hug = drawn(element, s ? { ...rect, ownScale: { x: 2, y: 2 } } : rect); + expect(hug()).toBe(300); + element.remove(); + }, +); + it("an unsealed layer's crop hug follows its lift and its drop", () => { sealed = false; const element = document.body.appendChild(document.createElement("div")); diff --git a/packages/studio/src/hooks/useCropOverlay.ts b/packages/studio/src/hooks/useCropOverlay.ts index 0d0eec6b1e..7b86be8a33 100644 --- a/packages/studio/src/hooks/useCropOverlay.ts +++ b/packages/studio/src/hooks/useCropOverlay.ts @@ -3,8 +3,7 @@ import type { OverlayRect } from "../components/editor/domEditOverlayGeometry"; import type { DomEditSelection } from "../components/editor/domEditing"; import { cropLiftsVersion, - isElementCropLifted, - readElementCropInsets, + hugRectForElement, subscribeCropLifts, } from "../components/editor/domEditOverlayCrop"; @@ -20,30 +19,18 @@ export function useCropOverlay(params: { const { selection, overlayRect } = params; useSyncExternalStore(subscribeCropLifts, cropLiftsVersion); - const cropInsets = - selection && !isElementCropLifted(selection.element) - ? readElementCropInsets(selection.element) - : null; - const hasCropInsets = Boolean( - cropInsets && - (cropInsets.top > 0 || cropInsets.right > 0 || cropInsets.bottom > 0 || cropInsets.left > 0), - ); - - // Scaled insets for the crop outline child. The box div stays border-less at - // full bounds; a child draws the outline ON the crop boundary (a clip on the - // box would swallow the border everywhere the crop edge doesn't touch the - // element edge). - const sx = overlayRect && overlayRect.editScaleX > 0 ? overlayRect.editScaleX : 1; - const sy = overlayRect && overlayRect.editScaleY > 0 ? overlayRect.editScaleY : 1; + // The box div stays border-less at full bounds; a child draws the outline ON the crop boundary (a clip on the box + // would swallow the border everywhere the crop edge doesn't touch the element edge). + const hug = selection && overlayRect ? hugRectForElement(overlayRect, selection.element) : null; const cropOutlineInsetPx = - cropInsets && hasCropInsets + hug && overlayRect && hug !== overlayRect ? { - top: cropInsets.top * sy, - right: cropInsets.right * sx, - bottom: cropInsets.bottom * sy, - left: cropInsets.left * sx, + top: hug.top - overlayRect.top, + right: overlayRect.left + overlayRect.width - (hug.left + hug.width), + bottom: overlayRect.top + overlayRect.height - (hug.top + hug.height), + left: hug.left - overlayRect.left, } : undefined; - return { hasCropInsets, cropOutlineInsetPx }; + return { hasCropInsets: Boolean(cropOutlineInsetPx), cropOutlineInsetPx }; } diff --git a/packages/studio/src/player/lib/previewElements.ts b/packages/studio/src/player/lib/previewElements.ts index e925ec15be..5396f9ca00 100644 --- a/packages/studio/src/player/lib/previewElements.ts +++ b/packages/studio/src/player/lib/previewElements.ts @@ -200,13 +200,20 @@ const isSourceBox = (value: unknown) => const isClipPath = isValueOrNull; +const isLayout = (value: unknown) => + isFields(value) && + [value.width, value.height].every( + (side) => Number.isFinite(side) && (side as number) >= 0 && (side as number) <= MAX_DRAFT_PX, + ); + const isBox = (value: unknown): value is EditingElementBox => isFields(value) && isRect(value.rect) && Number.isFinite(value.angle) && isCorners(value.corners) && isSourceBox(value.source) && - isClipPath(value.clipPath); + isClipPath(value.clipPath) && + isLayout(value.layout); const readGeometry = (value: unknown): EditingElementGeometry | null => { if (!isBox(value) || !isFields(value) || typeof value.visible !== "boolean") return null; @@ -248,12 +255,6 @@ const isFlag = (value: unknown) => typeof value === "boolean"; const isFiniteFields = (value: unknown, keys: string[]) => isFields(value) && keys.every((key) => Number.isFinite(value[key])); -const isLayout = (value: unknown) => - isFields(value) && - [value.width, value.height].every( - (side) => Number.isFinite(side) && (side as number) >= 0 && (side as number) <= MAX_DRAFT_PX, - ); - const isTurnOrNull = (value: unknown) => value === null || (Number.isFinite(value) && Math.abs(value as number) <= MAX_DRAFT_DEG); @@ -284,9 +285,8 @@ export type ReadGestureStart = Omit< const readGestureStart = (value: unknown): ReadGestureStart | null => { if (!readGeometry(value) || !isFields(value)) return null; - const { layout, move, gsap, gsapRotation, grow, cssRotation } = value; + const { move, gsap, gsapRotation, grow, cssRotation } = value; const valid = [ - isLayout(layout), move === null || isFiniteFields(move, ["a", "b", "c", "d"]), gsap === null || (isFields(gsap) && isFiniteFields(gsap, ["x", "y"]) && isFlag(gsap.moving)), ]; From dd7799037396404e4e9b7f2803072ac87dc2fcc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 15:06:47 +0000 Subject: [PATCH 129/367] fix(studio): the viewport gate tells a virtualized timeline by its mounted rows, not its clips (#8511) * test(studio): the viewport gate reads a virtualized timeline as on while its rows fill at load * fix(studio): the viewport gate tells a virtualized timeline by its mounted rows, not its clips --- .../tests/e2e/timeline-viewport-verdict.mjs | 5 +++++ .../e2e/timeline-viewport-verdict.test.mjs | 14 ++++++++++++++ .../tests/e2e/timeline-virtualization.mjs | 17 ++++++++--------- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/packages/studio/tests/e2e/timeline-viewport-verdict.mjs b/packages/studio/tests/e2e/timeline-viewport-verdict.mjs index 4437cb43e5..831b21fd7b 100644 --- a/packages/studio/tests/e2e/timeline-viewport-verdict.mjs +++ b/packages/studio/tests/e2e/timeline-viewport-verdict.mjs @@ -123,6 +123,11 @@ export function describeAgainstBase({ head, base, interactions, frameIntervals, ].join(", "); } +/** Which build is measured: a row-virtualized timeline mounts only the rows in view, an unvirtualized one every row. */ +export function rowVirtualizationOf({ mountedRows }, budgets) { + return mountedRows <= budgets.maxMountedRows ? "on" : "off"; +} + /** A failed timing attempt is measured once more, so one bad stretch of a shared runner cannot fail the gate alone. */ export const TIMING_ATTEMPTS = 2; diff --git a/packages/studio/tests/e2e/timeline-viewport-verdict.test.mjs b/packages/studio/tests/e2e/timeline-viewport-verdict.test.mjs index 7ec09c29d2..4a9d319054 100644 --- a/packages/studio/tests/e2e/timeline-viewport-verdict.test.mjs +++ b/packages/studio/tests/e2e/timeline-viewport-verdict.test.mjs @@ -9,6 +9,7 @@ import { percentile, shouldCompareWithBase, responsivenessLimits, + rowVirtualizationOf, } from "./timeline-viewport-verdict.mjs"; const LIMITS = { samplesPerRun: 63, interactionLimitMs: 75, frameIntervalLimitMs: 75 }; @@ -239,3 +240,16 @@ describe("gatePassed", () => { expect(gatePassed({ ...passing, attempts: [], againstBase: pass })).toBe(false); }); }); + +describe("rowVirtualizationOf", () => { + // fails without the fix: main's gate read this load-time moment of a virtualized base as an unvirtualized build. + it("reads a virtualized timeline as on while its visible rows are full at load", () => { + const atLoad = { mountedRows: 8, mountedClipRoots: 1024, maxMountedClipRootsInOneRow: 128 }; + expect(rowVirtualizationOf(atLoad, TIMELINE_VIEWPORT_BUDGETS)).toBe("on"); + }); + + it("reads a timeline that mounts every row as off", () => { + const everyRow = { mountedRows: 1000, mountedClipRoots: 1000, maxMountedClipRootsInOneRow: 1 }; + expect(rowVirtualizationOf(everyRow, TIMELINE_VIEWPORT_BUDGETS)).toBe("off"); + }); +}); diff --git a/packages/studio/tests/e2e/timeline-virtualization.mjs b/packages/studio/tests/e2e/timeline-virtualization.mjs index f6efd97328..54ce6e5cd8 100644 --- a/packages/studio/tests/e2e/timeline-virtualization.mjs +++ b/packages/studio/tests/e2e/timeline-virtualization.mjs @@ -33,6 +33,7 @@ import { judgeAgainstBase, judgeResponsiveness, responsivenessLimits, + rowVirtualizationOf, shouldCompareWithBase, TIMING_ATTEMPTS, timingPassed, @@ -477,22 +478,20 @@ async function assertProductionRuntime(page) { } async function assertRowVirtualization(page, budgets) { - // Trust the DOM, not the caller. A virtualized build cannot mount every clip - // and an unvirtualized one cannot avoid it, so the mounted count says which - // build is really being measured. - const observedClipRoots = await page.evaluate( - () => window.__studioTest.readTimelinePerformanceDiagnostics().mountedClipRoots, + // Trust the DOM, not the caller: the mounted rows say which build is really being measured. + const diagnostics = await page.evaluate(() => + window.__studioTest.readTimelinePerformanceDiagnostics(), ); - const observedRowVirtualization = observedClipRoots <= budgets.maxMountedClipRoots ? "on" : "off"; + const observedRowVirtualization = rowVirtualizationOf(diagnostics, budgets); if (observedRowVirtualization !== ROW_VIRTUALIZATION) { throw new Error( `Requested TIMELINE_ROW_VIRTUALIZATION=${ROW_VIRTUALIZATION} but the server under test ` + - `behaves as ${observedRowVirtualization}: ${observedClipRoots} clip roots mounted for ` + - `${ELEMENT_COUNT} elements against a ${budgets.maxMountedClipRoots} budget. ` + + `behaves as ${observedRowVirtualization}: ${diagnostics.mountedRows} rows mounted for ` + + `${ELEMENT_COUNT} elements against a ${budgets.maxMountedRows} budget. ` + "Set VITE_STUDIO_TIMELINE_ROW_VIRTUALIZATION_ENABLED on the Studio dev server to match.", ); } - return observedClipRoots; + return diagnostics.mountedClipRoots; } async function waitForFixtureRender(page, elementCount) { From b3d37f948cabec76e187bed2f2fbb1336da5ae3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 15:20:25 +0000 Subject: [PATCH 130/367] fix(studio): vitest exits when a project is open in the dev data folder (#8514) --- packages/studio/vite.config.test.ts | 35 +++++++++++++++++++++++++++-- packages/studio/vite.config.ts | 11 ++++----- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/packages/studio/vite.config.test.ts b/packages/studio/vite.config.test.ts index 29f35e916e..53455966ff 100644 --- a/packages/studio/vite.config.test.ts +++ b/packages/studio/vite.config.test.ts @@ -1,8 +1,24 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { describe, expect, it } from "vitest"; -import config, { stableStylesCssPlugin } from "./vite.config"; +import { createServer } from "vite"; +import { describe, expect, it, vi } from "vitest"; +import config, { devProjectApi, stableStylesCssPlugin } from "./vite.config"; + +const watchers = vi.hoisted(() => ({ open: new Set(), closed: new Set() })); +vi.mock("chokidar", async (importOriginal) => { + const chokidar = await importOriginal(); + return { + ...chokidar, + watch: (...args: Parameters) => { + const watcher = chokidar.watch(...args); + const close = watcher.close.bind(watcher); + watchers.open.add(watcher); + watcher.close = () => (watchers.closed.add(watcher), close()); + return watcher; + }, + }; +}); const packageJson = JSON.parse(readFileSync(resolve(__dirname, "package.json"), "utf8")) as { publishConfig: { exports: Record }; @@ -87,3 +103,18 @@ describe("stableStylesCssPlugin", () => { } }); }); + +describe("devProjectApi", () => { + // fails without the fix: the project watcher closed only with an http server, so `vitest list` never exited. + it("closes its project watcher when a server with no http server closes", async () => { + const server = await createServer({ + configFile: false, + logLevel: "silent", + plugins: [devProjectApi()], + server: { middlewareMode: true, ws: false }, + }); + expect(watchers.open.size).toBe(1); + await server.close(); + expect(watchers.closed).toEqual(watchers.open); + }); +}); diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.ts index d9cca1cf66..f0b50a7502 100644 --- a/packages/studio/vite.config.ts +++ b/packages/studio/vite.config.ts @@ -13,7 +13,7 @@ import { isIP } from "node:net"; import { join, resolve } from "node:path"; import { readNodeRequestBody } from "./vite.request-body.js"; import { bindNodeRequestSignal } from "./vite.request-signal.js"; -import { watch } from "chokidar"; +import { type FSWatcher, watch } from "chokidar"; import { createProjectSignatureCache, createViteAdapter } from "./vite.adapter"; import { previewConfigPayload } from "./vite.preview-config"; import { loadStudioServerDevModule } from "./vite.studio-server-module"; @@ -111,9 +111,10 @@ function viteAllowsHost(host: string, allowedHosts: readonly string[]): boolean // ── Vite plugin ────────────────────────────────────────────────────────────── -function devProjectApi(): Plugin { +export function devProjectApi(): Plugin { const dataDir = resolve(__dirname, "data/projects"); const runtimePath = resolve(__dirname, "../core/dist/hyperframe.runtime.iife.js"); + let watching: FSWatcher | undefined; return { name: "studio-dev-api", @@ -139,12 +140,12 @@ function devProjectApi(): Plugin { /* dataDir doesn't exist yet */ } - const projectWatcher = watch([...watchedProjects.keys()], { + const projectWatcher = (watching = watch([...watchedProjects.keys()], { ignoreInitial: true, // A project write is a whole-file replace; wait for it to settle so a // half-written composition is never announced. awaitWriteFinish: { stabilityThreshold: 40, pollInterval: 10 }, - }); + })); // This watcher, and not Vite's, is what clears the preview signature. // Vite's ignores `data/projects/**`, so subscribing the cache to it left @@ -355,8 +356,8 @@ function devProjectApi(): Plugin { }, }); }); - server.httpServer?.on("close", () => void projectWatcher.close()); }, + closeBundle: () => watching?.close(), }; } From 086948766477b8ae4c4fa1be0b4215a627e1062b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 15:21:06 +0000 Subject: [PATCH 131/367] ci(studio): a failed walk in the viewport gate job names itself on the check (#8516) --- .github/workflows/ci.yml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ebac9fb2bd..f7e1b3fad2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1169,28 +1169,29 @@ jobs: echo "FAIL: studio dev server did not start on port 5316" exit 1 fi - # All checks run even when an earlier one fails. + # All checks run even when an earlier one fails; each failure names its walk on the check. rc=0 + failed() { echo "::error title=Studio walk failed::$1"; rc=1; } STUDIO_URL="http://localhost:5316/#project/fade-handles" \ - node packages/studio/tests/e2e/fade-handles.mjs || rc=1 + node packages/studio/tests/e2e/fade-handles.mjs || failed "fade handles" STUDIO_URL="http://localhost:5316/#project/fade-handles?tab=renders" \ - node packages/studio/tests/e2e/render-selects.mjs || rc=1 + node packages/studio/tests/e2e/render-selects.mjs || failed "render selects" STUDIO_URL="http://localhost:5316/" \ - node packages/studio/tests/e2e/thumbnail-save.mjs || rc=1 + node packages/studio/tests/e2e/thumbnail-save.mjs || failed "thumbnail connection release" STUDIO_URL="http://localhost:5316/#project/timeline-trim-snap" \ - node packages/studio/tests/e2e/timeline-trim-snap.mjs || rc=1 + node packages/studio/tests/e2e/timeline-trim-snap.mjs || failed "trim snapping" rm -rf packages/studio/data/projects/timeline-trim-snap cp -R packages/studio/tests/e2e/fixtures/timeline-trim-snap \ packages/studio/data/projects/timeline-trim-snap STUDIO_URL="http://localhost:5316/#project/timeline-trim-snap" \ - node packages/studio/tests/e2e/timeline-snap-release.mjs || rc=1 + node packages/studio/tests/e2e/timeline-snap-release.mjs || failed "snap release" STUDIO_URL="http://localhost:5316/#project/aroll-backdrop" \ - node packages/studio/tests/e2e/aroll-backdrop.mjs || rc=1 + node packages/studio/tests/e2e/aroll-backdrop.mjs || failed "script-hidden backdrop" rm -rf packages/studio/data/projects/graded-video-transitions cp -R packages/studio/tests/e2e/fixtures/graded-video-transitions \ packages/studio/data/projects/graded-video-transitions STUDIO_URL="http://localhost:5316/#project/graded-video-transitions" \ - node packages/studio/tests/e2e/graded-video-transitions.mjs || rc=1 + node packages/studio/tests/e2e/graded-video-transitions.mjs || failed "graded video transitions" exit "$rc" - name: Measure the caret of a text edited in place if: success() || failure() From f38a4e3675a76d8742acf8843fd6f909e2a0e96b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 15:21:39 +0000 Subject: [PATCH 132/367] test(cli): the diagnostic test's ffmpeg stand-in answers the demuxer listing, writing no file (#8515) --- packages/cli/src/ui/renderDiagnostic.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/ui/renderDiagnostic.test.ts b/packages/cli/src/ui/renderDiagnostic.test.ts index 3038918c4e..f9fadb910d 100644 --- a/packages/cli/src/ui/renderDiagnostic.test.ts +++ b/packages/cli/src/ui/renderDiagnostic.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { @@ -240,7 +240,7 @@ const cases: Array<{ name: string; script?: string; expected: AudioFailureDiagno { name: "group submix", script: - 'const fs = require("node:fs"); if (process.argv.includes("-filter_complex_script")) process.exit(9); fs.writeFileSync(process.argv.at(-1), "audio");', + 'const fs = require("node:fs"); if (process.argv.includes("-demuxers")) process.exit(0); if (process.argv.includes("-filter_complex_script")) process.exit(9); fs.writeFileSync(process.argv.at(-1), "audio");', expected: { stage: "mix", reason: "ffmpeg_failed", @@ -258,6 +258,9 @@ for (const scenario of cases) { async () => { const root = mkdtempSync(join(tmpdir(), "hf-diagnostic-private-")); roots.push(root); + // A stand-in answering every call as an encode wrote "audio" to `-demuxers`, the listing's last argument. + const stray = join(process.cwd(), "-demuxers"); + rmSync(stray, { force: true }); const executable = join(root, "ffmpeg-private"); if (scenario.script) { writeFileSync(executable, `#!${process.execPath}\n${scenario.script}\n`); @@ -311,6 +314,7 @@ for (const scenario of cases) { "private-customer-stderr", ]) expect(line).not.toContain(secret); + expect(existsSync(stray)).toBe(false); }, ); } From 5d4420fee1bae9ca9cd0b157e33c7de2680be906 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 15:24:10 +0000 Subject: [PATCH 133/367] fix(core): a timeline whose labels throw no longer empties the clip list (#8512) * test: one timeline's throwing labels don't empty the clip list * fix(core): a timeline whose labels throw leaves only its own clips unlabeled --- packages/core/src/runtime/timeline.test.ts | 28 +++++++++++++++++++ packages/core/src/runtime/transitionLabels.ts | 11 ++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packages/core/src/runtime/timeline.test.ts b/packages/core/src/runtime/timeline.test.ts index e6d003eaf2..ab7227bbb7 100644 --- a/packages/core/src/runtime/timeline.test.ts +++ b/packages/core/src/runtime/timeline.test.ts @@ -139,6 +139,34 @@ describe("collectRuntimeTimelinePayload", () => { ]); }); + it("still lists every clip, with the labels it can read, when one timeline's labels throw", () => { + const root = document.createElement("div"); + root.setAttribute("data-composition-id", "main"); + root.setAttribute("data-duration", "10"); + root.innerHTML = ` +
+
`; + document.body.appendChild(root); + (window as TimelineTestWindow).__timelines = { + broken: { + duration: () => 10, + getLabels: () => { + throw new Error("a page's own timeline"); + }, + } as never, + main: { duration: () => 10, labels: { "hf:transition:a:b:fade": 2 } } as never, + }; + + const labels = collectRuntimeTimelinePayload(defaultParams).clips.map((clip) => [ + clip.id, + clip.transitionLabel, + ]); + expect(labels).toEqual([ + ["a", "hf:transition:a:b:fade"], + ["b", "hf:transition:a:b:fade"], + ]); + }); + it("collects clips from elements with data-start and data-duration", () => { const root = document.createElement("div"); root.setAttribute("data-composition-id", "main"); diff --git a/packages/core/src/runtime/transitionLabels.ts b/packages/core/src/runtime/transitionLabels.ts index 13c9e21bb0..3eccf0089e 100644 --- a/packages/core/src/runtime/transitionLabels.ts +++ b/packages/core/src/runtime/transitionLabels.ts @@ -26,6 +26,14 @@ function findTimedElement(doc: Document, markerId: string): Element | null { ); } +function labelsOf(timeline: TimelineWithLabels | undefined): Record { + try { + return timeline?.getLabels?.() ?? timeline?.labels ?? {}; + } catch { + return {}; + } +} + export function transitionLabelsForDocument( doc: Document, timelines: Readonly> | undefined, @@ -34,8 +42,7 @@ export function transitionLabelsForDocument( if (!timelines) return labels; for (const timeline of Object.values(timelines) as Array) { - const timelineLabels = timeline?.getLabels?.() ?? timeline?.labels ?? {}; - for (const label of Object.keys(timelineLabels)) { + for (const label of Object.keys(labelsOf(timeline))) { const pair = transitionParts(label); if (!pair) continue; const outgoing = findTimedElement(doc, pair[0]); From fbd1cd4bcf8b5888c0dd21b62a637a7b2143abac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 15:35:47 +0000 Subject: [PATCH 134/367] fix(cli): cloudrun and lambda say a usage error before loading their cloud SDK (#8510) --- .../src/commands/cloudUsageBeforeSdk.test.ts | 34 +++++++++++++++ packages/cli/src/commands/cloudrun.ts | 43 ++++++++----------- packages/cli/src/commands/lambda.ts | 40 ++++++++--------- 3 files changed, 72 insertions(+), 45 deletions(-) create mode 100644 packages/cli/src/commands/cloudUsageBeforeSdk.test.ts diff --git a/packages/cli/src/commands/cloudUsageBeforeSdk.test.ts b/packages/cli/src/commands/cloudUsageBeforeSdk.test.ts new file mode 100644 index 0000000000..70b38cfe9e --- /dev/null +++ b/packages/cli/src/commands/cloudUsageBeforeSdk.test.ts @@ -0,0 +1,34 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { CliUsageError } from "../utils/commandResult.js"; + +// A cold cloud SDK import took past a 15 s spawn limit on Windows runners; a usage error must not wait on one. +const loaded = vi.hoisted(() => [] as string[]); +vi.mock("@hyperframes/gcp-cloud-run/sdk", () => (loaded.push("gcp-cloud-run/sdk"), {})); +vi.mock("@hyperframes/gcp-cloud-run/terraform", () => (loaded.push("gcp-cloud-run/terraform"), {})); +vi.mock("@hyperframes/aws-lambda/sdk", () => (loaded.push("aws-lambda/sdk"), {})); + +const commands = { + cloudrun: () => import("./cloudrun.js"), + lambda: () => import("./lambda.js"), +}; + +afterEach(() => { + loaded.length = 0; + vi.restoreAllMocks(); +}); + +describe("a cloud command's usage error loads no cloud SDK", () => { + it.each([ + ["cloudrun", "progress"], + ["cloudrun", "render"], + ["lambda", "progress"], + ["lambda", "render"], + ] as const)("`%s %s` with no target", async (command, subcommand) => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const { default: cmd } = await commands[command](); + await expect( + Promise.resolve(cmd.run?.({ args: { subcommand } } as never)), + ).rejects.toBeInstanceOf(CliUsageError); + expect(loaded).toEqual([]); + }); +}); diff --git a/packages/cli/src/commands/cloudrun.ts b/packages/cli/src/commands/cloudrun.ts index 03d56d1655..cdea64354f 100644 --- a/packages/cli/src/commands/cloudrun.ts +++ b/packages/cli/src/commands/cloudrun.ts @@ -102,6 +102,18 @@ function loadCloudRunAdapter(): Promise { return cloudRunAdapterPromise; } +async function cloudRunAdapter(subcommand: string): Promise { + try { + return await loadCloudRunAdapter(); + } catch (error) { + if (isMissingCloudRunAdapterError(error)) { + console.error(missingCloudRunAdapterMessage(subcommand)); + failCommand(); + } + throw error; + } +} + export function isMissingCloudRunAdapterError(error: unknown): boolean { return isMissingPackageError(error, "@hyperframes/gcp-cloud-run"); } @@ -232,25 +244,6 @@ export default defineCommand({ console.log(HELP); return; } - const verbsNeedingAdapter = new Set([ - "deploy", - "sites", - "render", - "render-batch", - "progress", - "destroy", - ]); - if (verbsNeedingAdapter.has(subcommand)) { - try { - await loadCloudRunAdapter(); - } catch (error) { - if (isMissingCloudRunAdapterError(error)) { - console.error(missingCloudRunAdapterMessage(subcommand)); - failCommand(); - } - throw error; - } - } switch (subcommand) { case "deploy": return runDeploy(args); @@ -344,7 +337,7 @@ async function runDeploy(args: Record): Promise { } const region = (args.region as string | undefined) ?? "us-central1"; const repo = (args.repo as string | undefined) ?? "hyperframes"; - const { getTerraformModuleDir } = await loadCloudRunAdapter(); + const { getTerraformModuleDir } = await cloudRunAdapter("deploy"); const tfDir = getTerraformModuleDir(); const repoRoot = findRepoRoot(tfDir); @@ -515,7 +508,7 @@ async function runSites(args: Record): Promise { failUsage(); } const state = readState(args); - const { deploySite } = await loadCloudRunAdapter(); + const { deploySite } = await cloudRunAdapter("sites"); const handle = await deploySite({ projectDir: resolve(projectDir), bucketName: state.bucketName, @@ -569,7 +562,7 @@ async function runRender(args: Record): Promise { const intervalMs = parsePositiveInt(args["wait-interval-ms"], "--wait-interval-ms") ?? 5000; const state = readState(args); - const { renderToCloudRun, getRenderProgress } = await loadCloudRunAdapter(); + const { renderToCloudRun, getRenderProgress } = await cloudRunAdapter("render"); const handle = await renderToCloudRun({ projectDir: resolve(projectDir), includeOutsideFiles: args["include-outside-files"] === true, @@ -626,7 +619,7 @@ async function runProgress(args: Record): Promise { console.error("[cloudrun progress] usage: hyperframes cloudrun progress "); failUsage(); } - const { getRenderProgress } = await loadCloudRunAdapter(); + const { getRenderProgress } = await cloudRunAdapter("progress"); const progress = await getRenderProgress({ executionName }); if (args.json) { console.log(JSON.stringify(progress, null, 2)); @@ -701,7 +694,7 @@ async function runRenderBatch(args: Record): Promise { const maxConcurrent = parsePositiveInt(args["max-concurrent"], "--max-concurrent") ?? DEFAULT_BATCH_MAX_CONCURRENT; const state = readState(args); - const { deploySite, renderToCloudRun } = await loadCloudRunAdapter(); + const { deploySite, renderToCloudRun } = await cloudRunAdapter("render-batch"); // Upload the project once; every entry reuses the same content-addressed // site handle so the tar+upload cost is paid a single time. @@ -791,7 +784,7 @@ function parseBatchFile(path: string): BatchEntry[] { // fallow-ignore-next-line complexity async function runDestroy(args: Record): Promise { - const { getTerraformModuleDir } = await loadCloudRunAdapter(); + const { getTerraformModuleDir } = await cloudRunAdapter("destroy"); const tfDir = getTerraformModuleDir(); const state = existsSync(statePath()) ? (JSON.parse(readFileSync(statePath(), "utf8")) as Partial) diff --git a/packages/cli/src/commands/lambda.ts b/packages/cli/src/commands/lambda.ts index 8290c251a1..21fb0abdcd 100644 --- a/packages/cli/src/commands/lambda.ts +++ b/packages/cli/src/commands/lambda.ts @@ -84,6 +84,22 @@ ${c.bold("REQUIREMENTS:")} • bun on PATH (used to build the handler ZIP) `; +/** The Lambda SDK for `subcommand`, loaded once its own checks passed, so a usage error never waits on it. It is a + * workspace devDependency (the published CLI stays small), so a missing one gets an install hint. */ +async function requireLambdaSdk(subcommand: string): Promise { + try { + await import("@hyperframes/aws-lambda/sdk"); + } catch (err) { + if (isMissingPackageError(err, "@hyperframes/aws-lambda")) { + console.error( + missingPackageMessage("@hyperframes/aws-lambda", `hyperframes lambda ${subcommand}`), + ); + failCommand(); + } + throw err; + } +} + export default defineCommand({ meta: { name: "lambda", description: "Deploy and drive renders on AWS Lambda" }, args: { @@ -254,26 +270,6 @@ export default defineCommand({ const regionFlag = args.region as string | undefined; if (regionFlag) process.env.AWS_REGION = regionFlag; - // The lambda subverbs dynamic-import `@hyperframes/aws-lambda` at call - // time. We keep aws-lambda as a workspace devDependency (not a runtime - // dep) so the published CLI install stays small for users who don't - // deploy to Lambda. These subverbs need it and get a friendly hint when it - // is missing; `deploy` reports that itself and `destroy` needs only SAM. - const verbsNeedingSDK = new Set(["sites", "render", "render-batch", "progress"]); - if (verbsNeedingSDK.has(subcommand)) { - try { - await import("@hyperframes/aws-lambda/sdk"); - } catch (err) { - if (isMissingPackageError(err, "@hyperframes/aws-lambda")) { - console.error( - missingPackageMessage("@hyperframes/aws-lambda", `hyperframes lambda ${subcommand}`), - ); - failCommand(); - } - throw err; - } - } - switch (subcommand) { case "deploy": { const { runDeploy } = await import("./lambda/deploy.js"); @@ -305,6 +301,7 @@ export default defineCommand({ ); failUsage(); } + await requireLambdaSdk("sites"); const { runSitesCreate } = await import("./lambda/sites.js"); await runSitesCreate({ projectDir, @@ -336,6 +333,7 @@ export default defineCommand({ ); failUsage(); } + await requireLambdaSdk("render"); const { runRender } = await import("./lambda/render.js"); const renderResolution = parseOutputResolution(args["output-resolution"]); await runRender({ @@ -394,6 +392,7 @@ export default defineCommand({ ); failUsage(); } + await requireLambdaSdk("render-batch"); const { runRenderBatch } = await import("./lambda/render-batch.js"); const batchResolution = parseOutputResolution(args["output-resolution"]); await runRenderBatch({ @@ -429,6 +428,7 @@ export default defineCommand({ ); failUsage(); } + await requireLambdaSdk("progress"); const { runProgress } = await import("./lambda/progress.js"); await runProgress({ target, stackName, json: Boolean(args.json) }); return; From 258a3cf4ea1a2b9c9d9305809be52a960b7e880e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 15:44:00 +0000 Subject: [PATCH 135/367] fix(producer): a probe step's out-of-memory error keeps its words, so it still reads as memory (#8513) * fix(producer): a probe step's out-of-memory error keeps its words, so it still reads as memory * fix(producer): drop the comment the memory check's name already says --- .../src/services/render/stages/probeStage.test.ts | 13 +++++++++++++ .../src/services/render/stages/probeStage.ts | 7 ++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/producer/src/services/render/stages/probeStage.test.ts b/packages/producer/src/services/render/stages/probeStage.test.ts index dad0f6ec24..af6edfa189 100644 --- a/packages/producer/src/services/render/stages/probeStage.test.ts +++ b/packages/producer/src/services/render/stages/probeStage.test.ts @@ -185,6 +185,8 @@ mock.module("@hyperframes/engine", () => ({ }, // Mirror of the real engine classifier. Canonical tests + pattern list // live in frameCapture-transientErrors.test.ts — update both if patterns change. + isMemoryExhaustionError: (error: unknown) => + /^out of memory\.?$/i.test(error instanceof Error ? error.message.trim() : ""), isTransientBrowserError: (error: unknown) => { const msg = error instanceof Error ? error.message : String(error); if (/Composition has zero duration[\s\S]*Runtime ready: false/.test(msg)) return true; @@ -1890,4 +1892,15 @@ describe("runProbeStage — a page call that never answers", () => { browserMediaError = null; } }); + + it("leaves a bare out-of-memory message as it is, so it is still read as memory exhaustion", async () => { + resetRetryMocks(); + browserMediaError = new Error("Out of memory"); + const { runProbeStage } = await import("./probeStage.js"); + try { + await expect(runProbeStage(makeProbeInput({}))).rejects.toThrow(/^Out of memory$/); + } finally { + browserMediaError = null; + } + }); }); diff --git a/packages/producer/src/services/render/stages/probeStage.ts b/packages/producer/src/services/render/stages/probeStage.ts index f79567fed6..3655e6cae4 100644 --- a/packages/producer/src/services/render/stages/probeStage.ts +++ b/packages/producer/src/services/render/stages/probeStage.ts @@ -44,6 +44,7 @@ import { getCompositionDuration, getCompositionLengthSource, initializeSession, + isMemoryExhaustionError, isTransientBrowserError, probeBeginFrameLiveness, videoAudioId, @@ -496,7 +497,11 @@ async function probeStep(step: string, call: () => Promise): Promise { try { return await call(); } catch (error) { - if (error instanceof Error && !error.message.startsWith(STOPPED)) + if ( + error instanceof Error && + !error.message.startsWith(STOPPED) && + !isMemoryExhaustionError(error) + ) error.message = `${STOPPED}${step}: ${error.message}`; throw error; } From 0bc7963ffd836fe262bfce8b9422f53dc4b06b8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 16:14:58 +0000 Subject: [PATCH 136/367] fix(studio-server): a page with thousands of script tags no longer stalls the preview (#8518) Deciding whether a preview needs the motion-path plugin read every script file the page loads, once per script tag, all at once, and kept reading after the check gave up. A page naming one file in thousands of script tags started thousands of reads and froze the server. The check now answers "preload the plugin" at once for a page with more than 64 script tags, reads each script file once, keeps at most 8 reads in flight, starts none after its time is up or once a script names a path, and cancels the reads still running when it ends. --- .../src/routes/preview.noPathTween.test.ts | 100 ++++++++++++++++++ packages/studio-server/src/routes/preview.ts | 84 ++++++++++----- 2 files changed, 156 insertions(+), 28 deletions(-) diff --git a/packages/studio-server/src/routes/preview.noPathTween.test.ts b/packages/studio-server/src/routes/preview.noPathTween.test.ts index a5cc851d61..c19237e45c 100644 --- a/packages/studio-server/src/routes/preview.noPathTween.test.ts +++ b/packages/studio-server/src/routes/preview.noPathTween.test.ts @@ -11,6 +11,8 @@ import { withPreviewRuntime, } from "./preview"; +type ScriptFiles = NonNullable[3]>; + const GSAP_FILE = "/*! GSAP 3.12.5 */ window.gsap = { timeline: function () {} };"; const PLAIN_TWEEN = ''; const LATE_PATH_TWEEN = @@ -116,6 +118,104 @@ describe("the preview builder's proof that no script can tween along a path", () }); }); +describe("the script scan's bounds", () => { + const tags = (srcs: string[]) => srcs.map((src) => ``).join(""); + const counting = (read: ScriptFiles["read"]) => { + const calls = { resolves: 0, reads: [] as string[] }; + const files: ScriptFiles = { + resolve: async (base, rel) => (calls.resolves++, join(base, rel)), + read: (file, signal) => (calls.reads.push(file), read(file, signal)), + }; + return { calls, files }; + }; + // As `readFile` does with its signal. + const untilAborted = (signal: AbortSignal) => + new Promise((_, reject) => + signal.addEventListener("abort", () => reject(signal.reason)), + ); + const scripts = (count: number) => + Object.fromEntries(Array.from({ length: count }, (_, i) => [`s${i}.js`, GSAP_FILE])); + + // fails without the fix: the scan resolved, stat'ed and read the one file once per tag. + it("answers false for a page with more script tags than it scans, reading nothing", async () => { + const { html, dir } = page(tags(Array(30_000).fill("gsap.min.js")), { + "gsap.min.js": GSAP_FILE, + }); + const { calls, files } = counting(async () => GSAP_FILE); + const answer = await provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files); + expect(calls.resolves).toBe(0); + expect(calls.reads).toHaveLength(0); + expect(answer).toBe(false); + }); + + // fails without the fix: each tag read its file again. + it("reads each script file once, however many tags and spellings name it", async () => { + const srcs = Array.from({ length: 40 }, (_, i) => ["a.js", "./a.js", "b.js", "c.js"][i % 4]!); + const { html, dir } = page(tags(srcs), { + "a.js": GSAP_FILE, + "b.js": GSAP_FILE, + "c.js": GSAP_FILE, + }); + const { calls, files } = counting(async () => GSAP_FILE); + expect(await provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files)).toBe(true); + expect(calls.reads.map((file) => file.slice(dir.length + 1)).sort()).toEqual([ + "a.js", + "b.js", + "c.js", + ]); + }); + + // fails without the fix: every tag's read started at once. + it("has at most 8 reads in flight", async () => { + const waiting: (() => void)[] = []; + let inFlight = 0; + let most = 0; + const { calls, files } = counting( + () => + new Promise((resolve) => { + most = Math.max(most, ++inFlight); + waiting.push(() => (inFlight--, resolve(GSAP_FILE))); + }), + ); + const { html, dir } = page(tags(Object.keys(scripts(20))), scripts(20)); + let answer: boolean | undefined; + void provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files).then((a) => (answer = a)); + while (answer === undefined) { + waiting.shift()?.(); + await new Promise(setImmediate); + } + expect(answer).toBe(true); + expect(calls.reads).toHaveLength(20); + expect(most).toBeLessThanOrEqual(8); + }); + + // fails without the fix: a read went on after the scan gave up on it. + it("aborts a read still in flight when the scan's time runs out", async () => { + const signals: (AbortSignal | undefined)[] = []; + const { files } = counting((_, signal) => { + signals.push(signal); + return untilAborted(signal); + }); + const { html, dir } = page(tags(["gsap.min.js"]), { "gsap.min.js": GSAP_FILE }); + expect(await provesNoPathTween(html, dir, performance.now() + 100, files)).toBe(false); + expect(signals).toHaveLength(1); + expect(signals[0]?.aborted).toBe(true); + }); + + // fails without the fix: every script was read even after one named a path. + it("starts no read after a script names a path, and aborts the ones in flight", async () => { + const signals: AbortSignal[] = []; + const { calls, files } = counting((file, signal) => { + signals.push(signal); + return file.endsWith("s0.js") ? Promise.resolve(LATE_PATH_TWEEN) : untilAborted(signal); + }); + const { html, dir } = page(tags(Object.keys(scripts(20))), scripts(20)); + expect(await provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files)).toBe(false); + expect(calls.reads.length).toBeLessThanOrEqual(8); + expect(signals.every((signal) => signal.aborted)).toBe(true); + }); +}); + describe("the preview's path-free mark", () => { it("is set only when the builder proved the page path-free", () => { const { html, dir } = page(""); diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index ae93aca6e4..7d9f3c4d8b 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -209,45 +209,49 @@ const PROJECT_PREVIEW_BASE = const MAX_READ_SCRIPT_BYTES = 4 * 1024 * 1024; const SCRIPT_SCAN_MS = 1000; +// A page with more script tags than this is unsure, and unsure already means it preloads the plugin. +const MAX_SCANNED_SCRIPTS = 64; +const SCRIPT_READS_IN_FLIGHT = 8; /** How the scan reaches a project's files: both off the event loop. */ interface ScriptFiles { resolve: (base: string, relativePath: string) => Promise; - read: (file: string) => Promise; + read: (file: string, signal: AbortSignal) => Promise; } const projectFiles: ScriptFiles = { resolve: resolveExistingProjectFileOff, - read: (file) => readFile(file, "utf-8"), + read: (file, signal) => readFile(file, { encoding: "utf-8", signal }), }; -async function projectScriptNamesNoPath( - src: string, - projectDir: string, - files: ScriptFiles, -): Promise { - if (/^(?:[a-z][\w+.-]*:|\/)/i.test(src)) return false; - try { - const file = await files.resolve(projectDir, decodeURIComponent(src.split(/[?#]/)[0]!)); - if (file === null) return false; - const info = await statFile(file); - if (!info.isFile() || info.size > MAX_READ_SCRIPT_BYTES) return false; - return !namesMotionPath(await files.read(file)); - } catch { - return false; - } +async function fileNamesNoPath(file: string, files: ScriptFiles, signal: AbortSignal) { + const info = await statFile(file); + if (!info.isFile() || info.size > MAX_READ_SCRIPT_BYTES || signal.aborted) return false; + return !namesMotionPath(await files.read(file, signal)); } -async function scriptCannotTweenAlongPath( - tag: string, - projectDir: string, - files: ScriptFiles, -): Promise { +function scriptTagAnswer(tag: string): boolean | { src: string } { if (tag.includes(RUNTIME_BOOTSTRAP_ATTR)) return true; if (/\stype\s*=\s*["']?module\b/i.test(tag)) return false; const match = SCRIPT_SRC_ATTR.exec(tag); if (!match) return true; const src = (match[1] ?? match[2] ?? match[3] ?? "").replace(/&/gi, "&"); - return GSAP_ON_ITS_CDN.test(src) || projectScriptNamesNoPath(src, projectDir, files); + if (GSAP_ON_ITS_CDN.test(src)) return true; + return /^(?:[a-z][\w+.-]*:|\/)/i.test(src) ? false : { src }; +} + +async function inPool( + items: Iterable, + size: number, + signal: AbortSignal, + work: (item: T) => Promise, +): Promise { + const pending = items[Symbol.iterator](); + const worker = async () => { + for (let next = pending.next(); !next.done && !signal.aborted; next = pending.next()) { + await work(next.value); + } + }; + await Promise.all(Array.from({ length: size }, worker)); } /** True only when no script the page loads can tween along a path: the page's text and each project script it loads @@ -265,14 +269,38 @@ export async function provesNoPathTween( const now = performance.now(); const deadline = now + Math.min(SCRIPT_SCAN_MS, (requestDeadline - now) / 2); if (deadline <= now) return false; - const scripts = findStartTags(html, "script").map((start) => - scriptCannotTweenAlongPath(html.slice(start, html.indexOf(">", start) + 1), projectDir, files), - ); + const tags = findStartTags(html, "script"); + if (tags.length > MAX_SCANNED_SCRIPTS) return false; + const srcs = new Set(); + for (const start of tags) { + const answer = scriptTagAnswer(html.slice(start, html.indexOf(">", start) + 1)); + if (answer === false) return false; + if (answer !== true) srcs.add(answer.src); + } + // Aborted when a script names a path or the scan ends, so it stops every read it started. + const scan = new AbortController(); + const byFile = new Map>(); + const check = async (src: string) => { + const file = await files.resolve(projectDir, decodeURIComponent(src.split(/[?#]/)[0]!)); + if (file === null) return false; + let answer = byFile.get(file); + if (!answer) byFile.set(file, (answer = fileNamesNoPath(file, files, scan.signal))); + return answer; + }; + const stopUnlessNoPath = async (src: string) => { + if (!(await check(src).catch(() => false))) scan.abort(); + }; try { - const answers = await withinDeadline(Promise.all(scripts), deadline, "scripts"); - return answers.every(Boolean); + await withinDeadline( + inPool(srcs, SCRIPT_READS_IN_FLIGHT, scan.signal, stopUnlessNoPath), + deadline, + "scripts", + ); + return !scan.signal.aborted; } catch { return false; + } finally { + scan.abort(); } } From ec9a3a8ef2b73e35fddea9a94e6fa474cf73e09a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 16:17:17 +0000 Subject: [PATCH 137/367] fix(core): a sealed move inside a nested composition shows where it was dropped (#8517) * fix(core): a patched tween on a resting scene timeline is drawn before the frame says patched * fix(core): the frame says patched only once each patched tween has rendered --- packages/core/src/runtime/adapters/gsap.ts | 11 +- .../editing/patchTween.sceneRest.test.ts | 119 ++++++++++++++++++ .../core/src/runtime/editing/patchTween.ts | 57 +++++++-- packages/core/src/runtime/init.ts | 28 ++--- packages/core/src/runtime/sceneRest.ts | 17 +++ 5 files changed, 202 insertions(+), 30 deletions(-) create mode 100644 packages/core/src/runtime/editing/patchTween.sceneRest.test.ts create mode 100644 packages/core/src/runtime/sceneRest.ts diff --git a/packages/core/src/runtime/adapters/gsap.ts b/packages/core/src/runtime/adapters/gsap.ts index c79682a409..38b7f67d4a 100644 --- a/packages/core/src/runtime/adapters/gsap.ts +++ b/packages/core/src/runtime/adapters/gsap.ts @@ -319,6 +319,16 @@ export function seekGsapTimeline( const from = landOn(timeline, t, suppressEvents, version); if (t < from && structure) reapplyStepsInAuthoredOrder(timeline, structure, t); if (from !== t || !gsapNeverRendered(timeline)) return false; + redrawGsapTimelineAt(timeline, t, structure); + return true; +} + +export function redrawGsapTimelineAt( + timeline: RuntimeTimelineLike, + t: number, + structure?: GsapStructureKey, +): void { + if (typeof timeline.totalTime !== "function") return; rerenderGsapTimelineAt( { totalTime: timeline.totalTime.bind(timeline), @@ -328,7 +338,6 @@ export function seekGsapTimeline( t, structure, ); - return true; } type GsapParent = { diff --git a/packages/core/src/runtime/editing/patchTween.sceneRest.test.ts b/packages/core/src/runtime/editing/patchTween.sceneRest.test.ts new file mode 100644 index 0000000000..ddb128e8ea --- /dev/null +++ b/packages/core/src/runtime/editing/patchTween.sceneRest.test.ts @@ -0,0 +1,119 @@ +import gsap from "gsap"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { initSandboxRuntimeModular } from "../init"; +import type { RuntimeTimelineLike } from "../types"; +import { resetRuntimeFixtureDom } from "../runtimeSeekFixture.test-helpers"; +import { patchTweens } from "./patchTween"; + +// fails without the fix: the runtime skips a scene resting at the time it would draw, so a patched tween on a +// scene's timeline was never drawn and the frame still answered patched. +describe("patch-tweens on a scene that rests", () => { + beforeEach(() => { + resetRuntimeFixtureDom(); + window.gsap = gsap as unknown as typeof window.gsap; + }); + + afterEach(() => { + window.__hfRuntimeTeardown?.(); + vi.restoreAllMocks(); + delete window.__player; + delete window.__playerReady; + delete window.__hf; + }); + + /** `#a` is held at x 40 by a set on scene a's timeline; at depth 2, scene a sits inside scene outer. */ + function load(depth: 1 | 2, holdA = (a: gsap.core.Timeline) => a.set("#a", { x: 40 }, 0)) { + const a = `
`; + document.body.innerHTML = + `
` + + (depth === 1 + ? a + : `
${a}
`) + + `
` + + `
`; + const scene = () => gsap.timeline({ paused: true }).to({}, { duration: 5 }, 0); + const b = scene().set("#b", { x: 10 }, 0); + const timelines: Record = { + main: scene(), + a: holdA(scene()), + b, + }; + if (depth === 2) timelines.outer = scene(); + window.__timelines = timelines as Record; + initSandboxRuntimeModular(); + window.__player?.seek(1); + window.__player?.seek(1); + return { b }; + } + + const shownX = (selector: string) => Number(gsap.getProperty(selector, "x")); + const patchA = (x: number) => + patchTweens({ + patches: [{ selector: "#a", change: { kind: "set", props: { x } } }], + seek: true, + }); + + it.each([1, 2] as const)( + "draws the patched set on a scene %i composition deep, and only then answers patched", + (depth) => { + load(depth); + expect(shownX("#a")).toBe(40); + expect(patchA(300)).toEqual({ patched: true }); + expect(shownX("#a")).toBe(300); + }, + ); + + it("still skips a scene at rest that no patch touched", () => { + const { b } = load(1); + const drawsB = [vi.spyOn(b, "totalTime"), vi.spyOn(b, "seek"), vi.spyOn(b, "render")]; + patchA(300); + expect(drawsB.map((draw) => draw.mock.calls.filter((call) => call.length > 0).length)).toEqual([ + 0, 0, 0, + ]); + }); + + it("answers not patched when the patched set sits in a child timeline that already ended", () => { + load(1, (a) => a.add(gsap.timeline().set("#a", { x: 40 }, 0), 0)); + expect(patchA(300)).toEqual({ patched: false }); + expect(shownX("#a")).toBe(40); + }); + + it("answers patched for a keyframe-step edit once the tween that replaced it renders", () => { + load(1, (a) => + a.to("#a", { keyframes: { "0%": { x: 40 }, "100%": { x: 40 } }, duration: 2 }, 0), + ); + const reply = patchTweens({ + patches: [ + { selector: "#a", change: { kind: "keyframe-rebuild", pct: 100, props: { x: 140 } } }, + ], + seek: true, + }); + expect(reply).toEqual({ patched: true }); + expect(shownX("#a")).toBe(90); + }); + + it("answers not patched when nothing draws the scene it changed", () => { + load(1); + delete window.__player; + expect(patchA(300)).toEqual({ patched: false }); + }); +}); + +// The reply reads GSAP's internal _initted: an upgrade that changes it fails here, not every reply. +describe("GSAP's init flag, as the patch reply reads it", () => { + it("is cleared by invalidate() and set again by the tween's next render", () => { + document.body.innerHTML = `
`; + const timeline = gsap + .timeline({ paused: true }) + .set("#a", { x: 40 }, 0) + .to({}, { duration: 2 }, 0); + timeline.totalTime(1); + const set = timeline.getChildren(true)[0] as gsap.core.Tween & { _initted?: unknown }; + expect(Boolean(set._initted)).toBe(true); + set.invalidate(); + expect(Boolean(set._initted)).toBe(false); + timeline.totalTime(0.5, true); + timeline.totalTime(1, true); + expect(Boolean(set._initted)).toBe(true); + }); +}); diff --git a/packages/core/src/runtime/editing/patchTween.ts b/packages/core/src/runtime/editing/patchTween.ts index 918fa58a7b..78d6d512f5 100644 --- a/packages/core/src/runtime/editing/patchTween.ts +++ b/packages/core/src/runtime/editing/patchTween.ts @@ -4,6 +4,7 @@ import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading"; import { recordLiveSet, swapWaiting } from "./softReload"; import { drawDrafts } from "../editingDraft"; +import { markRestingScenesForRedraw } from "../sceneRest"; import { parseDraftEnd, type EditingDraftEnd } from "../editingDraftEnd"; export interface SetPatchProps { @@ -281,16 +282,22 @@ function keyframeObject( const finiteStep = (props: KeyframeStep) => Object.values(props).every((v) => typeof v === "number" && Number.isFinite(v)); -function rebuildKeyframeTween(tween: PatchableTween, pct: number, props: KeyframeStep): boolean { - if (!replaceable(tween) || !finiteStep(props)) return false; +function rebuildKeyframeTween( + tween: PatchableTween, + pct: number, + props: KeyframeStep, +): PatchableTween | null { + if (!replaceable(tween) || !finiteStep(props)) return null; const kf = keyframeObject(tween.vars); const targets = tween.targets?.(); - if (!kf || !targets || targets.length === 0) return false; + if (!kf || !targets || targets.length === 0) return null; const next = mergeKeyframeStep(kf, pct, props); const position = tween.startTime(); + const parent = tween.parent; tween.kill(); - tween.parent.to(targets, { ...tween.vars, keyframes: next }, position); - return true; + const before = new Set(parent.getChildren?.(false)); + parent.to(targets, { ...tween.vars, keyframes: next }, position); + return parent.getChildren?.(false).find((child) => !before.has(child)) ?? null; } function changeChannels(change: RuntimeTweenChange): string[] | undefined { @@ -319,12 +326,28 @@ function restoreAuthoredOpacityForCapture(tween: PatchableTween): void { } } -function applyChange(tween: PatchableTween, change: RuntimeTweenChange): boolean { - if (change.kind === "set") return patchSet(tween, change.props); - if (change.kind === "keyframes") return patchKeyframes(tween, change.keyframes); +function applyChange(tween: PatchableTween, change: RuntimeTweenChange): PatchableTween | null { + if (change.kind === "set") return patchSet(tween, change.props) ? tween : null; + if (change.kind === "keyframes") return patchKeyframes(tween, change.keyframes) ? tween : null; if (change.kind === "keyframe-rebuild") return rebuildKeyframeTween(tween, change.pct, change.props); - return false; + return null; +} + +type GsapInitFlag = { _initted?: unknown }; + +/** Reads GSAP's internal `_initted`: invalidate() clears it and the tween's next render sets it. */ +const renderedOnceReached = (tween: PatchableTween): boolean => { + const now = tween.parent?.time?.(); + const reached = typeof now === "number" && now >= (tween.startTime?.() ?? 0); + return !reached || Boolean((tween as GsapInitFlag)._initted); +}; + +function timelinesAbove(tween: PatchableTween): object[] { + const chain: object[] = []; + for (let parent = tween.parent; parent; parent = (parent as PatchableTween).parent) + chain.push(parent); + return chain; } function seekToCurrent(target: PatchTarget, timeline: PatchableTimeline): void { @@ -345,6 +368,7 @@ export function patchTween( change: Exclude, compositionId?: string, deferSeek = false, + patchedTweens: PatchableTween[] = [], ): boolean { try { const kind = change.kind === "set" ? "set" : "keyframe"; @@ -352,10 +376,13 @@ export function patchTween( if (!resolved) return false; const { tween, timeline } = resolved; if (changeTouchesOpacity(change)) restoreAuthoredOpacityForCapture(tween); - if (!applyChange(tween, change)) return false; + const patched = applyChange(tween, change); + if (!patched) return false; + patchedTweens.push(patched); // Only the edited tween: a timeline-wide invalidate re-captures every from() against // the grading engine's opacity-0 hide, and graded elements vanish. if (change.kind !== "keyframe-rebuild") tween.invalidate?.(); + markRestingScenesForRedraw(timelinesAbove(patched)); if (!deferSeek) seekToCurrent(target, timeline); return true; } catch { @@ -473,11 +500,15 @@ export function patchTweens({ patches, seek, endsDrafts }: PatchTweensParams): { }; if (swapWaiting()) return { patched: false }; const renderAt = lastTweenPatch(patches); + const patchedTweens: PatchableTween[] = []; const missed = patches.find(({ selector, change }, index) => { if (change.kind === "global-set") return applyGlobalSet(target, selector, change.props) === null; - return !patchTween(target, selector, change, undefined, !(seek && index === renderAt)); + const defer = !(seek && index === renderAt); + return !patchTween(target, selector, change, undefined, defer, patchedTweens); }); - if (missed === undefined && endsDrafts) drawDrafts(endsDrafts); - return { patched: missed === undefined }; + const shown = !seek || patchedTweens.every(renderedOnceReached); + const patched = missed === undefined && shown; + if (patched && endsDrafts) drawDrafts(endsDrafts); + return { patched }; } diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts index d56d008752..d7a1897ba7 100644 --- a/packages/core/src/runtime/init.ts +++ b/packages/core/src/runtime/init.ts @@ -1,5 +1,6 @@ // fallow-ignore-file code-duplication complexity import { rememberSourceLength, sourceLengthOf } from "./sourceLength"; +import { restSceneAt, sceneRestingAt, takeSceneRedrawDue } from "./sceneRest"; import { wallClearTimeout, wallSetTimeout } from "./wallClock"; import { setPreviewRasterScale } from "./previewRasterHints"; import { createFarSceneSkip } from "./farScenes"; @@ -73,7 +74,7 @@ import { createGsapAdapter, holdFrameMarks, muteDiscreteCallbacks, - rerenderGsapTimelineAt, + redrawGsapTimelineAt, gsapTimelineOf, seekGsapTimeline, type GsapStructureKey, @@ -5707,12 +5708,15 @@ export function initSandboxRuntimeModular(): void { timeline: RuntimeTimelineLike, timeSeconds: number, options?: RuntimeSeekOptions, + redrawDue = false, ) => { try { const suppressEvents = options?.suppressEvents === true; // Guarded: a partial timeline without pause() must still get its seek. pauseTimelineIfPossible(timeline); - seekGsapTimeline(timeline, timeSeconds, suppressEvents, gsapStructureOf(timeline), renderFps); + const structure = gsapStructureOf(timeline); + const redrawn = seekGsapTimeline(timeline, timeSeconds, suppressEvents, structure, renderFps); + if (redrawDue && !redrawn) redrawGsapTimelineAt(timeline, timeSeconds, structure); } catch (err) { // The scene's own callback threw. A warning, not a script error: it must not turn a // timed-out timeline wait into a script failure. @@ -5774,9 +5778,8 @@ export function initSandboxRuntimeModular(): void { sceneClocks.set(timeline, clock); return clock; }; - const restingAt = new WeakMap(); const restsAt = (timeline: RuntimeTimelineLike, time: number): boolean => { - if (restingAt.get(timeline) !== time) return false; + if (sceneRestingAt(timeline) !== time) return false; try { return ( (timeline.paused as () => unknown)() === true && Number(timeline.totalTime?.()) === time @@ -5819,9 +5822,10 @@ export function initSandboxRuntimeModular(): void { : sourceTime, ); // A scene before or after its clip rests where the last frame left it: no redraw. - if (!renderCaptureSeekStarted && restsAt(timeline, localTime)) continue; - seekSceneTimeline(compositionId, timeline, localTime, options); - restingAt.set(timeline, localTime); + const redrawDue = takeSceneRedrawDue(timeline); + if (!redrawDue && !renderCaptureSeekStarted && restsAt(timeline, localTime)) continue; + seekSceneTimeline(compositionId, timeline, localTime, options, redrawDue); + restSceneAt(timeline, localTime); } }; @@ -5950,15 +5954,7 @@ export function initSandboxRuntimeModular(): void { const redrawn = seekGsapTimeline(tl, tlSeekTime, suppressEvents, structure, renderFps); if (!redrawn && !suppressEvents && !hasZeroDurationCallbackTween(tl, structure)) { // The first seek is the only eventful one; the re-render only refreshes styles. - rerenderGsapTimelineAt( - { - totalTime: tl.totalTime.bind(tl), - totalDuration: tl.totalDuration?.bind(tl), - getChildren: tl.getChildren?.bind(tl), - }, - tlSeekTime, - structure, - ); + redrawGsapTimelineAt(tl, tlSeekTime, structure); } } else { tl.seek(tlSeekTime, suppressEvents); diff --git a/packages/core/src/runtime/sceneRest.ts b/packages/core/src/runtime/sceneRest.ts new file mode 100644 index 0000000000..408cd0601b --- /dev/null +++ b/packages/core/src/runtime/sceneRest.ts @@ -0,0 +1,17 @@ +// The local time each scene timeline was last drawn at: a seek that would draw it there again skips it. +const restingAt = new WeakMap(); +const redrawDue = new WeakSet(); + +export function restSceneAt(timeline: object, time: number): void { + restingAt.set(timeline, time); +} + +export const sceneRestingAt = (timeline: object): number | undefined => restingAt.get(timeline); + +export function takeSceneRedrawDue(timeline: object): boolean { + return redrawDue.delete(timeline); +} + +export function markRestingScenesForRedraw(timelines: readonly object[]): void { + for (const timeline of timelines) if (restingAt.has(timeline)) redrawDue.add(timeline); +} From c19d98d9a15ed060ae1a7c989c7ca10c75bf3488 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 16:40:09 +0000 Subject: [PATCH 138/367] fix(player): a late timeline from the old film no longer keeps a switched player ready (#8500) * test(player): a late timeline from the old document must not make the next load ready * fix(player): a late timeline from the old frame document no longer makes the next load ready * test(player): type the announce filter in the late timeline rows * test(player): a static ready at load still asks for the runtime's held timeline * fix(player): a static ready at load still asks the runtime for the timeline it held * test(player): a late message the left document stamped is dropped without waiting for load * fix(player): drop a late message from the left document, so the next is ready before its load * test(player): the late-timeline row replays the sealed document's own timeline * chore(player): the player's size budget sits 5% above its measured size again * test: runtime load draws no page randomness; Studio pins the announce capability * fix(core): the runtime's document id comes from its time origin, so renders keep their random draws * test(core): two documents loaded at one coarsened time get different runtime ids * fix(core): the runtime's document id is a random UUID where the browser has one --- packages/core/src/runtime/bridge.test.ts | 30 ++++++ packages/core/src/runtime/bridge.ts | 7 +- packages/core/src/runtime/init.ts | 5 + packages/core/src/runtime/protocol.ts | 1 + .../player/src/hyperframes-player.test.ts | 94 +++++++++++++++++++ packages/player/src/hyperframes-player.ts | 42 ++++++++- .../player/src/runtime-message-handler.ts | 4 + .../player/tests/browser/sandbox-origin.ts | 41 ++++++++ .../src/player/lib/runtimeProtocol.test.ts | 1 + scripts/package-size-budgets.json | 4 +- 10 files changed, 222 insertions(+), 7 deletions(-) diff --git a/packages/core/src/runtime/bridge.test.ts b/packages/core/src/runtime/bridge.test.ts index 1e8402b0c0..3329effb77 100644 --- a/packages/core/src/runtime/bridge.test.ts +++ b/packages/core/src/runtime/bridge.test.ts @@ -575,3 +575,33 @@ describe("flash-elements", () => { expect(document.querySelector(".target")?.classList.contains("__hf-flash")).toBe(true); }); }); + +describe("the runtime's document id", () => { + afterEach(() => vi.restoreAllMocks()); + + // fails without the fix: a render seeds crypto.getRandomValues, so an id drawn there shifted the film's random draws. + it("draws nothing from the page's random sources when the runtime loads", async () => { + const values = vi.spyOn(crypto, "getRandomValues"); + const random = vi.spyOn(Math, "random"); + vi.resetModules(); + await import("./bridge"); + expect({ values: values.mock.calls.length, random: random.mock.calls.length }).toEqual({ + values: 0, + random: 0, + }); + }); + + // fails without the fix: a coarsened timeOrigin gave two quick documents one id, so the second was dropped. + it("gives two documents loaded at the same coarsened time different ids", async () => { + vi.spyOn(performance, "timeOrigin", "get").mockReturnValue(1_000); + const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {}); + const idOfNewDocument = async () => { + vi.resetModules(); + const bridge = await import("./bridge"); + bridge.postRuntimeMessage({ source: "hf-preview", type: "timeline" } as never); + return (post.mock.calls.at(-1)![0] as { documentId: string }).documentId; + }; + const [first, second] = [await idOfNewDocument(), await idOfNewDocument()]; + expect(first).not.toBe(second); + }); +}); diff --git a/packages/core/src/runtime/bridge.ts b/packages/core/src/runtime/bridge.ts index 7a779f0b4f..4d2edd5c6d 100644 --- a/packages/core/src/runtime/bridge.ts +++ b/packages/core/src/runtime/bridge.ts @@ -40,6 +40,7 @@ type BridgeDeps = { onSetCopiesAhead?: (on: boolean) => void; onRetryPreviewCopies?: () => void; onRequestPreviewFacts?: () => void; + onAnnounceTimeline?: () => void; onScrubAudio?: (target: PreviewTarget | null, time: number | null, volume: number) => void; getCanonicalFps: () => number; }; @@ -70,10 +71,13 @@ let markedForAnotherSite = false; const forAnotherSite = (): boolean => (markedForAnotherSite ||= typeof document !== "undefined" && servedToAnotherSite(document)); +const UNSEEDED_DOCUMENT_ID = crypto.randomUUID?.() ?? String(performance.timeOrigin); + export function postRuntimeMessage(payload: RuntimeOutboundMessage): void { if (forAnotherSite() && !ANOTHER_SITE_SEES.has(payload.type)) return; try { - window.parent.postMessage({ ...payload, ...runtimeProtocolMetadata(runtimeProtocolFps) }, "*"); + const metadata = runtimeProtocolMetadata(runtimeProtocolFps); + window.parent.postMessage({ ...payload, ...metadata, documentId: UNSEEDED_DOCUMENT_ID }, "*"); } catch (err) { // Cross-frame posting can throw if the parent is gone or origin-isolated. swallow("bridge.postMessage", err); @@ -188,6 +192,7 @@ const CONTROL_HANDLERS = new Map( "set-copies-ahead": (data, deps) => deps.onSetCopiesAhead?.(data.on === true), "retry-preview-copies": (_d, deps) => deps.onRetryPreviewCopies?.(), "request-preview-facts": (_d, deps) => deps.onRequestPreviewFacts?.(), + "announce-timeline": (_d, deps) => deps.onAnnounceTimeline?.(), "set-root-duration": (data, deps) => { const durationSeconds = readNumber(data.durationSeconds, 0); if (durationSeconds !== null) deps.onSetRootDuration(durationSeconds); diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts index d7a1897ba7..ce2b123066 100644 --- a/packages/core/src/runtime/init.ts +++ b/packages/core/src/runtime/init.ts @@ -4063,6 +4063,7 @@ export function initSandboxRuntimeModular(): void { let assetsSettled = false; let liveRootDurationOverrideSeconds = 0; let lastPostedManifest = ""; + let lastTimeline: ReturnType | null = null; const computeClipTreeSignature = (): string => { let sig = ""; for (const el of document.querySelectorAll("[data-start]")) { @@ -4134,6 +4135,7 @@ export function initSandboxRuntimeModular(): void { clipTreeSignature = currentSignature; } + lastTimeline = payload; postRuntimeMessage({ ...payload, assetsReady: assetsSettled }); if (!assetsReadyStarted) { assetsReadyStarted = true; @@ -6842,6 +6844,9 @@ export function initSandboxRuntimeModular(): void { noteDisplayScale(scale); }, onScrubAudio: scrubAudio.scrub, + onAnnounceTimeline: () => { + if (lastTimeline) postRuntimeMessage({ ...lastTimeline, assetsReady: assetsSettled }); + }, onRequestPreviewFacts: () => postRuntimeMessage({ source: "hf-preview", diff --git a/packages/core/src/runtime/protocol.ts b/packages/core/src/runtime/protocol.ts index cec9878800..2927379ef5 100644 --- a/packages/core/src/runtime/protocol.ts +++ b/packages/core/src/runtime/protocol.ts @@ -11,6 +11,7 @@ export const RUNTIME_PROTOCOL_CAPABILITIES = [ "composition-manifest-v1", "runtime-data", "play-range", + "announce-timeline", ] as const; export type RuntimeProtocolFps = { diff --git a/packages/player/src/hyperframes-player.test.ts b/packages/player/src/hyperframes-player.test.ts index 99bdd3cf58..962ae11933 100644 --- a/packages/player/src/hyperframes-player.test.ts +++ b/packages/player/src/hyperframes-player.test.ts @@ -4108,6 +4108,100 @@ describe("HyperframesPlayer asset-ready gate", () => { player.remove(); }); + describe("a timeline between a navigation and the next document's load", () => { + const protocol = (capabilities: string[]) => ({ + protocolVersion: 1, + fps: { numerator: 30, denominator: 1 }, + capabilities, + }); + async function navigatedUnreadable() { + const player = (await createConnectedPlayer()) as PlayerInternal & { + probe: { start(): void }; + _abandonComposition(reason: string): void; + _getSameOriginIframeDocument(): Document | null; + }; + const start = vi.spyOn(player.probe, "start"); + const sent = vi.spyOn(player.iframe.contentWindow!, "postMessage"); + vi.spyOn(player, "_getSameOriginIframeDocument").mockReturnValue(null); + player._abandonComposition("navigated"); + return { player, start, sent }; + } + const announced = (sent: { mock: { calls: unknown[][] } }) => + sent.mock.calls.filter( + ([data]) => (data as { action?: string })?.action === "announce-timeline", + ); + + // fails without the fix: the old document's late timeline made the next sealed load skip its probe. + it("drops a late message the left document stamped, and takes the next document's before its load", async () => { + const { player, start } = await navigatedUnreadable(); + const stamped = (documentId: string) => ({ + type: "timeline", + durationInFrames: 60, + documentId, + ...protocol(["seconds-time", "announce-timeline"]), + }); + post(player, stamped("old")); + player.iframe.dispatchEvent(new Event("load")); + post(player, stamped("old")); + expect(player._ready).toBe(true); + start.mockClear(); + + player._abandonComposition("navigated again"); + post(player, stamped("old")); + expect(player._ready).toBe(false); + post(player, stamped("new")); + expect(player._ready).toBe(true); + + player.iframe.dispatchEvent(new Event("load")); + expect(start).not.toHaveBeenCalled(); + player.remove(); + }); + + it("asks a document that never stamped a message again, and only its answer makes it ready", async () => { + const { player, start, sent } = await navigatedUnreadable(); + const capable = protocol(["seconds-time", "announce-timeline"]); + post(player, { type: "timeline", durationInFrames: 60, ...capable }); + expect(player._ready).toBe(false); + + player.iframe.dispatchEvent(new Event("load")); + expect(start).toHaveBeenCalledOnce(); + expect(announced(sent)).toHaveLength(1); + expect(player._ready).toBe(false); + + post(player, { type: "timeline", durationInFrames: 60, ...capable }); + expect(player._ready).toBe(true); + player.remove(); + }); + + it("takes a runtime's timeline as today when the runtime cannot be asked again", async () => { + const { player, start, sent } = await navigatedUnreadable(); + post(player, { type: "timeline", durationInFrames: 60, ...protocol(["seconds-time"]) }); + + player.iframe.dispatchEvent(new Event("load")); + expect(player._ready).toBe(true); + expect(start).not.toHaveBeenCalled(); + expect(announced(sent)).toHaveLength(0); + player.remove(); + }); + + it("keeps a static-composition ready at load and still asks for the runtime's timeline", async () => { + const { player, sent } = await navigatedUnreadable(); + const capable = protocol(["seconds-time", "announce-timeline"]); + post(player, { type: "static-composition", durationSeconds: 2, width: 640, height: 360 }); + post(player, { type: "timeline", durationInFrames: 60, ...capable }); + + player.iframe.dispatchEvent(new Event("load")); + expect(player._ready).toBe(true); + expect(announced(sent)).toHaveLength(1); + + post(player, { type: "timeline", durationInFrames: 60, ...capable }); + expect((player as unknown as { _readyBeforeRuntime: boolean })._readyBeforeRuntime).toBe( + false, + ); + player.remove(); + }); + }); + it("paints a document before its load when nothing first-frame is pending", async () => { const player = await createConnectedPlayer(); player._ready = false; diff --git a/packages/player/src/hyperframes-player.ts b/packages/player/src/hyperframes-player.ts index 16e4e515b6..c16cd8e0cb 100644 --- a/packages/player/src/hyperframes-player.ts +++ b/packages/player/src/hyperframes-player.ts @@ -134,6 +134,12 @@ class HyperframesPlayer extends HTMLElement { private _ready = false; private _readyBeforeRuntime = false; private _readyDocument: Document | null = null; + private _awaitingLoad = false; + private _documentId: string | null = null; + private _leftDocumentId: string | null = null; + private _leftDocumentUnknown = false; + private _runtimeAnnounces = false; + private _timelineHeldForLoad = false; private _connected = false; private _assetsReady = false; private _painted = false; @@ -1248,10 +1254,20 @@ class HyperframesPlayer extends HTMLElement { private _onMessage(e: MessageEvent) { // The iframe window outlives its documents: a late composition message must not reach a video. - if (this._videoSource || this.probe.failed) return; + if (this._videoSource || this.probe.failed || this._fromLeftDocument(e)) return; this._applyThenEmit(() => this._handleRuntimeMessage(e)); } + /** True for a message the document a host navigation left stamped; another stamp becomes the current document's. */ + private _fromLeftDocument(e: MessageEvent): boolean { + const id = + e.source === this.iframe.contentWindow && (e.data as { documentId?: unknown })?.documentId; + if (typeof id !== "string") return false; + if (id === this._leftDocumentId) return true; + this._documentId = id; + return false; + } + private _handleRuntimeMessage(e: MessageEvent) { handleRuntimeMessage(e, this.iframe.contentWindow, { getPlaybackState: () => ({ @@ -1298,6 +1314,9 @@ class HyperframesPlayer extends HTMLElement { setRuntimeOwnsPlayRange: (owns) => { this._runtimeOwnsPlayRange = owns; }, + setRuntimeAnnounces: (announces) => { + this._runtimeAnnounces = announces; + }, shouldPromoteMediaAutoplayFallback: () => !this._isSlideshowPlayer(), setScenes: (scenes) => { this._scenes = scenes; @@ -1315,6 +1334,11 @@ class HyperframesPlayer extends HTMLElement { } private _onRuntimeTimelineReady(duration: number, assetsReady: boolean | undefined) { + const mayBeLeft = this._awaitingLoad && this._leftDocumentUnknown; + if (mayBeLeft && this._runtimeAnnounces && !this._getSameOriginIframeDocument()) { + this._timelineHeldForLoad = true; + return; + } if (this._ready && !this._readyBeforeRuntime) return; const alreadyReady = this._readyBeforeRuntime; this._readyBeforeRuntime = false; @@ -1483,6 +1507,11 @@ class HyperframesPlayer extends HTMLElement { this.probe.stop(); this._ready = false; this._readyBeforeRuntime = false; + this._awaitingLoad = true; + this._timelineHeldForLoad = false; + this._leftDocumentUnknown = this._documentId === null; + this._leftDocumentId = this._documentId ?? this._leftDocumentId; + this._documentId = null; this._readyDocument = null; this._invalidateAssetsWait(); this._releaseDocument(); @@ -1624,13 +1653,17 @@ class HyperframesPlayer extends HTMLElement { private _onIframeLoad() { // In video mode the iframe only ever loads about:blank; its load must not reset the video. if (!this._connected || this._videoSource) return; - // The runtime posts its timeline once its scripts ran, before or after `load`, and every - // host-initiated navigation clears `_ready` first. So a ready player already holds this - // document's handshake (an opaque origin reads as null); a paused runtime never posts it again. + // A runtime posts its timeline before or after `load`. One seen since a host navigation from a document that never + // stamped a message may be that document's: an unreadable frame's runtime that can be asked again held it, and is + // asked below; else it stands, as a paused runtime never posts again (an opaque origin reads null on both sides). + const askAgain = this._timelineHeldForLoad; + this._awaitingLoad = false; + this._timelineHeldForLoad = false; const doc = this._getSameOriginIframeDocument(); if (this._ready && doc === this._readyDocument) { // Its asset wait scanned at DOMContentLoaded; a script may have added first-frame media since. if (doc && this._hasPendingFirstFrameAssets(doc)) this._waitForAssetsReady(doc); + if (askAgain) this._sendControl("announce-timeline"); return; } @@ -1643,6 +1676,7 @@ class HyperframesPlayer extends HTMLElement { this._invalidateAssetsWait(); this._releaseDocument(); this.probe.start(); + if (askAgain) this._sendControl("announce-timeline"); } private _setupControls() { diff --git a/packages/player/src/runtime-message-handler.ts b/packages/player/src/runtime-message-handler.ts index 69152c63cd..c0dfd7a788 100644 --- a/packages/player/src/runtime-message-handler.ts +++ b/packages/player/src/runtime-message-handler.ts @@ -58,6 +58,7 @@ export interface MessageHandlerCallbacks extends PlaybackStateCallbacks { setBuffering?: (buffering: boolean) => void; setRuntimeFps?: (fps: number) => void; setRuntimeOwnsPlayRange?: (owns: boolean) => void; + setRuntimeAnnounces?: (announces: boolean) => void; /** Called with the scene list whenever a "timeline" message is received. */ setScenes: (scenes: SceneRecord[]) => void; /** Return false to ignore the iframe runtime's audible-media autoplay fallback. @@ -88,6 +89,9 @@ export function handleRuntimeMessage( const ownsPlayRange = protocol.status === "supported" && protocol.metadata.capabilities.includes("play-range"); callbacks.setRuntimeOwnsPlayRange?.(ownsPlayRange); + callbacks.setRuntimeAnnounces?.( + protocol.status === "supported" && protocol.metadata.capabilities.includes("announce-timeline"), + ); if (data["type"] === "shader-transition-state") { const state: ShaderTransitionState = diff --git a/packages/player/tests/browser/sandbox-origin.ts b/packages/player/tests/browser/sandbox-origin.ts index 2ba79434ca..c97ab29ae7 100644 --- a/packages/player/tests/browser/sandbox-origin.ts +++ b/packages/player/tests/browser/sandbox-origin.ts @@ -47,6 +47,47 @@ try { true, "removing the policy must reload into the documented trusted mode", ); + + // fails without the fix: the old document's timeline, landing after a switch, made the new load skip its probe. + const switched = await browser.newPage(); + await switched.evaluateOnNewDocument(() => { + addEventListener("message", (event) => { + const data = event.data as { source?: string; type?: string } | null; + if (data?.source === "hf-preview" && data.type === "timeline") + (window as { __lastTimeline?: unknown }).__lastTimeline = data; + }); + }); + await switched.goto(`${server.origin}/host.html?fixture=gsap-heavy`, { + waitUntil: "domcontentloaded", + }); + await switched.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 }); + await switched.evaluate(() => { + (window as { __lastTimeline?: unknown }).__lastTimeline = undefined; + document.querySelector("hyperframes-player")!.setAttribute("sandbox-origin", "opaque"); + }); + // The sealed document's own timeline, which comes after its static ready: the one a switch leaves behind. + await switched.waitForFunction( + () => (window as { __lastTimeline?: unknown }).__lastTimeline !== undefined, + { timeout: 15_000 }, + ); + const lateError = await switched.evaluate(async () => { + const w = window as { __lastTimeline?: unknown; __playerError?: string }; + const player = document.querySelector("hyperframes-player")!; + const frame = player.shadowRoot!.querySelector("iframe")!; + w.__playerError = undefined; + player.setAttribute("src", "/fixtures/sandbox-probe/index.html"); + dispatchEvent( + new MessageEvent("message", { data: w.__lastTimeline, source: frame.contentWindow }), + ); + const started = performance.now(); + while (performance.now() - started < 14_000 && w.__playerError === undefined) + await new Promise((resolve) => setTimeout(resolve, 100)); + return w.__playerError ?? null; + }); + assert.ok( + lateError, + "a sealed player switched to a film with no runtime must fail, even after a late old timeline", + ); } finally { await browser.close(); await server.stop(); diff --git a/packages/studio/src/player/lib/runtimeProtocol.test.ts b/packages/studio/src/player/lib/runtimeProtocol.test.ts index 3ec66f79fc..98454ed995 100644 --- a/packages/studio/src/player/lib/runtimeProtocol.test.ts +++ b/packages/studio/src/player/lib/runtimeProtocol.test.ts @@ -21,6 +21,7 @@ describe("Studio runtime protocol", () => { "composition-manifest-v1", "runtime-data", "play-range", + "announce-timeline", ], fps: { numerator: 60, denominator: 1 }, timeSeconds: 1.25, diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index 2a816727a4..81b612772d 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -32,8 +32,8 @@ "unpacked": 915000 }, "@hyperframes/player": { - "packed": 162000, - "unpacked": 554000 + "packed": 172000, + "unpacked": 590000 }, "@hyperframes/producer": { "packed": 993551, From 4202462ca5549738c044ce45f09d27fb409a01db Mon Sep 17 00:00:00 2001 From: WaterrrForever Date: Sun, 22 Nov 2026 16:56:27 +0000 Subject: [PATCH 139/367] fix(cli): print project file names in check's stderr notes as visible escapes (#8485) * fix(cli): print project file names in check's stderr notes as visible escapes (SECOPS-2752) The text_over_face note printed the unread video's reason raw, and that reason carries the project's file name and the decoder's own error text, so a video named with ESC, BEL or CR could drive the terminal during `hyperframes check`. The same check output path had four more lines printing project-derived text raw: the project-lock waiting notice (the holder is read from the project's lock file), the "images did not load" warning (image addresses read back from the page), the font-localization warning (the injector's error text), and the saved report's Revision line (read from the project's history). Each now goes through the existing @hyperframes/core terminal-text helper: terminalLines where the text is an error message whose line breaks are kept, terminalText for one-line notices. Plain names print as before. Co-Authored-By: Claude Opus 5.5 * fix(cli): keep check's escape fix within the comment ratchet and testable on Windows (SECOPS-2752) Drop the three comment lines the escape fix added to source files, which raised their comment share. The text_over_face hostile-name test now feeds the name through the candidate and an injected reader, so it runs on every platform; the real-reader case, which needs a file named with control characters, runs everywhere but Windows, whose file names cannot hold them. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../capture/captureCompositionFrame.test.ts | 23 +++++ .../src/capture/captureCompositionFrame.ts | 9 +- packages/cli/src/commands/check.test.ts | 31 +++++++ packages/cli/src/commands/check.ts | 4 +- .../utils/bundleWithLocalizedFonts.test.ts | 19 +++++ .../cli/src/utils/bundleWithLocalizedFonts.ts | 3 +- packages/cli/src/utils/projectLock.test.ts | 34 ++++++++ packages/cli/src/utils/projectLock.ts | 5 +- packages/cli/src/utils/textOverFace.test.ts | 85 +++++++++++++++++++ packages/cli/src/utils/textOverFace.ts | 5 +- 10 files changed, 211 insertions(+), 7 deletions(-) diff --git a/packages/cli/src/capture/captureCompositionFrame.test.ts b/packages/cli/src/capture/captureCompositionFrame.test.ts index 40ed1979b4..25977ba180 100644 --- a/packages/cli/src/capture/captureCompositionFrame.test.ts +++ b/packages/cli/src/capture/captureCompositionFrame.test.ts @@ -19,6 +19,7 @@ import { seekCompositionTimeline, seekCompositionTimelineOnly, settleCompositionSeek, + unloadedImagesWarning, waitForRuntimeReady, type CompositionSeekPage, } from "./captureCompositionFrame.js"; @@ -103,6 +104,28 @@ describe("waitForRuntimeReady", () => { }); }); +describe("unloadedImagesWarning", () => { + // Built rather than written: a literal control character in the source is a lint error. + const esc = String.fromCharCode(27); + const sgr = new RegExp(`${esc}\\[[0-9;]*m`, "g"); + + // fails without the fix: the page's image address reached the terminal with its ESC and BEL raw + it("prints the page's image addresses with control characters as visible escapes", () => { + const line = unloadedImagesWarning( + 5000, + `http://127.0.0.1/hero${esc}]0;owned${String.fromCharCode(7)}.png`, + ).replace(sgr, ""); + expect(line).not.toContain(esc); + expect(line).toContain("http://127.0.0.1/hero\\x1b]0;owned\\x07.png. They may show blank."); + }); + + it("prints plain addresses as they are", () => { + expect(unloadedImagesWarning(5000, "http://127.0.0.1/a.png, b.png").replace(sgr, "")).toBe( + " ⚠ Some images did not load within 5000ms: http://127.0.0.1/a.png, b.png. They may show blank.", + ); + }); +}); + describe("seekCompositionTimeline", () => { it("keeps the raced double-frame settle and adds a bounded font wait by default", async () => { const { page, evaluate, waitForFunction } = fakeSeekPage(); diff --git a/packages/cli/src/capture/captureCompositionFrame.ts b/packages/cli/src/capture/captureCompositionFrame.ts index 4ca69dc254..8c26e8e389 100644 --- a/packages/cli/src/capture/captureCompositionFrame.ts +++ b/packages/cli/src/capture/captureCompositionFrame.ts @@ -6,6 +6,7 @@ import { resolveManagedGpuMode, } from "../browser/launch.js"; import { spawn } from "node:child_process"; +import { terminalText } from "@hyperframes/core/terminal-text"; import type { Browser, Page } from "puppeteer-core"; import type { InProcessRequest, InProcessResponse } from "../utils/staticProjectServer.js"; import { c } from "../ui/colors.js"; @@ -271,13 +272,15 @@ async function waitForCompositionSettle( const { resolveConfig, waitForImagesReady } = await import("@hyperframes/engine"); const imageTimeoutMs = resolveConfig().playerReadyTimeout; await waitForImagesReady(page, imageTimeoutMs, (sources) => - console.warn( - ` ${c.warn("⚠")} Some images did not load within ${imageTimeoutMs}ms: ${sources}. They may show blank.`, - ), + console.warn(unloadedImagesWarning(imageTimeoutMs, sources)), ); return runtimeReady; } +export function unloadedImagesWarning(timeoutMs: number, sources: string): string { + return ` ${c.warn("⚠")} Some images did not load within ${timeoutMs}ms: ${terminalText(sources)}. They may show blank.`; +} + async function waitForLateSubresources(page: Page, timeoutMs: number): Promise { let cap: ReturnType | undefined; const deadline = Date.now() + timeoutMs; diff --git a/packages/cli/src/commands/check.test.ts b/packages/cli/src/commands/check.test.ts index b23ff13bce..e3818aba83 100644 --- a/packages/cli/src/commands/check.test.ts +++ b/packages/cli/src/commands/check.test.ts @@ -521,6 +521,37 @@ describe("check --prepare-media", () => { consumeCommandResult(); }); + // fails without the fix: the revision read from the project's history reached stdout raw + it("prints the saved report's revision with control characters as visible escapes", async () => { + // Built rather than written: a literal control character in the source is a lint error. + const esc = String.fromCharCode(27); + const { report } = await runScenario(fakeDriver()); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + await runCommand( + createCheckCommand({ + resolveProject: () => PROJECT, + runPipeline: async () => ({ + ...report, + saved: { + id: "check-1", + revision: `r1${esc}]0;owned${String.fromCharCode(7)}`, + report: "/work/.hyperframes/artifacts/checks/check-1.json", + attribution: "recorded-revision", + }, + }), + prepareMedia: vi.fn(), + withMeta: (value) => value, + }), + { rawArgs: [] }, + ); + const human = log.mock.calls.map((call) => call.join(" ")).join("\n"); + + expect(human.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "")).not.toContain(esc); + expect(human).toContain("Revision: r1\\x1b]0;owned\\x07 (recorded-revision)"); + expect(human).toContain("Report: /work/.hyperframes/artifacts/checks/check-1.json"); + consumeCommandResult(); + }); + it("prints a folder name with control characters as visible escapes", async () => { // Built rather than written: a literal control character in the source is a lint error. const esc = String.fromCharCode(27); diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index b11f02dc32..101caf5bfa 100644 --- a/packages/cli/src/commands/check.ts +++ b/packages/cli/src/commands/check.ts @@ -371,7 +371,9 @@ export function createCheckCommand( if (report.saved) { console.log(terminalText(`Report: ${report.saved.report}`)); console.log( - `Revision: ${report.saved.revision ?? "none"} (${report.saved.attribution})`, + terminalText( + `Revision: ${report.saved.revision ?? "none"} (${report.saved.attribution})`, + ), ); } } diff --git a/packages/cli/src/utils/bundleWithLocalizedFonts.test.ts b/packages/cli/src/utils/bundleWithLocalizedFonts.test.ts index 1d9300b401..284090faf5 100644 --- a/packages/cli/src/utils/bundleWithLocalizedFonts.test.ts +++ b/packages/cli/src/utils/bundleWithLocalizedFonts.test.ts @@ -81,4 +81,23 @@ describe("localizeWithProducer", () => { // snapshot/check re-bundle per grid point; the warning must fire once. expect(warn).toHaveBeenCalledOnce(); }); + + // fails without the fix: a font address from the project reached the terminal with its ESC raw + it("prints the injector's failure with control characters as visible escapes", async () => { + // Built rather than written: a literal control character in the source is a lint error. + const esc = String.fromCharCode(27); + const printed = vi.spyOn(console, "warn").mockImplementation(() => undefined); + const boom: () => Promise = () => + Promise.reject( + new Error(`cannot fetch fonts/brand${esc}]0;owned${String.fromCharCode(7)}.woff2`), + ); + await localizeWithProducer("", async () => boom); + const line = String(printed.mock.calls[0]?.[0]).replace( + new RegExp(`${esc}\\[[0-9;]*m`, "g"), + "", + ); + printed.mockRestore(); + expect(line).not.toContain(esc); + expect(line).toContain("cannot fetch fonts/brand\\x1b]0;owned\\x07.woff2"); + }); }); diff --git a/packages/cli/src/utils/bundleWithLocalizedFonts.ts b/packages/cli/src/utils/bundleWithLocalizedFonts.ts index 19f869b870..20230120ab 100644 --- a/packages/cli/src/utils/bundleWithLocalizedFonts.ts +++ b/packages/cli/src/utils/bundleWithLocalizedFonts.ts @@ -1,4 +1,5 @@ import type { BundleOptions } from "@hyperframes/core/compiler"; +import { terminalLines } from "@hyperframes/core/terminal-text"; import { normalizeErrorMessage } from "./errorMessage.js"; import { c } from "../ui/colors.js"; @@ -78,7 +79,7 @@ export function __resetFontLocalizationWarningsForTests(): void { export async function localizeWithProducer( html: string, loadInjector: () => Promise = loadFontInjector, - warn: (message: string) => void = (m) => console.warn(` ${c.warn("⚠")} ${m}`), + warn: (message: string) => void = (m) => console.warn(` ${c.warn("⚠")} ${terminalLines(m)}`), ): Promise { const inject = await loadInjector(); if (!inject) return html; diff --git a/packages/cli/src/utils/projectLock.test.ts b/packages/cli/src/utils/projectLock.test.ts index dcbc5c0b43..eee76b21d3 100644 --- a/packages/cli/src/utils/projectLock.test.ts +++ b/packages/cli/src/utils/projectLock.test.ts @@ -116,6 +116,40 @@ describe("withProjectLock", () => { said.mockRestore(); }); + // fails without the fix: the command named in the project's lock file reached stderr raw + it("prints the holder a project's lock file names with control characters as visible escapes", async () => { + // Built rather than written: a literal control character in the source is a lint error. + const esc = String.fromCharCode(27); + const dir = project(); + const lock = projectLockPath(dir); + mkdirSync(dirname(lock), { recursive: true }); + writeFileSync( + lock, + JSON.stringify({ + pid: process.pid, + command: `render${esc}]0;owned${String.fromCharCode(7)}${esc}[2K${String.fromCharCode(13)}`, + startedAt: Date.now(), + }), + ); + const said = vi.spyOn(console, "error").mockImplementation(() => undefined); + const base = Date.now(); + const clock = vi + .spyOn(Date, "now") + .mockReturnValueOnce(base) + .mockReturnValue(base + 6_000); + await expect(withProjectLock(dir, "check", async () => "ran", locked(300))).rejects.toThrow( + ProjectLockTimeout, + ); + clock.mockRestore(); + const line = String(said.mock.calls[0]?.[0]); + said.mockRestore(); + expect(line).not.toContain(esc); + expect(line).not.toContain(String.fromCharCode(13)); + expect(line).toContain( + `waiting for render\\x1b]0;owned\\x07\\x1b[2K\\x0d (pid ${process.pid}, running `, + ); + }); + it("takes over a lock whose process has exited", async () => { const dir = project(); hold(dir, 2 ** 22 + 12345); diff --git a/packages/cli/src/utils/projectLock.ts b/packages/cli/src/utils/projectLock.ts index 0a2015ed4e..72adf4729f 100644 --- a/packages/cli/src/utils/projectLock.ts +++ b/packages/cli/src/utils/projectLock.ts @@ -1,4 +1,5 @@ import { readFileSync, unlinkSync } from "node:fs"; +import { terminalText } from "@hyperframes/core/terminal-text"; import { createFileAtomically } from "@hyperframes/core/atomic-file"; import { join } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; @@ -79,7 +80,9 @@ function sayWaiting(current: Holder | null, waitMs: number): void { if (!current) return; const running = Math.round((Date.now() - current.startedAt) / 1000); console.error( - `[hyperframes] waiting for ${current.command} (pid ${current.pid}, running ${running}s) to finish with this project; waiting up to ${Math.round(waitMs / 1000)}s`, + terminalText( + `[hyperframes] waiting for ${current.command} (pid ${current.pid}, running ${running}s) to finish with this project; waiting up to ${Math.round(waitMs / 1000)}s`, + ), ); } diff --git a/packages/cli/src/utils/textOverFace.test.ts b/packages/cli/src/utils/textOverFace.test.ts index c8092cd6a3..55765884b7 100644 --- a/packages/cli/src/utils/textOverFace.test.ts +++ b/packages/cli/src/utils/textOverFace.test.ts @@ -364,6 +364,91 @@ describe("findTextOverFace on a shipped playlist", () => { ); }); +describe("findTextOverFace's stderr note on a hostile file name", () => { + afterEach(() => vi.restoreAllMocks()); + // Built rather than written: a literal control character in the source is a lint error. + const ESC = String.fromCharCode(27); + const BEL = String.fromCharCode(7); + const CR = String.fromCharCode(13); + + // fails without the fix: the file name the candidate names reached stderr with its ESC, BEL and CR raw + it("prints a project file name with control characters as visible escapes", async () => { + const file = `/project/take${ESC}]0;owned${BEL}${ESC}[2K${CR}clean.mp4`; + const errors = vi.spyOn(console, "error").mockImplementation(() => undefined); + const facesIn = vi.fn(async (named) => { + throw new Error(`could not read every frame of ${named}`); + }); + + const { faceCheck } = await findTextOverFace( + [candidate({ video: { ...candidate().video, file } })], + facesIn, + ); + + expect(facesIn).toHaveBeenCalledWith(file, [7], expect.anything()); + const line = String(errors.mock.calls[0]?.[0]); + for (const raw of [ESC, BEL, CR]) expect(line).not.toContain(raw); + expect(line).toBe( + "[hyperframes] check: text over a face was not looked for in 1 of 1 video(s): could not read every frame of /project/take\\x1b]0;owned\\x07\\x1b[2K\\x0dclean.mp4", + ); + // The report keeps the reason as it was: JSON output escapes it on its own. + expect(faceCheck).toEqual({ ran: false, reason: `could not read every frame of ${file}` }); + }); + + // Windows refuses control characters in a file name, so only other systems can ship one. + // fails without the fix: the real reader's refusal reached stderr with the name's ESC, BEL and CR raw + it.skipIf(process.platform === "win32")( + "escapes a hostile name the real reader refuses", + async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-face-escape-")); + try { + // A playlist naming a file outside its folder is refused before ffprobe runs, by its name. + const file = join(dir, `take${ESC}]0;owned${BEL}${ESC}[2K${CR}clean.m3u8`); + writeFileSync(file, "#EXTM3U\n#EXTINF:1,\n../outside.ts\n#EXT-X-ENDLIST\n"); + const errors = vi.spyOn(console, "error").mockImplementation(() => undefined); + + const { faceCheck } = await findTextOverFace([ + candidate({ video: { ...candidate().video, file } }), + ]); + + expect(errors).toHaveBeenCalledTimes(1); + const line = String(errors.mock.calls[0]?.[0]); + for (const raw of [ESC, BEL, CR]) expect(line).not.toContain(raw); + expect(line).toContain(`take\\x1b]0;owned\\x07\\x1b[2K\\x0dclean.m3u8 is not media`); + expect(faceCheck).toMatchObject({ ran: false, reason: expect.stringContaining(file) }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, + ); + + it("keeps a plain reason, its line breaks included, exactly as before", async () => { + const errors = vi.spyOn(console, "error").mockImplementation(() => undefined); + const facesIn = vi.fn(async () => { + throw new Error("ffmpeg cannot read /project/take.mp4:\nInvalid data found"); + }); + + await findTextOverFace([candidate()], facesIn); + + expect(errors).toHaveBeenCalledWith( + "[hyperframes] check: text over a face was not looked for in 1 of 1 video(s): ffmpeg cannot read /project/take.mp4:\nInvalid data found", + ); + }); + + // fails without the fix: an error text the decoder wrote reached stderr with its ESC raw + it("escapes control characters in the error text as well as the file name", async () => { + const errors = vi.spyOn(console, "error").mockImplementation(() => undefined); + const facesIn = vi.fn(async () => { + throw new Error(`decoder said ${ESC}[31mred${BEL}`); + }); + + await findTextOverFace([candidate()], facesIn); + + expect(String(errors.mock.calls[0]?.[0])).toBe( + "[hyperframes] check: text over a face was not looked for in 1 of 1 video(s): decoder said \\x1b[31mred\\x07", + ); + }); +}); + describe.skipIf(!findFFprobe())("findTextOverFace on a source the time limit stops", () => { afterEach(() => { stalled.file = ""; diff --git a/packages/cli/src/utils/textOverFace.ts b/packages/cli/src/utils/textOverFace.ts index fe4bb547b2..bfe6b07f1b 100644 --- a/packages/cli/src/utils/textOverFace.ts +++ b/packages/cli/src/utils/textOverFace.ts @@ -7,6 +7,7 @@ import type { FaceCheck, TextOverVideoCandidate, } from "./checkTypes.js"; +import { terminalLines } from "@hyperframes/core/terminal-text"; import { normalizeErrorMessage } from "./errorMessage.js"; /** Below this share of the face a descender or a letter's corner touches it, which hides nothing. */ @@ -190,7 +191,9 @@ export async function findTextOverFace( const reason = unread[0]; if (reason !== undefined) { console.error( - `[hyperframes] check: text over a face was not looked for in ${unread.length} of ${timesByFile.size} video(s): ${reason}`, + terminalLines( + `[hyperframes] check: text over a face was not looked for in ${unread.length} of ${timesByFile.size} video(s): ${reason}`, + ), ); if (faces.size === 0) return { issues: [], faceCheck: { ran: false, reason } }; } From 886f609c43b3e622402d2856ba5e63165e248f76 Mon Sep 17 00:00:00 2001 From: WaterrrForever Date: Sun, 22 Nov 2026 17:00:42 +0000 Subject: [PATCH 140/367] fix(cli): publish updates a committed project only when this machine linked the folder (#8487) * fix(cli): publish updates a committed project only when this machine linked the folder (SECOPS-2048) .hyperframes/project.json travels with every copy of a project (a clone, a zip, a download), yet publish took its project id and space id as the update target, and with --yes overwrote any project the recipient could write without asking. Publish now updates the descriptor's project, and uses its space, only when this machine's own link record (outside the folder, keyed by its path) names the same project and space. The link record now keeps the space it published into; records from before keep linking their own project. Otherwise: - interactively, publish asks "Update project in place? No publishes this folder as its own project." with No as the default; No publishes a new project and rewrites the descriptor to it - with --yes, publish refuses (publish_target_unconfirmed) and points to --update [--space ] - --update still names the project explicitly, but the descriptor's space is not used unless --space names it checkPublishTransition counts the descriptor as a legacy update under the same rule. Co-Authored-By: Claude Opus 5.5 * refactor(cli): carry the publish link rules in names, not comments (SECOPS-2048) The comment ratchet allows a file's comment share only to go down. Drop the comments the fix added and name the meaning instead: PERSONAL_SPACE for the "" space id, recordPredatesSpaces for a link record written before the space was kept, teamLinkedHere in the publish transition. Co-Authored-By: Claude Opus 5.5 * test(cli): keep projectLink's real exports in the publishProject mock (SECOPS-2048) publishProject now imports PERSONAL_SPACE from projectLink; the mock replaced the whole module, so the constant was missing. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- packages/cli/src/commands/publish.test.ts | 156 +++++++++++++++++- packages/cli/src/commands/publish.ts | 64 ++++++- .../cli/src/share/publishTransition.test.ts | 13 +- packages/cli/src/share/publishTransition.ts | 8 +- packages/cli/src/utils/projectLink.test.ts | 40 ++++- packages/cli/src/utils/projectLink.ts | 22 ++- packages/cli/src/utils/publishProject.test.ts | 4 +- packages/cli/src/utils/publishProject.ts | 18 +- 8 files changed, 303 insertions(+), 22 deletions(-) diff --git a/packages/cli/src/commands/publish.test.ts b/packages/cli/src/commands/publish.test.ts index 52514d1eba..35face9281 100644 --- a/packages/cli/src/commands/publish.test.ts +++ b/packages/cli/src/commands/publish.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; @@ -240,6 +240,8 @@ describe("publish visibility messaging", () => { vi.stubEnv("HYPERFRAMES_CONFIG_DIR", config); vi.stubEnv("HEYGEN_API_KEY", ""); vi.stubEnv("HYPERFRAMES_API_KEY", ""); + // This machine published the folder there, so the descriptor is its own link. + writeProjectLink(project, { projectId: "existing-\u001b[2Kproject", url: "", spaceId: "" }); publishState.publish.mockReset(); publishState.confirm.mockReset(); publishState.confirm.mockResolvedValue(false); @@ -622,6 +624,158 @@ describe("publish --update / --space ownership preflight", () => { }); }); +describe("publish with a committed team descriptor (SECOPS-2048)", () => { + // `.hyperframes/project.json` travels with every copy of a folder; only this machine's own + // record (outside the folder, keyed by its path) may make it pick the project to overwrite. + async function runWithDescriptor(options: { + team: { projectId: string; spaceId?: string }; + record?: { projectId: string; spaceId?: string }; + args?: Record; + answers?: boolean[]; + }): Promise<{ output: string; error: unknown; exitCode: number; descriptor: string }> { + const project = mkdtempSync(join(tmpdir(), "hf-publish-received-")); + const config = mkdtempSync(join(tmpdir(), "hf-publish-received-config-")); + writeFileSync(join(project, "index.html"), VISIBLE_INDEX); + vi.stubEnv("HYPERFRAMES_CONFIG_DIR", config); + vi.stubEnv("HEYGEN_API_KEY", ""); + vi.stubEnv("HYPERFRAMES_API_KEY", ""); + writeTeamProject(project, options.team); + if (options.record) { + writeProjectLink(project, { + projectId: options.record.projectId, + url: `https://hyperframes.dev/p/${options.record.projectId}`, + ...(options.record.spaceId !== undefined ? { spaceId: options.record.spaceId } : {}), + }); + } + publishState.publish.mockReset(); + publishState.publish.mockImplementation(async (_dir: string, opts: { projectId?: string }) => ({ + title: "test", + fileCount: 1, + claimed: true, + // The server updates a project the user can write, so it echoes the requested id. + projectId: opts.projectId, + url: `https://hyperframes.dev/p/${String(opts.projectId)}`, + })); + publishState.confirm.mockReset(); + for (const answer of options.answers ?? []) publishState.confirm.mockResolvedValueOnce(answer); + let error: unknown; + try { + await writeStore({ oauth: { access_token: "token" } }, join(config, "credentials")); + consumeCommandResult(); + const output = await captureLog(async () => { + try { + await publishCommand.run?.({ + args: { dir: project, public: false, proxy: false, ...options.args }, + } as never); + } catch (err) { + error = err; + } + }); + const descriptor = readFileSync(join(project, ".hyperframes", "project.json"), "utf-8"); + return { output, error, exitCode: consumeCommandResult().exitCode, descriptor }; + } finally { + vi.unstubAllEnvs(); + rmSync(project, { recursive: true, force: true }); + rmSync(config, { recursive: true, force: true }); + } + } + + it("refuses --yes for a received descriptor instead of updating the project it names", async () => { + const { error, descriptor } = await runWithDescriptor({ + team: { projectId: "victim-project", spaceId: "victim-space" }, + args: { yes: true }, + }); + + expect(publishState.publish).not.toHaveBeenCalled(); + expect(error).toMatchObject({ + name: "CliUsageError", + code: "publish_target_unconfirmed", + message: + ".hyperframes/project.json names project victim-project in team space victim-space, but this machine has not published this folder to it, so --yes will not update it.", + hint: "To update that project, run again with --update victim-project --space victim-space. To publish this folder as its own project, delete .hyperframes/project.json and run again.", + }); + expect(descriptor).toContain("victim-project"); + }); + + it("asks before updating a received descriptor's project, defaulting to a new project", async () => { + const { output, descriptor } = await runWithDescriptor({ + team: { projectId: "victim-project", spaceId: "victim-space" }, + answers: [false, true], + }); + + expect(output).toContain( + ".hyperframes/project.json names project victim-project in team space victim-space, but this machine has not published this folder to it.", + ); + expect(publishState.confirm).toHaveBeenNthCalledWith(1, { + message: + "Update project victim-project in place? No publishes this folder as its own project.", + initialValue: false, + }); + expect(publishState.publish).toHaveBeenCalledTimes(1); + const [, opts] = publishState.publish.mock.calls[0] as [string, Record]; + expect(opts.projectId).not.toBe("victim-project"); + expect(opts.spaceId).toBeUndefined(); + // The folder is now its own project, so its descriptor names the new one. + expect(descriptor).not.toContain("victim-project"); + expect(descriptor).toContain(String(opts.projectId)); + }); + + it("updates a received descriptor's project and space once the user confirms", async () => { + await runWithDescriptor({ + team: { projectId: "team-project", spaceId: "team-space" }, + answers: [true, true], + }); + + expect(publishState.publish).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ projectId: "team-project", spaceId: "team-space" }), + ); + }); + + it("does not take the space from a received descriptor when --update names the project", async () => { + await runWithDescriptor({ + team: { projectId: "team-project", spaceId: "team-space" }, + args: { yes: true, update: "team-project" }, + }); + + expect(publishState.publish).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ projectId: "team-project", spaceId: undefined }), + ); + }); + + it("refuses --yes when the descriptor's space differs from the one this machine published to", async () => { + const { error } = await runWithDescriptor({ + team: { projectId: "own-project", spaceId: "other-space" }, + record: { projectId: "own-project", spaceId: "" }, + args: { yes: true }, + }); + + expect(error).toMatchObject({ code: "publish_target_unconfirmed" }); + expect(publishState.publish).not.toHaveBeenCalled(); + }); + + it.each([ + { name: "a record that keeps the space", record: { projectId: "own", spaceId: "team" } }, + { name: "a record from before the space was kept", record: { projectId: "own" } }, + ])("re-publishes in place without asking from $name", async ({ record }) => { + const { output, error, exitCode } = await runWithDescriptor({ + team: { projectId: "own", spaceId: "team" }, + record, + args: { yes: true }, + }); + + expect(error).toBeUndefined(); + expect(exitCode).toBe(0); + expect(publishState.confirm).not.toHaveBeenCalled(); + expect(publishState.publish).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ projectId: "own", spaceId: "team" }), + ); + expect(output).toContain("Updated existing project"); + }); +}); + describe("expired transition preserves only owned legacy updates", () => { it.each(["anonymous", "api-key", "oauth"])( "checks %s ownership before publication", diff --git a/packages/cli/src/commands/publish.ts b/packages/cli/src/commands/publish.ts index eff83d23c3..558981aceb 100644 --- a/packages/cli/src/commands/publish.ts +++ b/packages/cli/src/commands/publish.ts @@ -1,6 +1,6 @@ import { assertLegacyPublishOwner, checkPublishTransition } from "../share/publishTransition.js"; import { join, posix, relative, resolve } from "node:path"; -import { failCommand, setCommandExitCode } from "../utils/commandResult.js"; +import { CliUsageError, failCommand, setCommandExitCode } from "../utils/commandResult.js"; import { existsSync } from "node:fs"; import { terminalLines, terminalText } from "@hyperframes/core"; import { defineCommand } from "../utils/defineCommand.js"; @@ -29,6 +29,8 @@ import { ensureProjectId, readProjectLink, readTeamProject, + type TeamProject, + teamProjectLinkedHere, writeTeamProject, } from "../utils/projectLink.js"; import { cliSourced } from "../utils/sourceTag.js"; @@ -47,6 +49,24 @@ export const examples: Example[] = [ ["Show full lint findings instead of the summary line", "hyperframes publish --lint-verbose"], ]; +const shownId = (id: string): string => id.replace(/[^!-~]/g, "?"); + +function describeTeamProject(team: TeamProject): string { + const space = team.spaceId ? ` in team space ${shownId(team.spaceId)}` : ""; + return `project ${shownId(team.projectId)}${space}`; +} + +export function unlinkedTeamProjectError(team: TeamProject): CliUsageError { + const space = team.spaceId ? ` --space ${shownId(team.spaceId)}` : ""; + return new CliUsageError( + `.hyperframes/project.json names ${describeTeamProject(team)}, but this machine has not published this folder to it, so --yes will not update it.`, + { + code: "publish_target_unconfirmed", + hint: `To update that project, run again with --update ${shownId(team.projectId)}${space}. To publish this folder as its own project, delete .hyperframes/project.json and run again.`, + }, + ); +} + /** Extract a project id from a published URL (with or without scheme, query, or hash) or accept a bare id. */ export function parseUpdateTarget(value: string): string { const trimmed = value.trim(); @@ -196,11 +216,40 @@ export default defineCommand({ } } + let linkedTeam: TeamProject | null = + committedTeam && teamProjectLinkedHere(dir, committedTeam) ? committedTeam : null; + let declinedTeam = false; + if (committedTeam && !linkedTeam && !updateTarget && credential?.type === "oauth") { + if (args.yes === true) throw unlinkedTeamProjectError(committedTeam); + console.log(); + console.log( + ` ${c.bold(terminalText(`.hyperframes/project.json names ${describeTeamProject(committedTeam)}, but this machine has not published this folder to it.`))}`, + ); + console.log( + ` ${c.dim("It may have come with a cloned, copied or downloaded project. Updating it overwrites that project for everyone who can open it.")}`, + ); + console.log(); + const adopt = await clack.confirm({ + message: terminalText( + `Update project ${shownId(committedTeam.projectId)} in place? No publishes this folder as its own project.`, + ), + initialValue: false, + }); + if (clack.isCancel(adopt)) { + console.log(); + console.log(` ${c.dim("Aborted.")}`); + console.log(); + return; + } + if (adopt === true) linkedTeam = committedTeam; + else declinedTeam = true; + } + const existingTarget = credential?.type === "oauth" ? ( updateTarget ?? - committedTeam?.projectId ?? + linkedTeam?.projectId ?? (priorLink?.url ? priorLink.projectId : undefined) )?.replace(/[^!-~]/g, "?") : undefined; @@ -238,10 +287,10 @@ export default defineCommand({ } } - // Stable id: explicit --update wins, else the committed team id, else this machine's stored/minted id. - const requestedProjectId = updateTarget ?? committedTeam?.projectId ?? ensureProjectId(dir); - // Team space: explicit --space wins, else the committed space id, else the personal space. - const spaceId = spaceOverride ?? committedTeam?.spaceId; + // Stable id: explicit --update wins, else the linked team id, else this machine's stored/minted id. + const requestedProjectId = updateTarget ?? linkedTeam?.projectId ?? ensureProjectId(dir); + // Team space: explicit --space wins, else the linked space id, else the personal space. + const spaceId = spaceOverride ?? linkedTeam?.spaceId; // Continuity cue: if this directory was published before, show where it lives so the // user knows a re-publish updates that same link (when logged in). @@ -353,7 +402,7 @@ export default defineCommand({ // Warn whenever we aimed at a KNOWN existing project (an explicit --update target or // a committed team id) but the server created a fresh one instead — so a teammate // whose space doesn't own the committed project doesn't silently lose the shared link. - if ((updateTarget || committedTeam) && !updatedInPlace) { + if ((updateTarget || linkedTeam) && !updatedInPlace) { const targetDesc = updateTarget ? "The requested project" : "The committed team project"; console.log(); console.log( @@ -365,6 +414,7 @@ export default defineCommand({ // into a "Publish failed" (the outer catch owns publish failures only). if ( committedTeam === null || + declinedTeam || (spaceId !== undefined && committedTeam.spaceId !== spaceId) ) { try { diff --git a/packages/cli/src/share/publishTransition.test.ts b/packages/cli/src/share/publishTransition.test.ts index bf84cb1fbe..b7d5e166b4 100644 --- a/packages/cli/src/share/publishTransition.test.ts +++ b/packages/cli/src/share/publishTransition.test.ts @@ -73,10 +73,21 @@ describe("publish transition guard", () => { expect.stringContaining("uses the legacy update workflow"), ); }); - it("keeps committed team project targets", () => { + it("keeps committed team project targets this machine linked the folder to", () => { writeTeamProject(dir, { projectId: "legacy-team", spaceId: "team" }); + writeProjectLink(dir, { projectId: "legacy-team", url: "", spaceId: "team" }); expect(() => checkPublishTransition({ dir }, start)).not.toThrow(); }); + it("does not count a received team descriptor as this user's legacy update", () => { + writeTeamProject(dir, { projectId: "someone-elses", spaceId: "team" }); + expect(() => checkPublishTransition({ dir }, start)).toThrowError( + expect.objectContaining({ code: "publish_replaced" }), + ); + writeProjectLink(dir, { projectId: "mine", url: "" }); + expect(() => checkPublishTransition({ dir }, start)).toThrowError( + expect.objectContaining({ code: "publish_replaced" }), + ); + }); it("does not count an unused local identity or whitespace as a published project", () => { writeProjectLink(dir, { projectId: "unused", url: "" }); expect(() => checkPublishTransition({ dir, update: " " }, start)).toThrowError(CliUsageError); diff --git a/packages/cli/src/share/publishTransition.ts b/packages/cli/src/share/publishTransition.ts index e562188c67..b76a0be965 100644 --- a/packages/cli/src/share/publishTransition.ts +++ b/packages/cli/src/share/publishTransition.ts @@ -1,7 +1,7 @@ import { resolve } from "node:path"; import { CliUsageError } from "../utils/commandResult.js"; import { asNotice } from "../utils/jsonError.js"; -import { readProjectLink, readTeamProject } from "../utils/projectLink.js"; +import { readProjectLink, readTeamProject, teamProjectLinkedHere } from "../utils/projectLink.js"; /** Set to the announced notice release's UTC timestamp in the release PR, after launch gates pass. */ const PUBLISH_NOTICE_RELEASE: string | null = null; @@ -30,9 +30,9 @@ export function checkPublishTransition( ): ReturnType { const dir = resolve(args.dir ?? "."); const prior = readProjectLink(dir); - const legacyUpdate = Boolean( - args.update?.trim() || prior?.url || readTeamProject(dir)?.projectId, - ); + const team = readTeamProject(dir); + const teamLinkedHere = team !== null && teamProjectLinkedHere(dir, team); + const legacyUpdate = Boolean(args.update?.trim() || prior?.url || teamLinkedHere); const phase = publishPhase(noticeRelease); asNotice(() => process.stderr.write(publishNotice(phase, legacyUpdate) + "\n")); if (publishTransitionDecision(phase, legacyUpdate) === "guide_to_share") { diff --git a/packages/cli/src/utils/projectLink.test.ts b/packages/cli/src/utils/projectLink.test.ts index 0a43b32ddd..3ca91fdc7a 100644 --- a/packages/cli/src/utils/projectLink.test.ts +++ b/packages/cli/src/utils/projectLink.test.ts @@ -27,14 +27,21 @@ describe("projectLink", () => { let writeProjectLink: typeof import("./projectLink.js").writeProjectLink; let readTeamProject: typeof import("./projectLink.js").readTeamProject; let writeTeamProject: typeof import("./projectLink.js").writeTeamProject; + let teamProjectLinkedHere: typeof import("./projectLink.js").teamProjectLinkedHere; beforeEach(async () => { osState.home = mkdtempSync(join(tmpdir(), "hf-home-")); projectsPath = join(osState.home, ".hyperframes", "projects.json"); projectDirs = []; vi.resetModules(); - ({ ensureProjectId, readProjectLink, writeProjectLink, readTeamProject, writeTeamProject } = - await import("./projectLink.js")); + ({ + ensureProjectId, + readProjectLink, + writeProjectLink, + readTeamProject, + writeTeamProject, + teamProjectLinkedHere, + } = await import("./projectLink.js")); }); afterEach(() => { @@ -149,4 +156,33 @@ describe("projectLink", () => { expect(() => writeTeamProject(dir, { projectId: "hfp_new" })).toThrow(/Could not write/); expect(readFileSync(victim, "utf-8")).toBe("victim bytes\n"); }); + + it("keeps the published space in the link record", () => { + const dir = makeProjectDir(); + writeProjectLink(dir, { projectId: "hfp_1", url: "u", spaceId: "space-1" }); + expect(readProjectLink(dir)).toEqual({ projectId: "hfp_1", url: "u", spaceId: "space-1" }); + }); + + it("links a team descriptor only when this machine's record names its project and space", () => { + const dir = makeProjectDir(); + const team = { projectId: "hfp_team", spaceId: "space-42" }; + + // A descriptor that came with the folder, and nothing on this machine. + expect(teamProjectLinkedHere(dir, team)).toBe(false); + + writeProjectLink(dir, { projectId: "hfp_other", url: "u", spaceId: "space-42" }); + expect(teamProjectLinkedHere(dir, team)).toBe(false); + + writeProjectLink(dir, { projectId: "hfp_team", url: "u", spaceId: "" }); + expect(teamProjectLinkedHere(dir, team)).toBe(false); + + writeProjectLink(dir, { projectId: "hfp_team", url: "u", spaceId: "space-42" }); + expect(teamProjectLinkedHere(dir, team)).toBe(true); + expect(teamProjectLinkedHere(makeProjectDir(), team)).toBe(false); + + // A record from before the space was kept still links its own project. + writeProjectLink(dir, { projectId: "hfp_team", url: "u" }); + expect(teamProjectLinkedHere(dir, team)).toBe(true); + expect(teamProjectLinkedHere(dir, { projectId: "hfp_team" })).toBe(true); + }); }); diff --git a/packages/cli/src/utils/projectLink.ts b/packages/cli/src/utils/projectLink.ts index 578d69d78c..fdbae7a08c 100644 --- a/packages/cli/src/utils/projectLink.ts +++ b/packages/cli/src/utils/projectLink.ts @@ -8,8 +8,11 @@ import { readRecord, recordKind, writeRecord } from "./projectRecords.js"; interface ProjectLink { projectId: string; url: string; + spaceId?: string; } +export const PERSONAL_SPACE = ""; + type ProjectLinks = Record; const configDir = () => hyperframesConfigDir(); @@ -42,13 +45,21 @@ function isProjectLink(value: unknown): value is ProjectLink { ); } +function projectLinkRecord(link: ProjectLink): ProjectLink { + return { + projectId: link.projectId, + url: link.url, + ...(typeof link.spaceId === "string" ? { spaceId: link.spaceId } : {}), + }; +} + function readProjectLinks(): ProjectLinks { const record = readJsonRecord(projectsFile()); if (!record) return {}; const links: ProjectLinks = {}; for (const [path, value] of Object.entries(record)) { if (isProjectLink(value)) { - links[path] = { projectId: value.projectId, url: value.url }; + links[path] = projectLinkRecord(value); } } return links; @@ -69,7 +80,7 @@ export function readProjectLink(absDir: string): ProjectLink | null { export function writeProjectLink(absDir: string, link: ProjectLink): void { const links = readProjectLinks(); - links[resolve(absDir)] = { projectId: link.projectId, url: link.url }; + links[resolve(absDir)] = projectLinkRecord(link); writeProjectLinks(links); } @@ -130,3 +141,10 @@ export function writeTeamProject(projectDir: string, team: TeamProject): string throw new Error(`Could not write ${file}`); return file; } + +export function teamProjectLinkedHere(projectDir: string, team: TeamProject): boolean { + const link = readProjectLink(projectDir); + if (!link || link.projectId !== team.projectId) return false; + const recordPredatesSpaces = link.spaceId === undefined; + return recordPredatesSpaces || link.spaceId === (team.spaceId ?? PERSONAL_SPACE); +} diff --git a/packages/cli/src/utils/publishProject.test.ts b/packages/cli/src/utils/publishProject.test.ts index db2a86f37f..1223f708ae 100644 --- a/packages/cli/src/utils/publishProject.test.ts +++ b/packages/cli/src/utils/publishProject.test.ts @@ -25,7 +25,8 @@ const linkMocks = vi.hoisted(() => ({ writeProjectLink: vi.fn(), })); -vi.mock("./projectLink.js", () => ({ +vi.mock("./projectLink.js", async (importOriginal) => ({ + ...(await importOriginal()), writeProjectLink: linkMocks.writeProjectLink, })); @@ -1205,6 +1206,7 @@ describe("publishProjectArchive", () => { expect(linkMocks.writeProjectLink).toHaveBeenCalledWith(dir, { projectId: "hfp_stable", url: "https://hyperframes.dev/p/hfp_stable", + spaceId: "", }); } finally { rmSync(dir, { recursive: true, force: true }); diff --git a/packages/cli/src/utils/publishProject.ts b/packages/cli/src/utils/publishProject.ts index 43bee211bf..2fc2677713 100644 --- a/packages/cli/src/utils/publishProject.ts +++ b/packages/cli/src/utils/publishProject.ts @@ -22,7 +22,7 @@ import { tryResolveCredential } from "../auth/index.js"; import { isAuthError } from "../auth/errors.js"; import { envCredentialVar, isTokenExpired, type ResolvedCredential } from "../auth/resolver.js"; import { refreshIfNeeded } from "../cloud/auth.js"; -import { writeProjectLink } from "./projectLink.js"; +import { PERSONAL_SPACE, writeProjectLink } from "./projectLink.js"; import { isHiddenProjectFile, isPrivateCompositionFile, @@ -1241,8 +1241,18 @@ export async function publishProjectArchive( throw error; } // Remember the server's id + url so the next publish of this directory updates in place. - if (result.claimed) { - writeProjectLink(projectDir, { projectId: result.projectId, url: result.url }); - } + if (result.claimed) rememberPublishedLink(projectDir, result, spaceId); return result; } + +function rememberPublishedLink( + projectDir: string, + result: PublishedProjectResponse, + spaceId: string | undefined, +): void { + writeProjectLink(projectDir, { + projectId: result.projectId, + url: result.url, + spaceId: spaceId ?? PERSONAL_SPACE, + }); +} From bd7a8402db87662cf256c4e2e29212c03b48b7de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 17:03:38 +0000 Subject: [PATCH 141/367] fix(studio): paste and duplicate check the file they write, after every edit to it (#8519) * test(studio): a paste writes only the markup it checked, comments included * fix(studio): paste and duplicate check the file they write, after every edit to it * test(studio): the paste check reads the saved copy's values and the file's parsed ids * fix(studio): the paste check allows the copy as saved in the file, matched by its values * fix(studio): a copied look rule is skipped only when it holds a tag opener * test(studio): a paste is checked as a tree, as the preview server serves the file * fix(studio): the paste check compares whole copies in the file as the preview serves it * test(studio): a batch paste compares each copy only with its own candidates * perf(studio): the paste check finds each copy by its signature, not by scanning the file --- .../src/hooks/useClipboard.sealed.test.ts | 70 ++++++ .../studio/src/hooks/useClipboard.test.ts | 11 +- packages/studio/src/hooks/useClipboard.ts | 131 ++++------ .../src/hooks/useClipboard.written.test.ts | 238 ++++++++++++++++++ packages/studio/src/utils/clipboardLook.ts | 59 ++--- packages/studio/src/utils/clipboardMarkup.ts | 157 +++++++++++- .../studio/src/utils/clipboardPayload.test.ts | 26 -- packages/studio/src/utils/clipboardPayload.ts | 16 -- .../studio/src/utils/timelineAssetDrop.ts | 10 +- 9 files changed, 542 insertions(+), 176 deletions(-) create mode 100644 packages/studio/src/hooks/useClipboard.written.test.ts diff --git a/packages/studio/src/hooks/useClipboard.sealed.test.ts b/packages/studio/src/hooks/useClipboard.sealed.test.ts index 4023cad5c5..728aa00bc2 100644 --- a/packages/studio/src/hooks/useClipboard.sealed.test.ts +++ b/packages/studio/src/hooks/useClipboard.sealed.test.ts @@ -8,6 +8,7 @@ import { usePlayerStore, type TimelineElement } from "../player"; import type { DomEditSelection } from "../components/editor/domEditing"; import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers"; import { setCompositionSourceMap } from "../components/editor/domEditingDom"; +import { parseHTMLContent } from "@hyperframes/core/compiler/html-document"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -178,6 +179,75 @@ it("pastes a sealed preview's own element only when its markup runs no code", as } }); +// The sealed path to the writes useClipboard.written.test.ts fails main on; jsdom keeps CSS escapes, so this one holds. +it("writes no running code when a sealed preview's own element hides markup in a comment", async () => { + const hidden = [ + '
Made
', + ]; + for (const markup of hidden) { + const selection = { + id: "made", + selector: "#made", + sourceFile: "index.html", + } as DomEditSelection; + const { clipboard, writes } = sealedClipboard( + selection, + markup, + SAVED.replace("", ""), + ); + expect(clipboard().handleCopy()).toBe(true); + await clipboard().handlePaste(); + for (const written of writes) { + const parsed = new DOMParser().parseFromString(written, "text/html"); + const handlers = Array.from(parsed.querySelectorAll("*")).flatMap((el) => + el.getAttributeNames().filter((name) => name.startsWith("on")), + ); + expect(handlers).toEqual([]); + } + act(() => root?.unmount()); + root = null; + } +}); + +/** Handlers in a written file, read as saved and as the preview server serves it. */ +function handlersServed(written: string): string[] { + return [written, parseHTMLContent(written).toString()].flatMap((html) => + Array.from(new DOMParser().parseFromString(html, "text/html").querySelectorAll("*")).flatMap( + (el) => el.getAttributeNames().filter((name) => name.startsWith("on")), + ), + ); +} + +// fails without the fix: a comment in an svg passed the check, and the server's parser serves it as markup. +it("writes nothing the server serves as running code, from the live copy or a saved one", async () => { + const svg = "<svg><title><!-- -->"; + const live = sealedClipboard( + { id: "made", selector: "#made", sourceFile: "index.html" } as DomEditSelection, + `
${svg}
`, + ); + expect(live.clipboard().handleCopy()).toBe(true); + await live.clipboard().handlePaste(); + for (const file of live.writes) expect(handlersServed(file)).toEqual([]); + act(() => root?.unmount()); + root = null; + + setCompositionSourceMap(new Map([["recv", "compositions/recv.html"]])); + const received = `
+
${svg}
+
`; + const saved = sealedClipboard( + { id: "go", selector: "#go", sourceFile: "compositions/recv.html" } as DomEditSelection, + `
${svg}
`, + SAVED, + { "compositions/recv.html": received }, + ); + expect(saved.clipboard().handleCopy()).toBe(true); + await saved.clipboard().handlePaste(); + for (const file of saved.writes) expect(handlersServed(file)).toEqual([]); +}); + // fails without the fix: markup the copy found in another file was taken as saved and pasted unchecked. it("checks a saved element read from another file before pasting it into this one", async () => { const received = `
diff --git a/packages/studio/src/hooks/useClipboard.test.ts b/packages/studio/src/hooks/useClipboard.test.ts index a165aa0d1b..738306287f 100644 --- a/packages/studio/src/hooks/useClipboard.test.ts +++ b/packages/studio/src/hooks/useClipboard.test.ts @@ -215,20 +215,17 @@ describe("pasteTimelineClips", () => { expect(hfIdsIn(content)).toHaveLength(1); }); - it("still strips data-hf-id from bare text with no element root", () => { + it("refuses bare text with no element root", () => { const noRoot: TimelineClipboardClip = { html: 'text mentioning data-hf-id="hf-leak" with no tag at all', start: 0, duration: 1, track: 0, }; - const { content } = pasteTimelineClips(ROOT, [noRoot], 0, []); - expect(content).not.toContain("data-hf-id"); + expect(() => pasteTimelineClips(ROOT, [noRoot], 0, [])).toThrow(/^Couldn't paste/); }); - it("still strips data-hf-id from a tag the HTML parser hoists out of body (e.g. title)", () => { - // A never reaches DOMParser's body, so remintHfIds's DOM walk sees - // no root element here -- this exercises the regex fallback, not the walk. + it("gives a tag a document would hoist out of body (e.g. title) a fresh data-hf-id, never the copied one", () => { // Only an in-file copy gets that far: from anywhere else a <title> is refused. const hoisted: TimelineClipboardClip = { html: '<title data-hf-id="hf-leak">x', @@ -238,7 +235,7 @@ describe("pasteTimelineClips", () => { track: 0, }; const { content } = pasteTimelineClips(ROOT, [hoisted], 0, [], true, "index.html"); - expect(content).not.toContain("data-hf-id"); + expect(content).not.toContain("hf-leak"); expect(() => pasteTimelineClips(ROOT, [{ ...hoisted, readFrom: null }], 0, [])).toThrow( /^Couldn't paste/, ); diff --git a/packages/studio/src/hooks/useClipboard.ts b/packages/studio/src/hooks/useClipboard.ts index 443d803ec2..7ae2872545 100644 --- a/packages/studio/src/hooks/useClipboard.ts +++ b/packages/studio/src/hooks/useClipboard.ts @@ -1,5 +1,4 @@ import { useCallback, useRef } from "react"; -import { EXCLUDED_TAGS, mintHfId, walkCompositionDescendants } from "@hyperframes/parsers/hf-ids"; import type { TimelineElement } from "../player"; import { usePlayerStore } from "../player"; import { toAuthoredStart } from "../player/store/timelineElement"; @@ -7,13 +6,10 @@ import type { DomEditSelection } from "../components/editor/domEditing"; import { type ClipboardPayload, type TimelineClipboardClip, - ID_ATTR_RE, - deduplicateIds, insertAsSibling, } from "../utils/clipboardPayload"; -import { carryLook, renamedIds } from "../utils/clipboardLook"; -import { collectHtmlIds } from "../utils/studioHelpers"; -import { insertTimelineAssetIntoSource, writtenTrackIndex } from "../utils/timelineAssetDrop"; +import { carryLook } from "../utils/clipboardLook"; +import { placeUnderCompositionRoot, writtenTrackIndex } from "../utils/timelineAssetDrop"; import { extendRootDurationInSource } from "../utils/rootDuration"; import { saveProjectFilesWithHistory } from "../utils/studioFileHistory"; import { formatTimelineAttributeNumber } from "../player/components/timelineEditing"; @@ -29,7 +25,7 @@ import { savedMarkupElseLive, } from "../utils/authoredSource"; import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator"; -import { copiedFile, refuseUnlistedMarkup } from "../utils/clipboardMarkup"; +import { copiedFile, idsInFile, prepareCopy, refuseAddedMarkup } from "../utils/clipboardMarkup"; import { knownCompositionFile } from "../components/editor/domEditingDom"; type InPlace = { inPlace?: boolean }; @@ -159,61 +155,28 @@ export function resolveFreeTrack(preferred: PlacedClip, taken: readonly PlacedCl return maxTrack + 1; } -/** Gives a clone's root and every descendant a fresh data-hf-id, clear of `taken`. Minted here, - * inside the edit, or the server stamps them on the next preview load, behind undo's back. - * DOMParser, not a regex, so a `>` inside an attribute value can't defeat it. */ -function remintHfIds( - html: string, - parser: DOMParser, - taken: Set, - check: (doc: Document) => void, -): string { - const doc = parser.parseFromString(html, "text/html"); - check(doc); - const root = doc.body.firstElementChild; - if (!root) { - // A tag the HTML parser hoists out of (title/meta/style/base/link) - // never reaches the walk above — fall back to a direct strip so - // data-hf-id still can't survive, even though no real clip root is one - // of these tags today. - return html.replace(/\sdata-hf-id=("[^"]*"|'[^']*')/g, ""); - } - const elements = [root]; - walkCompositionDescendants(root, (el) => elements.push(el)); - for (const el of elements) { - if (EXCLUDED_TAGS.has(el.tagName.toLowerCase())) el.removeAttribute("data-hf-id"); - else el.setAttribute("data-hf-id", mintHfId(el, taken)); - } - return root.outerHTML; -} - -const HF_ID_ATTR_RE = /\bdata-hf-id\s*=\s*["']?([^"'\s>]+)/gi; -const hfIdsInFile = (content: string) => - new Set(Array.from(content.matchAll(HF_ID_ATTR_RE), (match) => match[1])); - export function pasteElementHtml( content: string, payload: { html: string; readFrom?: string | null }, fromThisFile = false, writeTo: string | null = null, ): string { - const parser = new DOMParser(); - const check = (doc: Document) => refuseUnlistedMarkup(doc, payload.readFrom, writeTo); - const reminted = remintHfIds(payload.html, parser, hfIdsInFile(content), check); - const deduped = deduplicateIds(reminted, collectHtmlIds(content)); - const anchorFromThisFile = - fromThisFile && !!payload.readFrom && payload.readFrom === writeTo - ? parser - .parseFromString(payload.html, "text/html") - .body.firstElementChild?.getAttribute("data-hf-id") - : null; - const result = insertAsSibling(content, deduped, anchorFromThisFile ?? undefined); - return fromThisFile ? carryLook(result, renamedIds(reminted, deduped), 0) : result; + const taken = idsInFile(content); + const copy = prepareCopy(payload.html, taken.hfIds, taken.ids); + const fromItsFile = fromThisFile && !!payload.readFrom && payload.readFrom === writeTo; + const inserted = insertAsSibling( + content, + copy.html, + (fromItsFile && copy.originalHfId) || undefined, + ); + const result = fromThisFile ? carryLook(inserted, copy.renames, 0) : inserted; + refuseAddedMarkup(content, result, [{ html: copy.html, readFrom: payload.readFrom }], writeTo); + return result; } /** Shared insertion path for paste and duplicate, anchored at the playhead or the selection's end. Returns the - * final ids so the caller can select what it placed, and the furthest end any clip lands at so it can grow the - * root duration to cover it. `fromThisFile`: the clips came from `content`, so a renamed copy takes its + * final ids so the caller can select what it placed; the root's data-duration grows to the furthest end, since a + * clip past it never plays or exports. `fromThisFile`: the clips came from `content`, so a renamed copy takes its * original's look. */ export function pasteTimelineClips( content: string, @@ -224,22 +187,14 @@ export function pasteTimelineClips( writeTo: string | null = null, ): { content: string; ids: string[]; requiredEnd: number } { const groupMinStart = Math.min(...clips.map((c) => c.start)); - let existingIds = collectHtmlIds(content); const taken: PlacedClip[] = liveElements.map((el) => ({ track: writtenTrackIndex(el.authoredTrack ?? el.track), start: el.start, duration: el.duration, })); - const ids: string[] = []; - let result = content; + const { hfIds: takenHfIds, ids: takenIds } = idsInFile(content); let requiredEnd = 0; - const domParser = new DOMParser(); - const takenHfIds = hfIdsInFile(content); - for (const clip of clips) { - const check = (doc: Document) => refuseUnlistedMarkup(doc, clip.readFrom, writeTo); - const reminted = remintHfIds(clip.html, domParser, takenHfIds, check); - const deduped = deduplicateIds(reminted, existingIds); - existingIds = existingIds.concat(collectHtmlIds(deduped)); + const placed = clips.map((clip) => { const newStart = anchorTime + (clip.start - groupMinStart); const newTrack = resolveFreeTrack( { track: writtenTrackIndex(clip.track), start: newStart, duration: clip.duration }, @@ -247,27 +202,28 @@ export function pasteTimelineClips( ); taken.push({ track: newTrack, start: newStart, duration: clip.duration }); requiredEnd = Math.max(requiredEnd, newStart + clip.duration); - - // Only rewrite the outermost opening tag. The non-global regex matches - // the first occurrence, which is always in the root tag since outerHTML - // starts with it. Nested clips keep their own timing and track. - const rootTagEnd = deduped.indexOf(">"); - const rootTag = rootTagEnd >= 0 ? deduped.slice(0, rootTagEnd + 1) : deduped; - const patchedRootTag = rootTag - .replace(/data-start="[^"]*"/, `data-start="${formatTimelineAttributeNumber(newStart)}"`) - .replace(/data-track-index="[^"]*"/, `data-track-index="${newTrack}"`); - const withPatched = patchedRootTag + deduped.slice(rootTagEnd + 1); - check(domParser.parseFromString(withPatched, "text/html")); - result = insertTimelineAssetIntoSource(result, withPatched); - if (fromThisFile) { - const authored = Number(rootTag.match(/data-start="([^"]*)"/)?.[1]); - const authoredStart = Number.isFinite(authored) ? authored : clip.start; - result = carryLook(result, renamedIds(reminted, deduped), newStart - authoredStart); - } - - const id = patchedRootTag.match(ID_ATTR_RE)?.[1]; - if (id) ids.push(id); - } + let authoredStart = clip.start; + // Only the root moves: nested clips keep their own timing and track. + const copy = prepareCopy(clip.html, takenHfIds, takenIds, (root) => { + const authored = Number(root.getAttribute("data-start")); + if (root.hasAttribute("data-start") && Number.isFinite(authored)) authoredStart = authored; + if (root.hasAttribute("data-start")) + root.setAttribute("data-start", formatTimelineAttributeNumber(newStart)); + if (root.hasAttribute("data-track-index")) + root.setAttribute("data-track-index", String(newTrack)); + }); + return { copy, readFrom: clip.readFrom, delta: newStart - authoredStart }; + }); + const base = extendRootDurationInSource(content, requiredEnd); + let result = base; + const written = placed.map(({ copy, readFrom, delta }) => { + const { insertAt, written: html } = placeUnderCompositionRoot(result, copy.html); + result = result.slice(0, insertAt) + html + result.slice(insertAt); + if (fromThisFile) result = carryLook(result, copy.renames, delta); + return { html, readFrom }; + }); + refuseAddedMarkup(base, result, written, writeTo); + const ids = placed.flatMap(({ copy }) => copy.root.getAttribute("id") ?? []); return { content: result, ids, requiredEnd }; } @@ -443,10 +399,7 @@ export function useClipboard({ writeTo, ); pastedIds = pasted.ids; - // A clip pasted past the current composition end would exist in the - // file but never appear on the timeline or in playback/export (the - // root's data-duration is what actually bounds the render). - return extendRootDurationInSource(pasted.content, pasted.requiredEnd); + return pasted.content; }; const { label, toast } = pasteWords(payload); @@ -519,7 +472,7 @@ export function useClipboard({ targetPath, ); ids = pasted.ids; - return extendRootDurationInSource(pasted.content, pasted.requiredEnd); + return pasted.content; }; await saveProjectFilesWithHistory({ diff --git a/packages/studio/src/hooks/useClipboard.written.test.ts b/packages/studio/src/hooks/useClipboard.written.test.ts new file mode 100644 index 0000000000..87f37ee638 --- /dev/null +++ b/packages/studio/src/hooks/useClipboard.written.test.ts @@ -0,0 +1,238 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import { pasteElementHtml, pasteTimelineClips } from "./useClipboard"; +import { parseHTMLContent } from "@hyperframes/core/compiler/html-document"; +import { prepareCopy, refuseAddedMarkup } from "../utils/clipboardMarkup"; + +const FILE = `
+
Card
+
`; + +/** Every handler in `html` as saved and as the preview server serves it: what no paste may add. */ +function runningCode(html: string): string[] { + return [html, parseHTMLContent(html).toString()].flatMap(handlersIn); +} + +function handlersIn(html: string): string[] { + const doc = new DOMParser().parseFromString(html, "text/html"); + return Array.from(doc.querySelectorAll("*")).flatMap((el) => + el + .getAttributeNames() + .filter((name) => name.toLowerCase().startsWith("on")) + .map((name) => `${el.localName}[${name}]`), + ); +} + +/** The paste's own file, or nothing when it was refused. */ +function written(paste: () => string): string { + try { + return paste(); + } catch (error) { + expect(String(error)).toMatch(/Couldn't paste/); + return FILE; + } +} + +// fails without the fix: a comment that loses its data-hf-id text after the check closes early, and what followed it +// in the comment is written as markup. +describe("markup a paste writes is the markup it checked", () => { + const SPLIT_COMMENTS = ['"', "'"].flatMap((q) => [ + `
'; + + it("writes no running code when an element is pasted into its own file", () => { + const file = written(() => + pasteElementHtml(FILE, { html: COMMENTED_STYLE, readFrom: null }, true, "index.html"), + ); + expect(runningCode(file)).toEqual([]); + }); + + it("writes no running code when a clip is duplicated in its own file", () => { + const clip = { html: COMMENTED_STYLE, readFrom: null, start: 0, duration: 2, track: 1 }; + const file = written(() => pasteTimelineClips(FILE, [clip], 2, [], true, "index.html").content); + expect(runningCode(file)).toEqual([]); + }); + + it("still gives a pasted copy its original's look", () => { + const html = + '
Copy
'; + const file = pasteElementHtml(FILE, { html, readFrom: "index.html" }, true, "index.html"); + expect(file).toMatch(/#card-2\s*\{\s*color: red;?\s*\}/); + }); +}); + +describe("prepareCopy", () => { + it("renames each taken id on the copy's elements and leaves every other attribute as it was", () => { + const html = + '

x

y

'; + const copy = prepareCopy(html, new Set(), new Set(["hero", "hero-2"])); + expect(copy.root.getAttribute("id")).toBe("hero-3"); + expect(copy.root.getAttribute("data-composition-id")).toBe("hero"); + expect(copy.html).toContain('id="hero-2-2" data-id="hero"'); + expect(copy.html).toContain('id="free"'); + expect([...copy.renames]).toEqual([ + ["hero", "hero-3"], + ["hero-2", "hero-2-2"], + ]); + }); +}); + +// fails without the fix: the check compared attribute names only and ran the allowlist on the copy, not on the file. +describe("the final check reads what the saved file holds", () => { + const copy = 'Go'; + const before = FILE; + const inserted = (html: string) => before.replace('
{ + const after = inserted('Go'); + expect(() => + refuseAddedMarkup(before, after, [{ html: copy, readFrom: null }], "index.html"), + ).toThrow(/Couldn't paste/); + }); + + it("refuses a changed link even for a copy Studio read from this very file", () => { + const after = inserted('Go'); + expect(() => + refuseAddedMarkup(before, after, [{ html: copy, readFrom: "index.html" }], "index.html"), + ).toThrow(/Couldn't paste/); + }); + + it("refuses a saved copy whose elements moved to other parents in the same order", () => { + const nested = '

Caption

'; + const after = inserted('

Caption

'); + expect(() => + refuseAddedMarkup(before, after, [{ html: nested, readFrom: "index.html" }], "index.html"), + ).toThrow(/Couldn't paste/); + }); + + it("accepts the saved copy when it is the copy that was checked", () => { + expect(() => + refuseAddedMarkup(before, inserted(copy), [{ html: copy, readFrom: null }], "index.html"), + ).not.toThrow(); + }); +}); + +// fails without the fix: the file's ids were read as raw text, so an entity-escaped id never matched the copy's. +it("renames a pasted id the file already holds written with entities", () => { + const file = FILE.replace('
L\n
R', readFrom: null }, + false, + "index.html", + ); + const ids = Array.from( + new DOMParser().parseFromString(pasted, "text/html").querySelectorAll("span"), + (el) => el.id, + ); + expect(ids.sort()).toEqual(["left&right", "left&right-2"]); +}); + +// fails without the fix: an svg element named template has no template content, and reading the file's ids threw. +it("pastes into a file holding an svg element named template", () => { + const file = FILE.replace( + '
\n
N', readFrom: null }, + false, + "index.html", + ); + expect(pasted).toContain(' { + const html = + '
\n

x

\n
'; + const { content } = pasteTimelineClips( + FILE, + [{ html, readFrom: null, start: 0, duration: 1, track: 1 }], + 0, + [], + false, + "index.html", + ); + expect(content).toContain('id="multi"'); +}); + +// fails without the fix: the check read a comment in an svg as a comment, and the preview server's parser +// ends the title inside it, serving what follows as markup. +describe("a paste is checked as the preview server serves the file", () => { + const svgClip = + '<div id="icon" class="clip" data-start="0" data-duration="1" data-track-index="1">' + + "<svg><title><!-- -->
"; + + it.each([null, "compositions/recv.html", "index.html"])( + "as an element read from %s", + (readFrom) => { + const file = written(() => + pasteElementHtml(FILE, { html: svgClip, readFrom }, false, "index.html"), + ); + expect(runningCode(file)).toEqual([]); + }, + ); + + it.each([null, "compositions/recv.html", "index.html"])("as a clip read from %s", (readFrom) => { + const clip = { html: svgClip, readFrom, start: 0, duration: 1, track: 1 }; + const file = written(() => pasteTimelineClips(FILE, [clip], 0, [], true, "index.html").content); + expect(runningCode(file)).toEqual([]); + }); + + it("still pastes an svg whose title is plain text", () => { + const icon = + 'Icon </title>'; + const file = pasteElementHtml(FILE, { html: icon, readFrom: null }, false, "index.html"); + expect(file).toMatch(/]*>Icon <\/title><\/title><circle /); + }); +}); + +// fails without the fix: each copy was compared with every element of the file, so a batch paste took seconds. +it("compares each pasted copy with only the elements that could be it", () => { + const clips = Array.from({ length: 60 }, (_, i) => ({ + html: `<div id="c${i}" class="clip" data-start="0" data-duration="1" data-track-index="1"><span>${i}</span></div>`, + readFrom: null, + start: i, + duration: 1, + track: 1, + })); + const compared = vi.spyOn(Node.prototype, "isEqualNode"); + pasteTimelineClips(FILE, clips, 0, [], false, "index.html"); + expect(compared.mock.calls.length).toBeLessThanOrEqual(clips.length * 2); + compared.mockRestore(); +}); diff --git a/packages/studio/src/utils/clipboardLook.ts b/packages/studio/src/utils/clipboardLook.ts index 839fce11f9..ef88a5b8de 100644 --- a/packages/studio/src/utils/clipboardLook.ts +++ b/packages/studio/src/utils/clipboardLook.ts @@ -1,26 +1,10 @@ import { copyAnimationsInScript } from "@hyperframes/parsers/gsap-writer-acorn"; -import { ID_ATTR_RE } from "./clipboardPayload"; +import { tagsOutsideCommentsAndRawText } from "@hyperframes/core/compiler/html-document"; import { escapeRegex } from "./sourcePatcher"; -const ID_ATTRS = new RegExp(ID_ATTR_RE.source, "g"); -// One pass over both, so a `<style>` written inside a script's text is left as script. -const BLOCKS = - /(<script\b(?![^>]*\bsrc=)[^>]*>)([\s\S]*?)(<\/script>)|(<style\b[^>]*>)([\s\S]*?)(<\/style>)/gi; - -/** Each id a paste renamed (`goodbye` to `goodbye-2`), from the same markup before and after the rename. */ -export function renamedIds(before: string, after: string): Map<string, string> { - const ids = (html: string) => Array.from(html.matchAll(ID_ATTRS), (match) => match[1] as string); - const renamed = ids(after); - const renames = new Map<string, string>(); - ids(before).forEach((from, index) => { - const to = renamed[index]; - if (to && to !== from) renames.set(from, to); - }); - return renames; -} - /** Gives each renamed copy the look and motion its original has in `html`: a copy of every CSS rule keyed to - * the original's id, and of every tween on it, moved by `delta` seconds. */ + * the original's id, and of every tween on it, moved by `delta` seconds. Only real <style> and inline <script> + * elements are read, found with the tag scanner, so text in a comment or another element is never touched. */ export function carryLook( html: string, renames: ReadonlyMap<string, string>, @@ -28,19 +12,36 @@ export function carryLook( ): string { let result = html; for (const [from, to] of renames) { - result = result.replace( - BLOCKS, - (block, scriptOpen, script, scriptClose, styleOpen, css, styleClose) => - scriptOpen !== undefined - ? scriptOpen + copyAnimationsInScript(script, `#${from}`, `#${to}`, delta) + scriptClose - : styleOpen !== undefined - ? styleOpen + withCopiedRules(css, from, to) + styleClose - : block, + result = editBlocks(result, (kind, text) => + kind === "script" + ? copyAnimationsInScript(text, `#${from}`, `#${to}`, delta) + : withCopiedRules(text, from, to), ); } return result; } +function editBlocks( + html: string, + edit: (kind: "script" | "style", text: string) => string, +): string { + const tags = [...tagsOutsideCommentsAndRawText(html)]; + let out = ""; + let at = 0; + tags.forEach((tag, index) => { + const kind = tag.lowercaseName; + if (tag.closing || (kind !== "script" && kind !== "style")) return; + if (kind === "script" && /\ssrc\s*=/i.test(html.slice(tag.start, tag.endAfterBracket))) return; + const close = tags.slice(index + 1).find((t) => t.closing && t.lowercaseName === kind); + if (!close) return; + out += + html.slice(at, tag.endAfterBracket) + + edit(kind, html.slice(tag.endAfterBracket, close.start)); + at = close.start; + }); + return out + html.slice(at); +} + // Top-level rules only: a rule inside @media or @supports is not copied. function withCopiedRules(css: string, from: string, to: string): string { const sheet = new CSSStyleSheet(); @@ -56,7 +57,9 @@ function withCopiedRules(css: string, from: string, to: string): string { ); if (selectors.length === 0) return []; const copied = selectors.map((selector) => selector.replace(id, `#${to}`)).join(", "); - return [`\n${indent}${copied}${rule.cssText.slice(rule.selectorText.length)}`]; + const text = `${copied}${rule.cssText.slice(rule.selectorText.length)}`; + // Raw <style> text ends at "</style": a rule holding "<" is not copied. + return text.includes("<") ? [] : [`\n${indent}${text}`]; }); if (copies.length === 0) return css; const body = css.trimEnd(); diff --git a/packages/studio/src/utils/clipboardMarkup.ts b/packages/studio/src/utils/clipboardMarkup.ts index 4513ce21d3..a1459f9ce8 100644 --- a/packages/studio/src/utils/clipboardMarkup.ts +++ b/packages/studio/src/utils/clipboardMarkup.ts @@ -1,6 +1,10 @@ +import { parseHTMLContent } from "@hyperframes/core/compiler/html-document"; import { markupOutsideAllowlist } from "@hyperframes/core/html-attr-safety"; +import { EXCLUDED_TAGS, mintHfId, walkCompositionDescendants } from "@hyperframes/parsers/hf-ids"; import { knownCompositionFile } from "../components/editor/domEditingDom"; +const REFUSED = "Couldn't paste: the copied element holds markup that can't be pasted here."; + export function copiedFile( claimed: string | undefined, activeCompositionPath: string | null, @@ -10,14 +14,149 @@ export function copiedFile( throw new Error("Couldn't use this element: its file isn't one of this project's compositions."); } -/** Every clipboard write: only markup Studio itself read from the file it writes to skips the allowlist. */ -export function refuseUnlistedMarkup( - doc: Document, - readFrom: string | null | undefined, - writeTo: string | null, -): void { - if (readFrom && readFrom === writeTo) return; - if (markupOutsideAllowlist(doc.documentElement).length > 0) { - throw new Error("Couldn't paste: the copied element holds markup that can't be pasted here."); +export interface PreparedCopy { + html: string; + root: Element; + originalHfId: string | null; + renames: Map<string, string>; +} + +function fragment(html: string): HTMLTemplateElement { + const template = document.createElement("template"); + template.innerHTML = html; + return template; +} + +/** Fresh data-hf-ids minted in the edit (else the server stamps them behind undo's back); taken ids renamed. */ +export function prepareCopy( + html: string, + takenHfIds: Set<string>, + takenIds: Set<string>, + place?: (root: Element) => void, +): PreparedCopy { + const root = fragment(html).content.firstElementChild; + if (!root) throw new Error(REFUSED); + const originalHfId = root.getAttribute("data-hf-id"); + const elements = [root]; + walkCompositionDescendants(root, (el) => elements.push(el)); + for (const el of elements) { + if (EXCLUDED_TAGS.has(el.localName)) el.removeAttribute("data-hf-id"); + else el.setAttribute("data-hf-id", mintHfId(el, takenHfIds)); + } + const renames = new Map<string, string>(); + for (const el of [root, ...Array.from(root.querySelectorAll("[id]"))]) { + const id = el.getAttribute("id"); + if (!id) continue; + if (takenIds.has(id)) { + let counter = 2; + while (takenIds.has(`${id}-${counter}`)) counter++; + el.setAttribute("id", `${id}-${counter}`); + renames.set(id, `${id}-${counter}`); + } + takenIds.add(el.getAttribute("id")!); + } + place?.(root); + return { html: root.outerHTML, root, originalHfId, renames }; +} + +const parsed = (html: string) => new DOMParser().parseFromString(html, "text/html"); +// The page as served: the preview server and render compiler re-read a file with linkedom before a browser does. +const served = (html: string) => parsed(parseHTMLContent(html).toString()); + +const htmlTemplate = (node: Node): node is HTMLTemplateElement => + node instanceof Element && node.localName === "template" && node.namespaceURI === HTML_NS; +const HTML_NS = "http://www.w3.org/1999/xhtml"; + +function eachElement(nodes: ParentNode, visit: (el: Element) => void): void { + for (const el of Array.from(nodes.querySelectorAll("*"))) { + visit(el); + if (htmlTemplate(el)) eachElement(el.content, visit); } } + +const signature = (el: Element) => + JSON.stringify([ + el.namespaceURI, + el.localName, + Array.from(el.attributes, (a) => JSON.stringify([a.namespaceURI, a.name, a.value])).sort(), + ]); + +function subtree(root: Element): Element[] { + const elements = [root]; + eachElement(root, (el) => elements.push(el)); + return elements; +} + +// Raw <style>/<script> text is the look copy's to extend; the allowlist reads it on the saved node. +function withoutRawText(node: Node): Node { + const clone = node.cloneNode(true) as ParentNode & Node; + const scope: Element[] = clone instanceof Element ? [clone] : []; + eachElement(clone, (el) => scope.push(el)); + for (const el of scope) { + if (el.namespaceURI === HTML_NS && (el.localName === "style" || el.localName === "script")) + el.textContent = ""; + } + return clone; +} + +/** Equal by the DOM's own isEqualNode, template contents included, which it does not compare. */ +function sameTree(a: Node, b: Node): boolean { + if (!withoutRawText(a).isEqualNode(withoutRawText(b))) return false; + const templates = (node: Node) => + [node, ...Array.from((node as ParentNode).querySelectorAll("*"))].filter(htmlTemplate); + const left = templates(a); + const right = templates(b); + return ( + left.length === right.length && left.every((t, i) => sameTree(t.content, right[i].content)) + ); +} + +/** The file's ids and data-hf-ids as parsed values, so an id written with entities matches its copy's. */ +export function idsInFile(content: string): { ids: Set<string>; hfIds: Set<string> } { + const ids = new Set<string>(); + const hfIds = new Set<string>(); + eachElement(parsed(content), (el) => { + const id = el.getAttribute("id"); + const hfId = el.getAttribute("data-hf-id"); + if (id) ids.add(id); + if (hfId) hfIds.add(hfId); + }); + return { ids, hfIds }; +} + +/** Last step of every clipboard write: the saved file gains exactly the copies, each allowed or read here. */ +export function refuseAddedMarkup( + before: string, + after: string, + copies: ReadonlyArray<{ html: string; readFrom?: string | null }>, + writeTo: string | null, +): void { + const saved = served(after); + const counts = new Map<string, number>(); + const tally = (shape: string, sign: number) => counts.set(shape, (counts.get(shape) ?? 0) + sign); + const candidatesBySignatureOfMintedRoot = new Map<string, Element[]>(); + eachElement(saved, (el) => { + const shape = signature(el); + tally(shape, 1); + const bucket = candidatesBySignatureOfMintedRoot.get(shape); + if (bucket) bucket.push(el); + else candidatesBySignatureOfMintedRoot.set(shape, [el]); + }); + eachElement(served(before), (el) => tally(signature(el), -1)); + const claimed = new Set<Element>(); + for (const copy of copies) { + const expected = fragment(copy.html).content.firstElementChild; + if (!expected) throw new Error(REFUSED); + const found = (candidatesBySignatureOfMintedRoot.get(signature(expected)) ?? []).find( + (el) => subtree(el).every((e) => !claimed.has(e)) && sameTree(el, expected), + ); + if (!found) throw new Error(REFUSED); + const exempt = !!copy.readFrom && copy.readFrom === writeTo; + if (!exempt && markupOutsideAllowlist(found).length > 0) throw new Error(REFUSED); + for (const el of subtree(found)) { + claimed.add(el); + tally(signature(el), -1); + } + } + if (Array.from(counts.values()).some((count) => count !== 0)) throw new Error(REFUSED); +} diff --git a/packages/studio/src/utils/clipboardPayload.test.ts b/packages/studio/src/utils/clipboardPayload.test.ts index 65e7114d48..79d8f2ff8e 100644 --- a/packages/studio/src/utils/clipboardPayload.test.ts +++ b/packages/studio/src/utils/clipboardPayload.test.ts @@ -1,38 +1,12 @@ // @vitest-environment node import { describe, expect, it } from "vitest"; import { - deduplicateIds, serializeClipboardPayload, deserializeClipboardPayload, insertAsSibling, type ClipboardPayload, } from "./clipboardPayload"; -describe("deduplicateIds", () => { - it("renames ids that collide with existing ids", () => { - const html = '<div id="hero"><img id="photo" src="a.png" /></div>'; - const existingIds = ["hero", "other"]; - const result = deduplicateIds(html, existingIds); - expect(result).not.toContain('id="hero"'); - expect(result).toContain('id="photo"'); - expect(result).toMatch(/id="hero-\d+"/); - }); - - it("returns html unchanged when no collisions", () => { - const html = '<div id="unique"><p>hello</p></div>'; - const result = deduplicateIds(html, ["other"]); - expect(result).toBe(html); - }); - - it("does not rewrite data-composition-id or other data-*-id attributes", () => { - const html = '<div data-composition-id="hero" data-clip-id="hero" id="hero">content</div>'; - const result = deduplicateIds(html, ["hero"]); - expect(result).toContain('data-composition-id="hero"'); - expect(result).toContain('data-clip-id="hero"'); - expect(result).toMatch(/\sid="hero-\d+"/); - }); -}); - describe("serializeClipboardPayload / deserializeClipboardPayload", () => { it("round-trips a single-clip timeline payload", () => { const payload: ClipboardPayload = { diff --git a/packages/studio/src/utils/clipboardPayload.ts b/packages/studio/src/utils/clipboardPayload.ts index 7506054c85..c99ee506ab 100644 --- a/packages/studio/src/utils/clipboardPayload.ts +++ b/packages/studio/src/utils/clipboardPayload.ts @@ -148,19 +148,3 @@ export function insertAsSibling(source: string, newHtml: string, anchorHfId?: st ? source.slice(0, root.endAfterBracket) + newHtml + source.slice(root.endAfterBracket) : source + newHtml; } - -/** An `id="..."` attribute, not `data-id="..."` or similar — only matches - * when preceded by whitespace, the way every generated attribute is. */ -export const ID_ATTR_RE = /(?<=\s)id="([^"]+)"/; - -export function deduplicateIds(html: string, existingIds: string[]): string { - const existingSet = new Set(existingIds); - return html.replace(new RegExp(ID_ATTR_RE.source, "g"), (full, id: string) => { - if (!existingSet.has(id)) return full; - let counter = 2; - while (existingSet.has(`${id}-${counter}`)) counter++; - const newId = `${id}-${counter}`; - existingSet.add(newId); - return `id="${newId}"`; - }); -} diff --git a/packages/studio/src/utils/timelineAssetDrop.ts b/packages/studio/src/utils/timelineAssetDrop.ts index f87111e089..594ddf08f9 100644 --- a/packages/studio/src/utils/timelineAssetDrop.ts +++ b/packages/studio/src/utils/timelineAssetDrop.ts @@ -164,6 +164,14 @@ export function setCompositionDurationToContent( } export function insertTimelineAssetIntoSource(source: string, assetHtml: string): string { + const { insertAt, written } = placeUnderCompositionRoot(source, assetHtml); + return `${source.slice(0, insertAt)}${written}${source.slice(insertAt)}`; +} + +export function placeUnderCompositionRoot( + source: string, + assetHtml: string, +): { insertAt: number; written: string } { const match = COMPOSITION_ROOT_OPEN_TAG_RE.exec(source); if (!match || match.index == null) { throw new Error("No composition root found in target source"); @@ -176,5 +184,5 @@ export function insertTimelineAssetIntoSource(source: string, assetHtml: string) .split("\n") .map((line, i) => (i === 0 ? line : childIndent + line)) .join("\n"); - return `${source.slice(0, insertAt)}\n${childIndent}${indented}${source.slice(insertAt)}`; + return { insertAt, written: `\n${childIndent}${indented}` }; } From 675e3a876e550a5e5850b0b0123ffffec8be7cce Mon Sep 17 00:00:00 2001 From: WaterrrForever <miao.yang@heygen.com> Date: Sun, 22 Nov 2026 17:05:10 +0000 Subject: [PATCH 142/367] fix(cli): pinned-file downloaders check the cache folder is private before reading or writing it (#8486) * fix(cli): make the cache folder private before a pinned download writes into it (SECOPS-2745) The measuring tools' pinned-file downloader (measure/pinnedFiles.ts, for the MediaPipe hand landmarker) made its folder with a plain mkdir, downloaded into it, and only checked the folder was private in the seal afterwards. A folder another account owned, a group/world-writable one, or a link out of the cache received the bytes before the refusal. The model downloaders were worse: the TTS and background-removal models (utils/pinnedFile.ts) and the whisper models never checked at all, and trusted a cached copy from such a folder. Every pinned download into the HyperFrames cache now runs ensurePrivateCacheDir first: a new folder is made 0700, the person's own group/world-writable folder loses those bits, and a link, a foreign owner or a folder another account can change is refused before any partial or final file is written or any cached copy is used. Temp files stay inside the verified folder and are renamed into place. opencv.ts, which already did this, now shares ensurePinnedFiles instead of its own copy of the loop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): keep the pinned downloaders' comment share at the base (SECOPS-2745) Cuts the comment lines the private-cache fix added to pinnedFiles.ts, pinnedFile.ts and whisper/manager.ts so each file's comment share is back at or under its merge-base share, and names ensurePinnedFile's root cacheRoot so the call reads without the comment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .../cli/src/background-removal/manager.ts | 5 +- packages/cli/src/measure/opencv.ts | 59 +------- packages/cli/src/measure/pinnedFiles.test.ts | 126 ++++++++++++++++++ packages/cli/src/measure/pinnedFiles.ts | 19 ++- packages/cli/src/tts/manager.ts | 7 +- packages/cli/src/utils/pinnedFile.test.ts | 97 +++++++++++++- packages/cli/src/utils/pinnedFile.ts | 6 +- .../cli/src/whisper/manager.model.test.ts | 40 ++++++ packages/cli/src/whisper/manager.ts | 4 +- 9 files changed, 292 insertions(+), 71 deletions(-) create mode 100644 packages/cli/src/measure/pinnedFiles.test.ts diff --git a/packages/cli/src/background-removal/manager.ts b/packages/cli/src/background-removal/manager.ts index 51e91ecfe1..07dd41edf2 100644 --- a/packages/cli/src/background-removal/manager.ts +++ b/packages/cli/src/background-removal/manager.ts @@ -4,7 +4,8 @@ import { ensurePinnedFile } from "../utils/pinnedFile.js"; import type { ModelFile } from "../whisper/modelFile.js"; import { hyperframesCacheDir } from "@hyperframes/core/cache-dir"; -export const MODELS_DIR = hyperframesCacheDir("background-removal", "models"); +const CACHE_ROOT = hyperframesCacheDir(); +export const MODELS_DIR = join(CACHE_ROOT, "background-removal", "models"); export const DEFAULT_MODEL = "u2net_human_seg" as const; export type ModelId = typeof DEFAULT_MODEL; @@ -91,7 +92,7 @@ export async function ensureModel( model: ModelId = DEFAULT_MODEL, options?: { onProgress?: (message: string) => void }, ): Promise<string> { - return ensurePinnedFile(MODEL_URLS[model], modelPath(model), MODEL_PINS[model], { + return ensurePinnedFile(MODEL_URLS[model], modelPath(model), CACHE_ROOT, MODEL_PINS[model], { downloading: `Downloading ${model} weights (~168 MB)...`, onProgress: options?.onProgress, }); diff --git a/packages/cli/src/measure/opencv.ts b/packages/cli/src/measure/opencv.ts index 79988a28a8..b66e14e579 100644 --- a/packages/cli/src/measure/opencv.ts +++ b/packages/cli/src/measure/opencv.ts @@ -1,31 +1,19 @@ // OpenCV for the measuring tools that need it (template tracking, optical flow, faces), as opencv.js: one WebAssembly // file that gives every machine the same numbers. It is not shipped in the CLI; the first use downloads it and the // Haar face models, pinned by size and sha256, into ~/.cache/hyperframes/opencv/<version>/. -import { readFileSync, renameSync, rmSync } from "node:fs"; +import { readFileSync } from "node:fs"; import { createRequire } from "node:module"; import { join } from "node:path"; -import { - assertPrivateCachePath, - ensurePrivateCacheDir, - foreignWritablePath, - sealCacheInstall, - trustedCacheRoot, -} from "@hyperframes/core/cache-dir"; -import { downloadToFile } from "../cloud/download.js"; -import { verifies, type ModelFile } from "../whisper/modelFile.js"; -import { Fix } from "./media.js"; +import { trustedCacheRoot } from "@hyperframes/core/cache-dir"; +import { ensurePinnedFiles, type PinnedFile } from "./pinnedFiles.js"; const VERSION = "4.10.0"; const CODE_ROOT = trustedCacheRoot(); export const OPENCV_DIR = join(CODE_ROOT, "opencv", VERSION); -interface Pinned extends ModelFile { - url: string; -} - // opencv.js is @techstark/opencv-js 4.10.0-release.1 (Apache-2.0); the cascades are OpenCV's own (BSD-3-Clause). const CASCADES = "https://raw.githubusercontent.com/opencv/opencv/4.10.0/data/haarcascades"; -const FILES: readonly Pinned[] = [ +const FILES: readonly PinnedFile[] = [ { name: "opencv.js", bytes: 10_378_215, @@ -123,42 +111,9 @@ export interface Cv { const isCv = (v: unknown): v is Cv => typeof v === "object" && v !== null && "Mat" in v && "matFromArray" in v; -/** Every pinned file present and verified; the missing ones fetched. */ -// fallow-ignore-next-line complexity -async function ensureOpenCv( - onStatus?: (message: string) => void, - signal?: AbortSignal, -): Promise<void> { - const missing: Pinned[] = []; - for (const f of FILES) { - const file = join(OPENCV_DIR, f.name); - if (foreignWritablePath(file, CODE_ROOT) || !(await verifies(file, f))) missing.push(f); - } - if (!missing.length) return; - ensurePrivateCacheDir(OPENCV_DIR, CODE_ROOT); - for (const f of missing) { - onStatus?.(`Downloading ${f.name} (${Math.round(f.bytes / 1e5) / 10} MB, once)...`); - const temp = join(OPENCV_DIR, `${f.name}.part-${process.pid}`); - try { - await downloadToFile(f.url, temp, { signal }); - if (!(await verifies(temp, f))) - throw new Fix( - `${f.name} did not match its pinned size and sha256`, - "run the command again to retry the download", - ); - renameSync(temp, join(OPENCV_DIR, f.name)); - } catch (err) { - if (err instanceof Fix) throw err; - throw new Fix( - `could not download ${f.name} (${err instanceof Error ? err.message : String(err)})`, - "check the network and run the command again", - ); - } finally { - rmSync(temp, { force: true }); - } - } - sealCacheInstall(OPENCV_DIR, CODE_ROOT); - for (const f of FILES) assertPrivateCachePath(join(OPENCV_DIR, f.name), CODE_ROOT); +/** Every pinned file present and verified; the missing ones fetched into the folder once it is private. */ +function ensureOpenCv(onStatus?: (message: string) => void, signal?: AbortSignal): Promise<void> { + return ensurePinnedFiles(OPENCV_DIR, CODE_ROOT, FILES, onStatus, signal); } let loaded: Promise<Cv> | null = null; diff --git a/packages/cli/src/measure/pinnedFiles.test.ts b/packages/cli/src/measure/pinnedFiles.test.ts new file mode 100644 index 0000000000..69a598fb04 --- /dev/null +++ b/packages/cli/src/measure/pinnedFiles.test.ts @@ -0,0 +1,126 @@ +import { createHash } from "node:crypto"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { ensurePinnedFiles, type PinnedFile } from "./pinnedFiles.js"; + +const ownedByAnotherAccount = vi.hoisted(() => new Set<string>()); +// What each download saw of its folder the moment it began writing: its mode. +const writes = vi.hoisted(() => [] as { dest: string; folderMode: number }[]); +vi.mock("node:fs", async (importOriginal) => { + const fs = await importOriginal<typeof import("node:fs")>(); + const lstatSync = ((path: string, options?: object) => { + const stat = fs.lstatSync(path, options as never); + return stat && ownedByAnotherAccount.has(path) + ? Object.assign(stat, { uid: process.getuid!() + 1 }) + : stat; + }) as typeof fs.lstatSync; + return { ...fs, lstatSync }; +}); +vi.mock("../cloud/download.js", async () => { + const fs = await import("node:fs"); + const path = await import("node:path"); + return { + downloadToFile: async (_url: string, dest: string) => { + writes.push({ dest, folderMode: fs.statSync(path.dirname(dest)).mode & 0o777 }); + fs.writeFileSync(dest, "pinned bytes"); + }, + }; +}); + +const file: PinnedFile = { + name: "model.bin", + bytes: 12, + sha256: createHash("sha256").update("pinned bytes").digest("hex"), + url: "https://x.test/model.bin", +}; + +let root = ""; +let elsewhere = ""; +let dir = ""; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "hf-pinned-files-")); + elsewhere = mkdtempSync(join(tmpdir(), "hf-pinned-files-elsewhere-")); + dir = join(root, "tool", "1.0.0"); +}); +afterEach(() => { + ownedByAnotherAccount.clear(); + writes.length = 0; + rmSync(root, { recursive: true, force: true }); + rmSync(elsewhere, { recursive: true, force: true }); +}); + +it("downloads a missing file into a new owner-only folder", async () => { + await ensurePinnedFiles(dir, root, [file]); + + expect(readdirSync(dir)).toEqual(["model.bin"]); + expect(writes.map((w) => dirname(w.dest))).toEqual([dir]); + if (process.getuid) expect(statSync(dir).mode & 0o777).toBe(0o700); +}); + +// fails without the fix: the download landed in the folder, and only the seal afterwards refused it. +it.skipIf(!process.getuid)( + "writes nothing into a folder another account owns, refusing it first", + async () => { + mkdirSync(dir, { recursive: true }); + ownedByAnotherAccount.add(join(root, "tool")); + + await expect(ensurePinnedFiles(dir, root, [file])).rejects.toThrow( + `${join(root, "tool")} can be changed by another user account`, + ); + + expect(writes).toEqual([]); + expect(readdirSync(dir)).toEqual([]); + }, +); + +// fails without the fix: the download followed the link and wrote its bytes into the folder it named. +it.skipIf(!process.getuid)( + "writes nothing through a folder that is a link out of the cache", + async () => { + mkdirSync(dirname(dir), { recursive: true }); + symlinkSync(elsewhere, dir); + + await expect(ensurePinnedFiles(dir, root, [file])).rejects.toThrow( + "can be changed by another user account", + ); + + expect(writes).toEqual([]); + expect(readdirSync(elsewhere)).toEqual([]); + }, +); + +// fails without the fix: the folder stayed group- and world-writable until the seal after the download. +it.skipIf(!process.getuid)( + "takes group and other write off the person's own folder before the first byte", + async () => { + mkdirSync(dir, { recursive: true }); + chmodSync(dir, 0o777); + + await ensurePinnedFiles(dir, root, [file]); + + expect(writes).toHaveLength(1); + expect(writes[0]!.folderMode & 0o022).toBe(0); + }, +); + +it("touches nothing when every file is present and verified in a private folder", async () => { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + writeFileSync(join(dir, file.name), "pinned bytes"); + + await ensurePinnedFiles(dir, root, [file]); + + expect(writes).toEqual([]); + expect(existsSync(join(dir, file.name))).toBe(true); +}); diff --git a/packages/cli/src/measure/pinnedFiles.ts b/packages/cli/src/measure/pinnedFiles.ts index 6929b84202..73511c89ba 100644 --- a/packages/cli/src/measure/pinnedFiles.ts +++ b/packages/cli/src/measure/pinnedFiles.ts @@ -1,8 +1,13 @@ // Files a measuring tool needs but the CLI does not ship: fetched on first use into a folder under the trusted cache // root, each one checked against its pinned size and sha256 before it is used, and the folder sealed. -import { mkdirSync, renameSync, rmSync } from "node:fs"; +import { renameSync, rmSync } from "node:fs"; import { join } from "node:path"; -import { foreignWritablePath, sealCacheInstall } from "@hyperframes/core/cache-dir"; +import { + assertPrivateCachePath, + ensurePrivateCacheDir, + foreignWritablePath, + sealCacheInstall, +} from "@hyperframes/core/cache-dir"; import { downloadToFile } from "../cloud/download.js"; import { verifies, type ModelFile } from "../whisper/modelFile.js"; import { Fix } from "./media.js"; @@ -11,10 +16,10 @@ export interface PinnedFile extends ModelFile { url: string; } -async function fetchPinned(dir: string, file: PinnedFile): Promise<void> { +async function fetchPinned(dir: string, file: PinnedFile, signal?: AbortSignal): Promise<void> { const temp = join(dir, `${file.name}.part-${process.pid}`); try { - await downloadToFile(file.url, temp).catch((err: unknown) => { + await downloadToFile(file.url, temp, { signal }).catch((err: unknown) => { throw new Fix( `could not download ${file.name} (${err instanceof Error ? err.message : String(err)})`, "check the network and run the command again", @@ -37,6 +42,7 @@ export async function ensurePinnedFiles( root: string, files: readonly PinnedFile[], onStatus?: (message: string) => void, + signal?: AbortSignal, ): Promise<void> { const wanted: PinnedFile[] = []; for (const file of files) { @@ -44,10 +50,11 @@ export async function ensurePinnedFiles( if (foreignWritablePath(path, root) || !(await verifies(path, file))) wanted.push(file); } if (!wanted.length) return; - mkdirSync(dir, { recursive: true, mode: 0o700 }); + ensurePrivateCacheDir(dir, root); for (const file of wanted) { onStatus?.(`Downloading ${file.name} (${Math.round(file.bytes / 1e5) / 10} MB, once)...`); - await fetchPinned(dir, file); + await fetchPinned(dir, file, signal); } sealCacheInstall(dir, root); + for (const file of files) assertPrivateCachePath(join(dir, file.name), root); } diff --git a/packages/cli/src/tts/manager.ts b/packages/cli/src/tts/manager.ts index a39a1826a1..afa4a8d355 100644 --- a/packages/cli/src/tts/manager.ts +++ b/packages/cli/src/tts/manager.ts @@ -3,7 +3,8 @@ import { ensurePinnedFile } from "../utils/pinnedFile.js"; import type { ModelFile } from "../whisper/modelFile.js"; import { hyperframesCacheDir } from "@hyperframes/core/cache-dir"; -const CACHE_DIR = hyperframesCacheDir("tts"); +const CACHE_ROOT = hyperframesCacheDir(); +const CACHE_DIR = join(CACHE_ROOT, "tts"); const MODELS_DIR = join(CACHE_DIR, "models"); const VOICES_DIR = join(CACHE_DIR, "voices"); @@ -126,7 +127,7 @@ export async function ensureModel( ); } - return ensurePinnedFile(url, join(MODELS_DIR, `${model}.onnx`), pin, { + return ensurePinnedFile(url, join(MODELS_DIR, `${model}.onnx`), CACHE_ROOT, pin, { downloading: `Downloading TTS model ${model} (~311 MB)...`, onProgress: options?.onProgress, }); @@ -139,7 +140,7 @@ export async function ensureModel( export async function ensureVoices(options?: { onProgress?: (message: string) => void; }): Promise<string> { - return ensurePinnedFile(VOICES_URL, join(VOICES_DIR, VOICES_PIN.name), VOICES_PIN, { + return ensurePinnedFile(VOICES_URL, join(VOICES_DIR, VOICES_PIN.name), CACHE_ROOT, VOICES_PIN, { downloading: "Downloading voice data (~27 MB)...", onProgress: options?.onProgress, }); diff --git a/packages/cli/src/utils/pinnedFile.test.ts b/packages/cli/src/utils/pinnedFile.test.ts index ba23768738..fb99cce2e9 100644 --- a/packages/cli/src/utils/pinnedFile.test.ts +++ b/packages/cli/src/utils/pinnedFile.test.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; import { + chmodSync, existsSync, mkdirSync, mkdtempSync, @@ -7,6 +8,8 @@ import { readdirSync, renameSync, rmSync, + statSync, + symlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; @@ -16,6 +19,19 @@ import { downloadFile } from "./download.js"; import { ensurePinnedFile } from "./pinnedFile.js"; const served = vi.hoisted(() => ({ bytes: "model" })); +const ownedByAnotherAccount = vi.hoisted(() => new Set<string>()); +// The mode of the folder each download began writing into. +const folderModes = vi.hoisted(() => [] as number[]); +vi.mock("node:fs", async (importOriginal) => { + const fs = await importOriginal<typeof import("node:fs")>(); + const lstatSync = ((path: string, options?: object) => { + const stat = fs.lstatSync(path, options as never); + return stat && ownedByAnotherAccount.has(path) + ? Object.assign(stat, { uid: process.getuid!() + 1 }) + : stat; + }) as typeof fs.lstatSync; + return { ...fs, lstatSync }; +}); vi.mock("./download.js", () => ({ downloadFile: vi.fn( async ( @@ -28,6 +44,7 @@ vi.mock("./download.js", () => ({ ) => { if (await options.keepExisting(dest)) return; rmSync(dest, { force: true }); + folderModes.push(statSync(join(dest, "..")).mode & 0o777); writeFileSync(`${dest}.part`, served.bytes); await options.verify(`${dest}.part`).catch((error: unknown) => { rmSync(`${dest}.part`); @@ -53,6 +70,8 @@ beforeEach(() => { dest = join(dir, "models", "model.onnx"); }); afterEach(() => { + ownedByAnotherAccount.clear(); + folderModes.length = 0; rmSync(dir, { recursive: true, force: true }); vi.clearAllMocks(); }); @@ -61,13 +80,13 @@ it("uses a cached file that matches its pin without downloading it", async () => mkdirSync(join(dir, "models")); writeFileSync(dest, "model"); - await expect(ensurePinnedFile("https://x.test/m", dest, pin, progress)).resolves.toBe(dest); + await expect(ensurePinnedFile("https://x.test/m", dest, dir, pin, progress)).resolves.toBe(dest); expect(downloadFile).not.toHaveBeenCalled(); }); it("downloads a file that matches its pin", async () => { - await expect(ensurePinnedFile("https://x.test/m", dest, pin, progress)).resolves.toBe(dest); + await expect(ensurePinnedFile("https://x.test/m", dest, dir, pin, progress)).resolves.toBe(dest); expect(readFileSync(dest, "utf8")).toBe("model"); }); @@ -77,7 +96,7 @@ it("replaces a cached file of the same size that does not match its pin", async writeFileSync(dest, "other"); const onProgress = vi.fn(); - await ensurePinnedFile("https://x.test/m", dest, pin, { ...progress, onProgress }); + await ensurePinnedFile("https://x.test/m", dest, dir, pin, { ...progress, onProgress }); expect(readFileSync(dest, "utf8")).toBe("model"); expect(onProgress).toHaveBeenCalledWith( @@ -90,7 +109,7 @@ it("discards a download that does not match its pin and refuses it", async () => mkdirSync(join(dir, "models")); writeFileSync(dest, "other"); - await expect(ensurePinnedFile("https://x.test/m", dest, pin, progress)).rejects.toThrow( + await expect(ensurePinnedFile("https://x.test/m", dest, dir, pin, progress)).rejects.toThrow( "model.onnx was discarded because it does not match its expected size and sha256. " + "Retrying helps only if the download was interrupted or corrupted.", ); @@ -98,3 +117,73 @@ it("discards a download that does not match its pin and refuses it", async () => expect(existsSync(dest)).toBe(false); expect(readdirSync(join(dir, "models"))).toEqual([]); }); + +// fails without the fix: nothing checked the folder, so the download was written into it. +it.skipIf(!process.getuid)( + "downloads nothing into a models folder another account owns, refusing it first", + async () => { + mkdirSync(join(dir, "models")); + ownedByAnotherAccount.add(join(dir, "models")); + + await expect(ensurePinnedFile("https://x.test/m", dest, dir, pin, progress)).rejects.toThrow( + `${join(dir, "models")} can be changed by another user account`, + ); + + expect(downloadFile).not.toHaveBeenCalled(); + expect(readdirSync(join(dir, "models"))).toEqual([]); + }, +); + +// fails without the fix: a matching copy in a folder another account can swap was handed back as trusted. +it.skipIf(!process.getuid)( + "does not vouch for a cached copy in a folder another account owns", + async () => { + mkdirSync(join(dir, "models")); + writeFileSync(dest, "model"); + ownedByAnotherAccount.add(join(dir, "models")); + + await expect(ensurePinnedFile("https://x.test/m", dest, dir, pin, progress)).rejects.toThrow( + "can be changed by another user account", + ); + }, +); + +// fails without the fix: the download followed the link and wrote the model into the folder it named. +it.skipIf(!process.getuid)( + "writes nothing through a models folder that is a link out of the cache", + async () => { + const elsewhere = mkdtempSync(join(tmpdir(), "hf-pinned-file-elsewhere-")); + try { + symlinkSync(elsewhere, join(dir, "models")); + + await expect(ensurePinnedFile("https://x.test/m", dest, dir, pin, progress)).rejects.toThrow( + "can be changed by another user account", + ); + + expect(downloadFile).not.toHaveBeenCalled(); + expect(readdirSync(elsewhere)).toEqual([]); + } finally { + rmSync(elsewhere, { recursive: true, force: true }); + } + }, +); + +// fails without the fix: the person's own group- and world-writable folder received the download as it was. +it.skipIf(!process.getuid)( + "takes group and other write off the models folder before the download writes", + async () => { + mkdirSync(join(dir, "models")); + chmodSync(join(dir, "models"), 0o777); + + await ensurePinnedFile("https://x.test/m", dest, dir, pin, progress); + + expect(folderModes).toHaveLength(1); + expect(folderModes[0]! & 0o022).toBe(0); + }, +); + +it.skipIf(!process.getuid)("makes a new models folder owner-only", async () => { + await ensurePinnedFile("https://x.test/m", dest, dir, pin, progress); + + expect(statSync(join(dir, "models")).mode & 0o777).toBe(0o700); +}); diff --git a/packages/cli/src/utils/pinnedFile.ts b/packages/cli/src/utils/pinnedFile.ts index 0c8c32711f..cd91ab6e20 100644 --- a/packages/cli/src/utils/pinnedFile.ts +++ b/packages/cli/src/utils/pinnedFile.ts @@ -1,5 +1,6 @@ -import { mkdirSync, statSync } from "node:fs"; +import { statSync } from "node:fs"; import { dirname } from "node:path"; +import { ensurePrivateCacheDir } from "@hyperframes/core/cache-dir"; import { verifies, type ModelFile } from "../whisper/modelFile.js"; import { downloadFile } from "./download.js"; @@ -10,13 +11,14 @@ import { downloadFile } from "./download.js"; export async function ensurePinnedFile( url: string, dest: string, + cacheRoot: string, pin: ModelFile, progress: { downloading: string; onProgress?: (message: string) => void }, ): Promise<string> { + ensurePrivateCacheDir(dirname(dest), cacheRoot); const cached = statSync(dest, { throwIfNoEntry: false }) !== undefined; if (cached && (await verifies(dest, pin))) return dest; - mkdirSync(dirname(dest), { recursive: true }); progress.onProgress?.( cached ? `The cached ${pin.name} does not match its pinned sha256; downloading it again...` diff --git a/packages/cli/src/whisper/manager.model.test.ts b/packages/cli/src/whisper/manager.model.test.ts index 4fd818585b..08f2632305 100644 --- a/packages/cli/src/whisper/manager.model.test.ts +++ b/packages/cli/src/whisper/manager.model.test.ts @@ -1,10 +1,14 @@ import { + chmodSync, existsSync, mkdirSync, + mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, + statSync, + symlinkSync, truncateSync, writeFileSync, } from "node:fs"; @@ -19,9 +23,12 @@ vi.mock("node:os", async (original) => ({ ...(await original<typeof import("node:os")>()), homedir: () => home, })); +// The mode of the folder each download began writing into. +const folderModes = vi.hoisted(() => [] as number[]); vi.mock("../utils/download.js", () => ({ downloadFile: vi.fn( async (_url: string, dest: string, options: { verify: (path: string) => Promise<void> }) => { + folderModes.push(statSync(join(dest, "..")).mode & 0o777); writeFileSync(`${dest}.part`, "fresh"); await options.verify(`${dest}.part`).catch((error: unknown) => { rmSync(`${dest}.part`); @@ -40,6 +47,7 @@ const tiny = join(modelsDir, "ggml-tiny.bin"); beforeEach(() => mkdirSync(modelsDir, { recursive: true })); afterEach(() => { + folderModes.length = 0; rmSync(home, { recursive: true, force: true }); vi.clearAllMocks(); }); @@ -82,3 +90,35 @@ it("uses a model that is not pinned as it was downloaded", async () => { expect(downloadFile).not.toHaveBeenCalled(); expect(existsSync(custom)).toBe(true); }); + +// fails without the fix: the models folder was made with `mkdir -p` and written as found, link or not. +it.skipIf(!process.getuid)( + "downloads nothing through a models folder that is a link out of the cache", + async () => { + const elsewhere = mkdtempSync(join(home, "..", "hf-whisper-elsewhere-")); + try { + rmSync(modelsDir, { recursive: true }); + symlinkSync(elsewhere, modelsDir); + + await expect(ensureModel("tiny")).rejects.toThrow("can be changed by another user account"); + + expect(downloadFile).not.toHaveBeenCalled(); + expect(readdirSync(elsewhere)).toEqual([]); + } finally { + rmSync(elsewhere, { recursive: true, force: true }); + } + }, +); + +// fails without the fix: the person's own group- and world-writable folder received the download as it was. +it.skipIf(!process.getuid)( + "takes group and other write off the models folder before the download writes", + async () => { + chmodSync(modelsDir, 0o777); + + await expect(ensureModel("tiny")).resolves.toBe(tiny); + + expect(folderModes).toHaveLength(1); + expect(folderModes[0]! & 0o022).toBe(0); + }, +); diff --git a/packages/cli/src/whisper/manager.ts b/packages/cli/src/whisper/manager.ts index 159862ba0b..09266d456c 100644 --- a/packages/cli/src/whisper/manager.ts +++ b/packages/cli/src/whisper/manager.ts @@ -1,7 +1,7 @@ // fallow-ignore-file code-duplication complexity import { runsWithoutInstallPrompt } from "../utils/appleStubs.js"; import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs"; +import { existsSync, readdirSync, rmSync, statSync } from "node:fs"; import { platform } from "node:os"; import { dirname, join } from "node:path"; import { findFFmpeg } from "../browser/ffmpeg.js"; @@ -344,10 +344,10 @@ export async function ensureModel( ): Promise<string> { const modelPath = join(MODELS_DIR, `ggml-${model}.bin`); const pin = PINNED_MODELS.get(model); + ensurePrivateCacheDir(MODELS_DIR, hyperframesCacheDir()); const cachedBytes = statSync(modelPath, { throwIfNoEntry: false })?.size; if (cachedBytes !== undefined && (!pin || cachedBytes === pin.bytes)) return modelPath; - mkdirSync(MODELS_DIR, { recursive: true }); rmSync(modelPath, { force: true }); options?.onProgress?.( cachedBytes === undefined From 2425df5f4d8a94a1923cb11d76a97bba9f6e0d8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= <miguel.sierra@heygen.com> Date: Sun, 22 Nov 2026 17:16:16 +0000 Subject: [PATCH 143/367] fix(core): pasted or written markup never carries a composition source from elsewhere (#8520) --- .../core/src/compiler/inlineSubCompositions.ts | 5 +++-- packages/core/src/compositionSource.ts | 3 +++ packages/core/src/runtime/compositionLoader.ts | 5 +++-- .../src/utils/htmlAttrSafety.allowlist.test.ts | 4 ++++ packages/core/src/utils/htmlAttrSafety.ts | 2 ++ .../src/helpers/sourceMutation.test.ts | 18 ++++++++++++++++++ .../src/helpers/sourceMutation.ts | 1 + 7 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 packages/core/src/compositionSource.ts diff --git a/packages/core/src/compiler/inlineSubCompositions.ts b/packages/core/src/compiler/inlineSubCompositions.ts index beeebaf798..33de331537 100644 --- a/packages/core/src/compiler/inlineSubCompositions.ts +++ b/packages/core/src/compiler/inlineSubCompositions.ts @@ -56,6 +56,7 @@ import { } from "./compositionAssembly"; import { SCENE_NO_SWAP_ATTR, SCENE_PART_ATTR } from "../sceneParts"; import { terminalText } from "../terminalText"; +import { COMPOSITION_SRC_ATTR } from "../compositionSource"; // Anything a scene script can leave running, pending or registered outside its timeline, or that // throws when run again: only the timeline is torn down when a scene is swapped, so when unsure, refuse. @@ -481,7 +482,7 @@ export function inlineSubCompositions( })); for (let queueIndex = 0; queueIndex < queue.length; queueIndex += 1) { const { element: hostEl, ancestry, scene: parentScene } = queue[queueIndex]!; - const src = hostEl.getAttribute("data-composition-src"); + const src = hostEl.getAttribute(COMPOSITION_SRC_ATTR); if (!src) continue; const compHtml = resolveHtml(src); @@ -812,7 +813,7 @@ export function inlineSubCompositions( hostEl.insertAdjacentHTML("beforeend", el.outerHTML); hostEl.setAttribute("data-composition-file", src); - hostEl.removeAttribute("data-composition-src"); + hostEl.removeAttribute(COMPOSITION_SRC_ATTR); const nestedAncestry = [...ancestry, src]; const nested = enumerateNestedCompositionHosts(hostEl, nestedAncestry); diff --git a/packages/core/src/compositionSource.ts b/packages/core/src/compositionSource.ts new file mode 100644 index 0000000000..72c6b6b609 --- /dev/null +++ b/packages/core/src/compositionSource.ts @@ -0,0 +1,3 @@ +export const COMPOSITION_SRC_ATTR = "data-composition-src"; + +export const CODE_LOADING_ATTRS: ReadonlySet<string> = new Set([COMPOSITION_SRC_ATTR]); diff --git a/packages/core/src/runtime/compositionLoader.ts b/packages/core/src/runtime/compositionLoader.ts index 9d8a1da248..c92721e7ca 100644 --- a/packages/core/src/runtime/compositionLoader.ts +++ b/packages/core/src/runtime/compositionLoader.ts @@ -43,6 +43,7 @@ import { readRenderOverrides, } from "./getVariables"; import { isElementNode, isHtmlElement, isLinkElement, isStyleElement } from "./domRealm"; +import { COMPOSITION_SRC_ATTR } from "../compositionSource"; type LoadCompositionsParams = { injectedStyles: HTMLStyleElement[]; @@ -745,11 +746,11 @@ async function mountExternalCompositions( cleanupDetachedScopedVariables(); if (trackedHosts.length === 0) return []; const hostIdentityByElement = assignRuntimeCompositionIds(trackedHosts, new Set()); - const hosts = trackedHosts.filter((host) => host.hasAttribute("data-composition-src")); + const hosts = trackedHosts.filter((host) => host.hasAttribute(COMPOSITION_SRC_ATTR)); const mounted = await Promise.all( hosts.map(async (host): Promise<MountedComposition | null> => { - const src = host.getAttribute("data-composition-src"); + const src = host.getAttribute(COMPOSITION_SRC_ATTR); if (!src) return null; const hostIdentity = hostIdentityByElement.get(host); const authoredCompositionId = hostIdentity?.authoredCompositionId || null; diff --git a/packages/core/src/utils/htmlAttrSafety.allowlist.test.ts b/packages/core/src/utils/htmlAttrSafety.allowlist.test.ts index 3a9108d696..bc091bb234 100644 --- a/packages/core/src/utils/htmlAttrSafety.allowlist.test.ts +++ b/packages/core/src/utils/htmlAttrSafety.allowlist.test.ts @@ -27,6 +27,7 @@ const ALLOWED = [ ]; // fails without the fix: each of these passed the old denylist, and the first runs a handler once scripting is on. +// The last three passed the allowlist too: a composition source makes the runtime fetch and run another page. const REFUSED = [ '<div class="clip"><noscript><p title="</noscript><img src=x onerror=alert(1)>"></p></noscript></div>', '<div class="clip"><style>p{}</style><p>Made</p></div>', @@ -36,6 +37,9 @@ const REFUSED = [ '<div class="clip"><link rel="stylesheet" href="https://elsewhere.example/a.css"></div>', '<div class="clip"><template><img src=x onerror=alert(1)></template></div>', '<div class="clip"><form action="https://elsewhere.example/"><button>Go</button></form></div>', + '<div class="clip" data-composition-src="https://elsewhere.example/scene.html"></div>', + '<div class="clip"><div data-composition-src="//elsewhere.example/scene.html"></div></div>', + '<div class="clip"><template><div data-composition-src="scenes/b.html"></div></template></div>', ]; describe("markupOutsideAllowlist", () => { diff --git a/packages/core/src/utils/htmlAttrSafety.ts b/packages/core/src/utils/htmlAttrSafety.ts index 04fb423033..01719b5fde 100644 --- a/packages/core/src/utils/htmlAttrSafety.ts +++ b/packages/core/src/utils/htmlAttrSafety.ts @@ -6,6 +6,7 @@ */ import { SVG_ATTRIBUTES, SVG_ELEMENTS } from "./svgAllowlist"; +import { CODE_LOADING_ATTRS } from "../compositionSource"; export const ALLOWED_HTML_ATTRS = new Set([ "id", @@ -99,6 +100,7 @@ function linkAsBrowsersReadIt(value: string): string { } export function isSafeAttributeValue(name: string, value: string): boolean { + if (CODE_LOADING_ATTRS.has(name.toLowerCase())) return false; if (URI_BEARING_ATTRS.has(name.toLowerCase())) { const trimmed = linkAsBrowsersReadIt(value); if (DANGEROUS_URI_SCHEMES.test(trimmed)) return false; diff --git a/packages/studio-server/src/helpers/sourceMutation.test.ts b/packages/studio-server/src/helpers/sourceMutation.test.ts index 7c5eef124f..5d3ac7d212 100644 --- a/packages/studio-server/src/helpers/sourceMutation.test.ts +++ b/packages/studio-server/src/helpers/sourceMutation.test.ts @@ -347,6 +347,24 @@ describe("patchElementInHtml", () => { expect(result).not.toContain("font-size"); }); + // fails without the fix: either op wrote a composition source, which the runtime fetches and runs. + it("never writes a composition source, by either attribute op", () => { + for (const op of [ + { + type: "html-attribute", + property: "data-composition-src", + value: "https://elsewhere.example/a.html", + }, + { type: "attribute", property: "composition-src", value: "https://elsewhere.example/a.html" }, + { type: "attribute", property: "data-composition-src", value: "scenes/b.html" }, + ] as const) { + const { html: result } = patchElementInHtml(FIXTURE, { id: "hero" }, [op]); + expect(result.match(/data-composition-src/g)?.length ?? 0).toBe( + FIXTURE.match(/data-composition-src/g)?.length ?? 0, + ); + } + }); + it("removes attribute when value is null", () => { const { html: result } = patchElementInHtml( FIXTURE, diff --git a/packages/studio-server/src/helpers/sourceMutation.ts b/packages/studio-server/src/helpers/sourceMutation.ts index 4c5321522d..94d05034aa 100644 --- a/packages/studio-server/src/helpers/sourceMutation.ts +++ b/packages/studio-server/src/helpers/sourceMutation.ts @@ -342,6 +342,7 @@ export function patchElementInHtml( { const fullAttr = op.property.startsWith("data-") ? op.property : `data-${op.property}`; if (op.value != null) { + if (!isSafeAttributeValue(fullAttr, op.value)) break; opTarget.setAttribute(fullAttr, op.value); } else { opTarget.removeAttribute(fullAttr); From 87fddbc1a1c5b745be0f1bbae59e37639a3f5d92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= <miguel.sierra@heygen.com> Date: Sun, 22 Nov 2026 17:32:43 +0000 Subject: [PATCH 144/367] fix(player): a sealed film is heard when its frame may not start sound (#8495) * fix(player): a sealed film is heard when its frame may not start sound When a browser refuses the film's own play (an iPhone, or Chrome's tap-first rule for a sealed frame), the player plays copies of the film's media in its page. A sealed player could not read the frame, so it made no copies and muted the frame anyway: silence. The runtime now sends the clips to copy with the refusal, and again whenever they change. The player copies only files under the composition's own folder, anonymously, and mutes the frame only while a copy plays instead. * fix(player): a sealed film's copy plays its file from the composition's own origin The copy's address is now the composition's origin followed by the checked path, never the string the frame sent. The player's size budget rises by exactly what the sealed copies add (npm pack, main vs this branch). * fix(player): a sealed film's copy address is rebuilt from encoded path parts * fix(player): a sealed film's copy refuses an encoded way out of its folder * fix(player): a sealed film is muted only once its copy plays, and only from web addresses Copies come only from http(s) addresses, so two opaque origins never match. A clip with an invalid file address gets no copy, and the rest are still listed. The frame is muted once a copy is playing, and gets its sound back when the last one fails or is dropped. * fix(player): a sealed film gets its sound back when its last playing copy fails * fix(player): a sealed film's mute follows its copies' own state, whatever order events arrive in --- .github/workflows/player-perf.yml | 7 + packages/core/src/audibleVideo.test.ts | 54 ++++ packages/core/src/audibleVideo.ts | 37 +++ packages/core/src/runtime/init.ts | 46 ++- packages/core/src/runtime/state.ts | 6 +- packages/core/src/runtime/types.ts | 2 + packages/player/README.md | 2 + packages/player/package.json | 1 + .../player/src/hyperframes-player.test.ts | 23 +- packages/player/src/hyperframes-player.ts | 12 +- packages/player/src/parent-media.test.ts | 278 +++++++++++++++++- packages/player/src/parent-media.ts | 212 ++++++++----- .../src/runtime-message-handler.test.ts | 42 ++- .../player/src/runtime-message-handler.ts | 7 +- .../slideshow/hyperframes-slideshow.test.ts | 1 + packages/player/tests/browser/sealed-audio.ts | 48 +++ .../perf/fixtures/sealed-audio/index.html | 28 ++ .../tests/perf/fixtures/sealed-audio/tone.m4a | Bin 0 -> 17785 bytes packages/player/tests/perf/runner.ts | 4 +- packages/player/tests/perf/server.ts | 5 +- 20 files changed, 688 insertions(+), 127 deletions(-) create mode 100644 packages/player/tests/browser/sealed-audio.ts create mode 100644 packages/player/tests/perf/fixtures/sealed-audio/index.html create mode 100644 packages/player/tests/perf/fixtures/sealed-audio/tone.m4a diff --git a/.github/workflows/player-perf.yml b/.github/workflows/player-perf.yml index 4f0e22428e..a0e6cefa4d 100644 --- a/.github/workflows/player-perf.yml +++ b/.github/workflows/player-perf.yml @@ -143,6 +143,13 @@ jobs: PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }} run: bun run test:browser-box + - name: Verify a sealed player's sound plays where its frame may not start it (load shard only) + if: matrix.shard == 'load' + working-directory: packages/player + env: + PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }} + run: bun run test:browser-sealed-audio + - name: Run player perf — ${{ matrix.shard }} (measure mode) working-directory: packages/player env: diff --git a/packages/core/src/audibleVideo.test.ts b/packages/core/src/audibleVideo.test.ts index 2e2ee3fca2..53ed391e27 100644 --- a/packages/core/src/audibleVideo.test.ts +++ b/packages/core/src/audibleVideo.test.ts @@ -3,6 +3,7 @@ import { AUDIBLE_MEDIA_SELECTOR, audibleVideoNeedsWebAudio, isAudibleVideoElement, + parentCopyOf, } from "./audibleVideo"; const el = (tagName: string, attrs: Record<string, string>) => ({ @@ -66,3 +67,56 @@ describe("audibleVideoNeedsWebAudio", () => { expect(audibleVideoNeedsWebAudio(fields)).toBe(true); }); }); + +describe("parentCopyOf", () => { + const media = (html: string) => { + document.body.innerHTML = html; + return document.body.firstElementChild as HTMLMediaElement; + }; + + it("names a timed clip's file at the document's address, its window and where in the file it begins", () => { + expect( + parentCopyOf( + media( + '<audio src="music/a.m4a" data-start="2" data-duration="5" data-media-start="1.5"></audio>', + ), + ), + ).toEqual({ + kind: "audio", + src: new URL("music/a.m4a", document.baseURI).href, + start: 2, + duration: 5, + mediaStart: 1.5, + }); + }); + + it("reads a <source> child and gives an open-ended clip no end", () => { + expect(parentCopyOf(media('<video data-start="0"><source src="b.mp4"></video>'))).toMatchObject( + { kind: "video", src: new URL("b.mp4", document.baseURI).href, duration: Infinity }, + ); + }); + + it("copies nothing a render would not hear, or a clip the preloader has put off", () => { + expect(parentCopyOf(media('<video src="v.mp4" data-start="0" muted></video>'))).toBeNull(); + expect( + parentCopyOf(media('<video src="v.mp4" data-start="0" data-has-audio="false"></video>')), + ).toBeNull(); + expect( + parentCopyOf(media('<audio src="a.m4a" data-start="0" preload="metadata"></audio>')), + ).toBeNull(); + expect( + parentCopyOf(media('<audio src="a.m4a" data-start="0" preload="none"></audio>')), + ).toBeNull(); + expect(parentCopyOf(media('<audio data-start="0"></audio>'))).toBeNull(); + }); + + it("gives a clip whose file address is invalid no copy, and leaves the others alone", () => { + document.body.innerHTML = + '<audio src="https://[" data-start="0"></audio><audio src="b.m4a" data-start="0"></audio>'; + const copies = [...document.querySelectorAll("audio")].map((el) => parentCopyOf(el)); + expect(copies.map((c) => c?.src ?? null)).toEqual([ + null, + new URL("b.m4a", document.baseURI).href, + ]); + }); +}); diff --git a/packages/core/src/audibleVideo.ts b/packages/core/src/audibleVideo.ts index 6c3b9aead3..8f670ef7c9 100644 --- a/packages/core/src/audibleVideo.ts +++ b/packages/core/src/audibleVideo.ts @@ -1,3 +1,6 @@ +import { readClipTiming } from "./compositionContract.js"; +import { readLinkTiming } from "./mediaLink.js"; + export const AUDIBLE_VIDEO_QUALIFIER = ':not([muted]):is(:not([data-has-audio]),[data-has-audio="true"])'; @@ -25,3 +28,37 @@ export function audibleVideoNeedsWebAudio(fields: { Boolean(fields.fxChain || fields.automation || fields.audioGroup || fields.masterChain) ); } + +export interface ParentCopy { + kind: "audio" | "video"; + src: string; + start: number; + duration: number; + mediaStart: number; +} + +export function mediaFileOf(el: HTMLMediaElement): string | null { + const raw = el.getAttribute("src") || el.querySelector("source")?.getAttribute("src"); + if (!raw) return null; + try { + return new URL(raw, el.ownerDocument.baseURI).href; + } catch { + return null; + } +} + +export function parentCopyOf(el: HTMLMediaElement): ParentCopy | null { + if (el.preload === "metadata" || el.preload === "none") return null; + const tag = el.tagName.toLowerCase(); + if (tag !== "audio" && !isAudibleVideoElement(el)) return null; + const src = mediaFileOf(el); + if (!src) return null; + const timing = readClipTiming(el); + return { + kind: tag === "audio" ? "audio" : "video", + src, + start: timing.start ?? 0, + duration: timing.duration ?? Number.POSITIVE_INFINITY, + mediaStart: readLinkTiming(el).mediaStart, + }; +} diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts index ce2b123066..e132e012ec 100644 --- a/packages/core/src/runtime/init.ts +++ b/packages/core/src/runtime/init.ts @@ -266,7 +266,7 @@ import { isVideoElement, type StylableElement, } from "./domRealm"; -import { audibleVideoNeedsWebAudio, isAudibleVideoElement } from "../audibleVideo"; +import { audibleVideoNeedsWebAudio, isAudibleVideoElement, parentCopyOf } from "../audibleVideo"; /** * A `window.__timelines` entry is authored content and may be a PARTIAL @@ -536,6 +536,11 @@ const joinsWebAudio = (el: Element): el is HTMLMediaElement => })); const WEB_AUDIO_MEDIA = "audio[data-start], video[data-start]"; +const parentCopies = () => + Array.from(document.querySelectorAll(WEB_AUDIO_MEDIA)).flatMap((el) => + isMediaElement(el) ? (parentCopyOf(el) ?? []) : [], + ); + /** WebKit restarts a media element's audio 150 to 400 ms late; a decoded buffer on the context clock starts on time. */ function decodesFirst(el: HTMLMediaElement, webAudio: WebAudioTransport): boolean { return ( @@ -3293,6 +3298,43 @@ export function initSandboxRuntimeModular(): void { let bufferingFor: HTMLMediaElement[] = []; const playingOrHeldForData = () => clock.isPlaying() || bufferingFor.length > 0; let keepLateMedia = false; + // A sealed player copies only the clips this list names. ponytail: once blocked, every watched + // change re-reads all media; scope the observer to media records if that shows in a profile. + const postParentCopiesWhileTheyChange = () => { + let posted = ""; + const post = () => { + const media = parentCopies(); + const next = JSON.stringify(media); + if (next === posted || state.tornDown) return; + posted = next; + postRuntimeMessage({ source: "hf-preview", type: "media-autoplay-blocked", media }); + }; + post(); + if (typeof MutationObserver === "undefined") return; + let queued = false; + const observer = new MutationObserver(() => { + if (queued) return; + queued = true; + queueMicrotask(() => { + queued = false; + post(); + }); + }); + observer.observe(document.documentElement, { + subtree: true, + childList: true, + attributes: true, + attributeFilter: [ + ...DURATION_FLOOR_INPUT_ATTRIBUTES, + "src", + "preload", + "muted", + "data-has-audio", + "data-playback-start", + ], + }); + runtimeCleanupCallbacks.push(() => observer.disconnect()); + }; const preloadNearPlayhead = ( el: HTMLMediaElement, visible: boolean, @@ -3993,7 +4035,7 @@ export function initSandboxRuntimeModular(): void { onAutoplayBlocked: () => { if (state.mediaAutoplayBlockedPosted) return; state.mediaAutoplayBlockedPosted = true; - postRuntimeMessage({ source: "hf-preview", type: "media-autoplay-blocked" }); + postParentCopiesWhileTheyChange(); }, }); } diff --git a/packages/core/src/runtime/state.ts b/packages/core/src/runtime/state.ts index ccdaef7512..2c4098d4f5 100644 --- a/packages/core/src/runtime/state.ts +++ b/packages/core/src/runtime/state.ts @@ -32,11 +32,7 @@ export type RuntimeState = { * audible presenter playback and remote sync. */ webAudioMediaDisabled: boolean; - /** - * Latch so the `media-autoplay-blocked` outbound message is posted at most - * once per runtime session. The parent only needs the first signal — it - * takes over playback and further rejections are the same problem. - */ + /** Latch: the first refusal starts `media-autoplay-blocked`, which then follows the media list. */ mediaAutoplayBlockedPosted: boolean; /** * One-shot flag: force a hard media sync on the next tick. Set on diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.ts index d08ec4cbab..f31e09f372 100644 --- a/packages/core/src/runtime/types.ts +++ b/packages/core/src/runtime/types.ts @@ -3,6 +3,7 @@ import type { PreviewTarget } from "../studioPreviewMark"; import type { RuntimeAnalyticsEvent } from "./analytics"; import type { TextLayerRead } from "./editingElement"; import type { AudioFades } from "../audioFade"; +import type { ParentCopy } from "../audibleVideo"; import type { RateSpec } from "../speedRamp"; import type { VolumeKeyframe } from "./mediaVolumeEnvelope"; @@ -193,6 +194,7 @@ export type RuntimeStageSizeMessage = { export type RuntimeMediaAutoplayBlockedMessage = { source: "hf-preview"; type: "media-autoplay-blocked"; + media: ParentCopy[]; }; /** diff --git a/packages/player/README.md b/packages/player/README.md index a4a453ebad..3be1a95e1d 100644 --- a/packages/player/README.md +++ b/packages/player/README.md @@ -137,6 +137,8 @@ The player handles this automatically for same-origin iframes (the default — ` No changes are required by consumers — this works out of the box. +A sealed player (`sandbox-origin`) cannot read the frame. When the frame's own play is refused, the runtime sends the player the list of clips to copy, and sends it again when it changes. The player copies only files under the composition's own folder, on its origin, with `crossorigin="anonymous"`. Any other file is refused and named in a `playbackerror` event (`detail.refused`). A composition loaded from `srcdoc` has no folder of its own, so it gets no copies. The frame is muted only while a copy plays instead. + The optional `audio-src` attribute can be used to start preloading a primary audio track before the iframe loads (useful on slow connections), but is not required for mobile playback. ## JavaScript API diff --git a/packages/player/package.json b/packages/player/package.json index ebb3ea6d07..d7201acc9f 100644 --- a/packages/player/package.json +++ b/packages/player/package.json @@ -34,6 +34,7 @@ "test:browser-security": "bun run tests/browser/sandbox-origin.ts", "test:browser-raster": "bun run tests/browser/preview-raster-size.ts", "test:browser-box": "bun run tests/browser/player-box.ts", + "test:browser-sealed-audio": "bun run tests/browser/sealed-audio.ts", "perf": "bun run tests/perf/index.ts", "playbench": "bun run tests/playbench/run.ts" }, diff --git a/packages/player/src/hyperframes-player.test.ts b/packages/player/src/hyperframes-player.test.ts index 962ae11933..35888a7a65 100644 --- a/packages/player/src/hyperframes-player.test.ts +++ b/packages/player/src/hyperframes-player.test.ts @@ -1104,22 +1104,15 @@ describe("HyperframesPlayer seek() sync path", () => { stubIframeContentDocument(player.iframe, doc); stubContentWindow({ postMessage: post }); + player.setAttribute("audio-src", "https://cdn.example.com/background.mp3"); + const globalProxyPause = vi.spyOn(player._parentMedia[0]!.el, "pause"); const slideProxyPause = vi.fn(); - const globalProxyPause = vi.fn(); - player._parentMedia.push( - { - el: { pause: slideProxyPause, src: "https://cdn.example.com/slide.mp4" }, - start: 0, - duration: 5, - source: iframeVideo, - }, - { - el: { pause: globalProxyPause, src: "https://cdn.example.com/background.mp3" }, - start: 0, - duration: Infinity, - source: null, - }, - ); + player._parentMedia.push({ + el: { pause: slideProxyPause, src: "https://cdn.example.com/slide.mp4" }, + start: 0, + duration: 5, + source: iframeVideo, + }); player.stopMedia(); diff --git a/packages/player/src/hyperframes-player.ts b/packages/player/src/hyperframes-player.ts index c16cd8e0cb..7e15a909fc 100644 --- a/packages/player/src/hyperframes-player.ts +++ b/packages/player/src/hyperframes-player.ts @@ -196,6 +196,7 @@ class HyperframesPlayer extends HTMLElement { getPlaybackRate: () => this.playbackRate, getCurrentTime: () => this._currentTime, isPaused: () => this._paused, + setFrameMuted: (muted) => this._sendControl("set-media-output-muted", { muted }), }); this._directTimelineClock = new DirectTimelineClock({ @@ -1289,6 +1290,8 @@ class HyperframesPlayer extends HTMLElement { setCompositionSize: (w, h) => this._setCompositionSize(w, h), sendControl: (action, extra) => this._sendControl(action, extra), getIframeDoc: () => this.iframe.contentDocument, + getCompositionUrl: () => + this.iframe.hasAttribute("srcdoc") ? null : this.iframe.src || null, onRuntimeReady: () => { this._runtimeBridgeReady = true; this._replayBridgeState(); @@ -1721,14 +1724,7 @@ class HyperframesPlayer extends HTMLElement { this._media.mirrorTime(t, opts); } _promoteToParentProxy() { - let d: Document | null = null; - try { - d = this.iframe.contentDocument; - } catch { - /* x-origin */ - } - this._media.promoteToParentProxy(d, (t, o) => this._mirrorParentMediaTime(t, o)); - this._sendControl("set-media-output-muted", { muted: true }); + this._media.promoteToParentProxy((t, o) => this._mirrorParentMediaTime(t, o)); } _observeDynamicMedia(doc: Document) { this._media.setupFromIframe(doc); diff --git a/packages/player/src/parent-media.test.ts b/packages/player/src/parent-media.test.ts index c6c91139ca..64ac2a3449 100644 --- a/packages/player/src/parent-media.test.ts +++ b/packages/player/src/parent-media.test.ts @@ -29,6 +29,7 @@ function makeManager(overrides: Partial<{ isPaused: boolean; owner: "runtime" | getPlaybackRate: () => 1, getCurrentTime: () => 0, isPaused: () => overrides.isPaused ?? true, + setFrameMuted: () => {}, }); return mgr; } @@ -282,7 +283,7 @@ describe("ParentMediaManager following its clips", () => { clip.setAttribute("src", copy); await flushObserver(); - mgr.promoteToParentProxy(document); + mgr.promoteToParentProxy(); expect(mgr.entries.map((m) => m.el.src)).toEqual([copy]); }); @@ -290,7 +291,7 @@ describe("ParentMediaManager following its clips", () => { it("follows a re-pointed clip at once while the parent owns playback", async () => { const mgr = makeManager(); const clip = adoptedClip(mgr, "https://example.test/clip.mov"); - mgr.promoteToParentProxy(document); + mgr.promoteToParentProxy(); clip.setAttribute("src", copy); await flushObserver(); @@ -301,7 +302,7 @@ describe("ParentMediaManager following its clips", () => { const mgr = makeManager(); adoptedClip(mgr, "https://example.test/a.mov"); const b = adoptedClip(mgr, "https://example.test/b.mov"); - mgr.promoteToParentProxy(document); + mgr.promoteToParentProxy(); b.setAttribute("src", "https://example.test/a.mov"); await flushObserver(); @@ -317,7 +318,7 @@ describe("ParentMediaManager following its clips", () => { const mgr = makeManager(); const a = adoptedClip(mgr, "https://example.test/a.mov"); const b = adoptedClip(mgr, "https://example.test/b.mov"); - mgr.promoteToParentProxy(document); + mgr.promoteToParentProxy(); a.setAttribute("src", "https://example.test/b.mov"); b.setAttribute("src", "https://example.test/a.mov"); await flushObserver(); @@ -333,7 +334,7 @@ describe("ParentMediaManager following its clips", () => { b.setAttribute("src", "https://example.test/c.mov"); await flushObserver(); - mgr.promoteToParentProxy(document); + mgr.promoteToParentProxy(); expect(files(mgr)).toEqual(["https://example.test/b.mov", "https://example.test/c.mov"]); }); @@ -440,7 +441,7 @@ describe("ParentMediaManager takes cut from one joined file", () => { mgr.setupFromIframe(document); expect(mgr.entries).toHaveLength(audios.length); const tracks = mgr.entries.map((m) => trackSeeks(m.el)); - mgr.promoteToParentProxy(document); + mgr.promoteToParentProxy(); let t = 0; const playing: boolean[][] = []; @@ -470,7 +471,7 @@ describe("ParentMediaManager takes cut from one joined file", () => { const mgr = makeManager({ isPaused: false }); mgr.setupFromIframe(document); mgr.entries.forEach((m) => trackSeeks(m.el)); - mgr.promoteToParentProxy(document); + mgr.promoteToParentProxy(); mgr.mirrorTime(12); expect(mgr.entries.map((m) => !m.el.paused)).toEqual([false, true, false]); @@ -495,7 +496,7 @@ describe("ParentMediaManager takes cut from one joined file", () => { const mgr = makeManager({ isPaused: false }); mgr.setupFromIframe(document); const tracks = mgr.entries.map((m) => trackSeeks(m.el)); - mgr.promoteToParentProxy(document); + mgr.promoteToParentProxy(); mgr.mirrorTime(6.4); // inside take 1's window, 1.6 s before take 2 expect(tracks[1].seeks.at(-1)).toBeUndefined(); @@ -608,7 +609,7 @@ describe("ParentMediaManager drift policy", () => { }, }); Object.defineProperty(el, "paused", { get: () => false }); - mgr.promoteToParentProxy(null, () => {}); // owner parent without the alignment seek + mgr.promoteToParentProxy(() => {}); // owner parent without the alignment seek mgr.mirrorTime(5); // 250 ms behind time = 4.85; @@ -646,15 +647,270 @@ describe("proxy crossorigin", () => { const parent = Object.create(ParentMediaManager.prototype) as ParentMediaManager; Object.assign(parent, { _entries: [], - _urlTaken: () => false, _getMuted: () => false, _getVolume: () => 1, _getPlaybackRate: () => 1, }); - (parent as any)._createEntry("https://x/a.mp3", tag, 0, 5, source); + (parent as any)._createEntry( + { kind: tag, src: "https://x/a.mp3", start: 0, duration: 5, mediaStart: 0 }, + source, + ); const proxy = created.find((e) => e.tagName.toLowerCase() === tag)!; globalThis.Audio = OrigAudio; vi.restoreAllMocks(); expect(proxy.getAttribute("crossorigin")).toBe("anonymous"); }); }); + +describe("ParentMediaManager for a sealed film, from its runtime's list", () => { + const film = "https://films.test/f/index.html"; + const clip = (src: string, start = 0) => ({ + kind: "audio", + src, + start, + duration: 5, + mediaStart: 0, + }); + + function makeSealedManager() { + const events: CustomEvent[] = []; + const setFrameMuted = vi.fn(); + const mgr = new ParentMediaManager({ + dispatchEvent: (e) => events.push(e as CustomEvent), + getMuted: () => false, + getVolume: () => 1, + getPlaybackRate: () => 1, + getCurrentTime: () => 0, + isPaused: () => true, + setFrameMuted, + }); + return { mgr, events, setFrameMuted }; + } + + // A copy's own state, as the browser reports it, then the event that says it changed. + function becomes(el: HTMLMediaElement, state: "playing" | "pause" | "ended" | "error") { + const define = (key: string, value: unknown) => + Object.defineProperty(el, key, { configurable: true, get: () => value }); + define("paused", state !== "playing"); + define("readyState", state === "playing" ? 4 : 1); + define("ended", state === "ended"); + if (state === "error") define("error", { code: 2 }); + el.dispatchEvent(new Event(state)); + } + + it("copies only files under the composition's own folder, without credentials, and reports the rest", () => { + const { mgr, events } = makeSealedManager(); + + mgr.setupFromList( + [ + clip("https://films.test/f/music/a.m4a"), + clip("https://films.test/f/music/my%20take.m4a?v=3"), + clip("https://other.test/f/a.m4a"), + clip("https://films.test/g/a.m4a"), + clip("https://films.test/f/../secret.m4a"), + clip("data:audio/mp4;base64,AAAA"), + ], + film, + ); + + expect(mgr.entries.map((m) => m.el.src)).toEqual([ + "https://films.test/f/music/a.m4a", + "https://films.test/f/music/my%20take.m4a?v=3", + ]); + expect(mgr.entries.every((m) => m.el.getAttribute("crossorigin") === "anonymous")).toBe(true); + const refusal = events.find((e) => e.type === "playbackerror"); + expect(refusal?.detail.refused).toEqual([ + "https://other.test/f/a.m4a", + "https://films.test/g/a.m4a", + "https://films.test/f/../secret.m4a", + "data:audio/mp4;base64,AAAA", + ]); + }); + + it("refuses every way out of the composition's folder, and copies a file in a folder under it", () => { + const { mgr, events } = makeSealedManager(); + const escapes = [ + "https://films.test/f/%2e%2e/secret.m4a", + "https://films.test/f/..%2Fsecret.m4a", + "https://films.test/f/music%2F..%2F..%2Fsecret.m4a", + "https://films.test/f/..%5Csecret.m4a", + "https://films.test/f/..\\secret.m4a", + "https://elsewhere.test/f/a.m4a", + "//elsewhere.test/f/a.m4a", + ]; + + mgr.setupFromList( + [...escapes, "https://films.test/f/music/loops/a.m4a"].map((src) => clip(src)), + film, + ); + + expect(mgr.entries.map((m) => m.el.src)).toEqual(["https://films.test/f/music/loops/a.m4a"]); + expect(events.find((e) => e.type === "playbackerror")?.detail.refused).toEqual(escapes); + }); + + it("copies nothing when the composition has no address of its own", () => { + const { mgr } = makeSealedManager(); + mgr.setupFromList([clip("https://films.test/f/a.m4a")], null); + expect(mgr.entries).toHaveLength(0); + }); + + it("skips a list entry that is not a well-formed clip", () => { + const { mgr } = makeSealedManager(); + mgr.setupFromList( + [ + { kind: "audio", start: 0 }, + { ...clip("https://films.test/f/a.m4a"), start: Number.NaN }, + "x", + null, + ], + film, + ); + expect(mgr.entries).toHaveLength(0); + }); + + it("gives each clip on one file its own copy, and follows the list as it changes", () => { + const { mgr } = makeSealedManager(); + mgr.setupFromList( + [clip("https://films.test/f/a.m4a", 0), clip("https://films.test/f/a.m4a", 4)], + film, + ); + expect(mgr.entries.map((m) => m.start)).toEqual([0, 4]); + const kept = mgr.entries[1]; + + mgr.setupFromList([clip("https://films.test/f/a.m4a", 4)], film); + expect(mgr.entries).toEqual([kept]); + }); + + it("mutes the film only once a copy is playing, not when the copy is made or told to play", () => { + const { mgr, setFrameMuted } = makeSealedManager(); + + mgr.setupFromList([clip("https://films.test/f/a.m4a")], film); + mgr.promoteToParentProxy(); + expect(setFrameMuted).not.toHaveBeenCalled(); + + becomes(mgr.entries[0]!.el, "playing"); + expect(setFrameMuted.mock.calls).toEqual([[true]]); + }); + + it("gives the film its sound back when its last playing copy fails or is dropped", () => { + const { mgr, setFrameMuted } = makeSealedManager(); + mgr.setupFromList( + [clip("https://films.test/f/a.m4a"), clip("https://films.test/f/b.m4a")], + film, + ); + mgr.promoteToParentProxy(); + const [a, b] = mgr.entries.map((m) => m.el); + becomes(a!, "playing"); + becomes(b!, "playing"); + + becomes(a!, "error"); + expect(setFrameMuted.mock.calls).toEqual([[true]]); + + mgr.setupFromList([clip("https://films.test/f/a.m4a")], film); + expect(setFrameMuted.mock.calls).toEqual([[true], [false]]); + }); + + it("gives the film its sound back when the only copy still playing fails after the others stopped", () => { + const { mgr, setFrameMuted } = makeSealedManager(); + mgr.setupFromList( + ["a", "b", "c"].map((f) => clip(`https://films.test/f/${f}.m4a`)), + film, + ); + mgr.promoteToParentProxy(); + const [a, b, c] = mgr.entries.map((m) => m.el); + becomes(a!, "playing"); + becomes(b!, "playing"); + becomes(a!, "ended"); + becomes(c!, "playing"); + becomes(b!, "pause"); + + becomes(c!, "error"); + expect(setFrameMuted.mock.calls).toEqual([[true], [false]]); + }); + + it.each([ + ["before", true], + ["after", false], + ])( + "gives the film its sound back when the next copy's play is refused, the old copy's pause event arriving %s the refusal", + async (_order, pauseEventFirst) => { + let now = 1; + const setFrameMuted = vi.fn(); + const mgr = new ParentMediaManager({ + dispatchEvent: () => {}, + getMuted: () => false, + getVolume: () => 1, + getPlaybackRate: () => 1, + getCurrentTime: () => now, + isPaused: () => false, + setFrameMuted, + }); + mgr.setupFromList( + [clip("https://films.test/f/a.m4a", 0), clip("https://films.test/f/b.m4a", 5)], + film, + ); + const [a, b] = mgr.entries.map((m) => m.el); + let aPaused = true; + Object.defineProperty(a, "paused", { get: () => aPaused }); + Object.defineProperty(a, "readyState", { get: () => 4 }); + a!.play = async () => { + aPaused = false; + }; + a!.pause = () => { + aPaused = true; + }; + b!.play = () => Promise.reject(new DOMException("refused", "NotAllowedError")); + b!.pause = () => {}; + + mgr.promoteToParentProxy(); + a!.dispatchEvent(new Event("playing")); + now = 6; + mgr.mirrorTime(now, { force: true }); + if (pauseEventFirst) a!.dispatchEvent(new Event("pause")); + await vi.waitFor(() => expect(setFrameMuted.mock.calls.length).toBeGreaterThan(1)); + if (!pauseEventFirst) a!.dispatchEvent(new Event("pause")); + + expect(setFrameMuted.mock.calls).toEqual([[true], [false]]); + mgr.destroy(); + }, + ); + + it("mutes an unsealed film's own media once a copy of it is playing", () => { + const { mgr, setFrameMuted } = makeSealedManager(); + document.body.innerHTML = '<audio src="https://films.test/f/a.m4a" data-start="0"></audio>'; + mgr.setupFromIframe(document); + mgr.promoteToParentProxy(); + expect(setFrameMuted).not.toHaveBeenCalled(); + + becomes(mgr.entries[0]!.el, "playing"); + expect(setFrameMuted.mock.calls).toEqual([[true]]); + expect(document.querySelector("audio")!.muted).toBe(true); + mgr.destroy(); + }); + + it("copies only what a render hears: no copy for a video marked as having no sound", () => { + const { mgr } = makeSealedManager(); + document.body.innerHTML = + '<video src="https://films.test/f/v.mp4" data-start="0" data-has-audio="false"></video>' + + '<video src="https://films.test/f/w.mp4" data-start="0"></video>'; + mgr.setupFromIframe(document); + expect(mgr.entries.map((m) => m.el.src)).toEqual(["https://films.test/f/w.mp4"]); + mgr.destroy(); + }); + + it("never mutes the film for the player's own audio-src track alone", () => { + const { mgr, setFrameMuted } = makeSealedManager(); + mgr.setupFromUrl("https://cdn.test/narration.mp3"); + mgr.promoteToParentProxy(); + becomes(mgr.entries[0]!.el, "playing"); + expect(setFrameMuted).not.toHaveBeenCalled(); + }); + + it("never copies from an opaque origin, even when the composition's own origin is opaque too", () => { + const { mgr } = makeSealedManager(); + const opaque = [clip("data:audio/mp4;base64,AAAA"), clip("about:blank")]; + mgr.setupFromList(opaque, "about:blank"); + mgr.setupFromList(opaque, "data:audio/x,film"); + expect(mgr.entries).toHaveLength(0); + }); +}); diff --git a/packages/player/src/parent-media.ts b/packages/player/src/parent-media.ts index 496bb77931..138b2dcf8a 100644 --- a/packages/player/src/parent-media.ts +++ b/packages/player/src/parent-media.ts @@ -14,6 +14,7 @@ import { isRealmElement, isRealmHtmlMediaElement } from "./media-element-guards. import { isInClipWindow } from "@hyperframes/core/runtime/clip-window"; import { readClipTiming } from "@hyperframes/core/composition-contract"; import { readLinkTiming } from "@hyperframes/core/media-link"; +import { mediaFileOf, parentCopyOf, type ParentCopy } from "@hyperframes/core/audible-video"; import { mediaElementTime, startsSoundOnlyInsideATap } from "@hyperframes/core/runtime/media-clock"; import { MEDIA_SYNC_TOLERANCE_SECONDS, @@ -30,6 +31,8 @@ const SETTLED_OFFSET_DELTA_SECONDS = 0.004; */ const PRESEEK_SECONDS = 1.5; +const HAVE_FUTURE_DATA = 3; + export interface ProxyEntry { el: HTMLMediaElement; start: number; @@ -59,6 +62,9 @@ export class ParentMediaManager { * replaced or cleared instead of accumulating on every attribute change. */ private _urlAudioEntry: ProxyEntry | null = null; private _urlAudioSrc: string | null = null; + /** A sealed film's copies, keyed by the clip they play, from its runtime's list. */ + private _listed = new Map<string, ProxyEntry>(); + private _filmSilenced = false; private readonly _dispatchEvent: (event: Event) => void; private readonly _getMuted: () => boolean; @@ -66,6 +72,7 @@ export class ParentMediaManager { private readonly _getPlaybackRate: () => number; private readonly _getCurrentTime: () => number; private readonly _isPaused: () => boolean; + private readonly _setFrameMuted: (muted: boolean) => void; constructor(opts: { dispatchEvent: (event: Event) => void; @@ -74,6 +81,8 @@ export class ParentMediaManager { getPlaybackRate: () => number; getCurrentTime: () => number; isPaused: () => boolean; + /** Silences the film's own media while a copy plays it instead, and gives it back after. */ + setFrameMuted: (muted: boolean) => void; }) { this._dispatchEvent = opts.dispatchEvent; this._getMuted = opts.getMuted; @@ -81,6 +90,7 @@ export class ParentMediaManager { this._getPlaybackRate = opts.getPlaybackRate; this._getCurrentTime = opts.getCurrentTime; this._isPaused = opts.isPaused; + this._setFrameMuted = opts.setFrameMuted; } get audioOwner(): "runtime" | "parent" { @@ -99,8 +109,10 @@ export class ParentMediaManager { this.pauseAll(); for (const m of this._entries) if (m !== this._urlAudioEntry) m.el.src = ""; this._entries = this._urlAudioEntry ? [this._urlAudioEntry] : []; + this._listed.clear(); + this._filmSilenced = false; if (this._urlAudioSrc && !this._urlAudioEntry) - this._urlAudioEntry = this._createEntry(this._urlAudioSrc, "audio", 0, Infinity); + this._urlAudioEntry = this._createEntry(urlAudio(this._urlAudioSrc)); this.teardownObserver(); if (wasPromoted) { this._dispatchEvent( @@ -118,6 +130,8 @@ export class ParentMediaManager { m.el.src = ""; } this._entries = []; + this._listed.clear(); + this._filmSilenced = false; this._urlAudioEntry = null; this._urlAudioSrc = null; this._audioOwner = "runtime"; @@ -138,7 +152,10 @@ export class ParentMediaManager { private _playEntry(m: ProxyEntry): void { if (!m.el.src) return; - m.el.play().catch((err: unknown) => this._reportPlaybackError(err)); + m.el.play().catch((err: unknown) => { + this._syncFrameMute(); + this._reportPlaybackError(err); + }); } // Play only if the current playhead is inside the clip's (live) window, so @@ -234,9 +251,7 @@ export class ParentMediaManager { } stopAdoptedMedia(): void { - for (const m of this._entries) { - if (m.source) m.el.pause(); - } + for (const m of this._filmCopies()) m.el.pause(); } seekAll(timeInSeconds: number): void { @@ -305,32 +320,16 @@ export class ParentMediaManager { this._releaseSteering(m); } - /** - * Take ownership of audible playback in response to the runtime's - * `media-autoplay-blocked` signal. Idempotent. - * - * The caller is responsible for muting the iframe's own media output via the - * postMessage bridge (`set-media-output-muted`) after calling this. - */ /** * Take ownership of audible playback. Idempotent. The `onMirror` callback * is called with the current timeline time and `{ force: true }` so the * caller's mirror implementation runs (enabling test spies on the player * to fire). If omitted, `mirrorTime` is called directly. */ - promoteToParentProxy( - iframeDoc: Document | null, - onMirror?: (t: number, opts: { force: boolean }) => void, - ): void { + promoteToParentProxy(onMirror?: (t: number, opts: { force: boolean }) => void): void { if (this._audioOwner === "parent") return; this._audioOwner = "parent"; - // Synchronously mute iframe media to close the race window. - if (iframeDoc) { - for (const el of iframeDoc.querySelectorAll("video, audio")) { - if (isRealmHtmlMediaElement(el)) el.muted = true; - } - } for (const m of [...this._entries]) this._repointToSource(m); // One-shot alignment — bypass jitter-coalescing gate. @@ -367,7 +366,7 @@ export class ParentMediaManager { setupFromUrl(audioSrc: string): void { if (this._urlAudioSrc === audioSrc && this._urlAudioEntry) return; this.teardownUrlAudio(); - const entry = this._createEntry(audioSrc, "audio", 0, Infinity); + const entry = this._urlTaken(audioSrc) ? null : this._createEntry(urlAudio(audioSrc)); // Null when the composition already has a proxy for this URL: that one stays the // composition's, and a reset creates ours once that document's proxies are gone. this._urlAudioEntry = entry; @@ -407,25 +406,43 @@ export class ParentMediaManager { ); } - /** - * Create a parent-frame media element and start preloading it. A URL-driven - * proxy returns `null` when the file already has one; a clip always gets its - * own, since its window and media offset are its own. - */ - private _createEntry( - src: string, - tag: "audio" | "video", - start: number, - duration: number, - source?: HTMLMediaElement | null, - ): ProxyEntry | null { - if (!source && this._urlTaken(src)) return null; + /** Copies for a sealed film, from its runtime's list: only files under the composition's own folder. */ + setupFromList(list: unknown, compositionUrl: string | null): void { + const wanted = new Map<string, ParentCopy>(); + const refused: string[] = []; + for (const copy of readCopies(list)) { + const src = underComposition(copy.src, compositionUrl); + if (src) wanted.set(JSON.stringify(copy), { ...copy, src }); + else refused.push(copy.src); + } + for (const [key, entry] of this._listed) { + if (wanted.has(key)) continue; + this._removeEntry(entry); + this._listed.delete(key); + } + for (const [key, copy] of wanted) { + if (this._listed.has(key)) continue; + const entry = this._createEntry(copy, null, "anonymous"); + this._listed.set(key, entry); + this._copyAdded(entry); + } + if (refused.length === 0) return; + const error = new Error("a sealed film's media outside the composition's folder is not copied"); + this._dispatchEvent( + new CustomEvent("playbackerror", { detail: { source: "parent-proxy", error, refused } }), + ); + } - const el = tag === "video" ? document.createElement("video") : new Audio(); + /** Create a parent-frame media element and start preloading it. */ + private _createEntry( + copy: ParentCopy, + source?: HTMLMediaElement | null, + crossOrigin = source?.getAttribute("crossorigin") ?? null, + ): ProxyEntry { + const el = copy.kind === "video" ? document.createElement("video") : new Audio(); el.preload = "auto"; - const crossOrigin = source?.getAttribute("crossorigin"); if (crossOrigin != null) el.setAttribute("crossorigin", crossOrigin); - el.src = src; + el.src = copy.src; el.load(); el.muted = this._getMuted(); el.volume = this._getVolume(); @@ -434,50 +451,53 @@ export class ParentMediaManager { const entry: ProxyEntry = { el, - start, - duration, - mediaStart: source ? readLinkTiming(source).mediaStart : 0, + start: copy.start, + duration: copy.duration, + mediaStart: copy.mediaStart, source, }; el.addEventListener("seeked", () => this._noteSeekLanded(entry)); + for (const change of ["playing", "waiting", "pause", "ended", "error"]) + el.addEventListener(change, () => this._syncFrameMute()); this._entries.push(entry); return entry; } - /** Resolve an iframe media element's source to an absolute URL, or null. */ - private _resolveIframeMediaSrc(iframeEl: HTMLMediaElement): string | null { - const rawSrc = - iframeEl.getAttribute("src") || iframeEl.querySelector("source")?.getAttribute("src"); - return rawSrc ? new URL(rawSrc, iframeEl.ownerDocument.baseURI).href : null; + /** Every copy of the film's own media: all but the player's `audio-src` track. */ + private _filmCopies(): ProxyEntry[] { + return this._entries.filter((m) => m !== this._urlAudioEntry); } - // fallow-ignore-next-line complexity - private _adoptIframeMedia(iframeEl: HTMLMediaElement): void { - // Skip elements the preloader has demoted: the observer adopts one when its preload turns - // "auto" and drops its proxy, which fetches the whole file, when it turns back. - if (iframeEl.preload === "metadata" || iframeEl.preload === "none") return; - - if (this._entries.some((m) => m.source === iframeEl)) return; - - // A video authored muted is picture only: its file's audio belongs to the clip that plays it. - if (iframeEl.tagName === "VIDEO" && iframeEl.hasAttribute("muted")) return; - - const src = this._resolveIframeMediaSrc(iframeEl); - if (!src) return; - - const timing = readClipTiming(iframeEl); - const start = timing.start ?? 0; - const duration = timing.duration ?? Number.POSITIVE_INFINITY; - const tag = iframeEl.tagName === "VIDEO" ? ("video" as const) : ("audio" as const); - - const created = this._createEntry(src, tag, start, duration, iframeEl); - - // If already under parent ownership and playing, the new proxy must catch - // up immediately — bypass the jitter-coalescing gate. - if (created && this._audioOwner === "parent") { - this.mirrorTime(this._getCurrentTime(), { force: true }); - if (!this._isPaused()) this._playEntryIfActive(created); + // The film is silent exactly while a copy of its media is heard instead, read from each + // copy's own state so the order its events arrive in cannot leave the film muted. + private _syncFrameMute(): void { + const heard = + this._audioOwner === "parent" && + this._filmCopies().some( + ({ el }) => !el.paused && !el.ended && !el.error && el.readyState >= HAVE_FUTURE_DATA, + ); + if (heard === this._filmSilenced) return; + this._filmSilenced = heard; + const frameDoc = this._entries.find((m) => m.source)?.source?.ownerDocument; + if (heard) { + for (const el of frameDoc?.querySelectorAll("video, audio") ?? []) { + if (isRealmHtmlMediaElement(el)) el.muted = true; + } } + this._setFrameMuted(heard); + } + + // A copy made while the parent owns playback catches up at once, past the jitter gate. + private _copyAdded(entry: ProxyEntry): void { + if (this._audioOwner !== "parent") return; + this.mirrorTime(this._getCurrentTime(), { force: true }); + if (!this._isPaused()) this._playEntryIfActive(entry); + } + + private _adoptIframeMedia(iframeEl: HTMLMediaElement): void { + if (this._entries.some((m) => m.source === iframeEl)) return; + const copy = parentCopyOf(iframeEl); + if (copy) this._copyAdded(this._createEntry(copy, iframeEl)); } // The runtime re-points a clip (its preview copy, a new bound file). A proxy that is not @@ -495,12 +515,12 @@ export class ParentMediaManager { private _urlTaken(src: string): boolean { return this._entries.some((m) => { if (m.source && !m.source.isConnected) return false; - return ((m.source && this._resolveIframeMediaSrc(m.source)) || m.el.src) === src; + return ((m.source && mediaFileOf(m.source)) || m.el.src) === src; }); } private _repointToSource(entry: ProxyEntry): boolean { - const src = entry.source ? this._resolveIframeMediaSrc(entry.source) : null; + const src = entry.source ? mediaFileOf(entry.source) : null; if (!src || entry.el.src === src) return false; entry.el.src = src; entry.el.load(); @@ -516,6 +536,7 @@ export class ParentMediaManager { entry.el.pause(); entry.el.src = ""; this._entries.splice(this._entries.indexOf(entry), 1); + this._syncFrameMute(); } private _observeDynamicMedia(doc: Document): void { @@ -595,3 +616,44 @@ export class ParentMediaManager { this._mediaObserver = obs; } } + +function urlAudio(src: string): ParentCopy { + return { kind: "audio", src, start: 0, duration: Number.POSITIVE_INFINITY, mediaStart: 0 }; +} + +/** The well-formed clips of a list from the film; the frame is not trusted. */ +function readCopies(list: unknown): ParentCopy[] { + if (!Array.isArray(list)) return []; + return list.filter((item): item is ParentCopy => { + if (typeof item !== "object" || item === null) return false; + const c = item as Record<string, unknown>; + return ( + (c.kind === "audio" || c.kind === "video") && + typeof c.src === "string" && + Number.isFinite(c.start) && + typeof c.duration === "number" && + c.duration >= 0 && + Number.isFinite(c.mediaStart) + ); + }); +} + +/** The file's address on the composition's own origin when it is under its folder; otherwise null. */ +function underComposition(src: string, compositionUrl: string | null): string | null { + if (!compositionUrl) return null; + try { + const file = new URL(src); + const base = new URL(compositionUrl); + const web = /^https?:$/; + if (!web.test(file.protocol) || !web.test(base.protocol)) return null; + const folder = base.pathname.slice(0, base.pathname.lastIndexOf("/") + 1); + if (file.origin !== base.origin || !file.pathname.startsWith(folder)) return null; + const parts = file.pathname.slice(folder.length).split("/").map(decodeURIComponent); + if (parts.some((part) => /[/\\]/.test(part) || part === "." || part === "..")) return null; + const path = parts.map(encodeURIComponent).join("/"); + const query = file.search ? "?" + file.search.slice(1) : ""; + return base.origin + folder + path + query; + } catch { + return null; + } +} diff --git a/packages/player/src/runtime-message-handler.test.ts b/packages/player/src/runtime-message-handler.test.ts index 6e19ee2b65..0acab510bb 100644 --- a/packages/player/src/runtime-message-handler.test.ts +++ b/packages/player/src/runtime-message-handler.test.ts @@ -20,7 +20,12 @@ const makeCallbacks = (): MessageHandlerCallbacks => ({ seek: vi.fn(), play: vi.fn(), getLoop: vi.fn(() => false), - media: { mirrorTime: vi.fn(), promoteToParentProxy: vi.fn() } as unknown as ParentMediaManager, + media: { + mirrorTime: vi.fn(), + promoteToParentProxy: vi.fn(), + setupFromList: vi.fn(), + } as unknown as ParentMediaManager, + getCompositionUrl: vi.fn(() => null), getPlaybackState: vi.fn(() => ({ currentTime: 0, duration: 0, paused: true, lastUpdateMs: 0 })), setPlaybackState: vi.fn(), setScenes: vi.fn(), @@ -121,16 +126,43 @@ describe("handleRuntimeMessage media autoplay fallback", () => { data: { source: "hf-preview", type: "media-autoplay-blocked" }, }) as unknown as MessageEvent; - it("promotes and mutes iframe output by default", () => { + it("promotes, leaving the mute to the copies", () => { const frameWindow = {} as Window; const callbacks = makeCallbacks(); handleRuntimeMessage(autoplayBlockedEvent(frameWindow), frameWindow, callbacks); expect(callbacks.media.promoteToParentProxy).toHaveBeenCalled(); - expect(callbacks.sendControl).toHaveBeenCalledWith("set-media-output-muted", { - muted: true, - }); + expect(callbacks.sendControl).not.toHaveBeenCalled(); + }); + + it("builds a sealed film's copies from the runtime's list, against the composition's own address", () => { + const frameWindow = {} as Window; + const callbacks = { + ...makeCallbacks(), + getCompositionUrl: () => "https://films.test/f/index.html", + }; + const media = [ + { kind: "audio", src: "https://films.test/f/a.m4a", start: 0, duration: 5, mediaStart: 0 }, + ]; + + handleRuntimeMessage( + { + source: frameWindow, + data: { source: "hf-preview", type: "media-autoplay-blocked", media }, + } as unknown as MessageEvent, + frameWindow, + callbacks, + ); + + expect(callbacks.media.setupFromList).toHaveBeenCalledWith( + media, + "https://films.test/f/index.html", + ); + const order = (fn: unknown) => (fn as ReturnType<typeof vi.fn>).mock.invocationCallOrder[0]!; + expect(order(callbacks.media.setupFromList)).toBeLessThan( + order(callbacks.media.promoteToParentProxy), + ); }); it("does not promote or mute iframe output when the host vetoes the fallback", () => { diff --git a/packages/player/src/runtime-message-handler.ts b/packages/player/src/runtime-message-handler.ts index c0dfd7a788..fe4a5c455f 100644 --- a/packages/player/src/runtime-message-handler.ts +++ b/packages/player/src/runtime-message-handler.ts @@ -41,6 +41,7 @@ export interface MessageHandlerCallbacks extends PlaybackStateCallbacks { setCompositionSize: (width: number, height: number) => void; sendControl: (action: string, extra?: Record<string, unknown>) => void; getIframeDoc: () => Document | null; + getCompositionUrl: () => string | null; /** Invoked when the iframe runtime posts `{type: "ready"}` — the player * uses it to replay current bridge state (mute, volume, playback rate) so * control messages sent before the iframe's listener registered aren't lost. */ @@ -160,10 +161,8 @@ export function handleRuntimeMessage( } catch { /* cross-origin */ } - callbacks.media.promoteToParentProxy(iframeDoc, (t, opts) => - callbacks.media.mirrorTime(t, opts), - ); - callbacks.sendControl("set-media-output-muted", { muted: true }); + if (!iframeDoc) callbacks.media.setupFromList(data["media"], callbacks.getCompositionUrl()); + callbacks.media.promoteToParentProxy((t, opts) => callbacks.media.mirrorTime(t, opts)); return; } diff --git a/packages/player/src/slideshow/hyperframes-slideshow.test.ts b/packages/player/src/slideshow/hyperframes-slideshow.test.ts index f7f80681be..75be001303 100644 --- a/packages/player/src/slideshow/hyperframes-slideshow.test.ts +++ b/packages/player/src/slideshow/hyperframes-slideshow.test.ts @@ -569,6 +569,7 @@ describe("handleRuntimeMessage scenes seam", () => { setCompositionSize: () => {}, sendControl: () => {}, getIframeDoc: () => null, + getCompositionUrl: () => null, onRuntimeReady: () => {}, onRuntimeTimelineReady: () => {}, setScenes, diff --git a/packages/player/tests/browser/sealed-audio.ts b/packages/player/tests/browser/sealed-audio.ts new file mode 100644 index 0000000000..72b2108c27 --- /dev/null +++ b/packages/player/tests/browser/sealed-audio.ts @@ -0,0 +1,48 @@ +import assert from "node:assert/strict"; + +import { launchBrowser } from "../perf/runner.js"; +import { startServer } from "../perf/server.js"; + +const server = startServer(); +const browser = await launchBrowser({ autoplay: "gesture" }); + +try { + const page = await browser.newPage(); + await page.goto(`${server.origin}/host.html?fixture=sealed-audio`, { + waitUntil: "domcontentloaded", + }); + await page.waitForFunction(() => window.__playerReady || window.__playerError, { + timeout: 60_000, + }); + await page.evaluate(() => { + const player = document.getElementById("player")!; + player.removeAttribute("muted"); + window.__playerReady = false; + player.setAttribute("sandbox-origin", "opaque"); + }); + await page.waitForFunction(() => window.__playerReady || window.__playerError, { + timeout: 60_000, + }); + type Player = HTMLElement & { + play: () => void; + _audioOwner: string; + _parentMedia: { el: HTMLMediaElement }[]; + }; + await page.evaluate(() => (document.getElementById("player") as Player).play()); + await page.waitForFunction( + () => (document.getElementById("player") as Player)._audioOwner === "parent", + { timeout: 30_000 }, + ); + const copies = await page.evaluate(() => + (document.getElementById("player") as Player)._parentMedia.map((m) => m.el.src), + ); + assert.deepEqual( + copies, + [`${server.origin}/fixtures/sealed-audio/tone.m4a`], + "a sealed player loaded by src copies its film's sound into the page when the frame may not start it", + ); + console.log("[sealed-audio] a refused sealed frame's sound plays from a copy in the page"); +} finally { + await browser.close(); + await server.stop(); +} diff --git a/packages/player/tests/perf/fixtures/sealed-audio/index.html b/packages/player/tests/perf/fixtures/sealed-audio/index.html new file mode 100644 index 0000000000..a49fc3e671 --- /dev/null +++ b/packages/player/tests/perf/fixtures/sealed-audio/index.html @@ -0,0 +1,28 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>perf fixture: sealed-audio + + + + +
+
+ +
+ + + diff --git a/packages/player/tests/perf/fixtures/sealed-audio/tone.m4a b/packages/player/tests/perf/fixtures/sealed-audio/tone.m4a new file mode 100644 index 0000000000000000000000000000000000000000..d9df5b0feb73bd9f4a422743fabbdc121fa22ada GIT binary patch literal 17785 zcmajH2{@Er_&+?BM5G8I6xoGrC3~{(`!djh7co5iWp0b zB@M>TnD;#N{r`UN|9Y?MeXhAZ^K9pw=bZc8=W~DVd%$2Y7DvAzFKzMLS70z=7_@ix z^>ha!3WLGO9eo@eU@-Y2cl&#OQ^YW>dk^exhzf~H3W;17ff3u37$uGSh~m0S^CYZ% z<||e>Ra29Nzj9s*AX&4j{L%XNl3=;><+&kT$W%?ww7ZtEo!j>;+zJVHJSp+x2Ov-bXTj?|yE-pX|P|9#Zrc#GnApVQFL z($MMCDARJpaey<^M3SlFJ(j74m3*VgODNoGSGJ4`VSfxe#yn?QL#UtI!*w-{t`KH- zjzZU~>nqP5HHe4NF;W(2y?LBp{@s%=zWKeABo)=)3)ioUHL0nc{JAdH8Wr`Lk&$Wg zqoR(Y8y9-!%$rHwoMx-kswG8FM-RQ^m$hW6oSbRX&WeiaR$g|F9~CtoIZnUt0{gdp zpC#z@Z8atcoDu5yUAza=ktOj&WRqTu*zaNHeulAK2 zS-ILi9(+b#RxkqUqZ4`rzd`#|Q~c{nHqLN*buR}z9mf%-5Utj`McBa-#@2n~y;BBO zx;q1RCz?#&rCj65Rh5bh8kNE2`BPwI%{5-_TZB~Pr%ki02flc9hTej)w;(bPFh#%QJ6gE7Wd$fIn6^>#*Qzms{#5gt1p;I)=)2y1D%j#={x_Fp-y?{)V@ z-5h$#9vr>WW#9YQ*e5A(Hbver2CmP4Z4*=D*maUtNuMyw+J7p+dXMi7g0z62 z%KkQhk^$%4zSJNR; ztQ8sO*%uft>+DJLTP4J)!#qWafL4BgEew^aW9g4q73Uz;uaYr{yqZw0%xP*Q}%3=X*~H zc{-Hh6gR(=q`{Bp>Q7T-`S5(rgbPuj4Yb`V zR3a#*PU@u_{q2GQZ=Kh4SOiAt=A$afrAN+VfuhEwi%M21vX54DAmkg5+SI#h;&g%z za5;vJ^~S%;O&={OlbaK?$uB0HKlSa{B;2fO6O3KqdXc`w;36f+6V$8F2>K-Efqp`i zatY1-Y+bxGA%83&l&4`QdmD+G4wPNy4>7(igL~0Qp29%`W3U@kc@&P{JiIxyQ;Luf z4i?Z%b++H&rkj6S&8)HGjl@u;+0oOx>dN1`KBb>*aXg5kdML$G`Catkq2==5p_`P=W+*7hst`C+DTc&1oWHFeZu#&yWa!ec1~+ zi{adi@9mQ;9`-ntRB4{?pWE`92dQ5oHK(vWqDdX3M|{K&;<{TSPD;}&Re`2dMNK0H zO>k}QX7;{|M0D(Jd}_(ciXgSSv{-)xz!fhDik>N*(Xf%4m1uV3mj-B}5|SzKA-c~7L_ zPn^|8&*#9>J!PpfpKOOag4p-}G_+Ka6SUu!X71<~LHE11%PcnR&@{}Dwc$;_9t8yj zZg7OXh~dW|$r6}G&9$x%qpBSJ6PSE2_bM;0(L8(oa-Ktz_>1Ek@lqeS#ar>0RZ}b_ zOHw7{PtCkwN8nYIt~4sLkC6N6I3e}}2-fXWuj)}}cUGpiQ$uY4}uM5tA=T}Tr`dTvwT2>qM8g;G;Vc`A3-4dSVM$hNY{(|%+T_hp(P7%--DQ?q=u_Z$N z7{4^B!R;`5d$TC&1}`zZ3hDJo*s(wRhMU_@#{J*VdN*U$-8eH(dzdDi z*)%PsES}ueKDA2jsDyrhY#f0esus~Ks=*nI2;GTC0RfdWf^t*+TZz>8MuR_9dV9LJ z;*5V6sw^>E7Tv%f>`Z~r&Q!_WnbLXUr#Vwa8s56Z3fU%t`g(7P(yMFcRn3ODO7<1^ zUq<*8>i4Pt<;vAxJ5fWhdT@Lruj61nAFWt{J`5yGJl^v8-HXBI%Rj2+{%g#Ajf5lP ztF|+-(;bg7q7#&-bjZu`gg8UsY4C={!=(Bx1B1Ujd6#~#3k3gGk;E<>3|;O<(ny;Zqm#=V?%E(C{{? zidy=>F&=oViAoAJitOKL#FZHA32R#igtpevsY-$F@4<&YYik>28mSB|RNmK39v7%p ztPw>gYK!+-`Py8#S@rmm!MyN-ynVm-%51(BUF!X@&ljg$MV=}xXUjWMML8ww5f@!4 zo^_!~duGGG@HTWV;-v5OU+Wg0k0)Q)dLJ> zr#sA;-dRshU#Xeu{xMeMVlaD^NiICcbw#A4;QATjcb#W8;~f(UF{$Qfv&Ku(EmBWq znf|Z|FyRj7YFkFFzQDAGgO)s!G>HQ1&sYK%0%XUD(`HK$}H#k z3+U0}i1qE1Wz4Rwq!p;UhB;MeGqL>uNW zUOu;c!r1qG0TtER1&(DGsxt@okBuXnNNCX>%e(&C*pJi&*C_c)&Jf@0ANd_htzjcg zt#taKFe|f(Q%hH;ZEnG14&4Y~%>gP^XjD=hOsdmDBX+Tegqs1KeVs@7$dK)Y!w~nS zFbAszD*e8Na@1_mlPU!4y10!C2}h?1%OmFUGY0J({=fJ~0v=1fP#cP$ekUBIR>ANv zzfAe-uZRVWC*l;Bf^}JlS0wmZ{w+-T8XTb0Iaq1)kgLeU4zA_D^Yekb$l;xCOJg2^ zxCl;8EjNr_K;)M-xx_HJ9D-`|aPxJMF&np3lBkV&t;J%b+YJG!8R=LC!_YnYFK#b& zFCQBMk%Xu_h3A));5-uBM{8m@i;B8h>56MjH{5={ zlfI$+PUL6$gmh~2_TnvBRjdd48_Mat&?CMXfB1#*B8vwB@qs5`;6zdU`D+lnb4ObN z)mKd~=XZu7=~n+%RF{V&`Rd-9YMSA{!B>?jgBvJD$t-7XhCXLbl(H2uw|JUrbzv^K zz{1Gu|12Ir>3~IKr$|GtY!k4p?cRd^a%j-ZK4j*|GmX@!0(ipOi-3qKA) zigSwW9<}&z1a_5&`T6QV;C_vDa6mAG>{XAbx~#3F8wM)Od+A{?wfM`{-wm*BjFJAXs=_n9Cs7mc{ zb~e&AN~4=T)l#EC=!(ZTG)BrFnmgcBQNE&=tcz%r>6BuM6rMKo#v~I{5zm?#7AMhU1q&fu zh{XozrvlWq{^-!JJGEKkU(ukGN`d;k0EGkl%I+M8*h22jPP)crO`zB1J<%TH+5Tx< z8dQH4l-vI{bCVmzM}RR6TJXiyE;_n~+;#LGB7Tb^cBLY@OJXx&;*r8tbT;L0;sTM) z1-2IwUMHTOS+OG5V3MCAgQPgt8Pl=cMakVq6zNzk(!dJ2By)3mP z;!MetnedSO4-4NZJHMFiv~x&6kGq-%1f*ei&`7M#lq=_FWeSWQ$Cs4(@Jaf2mv*q| zupO&xLa+(0Sc5Z#w>bod#0--KD~LZYK%N*Cvq}InfKj1sC0JkHTjw#DuSUub9ERAh zuO_VYn8K*2JippjJ-(gW=o(d%svp{+uY8d?O?)_oaIK!3wBS`<&&a?p!|HC?w zfmFxOT>NR?^p&|UtH?XQvj|B-kT;$4daVlkP?DdAwdXE&f^aL;oBnk*z7n%j`UF$) zB8W&hprw>2aW3&16&2Mvfdb!rt9RO2nnUv!cr#DSTF%3L87@5Oc`CAdqJ94spD0<{ zJi-d<5O29+Fg}S#o?~;K{Iy)jrA5TfE>hN0{2EqX0A`O~64+8peC{tO`!q1#i=BAI z8p`>@Pf~hL@50}lgaV#Aoz`>D%G?9_VJ%}0T_>7&`w6g!R~D7vG}O;qum|D!xTDGC zt;%MZkfWO`I}^yDiZ*UDZSg7J6jJ+&)A6u#IX`Rd92($g56gzTr{CR3rBHFWD0Qc1 zDlC+X*e3q%W_PO&%TF54!nq%ZHEN|+{~2_!ipGg^(BC8sAy9SguJF%TMBLVD!f(yb zX}ly>TvMX^W23_jAA>Nt8gkv+cgU}H_+&_bkDkTl{M>9ENL4B+b7yz;?j35cQ5m;X zX)@Ffy--0b498!U9FlnhXDD0gRD0n20j-^I42ng~ih*mE(h{xf1vnpL=*v5Rp~+;$YU2=wm!O)VwTVilRt)xO|pIjVInEztG1JR-vgA< z{Q}3vg0^{P zJ_HJ>nK-;t!}jA(+N7mFlOM2x1qS)ChR-d3%K;~>Z@xCMPsprDRWwn2k%O3}jOvhD zK~DE|se)X%-Co?|%ZFdRN|z)aAb$JI0dxohT`YdP79e2qO+{A9n`nGnxcmyw#RXjA zxyu)D2ROft&#}ffkS~T=`})CTD^s-GAx-Uv7-!)P+KqDF`z7B-q+|k%M%qf=K5zT; zqS8EwsWa(Eiu)9kbNfn}&*G#;_!NTUqI z)_*v?V^ejwDs1Po>H1>&xZ45VPOR2+n1H;;k>u+=WM^OomI z=&oRx^$G(6&jQcvXRYJFB?h;~x32S%yx%?JFcj-w_6NS5rmWprrK1-Y6+Ct9UIKMF zMtn;zb`B2+E3NH*EkkYL?K`U)558;C^8%=W-|~(~Rq40y0S11rG-tVN+U@aa!)2m? zD^#QkN@^{3Z?I)*200NLSc*Z;hSJu{Cm1H-*`1f?7mcL2o{S2(tnTt+cpt^>2AT{Gxw7>s5ZUzdu$+PDrI8lqg7XTCKEZ7lS?8 zk!&|T(>rHfx}wuQIzL--g@WQ1Gm|)-!l>+Rb{=9Kmb!{@bK{)G5qJg{^Jbnzw|1yx zo6$>0=>c!FN1yXtDKq=-y@6_?-XvH z86-5@A+I7|?e=i_3gHp~HSXel^%-(_Z3iEe(A&eMqDB-MtLTcPiV!zLhkH=*nqQ%%1)1H|8O; z>18}xq1{=eBJ+RXs2x~2HCQiP0_GcIDmgpmZ`E;t9hbg7IoJ}xy^407^if~C&qCIQ zW3xla>`1fPOeW?yUE}Pa*LfYKMi9zc(R4YZ9VGd!bH({l=sW{mlj>E5Cdj598 zTI+6N(a7)vY)8yno6kjcO`FD{x`plIyS7I8~AF>Uot;UMs{Pc4{Lo+c9-#2!O$a( zn4ji#v%V@n5r-6#BclivfnS6r^r_LSiW zEv*qCe>u4xq?MCvOE<*I7;bUV>?{ETIh+3+e|?zYu!ZTjGX(#oirDG$(N}i(Fjod+$)~}d$I-Bl?3vc4r$K5MFkj%?qa&&sXIOtSg04y9z zzBk-%-3aH+uwQ+OyO)kjf4K0dwFE=x3^~C9c*cWe6thpnnK*eJrgsg@w~7rV!J_rxayCQTOjWD|%9z(v-;M{=9%ld1(s5i;+JwnPu13&CZvGn!5-_U2%3u^g{Ydjt#T!IDz)g4r?)&i~*C zM7sxWtj20}P(N%Tcr%I3{UvwZx>@?^fH?n`0ndK>KWld`jE*?5^?LbAw!`Fp91IxD zkqiQf4d|vEXq*alLSh>qGx_VM+2Hm&3c1g9>hzOrjgF4IrYjN9M-7!t^Z6t-bM~r8 zNpIIP4^S37Le=Ur1u2ZBz8*cn@8XcZIz;ZL#L5h?2bv(<*6v~vhwb+qm~4H~!RPve zjEpQ&Lr0h^e^7xD+L-P%&-EJx7OjnfjiAKWY2l^HYAvaq|jgw|Hak_%E*)mAT z|M4x|_+C8=cd?0oc6}f!x==tKUqiSh**e?wWqsA+z`?V^iuD_al+=WyR&ME0ND$Qk z1Bnt_Tp4KC$ub%6o?$%i`{P5z>?sm5ibBbz8RH08+1G%wUh{{rFR^BOW=whA<_{U| zDcH3|gMQEkk(*qy-h;82uc**K}{RKely!U5rI!MjYZfs?oGo3A8ef| z$J+K~IvR{k|AW&fEEp#%#c3su!G`t2U_zddf0cm#ei#P1(%12_%9u-oWq2Some;IK z<*^Y@9&jzgox6HIpb8Fubw{dMjA!l*=Tvr(-uYlAns-?x>1lvJNqbcOZ$oHmXE#&2}opqhw;L1WZ06!W8%6z3Shw`3*W>V8(bBDfn zuR=u5GSOKbo+Ljao9_AHnx2z!Yo$E1K(o zgemXA>=qB}1+7Y1buNe`29;bZoF0jfND;prZye!qFv__%eR`Yl>IMqyAZUvtlR$ zyvZ#{8G<1sS|bnp=HMA|*zpcD>IN>m+@-SOg7(dvMV|>27LKe{|>4VwTCG?w`D|6sJ?YCsQU(Nkt`3EI`ECn9!-Ayg)i+z{ofR7LMDo0$cnwfHFn?asEM{8E=MNL!xx$;vbrG$b_~qPJ zR>m4hVZ4Quw@7KBJ;?~J6du3y{ESMHwrqmATo z5J#nr_NXp*AWN>^>UGTf-_&E26pt`su6y@jsy?8s4KE+=J1`}kV^CuLFbEUgR>nhf zCEYO+84dy}jZ>Q)`JXO6*HU9G^i3J@h`)jrk4#Yi@!P<7juOhZIPL}gLYi{qK_H=T z+^R-fAmjjpT1jY2<1)MmjNqlO24%6z@zw>O=DUUaK%kkn&q$^_I^q4JGIIC#>;(mv zMP|Qf=a@W-r%yJ0G+dpT)(y9&48=qgX-vLy8T*!(A;xdAIAth4p7f+Y&?&t#z!`ZA zK1B6u73}~)DTqPrt`p>6cL*Ixmj>F3`K$Vl zyo(Pf>!;+80rMe!7Y2fZhvN=t4~Em(3bvRY==h1SN=!Vv`XWUTyDeOr z*WiUW9mHuo&lL_oe%)hoWu$!N=ocXoCk&5uJ;YDRCbZNT`|D>Y0BCZJh((Lsl8txxTf9M}TY@2|7LA8)O0gZ$u4mcQNTII{gVyRpv|)rXLQG$od*9 z$gpJoB&1vJ*T@?^`$ zMU2Zc?f~==Tpg<)&$I?irV$QhV%CJJogdN2Q+ZE0!nn9dwDzJV@1=PMSLoLtVXgN~ zx?(gnaZIlalI@dhd!L#!Pmv%M?(KrQl8LK8s8Mm~?KWZUNPdeD(jgK2-S{ZKJsc4> zVEG+hWJ8v2A%nH9Hg`w|pC-{9pR3{iqV5rY49A->{yWmn>dHtx=P7&HkM|xvH7Tci zn=5$C9RP~80K{t=%?X#~5Bw!6XWN@ww$?jBbAM#|iLS}u-apYynGgE5xC`QFdA3$T zGu5drC^Bmc8^QUU!iHMA=Y+G7}`A{mve{4k*+|(0=zqt$bi2ui$T|5pM-!3Am=xHWE zMHNe0aON|A<)f|r#4VXsy+M-;Unz+3pNZ+-h7?7JChwn>Cbnl>$c<E6&~Tk5;P7G+3jAVR=4(1C~WgYtyIfP7$YMysa2KTW9#pL;)AwZ3Mk7S>JDl* zIOSq4R=NLXl;;55!&MyVE`XFZCm`fF)_OliipPU6w@IkM@i5O+En#=jHFjN@DMqOu zI%$YTwwfL!AM8SemA=x$)^}xzXOz_4&d6L>b>z50-d*85&f_BR;ml@2Dvw?Y&*a+9 zy`rS@`*3&ti=fTN>uNLz=caDqSMag`R1TX1tQUst7V3=^ZDhEtny0nk?_tERtN?Ms zn6}}837KKc>)Sko5svxSd+)%wQEczhob{t?q(aYU3@?QH@9$gLxWHe<1r*0M2bd$A zLV2i z{po4-G3)GQ?Wnw>>!k!$VudfyHgW@@!j9Sf!t=n)gN&t(WekgYl}GC?wtGcqbxguv zJsDzvhf?N`p3}d(Fi<`!Rhp}D-))+kKlumABbcNftd!@^9=j-I+(}v$V6W7V{XMQ* zM+Eu3psdl!9-h_x_AsASm!ve)H^&5UOT1WGQrDUCZi4wDC%V_teWgfK@PYhGCwe2*wtN5Z$G@xsPC@c$ zh(x#x*f(p`zP4*jMhj*o?}%?EsAZJjSRo_N|8nJz4<vJZrS>xY2f>@nT}aPZXt2}Y`(v;mZKlSyH3C8@shn!StQ~U| z*S82WXe=RZs&00DAk;K`;z3_(g~s>yYHC{d|Fq2Xg4_-Y3Q5|L4;)?;i|b#~X}z+n z*Ow(wFS8bs$q-~}6+v{iwf>SoHK*2$=F4;4si3ExxbWo^ONuo79Zhy7WZ8(p=QbA))oT^1&1v8}x zVM;q3wM_3%im7G3f(JR5v*yKn6Z_n`dgE}UE2m;tQ-oK%$|-`JA{W{Ol!xhQZhD$f zsIZ)1SiO7|j**+z^4%cLB^>XU#(L=4{q~n_8q>Wl-gJaSpEg7X10bS&kw#wpOP}H4 z&$XPb3sWP$S4#z#6>lvI*wR2~7}ym_BtU}==y(GfTg#OcI+G>3w2Tl$ZL`7OUSlWnYC; z1f2e(I5~$wHjGv2`Baj2`b^23^bfRvTnF6QZHhcXH|l6VYmB*EEYbSz`l?6&=x9Y6 zjFa2VV4@&{Z2cpw1t5FZ$<`%B|G`zVhY1MA_ZZ`88(w14yu_OPelPgdtBIKy=?nJ` z4aB7i-LC%g*p9RJV*GkpFJz#$cL<0nSGbG+WWWNzn!;?q7$tahWw4Dr-J$9~3&KnB z{<`}HX>yl7$Bn$Yb&saY*<$}=wlK8;@s3E=`7*;dC3gR--H_Vo1FColwTJ(^6|C+# zeCUgQvHH31Oe#baD`Q3&=@$w&K*Ej%nm4HFk37>}>=wrr1zok%@0G|t$|&o8G`@o7 z)g7lZwfp3;;Yxk1kr15-@&}@%xSbH&hlIuh&DqVFY|J>p6XVI8X;7jdqT(idvo%INc4~}c^smhy%9t&qB7itu*veD{m$zQDG6+ouZDLQ?{?{zI54KsyAEY7>8jQ29fzxy|3 z3A-O$V#peOR4SN1hAkH-m+$w-C->R~Axd30PtBR*z{g1*1aRx0 zg(2mTd%rrW7YgS}6CX7)wv>yW?&VFd$1hn?KRSs;Ujz{qwU~EBC9JO<*^QUG6j=>c zAC_B@q8S#e}US#A1eH(B}-C&g=c5)h*qwpH+_?1xV?~fk04S~EzGx|!#LB+w*y|C6 zn>VoE;xpy^UYrh4W1L=ub&)xUklFp!Ja~F$Zp`U^7XS754+z*Humu0H!yHd=V@H`s z`TZ+!=PImB2g1rKkIjWXDDVoEEau8@4Ni?(1uCj*jBh%-)>q%jO8+jr#vvx_ng#gg za+sA$EssT`SX@1(G#KHrb>sExePt$ZH{{Mcdp@T7^9jb0RJ@BA=HDlfpCdi0yWDV$ zK)+51X?Hais@cQ`AYJ^i+LJ~`1yqvEWR~&kPW>ATKR2RW)GKAa|j zl0YesF<5t@=>5;vAV&=?wAIbzT4NoyyDObqZlIA0r3JT-aaNH%6qf+7BT*K!(A|;I z&|jVT`wjJjw&?8H2=3D^M_ZBKRbz1FitV`)365nNt7nIexn@_-|0tz=%(Cx?H5A+= z@QX~doXi4fh5;rn94(Jqu)bJc^cxr* z`P25rZms)-BU_ck?n zWksnRnKe|(laZY0cRrjDjPR69`rO0w1Gx};)c1uP8DqtA3g*?ND`wZpbE<{{WXnS+ zR~)Phwu3R7y}^Xq9RlrEr6sN#^*!Y1z+Zhp0q|K66YNN%KTWI%Hl-YjyQ-w~dRp@} zKh;Xx4hO)Krdk4t`5f5>8#{$?GSXQ ztXW*t*7HVDIYHPsSMQ)eUQ1Ze!$Hnolm1;`2hS?g2|Zo9`-+J+Q!)W{Yx7yF?CuDK zC521Q^E|_v8v(kmNqx-~`M*-m8(y#s?CpBG`Z#^nUJ&x`ffnXPbr;dxSCV4TCd?uy zD%)NDjw13aw+?nxeX7j;O^9k}u{;-QeS!>+BhVJZ0|CpGi5L21R$fG$GI(xdbLs5l zGDZDB1PNDJL`7=wfsABdZz!3XsZy1A)u~;Bi_h@ybkzU67XC*j0Q1H3TEK@~qqI*Kc z3-~)$lQdZPOjf*dYQu?0>QiW>e(9e{F<_7`H%ox)991SeLMa&#L{7a^>Yl%jK3or| z=4u&3Arkg>rOT64%zWF{*pugP1zsP%5edyM8Qdi*O;!_y&u>nBXd`_R@j25)sF1z^ z^`yA}#IJ#p-HsE2B~0ZvL9-p!KiB7b%7)j7ljxR8T5G5|iYq`TnZf;&#`wUm6;7GYLh&oS@Ka047+qfkZeTy^g)1F@Yn{BMb9pCZ z81CIp(rBeg6}%E(yTTQ>{;PVCDlH^TFj`s0u*3+UNfEOsgS%Uye~K%Tw4zMZ4E|;E z0cL_9@bM*tv3MQfShkRZP;1Oqx5t#wy`Vs1k67%_JsmA#wKcY&zX2W3f=}Q1I(B*^ zW|W5Jt#7201D~s)m$h@uPpfB!JZVmy4lfFpgyT01=^0GqGnv=#xn5I=tz6L%uvV0D z7^p=;+Vfv7qW?7%aMunFv|TNYzc65G}N&zTYEc%@EZ86#@uCji*WS7kH2XZ zU!Q(>7lgu=YMoLP=Yh~XU_6#j%k`vD=#axSxB|(D+Q^@4_uW#v&Jjao;yd&tHXYTQ z%y^#PDM0QO6DBV3D_#8$i0c6D_R3dc9~O`W(|ISw!Yg?raJM>ixI5+J=P#FqM6S7> zG1c@K;{$}ferQn~Q&Cyko231BUBr?jF|9RkmY;Wwbo$?$J7rNhgt#RcqA-~`&~~yC zg4M%r@CC@cyP8#VBunT%Q12?usu(yD-o~#_r2+S-+Q_E8q*4^v8dHs-Dt?TCV^!f zkRUE}TZC0Kj!-{Uqwh3S#iUV-{%=Z=L8t|%Dr;@e>0>Mc$gzLkA9=J2yRVh}CK`QI3;&*RGY@IHv_Cgc zZt}T@wC7yV7pde}=9;qW>(igQU;XGoZ@n71U(X?z*QLo#^K5_GAQGp%+I}TjrPiR) zWaM|L5lA`s$2Ed{aA%`+g8JbR*YXxeY1qxx1T>p7mq86ognf`tLz&x05}^5opYOt* zk8}?k++;NL2hHA`qK&9?CBAU)$CW*P8}qZntt}xsdc_kxtLR{zq(X=)hUnL%N2MMe zXitDXM0c0`KX#x8Lh;o5MMehHB1#Qy)wk{o%R|Xe*Qa9Z`XvH-K_>R9)9w{8aUHIaf zWmxdj0{1ltle`v$F<;0qXjr;VOi7!qdY;iNkerd4^0&YsDRc9+i8gwdovfg(-EZWD z)W-_=kLEB3gmEJwVSWYP%!1qBL4BXh?lHY{4Z<1uLw#gf@aGr*0EZZSwhjfqIq&vp zeUg2gN3t}Qcs6%IP3Q)I2hcB(j-yb=t~+CV3t|qrx1Cb?y=lEV?5GrlZHyL+ON(_m zovXqfrT&~ef>LA=0`F3#Tc+iOC4&CWM3h-6H|}Hd_VF4dCT8#Qxac2coay+r<>`>D z=pF5ftMdFW?;r_e8G#gD;Nrv+#>TOxz7>=E2V)6BX(;9g4&Ql6NG{=Mg3}lr(R0y& zFP>*Ga>&jKcPZ>u<8YFp ziQG%mB|H}yUTKt`sHpgLkUT#M(kkKzi0@YQLQTCp2Mha+PLGYtUJ`LA+By9|p7*&= z#HA5c$5oJ7Tx0R3OO~^atd$9#5G(HRE!`&ngdR2n^d1Na3XaLI;|PtJ)e@M1bEp-0 zPmJ65Dayio;=@5ba!W#ybDPAEAbR+0Rzli0lAgP2vDYT9%6|}hsCVa3|4jYnlE}xw z>1R&#+8SJpcIoxS&Q?%91w_SxlvVJ{3XrnOMi`SvnFfE)`0kV#hyAfS$zV_b(s$NV z>fBhVTxOskRri;Jb9zTOgpu$5b)xPUg5MM_QLoa?WM0sN_j;NZYWr2+NG-IC|B>*h zMALGwMW8I>#M3;^JOarLTuu`>ETR6_>{ftr4Qd%L-!(b$-C>4LfsxsQz6~DjPI%0u z55g}B6;FSg>*xQ-K) zFJz&xSc05meU*|f3Wt)l>-0;5w~wAHMiH|l%8&KF*V;b~%sluMXficlyIUE~v%3Ax z+{(9NoW(0LgX3C8+RVp7cY#elr)y16$>biR<3=FhCh@V*l%?JAUkN@WYzZXy}#o)sT+XwyL72j)(4?u#)1W$By&SND? zGBTw??u*GftC9QoaHREXdHo8pF$+vq0JFl*UskK)IzArOD29YV(`SKU)a4@Ct5W5Z z+8RmKLH*hO-*(ncny*l*QV4!4Vhd%m&vhS!?^KTVe#efX!#g(r7*xL%EjWo4v=N4HGpW` zBJ{0GR13$Yd_St}ZoJutET-lD$Pq)`yym~kwNDPYYicpdi3KtFf4Ri+x%hZ;u*?Y6 zOG&r)9{NO|IbWar`1HjrevJ;$UZ9$gV?ILerx8r(zKrP~sQx8-6keHcSM%Mzo<%Q= zE$ABbgQe$h&dGG=VS;|YJJpc>)sCa-G$1NfL?#c5DTyQ&B85(n1ymGxbq-cBe;fb< z2*ELP%ka9ZCZj0IGAweziDQF5bx*owHy0$rKur$zi!TSMY4 zQO=k=e_fenc`;p_;thr#Zu_3*VA+SXAIhhz@ZH)zh1QlLuF-7G>3y#j=dPMbE!9`f z4PWbJj2keRVY#r?;xe2s!JTV8&^%`?c-88$B$13k3iAjuAG?BYnyb#y7SC{%)PJd| zM)GOmVP|x7bfXQ7I7dd-0|qNSckXTkjPKK@2`|_w$+hiYFd`kc%kPO~(%!}Tt20jU z`K3^g9-x`$;A4beyEC0DhSsG!_}>ZE?za*3Ogp`44WjmkRx~0OR(g9%Yd~C&~Z1@n316-v8N%j!*ty_5At0f2{-~u0L=5`S?k}`}S@=|H^>* zdisM={h!Sc9NVki^RRbwfbJoMxjTC}f-mQN-Tz;Oa@wDqXR-HjfUZLu^h#9zK5kb| zzLR|R^|N&Y-(7tDeE%B^=pMMcmpIf=XoHSVHX_)0=nH5nwB2yG-r3{N2bK;S^2`=EOCfk3?tJp-MGL<SL&l&~s2fXaIrQ0@VxM z2lb^M5L+P7vw=YV>rdzz=su`TP&=SLgPwu<1?oHK7^(vjs2z|%ZHC$lU4!a!2LhE1 zorn4ddLBB4>V^6Y8Y`#{==i@rh3 z&uIaH&O?0wwFBxe8z4|Q|Gg_zF4S+(yWR%^^`8w8sNbRcpfNZ8w};As+6~nQeGdTw z>1G6wQ$Xl^{p_GNK^qZ}Ye1NNoxJR!10PQ}s4c`mhzJDmm&MoC3F@i;u0S_c1A+Fo z{`P+Nz#i`IaJ&a!VeJ3gfB>W8bI;2QD)Ikpg3c#aimTku6KV!4__rxgAy9$PKTmN4 M|2#zme6EZ9Ke}VEhX4Qo literal 0 HcmV?d00001 diff --git a/packages/player/tests/perf/runner.ts b/packages/player/tests/perf/runner.ts index 1074819adf..ffcba3bc20 100644 --- a/packages/player/tests/perf/runner.ts +++ b/packages/player/tests/perf/runner.ts @@ -10,6 +10,8 @@ export type LaunchOpts = { width?: number; height?: number; headless?: boolean; + /** "gesture": Chrome's own rule, where a frame without a tap may not start sound. */ + autoplay?: "free" | "gesture"; }; export type LoadOpts = { @@ -84,7 +86,7 @@ export async function launchBrowser(options: LaunchOpts = {}): Promise "--use-angle=swiftshader", "--font-render-hinting=none", "--force-color-profile=srgb", - "--autoplay-policy=no-user-gesture-required", + `--autoplay-policy=${options.autoplay === "gesture" ? "user-gesture-required" : "no-user-gesture-required"}`, `--window-size=${width},${height}`, ], }; diff --git a/packages/player/tests/perf/server.ts b/packages/player/tests/perf/server.ts index a3d1712deb..be7eb671d1 100644 --- a/packages/player/tests/perf/server.ts +++ b/packages/player/tests/perf/server.ts @@ -194,7 +194,10 @@ export function startServer(options: ServeOptions = {}): RunningServer { if (!filePath.startsWith(PATHS.fixturesDir)) { return new Response("Forbidden", { status: 403 }); } - return applyCacheHeaders(await readBunFile(filePath), noCache); + const res = applyCacheHeaders(await readBunFile(filePath), noCache); + // A sealed film has an opaque origin, so it reads its own media as from a CORS host. + res.headers.set("Access-Control-Allow-Origin", "*"); + return res; } return new Response("Not found", { status: 404 }); From e5e360154e08cf39b2e1bca3d95c5bfc0bbb2da9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 17:58:26 +0000 Subject: [PATCH 145/367] fix(studio): a turned layer's cropped box is the bounds of its cut corners (#8502) * fix(studio): a cropped layer's outline is cut at the layer's own scale, sealed or not * fix(core): the geometry stream keeps an element whose geometry now carries its layout size * fix(studio): a turned layer's crop is cut at its own scale, not its upright box's * fix(studio): a turned layer's cropped box is the bounds of its cut corners * test(studio): crossed and mirrored crop probes in both frames * fix(studio): crossed insets meet and mirrored layers cut their own edge in both previews * fix(studio): the CSS scale property counts in a cropped layer's box in both previews * fix(studio): every overlay measure reads the transform the browser composes * fix(studio): a layer turned out of its plane takes the box the browser paints * fix(studio): a projected transform chain takes the box the browser paints * fix(studio): a layer inside a 3D context takes the box the browser paints --- .../core/src/runtime/editingGeometry.test.ts | 5 + packages/core/src/runtime/editingGeometry.ts | 18 +- .../src/runtime/editingGestureStart.test.ts | 5 + packages/core/src/runtime/editingPort.ts | 5 - .../core/src/runtime/elementTransform.test.ts | 19 +++ packages/core/src/runtime/elementTransform.ts | 156 +++++++----------- .../editor/domEditOverlayCrop.test.ts | 74 +++++---- .../components/editor/domEditOverlayCrop.ts | 150 ++++++----------- .../editor/domEditOverlayGeometry.test.ts | 5 + .../editor/domEditOverlayGeometry.ts | 6 +- .../editor/overlayTransform.browser.test.ts | 118 +++++++++++++ .../editor/previewOverlayRects.test.ts | 76 ++++++++- .../components/editor/previewOverlayRects.ts | 6 +- 13 files changed, 394 insertions(+), 249 deletions(-) create mode 100644 packages/core/src/runtime/elementTransform.test.ts create mode 100644 packages/studio/src/components/editor/overlayTransform.browser.test.ts diff --git a/packages/core/src/runtime/editingGeometry.test.ts b/packages/core/src/runtime/editingGeometry.test.ts index a26737e3b4..b92a790f19 100644 --- a/packages/core/src/runtime/editingGeometry.test.ts +++ b/packages/core/src/runtime/editingGeometry.test.ts @@ -13,6 +13,11 @@ const CONNECT = { source: "hf-parent", type: "editing-connect", v: 1 }; // jsdom has neither; the 2D slice of each is all the geometry reads. class FakeDOMMatrix { a = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; b = 0; c = 0; d = 1; diff --git a/packages/core/src/runtime/editingGeometry.ts b/packages/core/src/runtime/editingGeometry.ts index 5244b0c970..d26e8ce142 100644 --- a/packages/core/src/runtime/editingGeometry.ts +++ b/packages/core/src/runtime/editingGeometry.ts @@ -12,7 +12,7 @@ import { type EditingRect, } from "./editingElement"; import { elementForHandle } from "./editingHandles"; -import { composeElementTransform, type PlanarTransformOps } from "./elementTransform"; +import { composeElementTransform } from "./elementTransform"; export type EditingCorner = "nw" | "ne" | "sw" | "se"; export type EditingCorners = Record; @@ -103,17 +103,10 @@ export function readElementTransformSnapshot( const DOMMatrixCtor = (win as Window & typeof globalThis).DOMMatrix; if (!DOMMatrixCtor) return null; const cs = win.getComputedStyle(element); - // The corner math transforms points, so this keeps the full matrix, translation included. - const ops: PlanarTransformOps = { - identity: () => new DOMMatrixCtor(), - fromTransform: (value) => new DOMMatrixCtor(value), - fromRotate: (degrees) => new DOMMatrixCtor().rotateSelf(degrees), - compose: (outer, inner) => outer.multiply(inner), - }; try { const matrix = composeElementTransform( element, - ops, + DOMMatrixCtor, (node) => (node === element ? cs : win.getComputedStyle(node)), memo, ); @@ -212,6 +205,8 @@ const finiteCorners = (corners: EditingCorners | null) => ? corners : null; +const turnedMirroredOrSkewed = ({ a, b, c, d }: DOMMatrix) => b !== 0 || c !== 0 || a < 0 || d < 0; + export function boxOf( element: HTMLElement, memo: Map, @@ -219,7 +214,10 @@ export function boxOf( const transform = readElementTransformSnapshot(window, element, memo); const turned = transform ? rotationDegreesFromMatrix(transform.matrix) : 0; const angle = Math.abs(turned) < ROTATION_GATE_EPSILON_DEG ? 0 : turned; - const corners = angle && transform ? elementCornerPoints(window, element, transform) : null; + const corners = + transform && turnedMirroredOrSkewed(transform.matrix) + ? elementCornerPoints(window, element, transform) + : null; return { rect: rectOf(element), angle, diff --git a/packages/core/src/runtime/editingGestureStart.test.ts b/packages/core/src/runtime/editingGestureStart.test.ts index 1efc9517d1..a64072f0ab 100644 --- a/packages/core/src/runtime/editingGestureStart.test.ts +++ b/packages/core/src/runtime/editingGestureStart.test.ts @@ -59,6 +59,11 @@ const GSAP_RENDERS = { _gsap: { renderTransform: () => {} } }; /** jsdom has no DOMMatrix: a 2D one reading `matrix(...)` and composing as the browser's does. */ class Matrix2D { a = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; b = 0; c = 0; d = 1; diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index a8a7d3b27a..3a9307edc1 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -168,11 +168,6 @@ export { type EditingStackingSibling, type LayerKind, } from "./editingLayers"; -export { - composeElementTransform, - individualRotateDegrees, - type PlanarTransformOps, -} from "./elementTransform"; export const EDITING_PROTOCOL_VERSION = 1 as const; /** Parent to frame, on the window: asks the runtime for the port. */ diff --git a/packages/core/src/runtime/elementTransform.test.ts b/packages/core/src/runtime/elementTransform.test.ts new file mode 100644 index 0000000000..4a75d8e252 --- /dev/null +++ b/packages/core/src/runtime/elementTransform.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { rotateFunction, scaleFunction } from "./elementTransform"; + +describe("the individual properties as transform functions", () => { + it("writes each computed rotate form Chrome serializes", () => { + expect(rotateFunction("45deg")).toBe("rotate(45deg)"); + expect(rotateFunction("x 30deg")).toBe("rotateX(30deg)"); + expect(rotateFunction("1 1 0 30deg")).toBe("rotate3d(1, 1, 0, 30deg)"); + expect(rotateFunction("none")).toBe(""); + expect(rotateFunction(undefined)).toBe(""); + }); + + it("writes each computed scale form, a depth scale as scale3d", () => { + expect(scaleFunction("2")).toBe("scale(2)"); + expect(scaleFunction("2 3")).toBe("scale(2, 3)"); + expect(scaleFunction("1 1 2")).toBe("scale3d(1, 1, 2)"); + expect(scaleFunction("none")).toBe(""); + }); +}); diff --git a/packages/core/src/runtime/elementTransform.ts b/packages/core/src/runtime/elementTransform.ts index 59d755da9e..89252858f2 100644 --- a/packages/core/src/runtime/elementTransform.ts +++ b/packages/core/src/runtime/elementTransform.ts @@ -1,109 +1,78 @@ /** - * One walk from an element up to its composition root, composing the transform - * it actually paints under. - * - * The overlay measures an element's angle in two places — the selection box and - * the crop frame — and they need different arithmetic: one works in DOMMatrix - * because it goes on to transform corner points, the other in plain 2D - * components because it only needs an angle and a scale. What they must never - * differ on is *which* transforms count and in what order, because when they - * disagree the chrome disagrees with itself: the selection box drawn at one - * angle and the crop outline at another, on the same element. - * - * So the walk lives here once and takes the arithmetic as a parameter. Adding - * an individual property CSS grew later — `translate`, `scale` — means adding - * one step here and one method to each algebra, rather than finding both walks - * and hoping. + * The one matrix every overlay measure reads: each node's `rotate`, `scale` and `transform`, in CSS's + * order, parsed and composed by the browser's `DOMMatrix`; null once a node or the chain leaves the plane. `translate` + * never changes a shape (callers re-anchor to the measured box) and `DOMMatrix` refuses its `50%`. */ /** The composition's own root; the walk stops there rather than at the document. */ const COMPOSITION_ROOT_ATTR = "data-composition-id"; -/** - * The arithmetic the walk needs, whatever the caller's matrix type is. - * - * `fromTransform` returns null for a transform the caller cannot use — a - * perspective matrix, say — which aborts the walk rather than composing a - * matrix that describes something other than what is painted. - */ -export interface PlanarTransformOps { - identity(): M; - fromTransform(value: string): M | null; - fromRotate(degrees: number): M; - /** `outer` applied around `inner`, as an ancestor composes over a child. */ - compose(outer: M, inner: M): M; +/** Computed `rotate` (`45deg`, `x 30deg`, `1 1 0 30deg`) as its transform function; "" for none. */ +export function rotateFunction(value: string | undefined): string { + const parts = value && value !== "none" ? value.trim().split(/\s+/) : []; + const angle = parts.pop(); + if (!angle) return ""; + if (parts.length === 0) return `rotate(${angle})`; + if (parts.length === 1) return `rotate${parts[0]!.toUpperCase()}(${angle})`; + return `rotate3d(${parts.join(", ")}, ${angle})`; } -/** - * The planar rotation in the CSS `rotate` property, in degrees. - * - * Computes to `none`, an angle (`-22deg`), or an axis plus an angle - * (`0 0 1 -22deg`). Only a rotation about z stays in the overlay's plane; any - * other axis is 3D and reports 0, which leaves the caller on its axis-aligned - * fallback rather than drawing a box at a plausible-looking wrong angle. - */ -export function individualRotateDegrees(value: string | undefined): number { - if (!value || value === "none") return 0; - const parts = value.trim().split(/\s+/); - const angle = parts.at(-1); - if (!angle?.endsWith("deg")) return 0; - if (parts.length === 4) { - const [x, y, z] = parts; - if (Number(x) !== 0 || Number(y) !== 0 || Math.abs(Number(z)) !== 1) return 0; - const deg = Number.parseFloat(angle); - return Number.isFinite(deg) ? deg * Math.sign(Number(z)) : 0; - } - if (parts.length !== 1) return 0; - const deg = Number.parseFloat(angle); - return Number.isFinite(deg) ? deg : 0; +/** Computed `scale` (`2`, `2 3`, `1 1 2`) as its transform function; "" for none. */ +export function scaleFunction(value: string | undefined): string { + const parts = value && value !== "none" ? value.trim().split(/\s+/) : []; + if (parts.length === 0) return ""; + return `${parts.length === 3 ? "scale3d" : "scale"}(${parts.join(", ")})`; } -/** One node's own contribution, with the individual properties applied before - * `transform` the way CSS does. Null when the node's transform is unusable. */ -function ownNodeTransform( +function ownNodeTransform( node: HTMLElement, - ops: PlanarTransformOps, + Matrix: typeof DOMMatrix, getStyle: (node: HTMLElement) => CSSStyleDeclaration | null, -): M | null { +): DOMMatrix | null { const style = getStyle(node); - if (!style) return null; - const transform = style.transform; - const own = transform && transform !== "none" ? ops.fromTransform(transform) : ops.identity(); - if (!own) return null; - const spin = individualRotateDegrees(style.rotate); - return spin === 0 ? own : ops.compose(ops.fromRotate(spin), own); + if (!style || inThreeDContext(node, getStyle)) return null; + const transform = style.transform && style.transform !== "none" ? style.transform : ""; + const list = [rotateFunction(style.rotate), scaleFunction(style.scale), transform]; + try { + const own = new Matrix(list.filter(Boolean).join(" ")); + return planar(own) ? own : null; + } catch { + return null; + } } -/** - * The element's transform composed with every ancestor's, up to the composition - * root. - * - * Within a node, CSS applies the individual properties before `transform`, so - * `rotate` composes on the left of it. Between nodes, an ancestor applies - * outside its child. Null means some node's transform was unusable and the - * caller should fall back rather than guess. - * - * `memo` holds each node's COMPOSED chain, for a caller walking many elements - * in one synchronous pass. - * - * A chain is `chain(parent)` composed with the node's own, so siblings share - * everything above them and the whole tree costs one style read and one - * compose per node instead of one per node PER DESCENDANT. Valid only for the - * length of one pass, which is why the caller owns it: nothing here writes to - * the DOM, so nothing can move under it, and it is dropped before anything - * else runs. Omitted, every call composes its own chain from scratch. - */ -export function composeElementTransform( - element: HTMLElement, - ops: PlanarTransformOps, +/** A parent's `perspective` or `preserve-3d` projects its children in ways a matrix product does not show. */ +function inThreeDContext( + node: HTMLElement, getStyle: (node: HTMLElement) => CSSStyleDeclaration | null, - memo?: Map, -): M | null { +) { + const parent = node.parentElement && getStyle(node.parentElement); + if (!parent) return false; + return ( + (!!parent.perspective && parent.perspective !== "none") || + parent.transformStyle === "preserve-3d" + ); +} + +/** Keeps the layer's plane flat and unprojected; anything else is left to the box the browser paints. */ +const planar = (m: DOMMatrix) => + [m.m13, m.m23, m.m14, m.m24, m.m44 - 1].every((v) => Math.abs(v) < 1e-9); + +/** + * The element's transform composed with every ancestor's, up to the composition root; an ancestor + * applies outside its child. Null when some node's transform cannot be parsed, so the caller falls back. + * + * `memo` holds each node's composed chain for a caller walking many elements in one synchronous pass: + * siblings share everything above them. Valid only for that pass, which is why the caller owns it. + */ +export function composeElementTransform( + element: HTMLElement, + Matrix: typeof DOMMatrix, + getStyle: (node: HTMLElement) => CSSStyleDeclaration | null, + memo?: Map, +): DOMMatrix | null { const pending: HTMLElement[] = []; - // `undefined` means nothing on the way up was already composed, so the chain - // starts from identity. A memoized `null` is an answer, not a miss: some node - // above carries a transform this algebra cannot represent. - let above: M | null | undefined; + let above: DOMMatrix | null | undefined; for (let node: HTMLElement | null = element; node; node = node.parentElement) { above = memo?.get(node); if (above !== undefined) break; @@ -111,14 +80,13 @@ export function composeElementTransform( if (node.hasAttribute(COMPOSITION_ROOT_ATTR)) break; } - let acc: M | null = above === undefined ? ops.identity() : above; + let acc: DOMMatrix | null = above === undefined ? new Matrix() : above; for (let i = pending.length - 1; i >= 0; i -= 1) { const node = pending[i]!; if (acc !== null) { - const own = ownNodeTransform(node, ops, getStyle); - // The ancestors' chain is the OUTER of the pair, as an ancestor applies - // around its child. - acc = own === null ? null : ops.compose(acc, own); + const own = ownNodeTransform(node, Matrix, getStyle); + const composed = own && acc.multiply(own); + acc = composed && planar(composed) ? composed : null; } memo?.set(node, acc); } diff --git a/packages/studio/src/components/editor/domEditOverlayCrop.test.ts b/packages/studio/src/components/editor/domEditOverlayCrop.test.ts index 088dd0f221..bb1211ce8c 100644 --- a/packages/studio/src/components/editor/domEditOverlayCrop.test.ts +++ b/packages/studio/src/components/editor/domEditOverlayCrop.test.ts @@ -8,7 +8,6 @@ import { resolveCropInsetFromMoveDrag, rotateDeltaIntoFrame, } from "./domEditOverlayCrop"; -import { individualRotateDegrees } from "@hyperframes/core/runtime/editing-port"; describe("resolveCropInsetFromEdgeDrag", () => { const startInsets = { top: 10, right: 20, bottom: 30, left: 40 }; @@ -158,6 +157,38 @@ describe("readElementCropInsets tri-state", () => { // Regression: crop UI drawn on the axis-aligned bounding box visually // "straightens" a rotated element — the dim masks the rotated corners. The // frame gives the element's own box + rotation so the UI rotates with it. +// A computed `transform` is always `matrix(...)` or `matrix3d(...)`, so this reads only those two forms. +class ComputedMatrix { + a = 1; + b = 0; + c = 0; + d = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; + constructor(list = "") { + const flat = /^matrix\(([^)]+)\)$/.exec(list)?.[1]?.split(",").map(Number); + const deep = /^matrix3d\(([^)]+)\)$/.exec(list)?.[1]?.split(",").map(Number); + if (flat) [this.a, this.b, this.c, this.d] = flat; + if (deep) + [this.a, this.b, this.c, this.d, this.m13, this.m23, this.m14, this.m24, this.m44] = [ + 0, 1, 4, 5, 2, 6, 3, 7, 15, + ].map((i) => deep[i]!); + } + multiply(inner: ComputedMatrix) { + const out = new ComputedMatrix(); + out.a = this.a * inner.a + this.c * inner.b; + out.b = this.b * inner.a + this.d * inner.b; + out.c = this.a * inner.c + this.c * inner.d; + out.d = this.b * inner.c + this.d * inner.d; + for (const k of ["m13", "m23", "m14", "m24"] as const) out[k] = this[k] + inner[k]; + out.m44 = this.m44 * inner.m44; + return out; + } +} + describe("readElementCropFrame", () => { const overlayRect = { left: 100, top: 50, width: 220, height: 130, editScaleX: 1, editScaleY: 1 }; @@ -170,7 +201,9 @@ describe("readElementCropFrame", () => { offsetHeight, parentElement: null, hasAttribute: () => false, - ownerDocument: { defaultView: { getComputedStyle: () => ({ transform }) } }, + ownerDocument: { + defaultView: { DOMMatrix: ComputedMatrix, getComputedStyle: () => ({ transform }) }, + }, }) as unknown as HTMLElement; it("identity transform → the axis-aligned overlay rect", () => { @@ -282,38 +315,6 @@ describe("rotateDeltaIntoFrame", () => { }); }); -describe("individualRotateDegrees", () => { - /** - * Studio's rotate handle writes the CSS `rotate` property, not `transform`. - * Everything that measured an element's angle read `transform` alone, so a - * turned element reported upright and the selection box, crop outline and - * child outlines all drew square across it. - */ - it("reads a plain angle", () => { - expect(individualRotateDegrees("-22deg")).toBeCloseTo(-22, 6); - expect(individualRotateDegrees("45deg")).toBeCloseTo(45, 6); - }); - - it("reads an explicit z-axis rotation, honouring the axis sign", () => { - expect(individualRotateDegrees("0 0 1 30deg")).toBeCloseTo(30, 6); - expect(individualRotateDegrees("0 0 -1 30deg")).toBeCloseTo(-30, 6); - }); - - it("reports nothing for a rotation that leaves the overlay's plane", () => { - // A 3D turn has no single in-plane angle. Reporting one would draw the - // chrome at a plausible-looking wrong angle instead of falling back square. - expect(individualRotateDegrees("1 0 0 45deg")).toBe(0); - expect(individualRotateDegrees("0 1 0 45deg")).toBe(0); - }); - - it("reports nothing when the property is absent or unparseable", () => { - expect(individualRotateDegrees("none")).toBe(0); - expect(individualRotateDegrees(undefined)).toBe(0); - expect(individualRotateDegrees("")).toBe(0); - expect(individualRotateDegrees("12")).toBe(0); - }); -}); - describe("readElementCropFrame — the composed walk", () => { /** * The case the crop outline got wrong: a text layer inside a rotated card. @@ -328,7 +329,9 @@ describe("readElementCropFrame — the composed walk", () => { offsetHeight: 300, parentElement: null, hasAttribute: (name: string) => name === "data-composition-id", - ownerDocument: { defaultView: { getComputedStyle: () => style(parentTransform) } }, + ownerDocument: { + defaultView: { DOMMatrix: ComputedMatrix, getComputedStyle: () => style(parentTransform) }, + }, }; return { offsetWidth: 200, @@ -337,6 +340,7 @@ describe("readElementCropFrame — the composed walk", () => { hasAttribute: () => false, ownerDocument: { defaultView: { + DOMMatrix: ComputedMatrix, getComputedStyle: (node: unknown) => node === parent ? style(parentTransform) : style(childTransform), }, diff --git a/packages/studio/src/components/editor/domEditOverlayCrop.ts b/packages/studio/src/components/editor/domEditOverlayCrop.ts index 8bd3b74ec9..32774ee389 100644 --- a/packages/studio/src/components/editor/domEditOverlayCrop.ts +++ b/packages/studio/src/components/editor/domEditOverlayCrop.ts @@ -1,8 +1,6 @@ import { - composeElementTransform, elementCornerPoints, readElementTransformSnapshot, - type PlanarTransformOps, } from "@hyperframes/core/runtime/editing-port"; import { parseInsetClipPathSides, @@ -22,25 +20,42 @@ export interface CropScreenRect { height: number; } -/** Element-space insets → the cropped region in overlay (screen) space. */ +/** + * Element-space insets → the cropped region's bounds in overlay (screen) space. With `corners` (a transformed + * layer's own corners) the insets cut along its own edges; insets that cross shrink until they meet, as CSS does. + */ export function cropRectFromInsets( rect: CropScreenRect, insets: ClipPathInsetSides, scaleX: number, scaleY: number, + corners?: OwnCorners, ): CropScreenRect { const sx = scaleX > 0 ? scaleX : 1; const sy = scaleY > 0 ? scaleY : 1; - const left = rect.left + insets.left * sx; - const top = rect.top + insets.top * sy; - return { - left, - top, - width: Math.max(0, rect.width - (insets.left + insets.right) * sx), - height: Math.max(0, rect.height - (insets.top + insets.bottom) * sy), + const { left: x, top: y, width: w, height: h } = rect; + const { nw, ne, sw } = corners ?? { nw: { x, y }, ne: { x: x + w, y }, sw: { x, y: y + h } }; + const [width, height] = [edge(nw, ne), edge(nw, sw)]; + const [l, r] = meet(insets.left * sx, insets.right * sx, width); + const [t, b] = meet(insets.top * sy, insets.bottom * sy, height); + const at = (u: number, v: number) => { + const [fu, fv] = [width > 0 ? u / width : 0, height > 0 ? v / height : 0]; + return { + x: nw.x + (ne.x - nw.x) * fu + (sw.x - nw.x) * fv, + y: nw.y + (ne.y - nw.y) * fu + (sw.y - nw.y) * fv, + }; }; + const cut = [at(l, t), at(width - r, t), at(width - r, height - b), at(l, height - b)]; + const xs = cut.map((p) => p.x); + const ys = cut.map((p) => p.y); + const [left, top] = [Math.min(...xs), Math.min(...ys)]; + return { left, top, width: Math.max(...xs) - left, height: Math.max(...ys) - top }; } +const edge = (a: Point, b: Point) => Math.hypot(b.x - a.x, b.y - a.y); +const meet = (a: number, b: number, side: number): [number, number] => + a + b > side && a + b > 0 ? [(a * side) / (a + b), (b * side) / (a + b)] : [a, b]; + // A selected croppable element shows uncropped so the crop UI can dim what is cut away. A rule keyed on its // identity does that, so the element's own clip-path stays the one record undo, redo and panel edits rewrite. // A sealed preview's lift is that rule in the frame (core `editing/cropLift.ts`), and `rule` is null. @@ -262,9 +277,13 @@ export function hugRectForElement(rect: HugRect, element: HTMLElement): CropScre type HugRect = CropScreenRect & { editScaleX: number; editScaleY: number; - ownScale?: { x: number; y: number }; + ownScale?: OwnScale; angle?: number; }; +type Point = { x: number; y: number }; +type OwnCorners = Record<"nw" | "ne" | "se" | "sw", Point>; +/** Overlay px per own CSS px along the layer's edges, and its own corners in overlay px when it is transformed. */ +export type OwnScale = { x: number; y: number; corners?: OwnCorners }; /** A live element's own-axis scale: an oriented rect's edges, or its turned corners' edges over its upright box. */ function liveOwnScale(rect: HugRect, element: HTMLElement): HugRect["ownScale"] { @@ -277,12 +296,17 @@ function liveOwnScale(rect: HugRect, element: HTMLElement): HugRect["ownScale"] const corners = transform && elementCornerPoints(win, element, transform); const box = element.getBoundingClientRect(); if (!corners || !(box.width > 0 && box.height > 0)) return upright; - const edge = (a: { x: number; y: number }, b: { x: number; y: number }) => - Math.hypot(b.x - a.x, b.y - a.y); - return { - x: (edge(corners.nw, corners.ne) / box.width) * upright.x, - y: (edge(corners.nw, corners.sw) / box.height) * upright.y, + const toOverlay = ({ x, y }: Point) => ({ + x: rect.left + ((x - box.left) * rect.width) / box.width, + y: rect.top + ((y - box.top) * rect.height) / box.height, + }); + const own = { + nw: toOverlay(corners.nw), + ne: toOverlay(corners.ne), + se: toOverlay(corners.se), + sw: toOverlay(corners.sw), }; + return { x: edge(own.nw, own.ne) / w, y: edge(own.nw, own.sw) / h, corners: own }; } const ownScaleXY = (own: HugRect["ownScale"], rect: HugRect): [number, number] => [ @@ -300,7 +324,9 @@ export function hugRectForClipPath( // Uneditable clip — show the full element rect. if (!insets || (insets.top <= 0 && insets.right <= 0 && insets.bottom <= 0 && insets.left <= 0)) return rect; - return cropRectFromInsets(rect, insets, ...ownScaleXY(ownScaleOf(), rect)); + const own = ownScaleOf(); + const corners = rect.angle === undefined ? own?.corners : undefined; + return cropRectFromInsets(rect, insets, ...ownScaleXY(own, rect), corners); } /** @@ -327,94 +353,28 @@ export interface CropFrame { scaleY: number; } -/** - * The element's own 2D transform as matrix components, plus the `rotate` - * property's angle. - * - * `rotate` is a separate CSS property, not part of `transform`, and it is the - * one Studio's rotate handle writes — reading `transform` alone reported a - * turned element as upright, so the crop outline drew square across it. - * - * Null means there is nothing planar to draw against: no transform and no - * rotation, or a 3D/unparseable matrix. The caller falls back to the - * axis-aligned box rather than guessing an angle. - */ -const IDENTITY = { a: 1, b: 0, c: 0, d: 1 }; - -/** Perspective terms this far from zero mean the mapping is not affine. */ -const PERSPECTIVE_EPSILON = 1e-6; +/** Components this close to the identity's count as the identity. */ +const IDENTITY_EPSILON = 1e-6; type Planar2D = { a: number; b: number; c: number; d: number }; -/** - * The 2D components of a computed transform, or null when it cannot be used. - * - * Accepts `matrix3d` as well as `matrix`, taking the same 2D projection the - * rest of the overlay reads through DOMMatrix. GSAP writes a 3D matrix for an - * ordinary 2D move or spin (force3D), and a composition that flips an element - * writes one with a negative z scale — treating either as unmeasurable left the - * crop outline square on an element every other piece of chrome drew rotated. - * - * Only a perspective term rules the matrix out, because that is where the - * mapping stops being affine and a single angle stops describing it. - */ -function parseMatrixComponents(transform: string): Planar2D | null { - const flat = /^matrix\(([^)]+)\)$/.exec(transform); - if (flat) { - const [a, b, c, d] = flat[1]!.split(",").map((v) => Number.parseFloat(v)); - return [a, b, c, d].every(Number.isFinite) ? { a: a!, b: b!, c: c!, d: d! } : null; - } - const spatial = /^matrix3d\(([^)]+)\)$/.exec(transform); - if (!spatial) return null; - const m = spatial[1]!.split(",").map((v) => Number.parseFloat(v)); - if (m.length !== 16 || !m.every(Number.isFinite)) return null; - const affine = [m[3], m[7], m[11]].every((v) => Math.abs(v!) < PERSPECTIVE_EPSILON); - if (!affine) return null; - return { a: m[0]!, b: m[1]!, c: m[4]!, d: m[5]! }; -} - -/** The crop frame only needs an angle and a scale, so it composes plain 2D components. */ -const PLANAR_2D_OPS: PlanarTransformOps = { - identity: () => IDENTITY, - fromTransform: parseMatrixComponents, - fromRotate: (degrees) => { - const rad = (degrees * Math.PI) / 180; - return { a: Math.cos(rad), b: Math.sin(rad), c: -Math.sin(rad), d: Math.cos(rad) }; - }, - compose: (outer, inner) => ({ - a: outer.a * inner.a + outer.c * inner.b, - b: outer.b * inner.a + outer.d * inner.b, - c: outer.a * inner.c + outer.c * inner.d, - d: outer.b * inner.c + outer.d * inner.d, - }), -}; - /** Whether the matrix leaves the box exactly as it found it. */ function isIdentity(m: Planar2D): boolean { return ( - Math.abs(m.a - 1) < PERSPECTIVE_EPSILON && - Math.abs(m.b) < PERSPECTIVE_EPSILON && - Math.abs(m.c) < PERSPECTIVE_EPSILON && - Math.abs(m.d - 1) < PERSPECTIVE_EPSILON + Math.abs(m.a - 1) < IDENTITY_EPSILON && + Math.abs(m.b) < IDENTITY_EPSILON && + Math.abs(m.c) < IDENTITY_EPSILON && + Math.abs(m.d - 1) < IDENTITY_EPSILON ); } -/** - * The transform the element paints under, in 2D components. - * - * Null when nothing up the chain transforms it: the caller's axis-aligned rect - * already describes it, and that comes from real layout rather than the - * element's untransformed box. - */ +/** The 2D components of the matrix the element paints under; null when upright and unscaled, or 3D. */ function readPlanarTransform(element: HTMLElement): Planar2D | null { - const acc = composeElementTransform(element, PLANAR_2D_OPS, (node) => { - try { - return node.ownerDocument.defaultView?.getComputedStyle(node) ?? null; - } catch { - return null; - } - }); - return acc && !isIdentity(acc) ? acc : null; + const win = element.ownerDocument.defaultView; + const matrix = win && readElementTransformSnapshot(win, element)?.matrix; + if (!matrix) return null; + const { a, b, c, d } = matrix; + return isIdentity({ a, b, c, d }) ? null : { a, b, c, d }; } /** What the frame measured of a stand-in's element at the press: a stand-in has no box of its own. */ diff --git a/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts b/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts index 914e12dfe8..7279aedc5c 100644 --- a/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts +++ b/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts @@ -50,6 +50,11 @@ describe("orientedOverlayRect — rotation gate (perf fix, V15 18a/18b)", () => // anchoredResizeCommitFeedsOffset.test.ts, which mock this module entirely. class FakeDOMMatrix { a = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; b = 0; c = 0; d = 1; diff --git a/packages/studio/src/components/editor/domEditOverlayGeometry.ts b/packages/studio/src/components/editor/domEditOverlayGeometry.ts index 5eb9b9e36a..94052de9ea 100644 --- a/packages/studio/src/components/editor/domEditOverlayGeometry.ts +++ b/packages/studio/src/components/editor/domEditOverlayGeometry.ts @@ -5,7 +5,7 @@ import { readPositiveDimension, } from "./domEditOverlayBasis"; import { isElementVisibleThroughAncestors } from "./domEditingDom"; -import { hugRectForElement } from "./domEditOverlayCrop"; +import { hugRectForElement, type OwnScale } from "./domEditOverlayCrop"; import { elementCornerPoints, readElementTransformSnapshot, @@ -26,7 +26,7 @@ export interface OverlayRect { height: number; editScaleX: number; editScaleY: number; - ownScale?: { x: number; y: number }; + ownScale?: OwnScale; /** Live screen-space rotation; omitted for axis-aligned group bounds. */ angle?: number; } @@ -185,7 +185,7 @@ export function frameRectToOverlay( scale: OverlayRootScale, elementRect: { left: number; top: number; width: number; height: number }, source: FrameSource, - ownScale?: { x: number; y: number }, + ownScale?: OwnScale, ): OverlayRect { const { iframeRect, overlayRect, rootScaleX, rootScaleY } = scale; const editScale = resolveDomEditCoordinateScale({ diff --git a/packages/studio/src/components/editor/overlayTransform.browser.test.ts b/packages/studio/src/components/editor/overlayTransform.browser.test.ts new file mode 100644 index 0000000000..20c1e259eb --- /dev/null +++ b/packages/studio/src/components/editor/overlayTransform.browser.test.ts @@ -0,0 +1,118 @@ +// @vitest-environment happy-dom +import { build } from "esbuild"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { closeTestChrome, launchTestChrome } from "../../../tests/chromeTestUtils"; + +vi.setConfig({ testTimeout: 60_000 }); + +let browser: Awaited> | undefined; + +afterEach(async () => { + await closeTestChrome(browser); + browser = undefined; +}); + +// Each layer is 200 x 100 CSS px; `own` is the size it paints at along its own edges, null for a layer +// turned out of its plane, which the walk declines so callers use the box Chrome paints. +const LAYERS: Array<{ id: string; style: string; own: [number, number] | null; parent?: string }> = + [ + { id: "depthScaled", style: "transform: rotate(45deg); scale: 1 1 2", own: [200, 100] }, + { id: "scaleProperty", style: "scale: 2", own: [400, 200] }, + { id: "turnedScaleProperty", style: "rotate: 45deg; scale: 2", own: [400, 200] }, + { id: "matrix", style: "transform: rotate(30deg) scale(2)", own: [400, 200] }, + { id: "mirrored", style: "transform: scaleX(-1); rotate: 20deg", own: [200, 100] }, + { id: "translated", style: "translate: 50% 10px; rotate: 10deg", own: [200, 100] }, + { id: "tipped", style: "rotate: x 60deg", own: null }, + { id: "tippedBack", style: "rotate: x -60deg", own: null, parent: "rotate: x 60deg" }, + { + id: "projected", + style: "transform: translateZ(100px) rotate(30deg)", + own: null, + parent: "transform: perspective(500px); transform-style: preserve-3d", + }, + { + id: "underPerspective", + style: "transform: translateZ(100px) rotate(30deg)", + own: null, + parent: "perspective: 500px", + }, + { + id: "inPreserved", + style: "rotate: 30deg", + own: null, + parent: "transform-style: preserve-3d", + }, + { + id: "spunFlat", + style: "transform: matrix3d(0.866, 0.5, 0, 0, -0.5, 0.866, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)", + own: [200, 100], + }, + { id: "nested", style: "scale: 1.5; rotate: 15deg", own: [300, 150], parent: "rotate: 30deg" }, + ]; + +// fails without the fix: under a parent's `perspective: 500px` a depth-moved child is projected, and the corners +// spanned 223 x 187 where Chrome paints 279 x 233. Any 3D context above a layer now leaves it to the painted box. +it("reads every layer's painted corners as Chrome paints them", async () => { + const bundle = await build({ + stdin: { + contents: `export { readElementTransformSnapshot, elementCornerPoints } from "./editingGeometry";`, + resolveDir: join(import.meta.dirname, "../../../../core/src/runtime"), + loader: "ts", + }, + bundle: true, + format: "iife", + globalName: "OverlayTransform", + platform: "browser", + write: false, + }); + browser = await launchTestChrome(); + const page = await browser.newPage(); + await page.setViewport({ width: 1600, height: 1200 }); + const layer = ({ id, style }: (typeof LAYERS)[number]) => + `
`; + await page.setContent(` +
+ ${LAYERS.map((l) => (l.parent ? `
${layer(l)}
` : layer(l))).join("")} +
`); + await page.addScriptTag({ content: bundle.outputFiles[0]?.text }); + + const measured = await page.evaluate( + (ids: string[]) => { + type Point = { x: number; y: number }; + const api = (window as unknown as { OverlayTransform: Record }) + .OverlayTransform; + const edge = (a: Point, b: Point) => Math.hypot(b.x - a.x, b.y - a.y); + return ids.map((id) => { + const element = document.getElementById(id)!; + const snapshot = api.readElementTransformSnapshot!(window, element); + const corners = snapshot && api.elementCornerPoints!(window, element, snapshot); + if (!corners) return { id, corners: null }; + const points = Object.values(corners) as Point[]; + const box = element.getBoundingClientRect(); + const xs = points.map((p) => p.x); + const ys = points.map((p) => p.y); + return { + id, + own: [edge(corners.nw, corners.ne), edge(corners.nw, corners.sw)], + bounds: [Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)], + painted: [box.width, box.height], + }; + }); + }, + LAYERS.map((l) => l.id), + ); + + for (const [i, { id, own }] of LAYERS.entries()) { + const got = measured[i]!; + if (!own) { + expect(got.corners, `${id} is declined`).toBeNull(); + continue; + } + expect(got.corners, id).not.toBeNull(); + expect(got.own![0], `${id} own width`).toBeCloseTo(own[0], 1); + expect(got.own![1], `${id} own height`).toBeCloseTo(own[1], 1); + expect(got.bounds![0], `${id} painted width`).toBeCloseTo(got.painted![0], 1); + expect(got.bounds![1], `${id} painted height`).toBeCloseTo(got.painted![1], 1); + } +}); diff --git a/packages/studio/src/components/editor/previewOverlayRects.test.ts b/packages/studio/src/components/editor/previewOverlayRects.test.ts index 6efdf0b3d4..d92b271c5d 100644 --- a/packages/studio/src/components/editor/previewOverlayRects.test.ts +++ b/packages/studio/src/components/editor/previewOverlayRects.test.ts @@ -39,6 +39,11 @@ installReactActEnvironment(); // The 2D slice of each that the overlay reads; one set for both frames, which share this window. class FakeDOMMatrix { a = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; b = 0; c = 0; d = 1; @@ -58,9 +63,6 @@ class FakeDOMMatrix { out.f = this.b * o.e + this.d * o.f + this.f; return out; } - rotateSelf() { - return this; - } transformPoint(p: { x: number; y: number }) { return { x: this.a * p.x + this.c * p.y + this.e, y: this.b * p.x + this.d * p.y + this.f }; } @@ -231,8 +233,8 @@ describe("overlay rects on an opaque frame match a scriptable one", () => { } }); - // fails without the fix: the cut took the turned layer's wider upright box as its scale, 167.4 px, not 173.2. - it("cuts a turned, scaled layer's crop at its own scale, not its upright box's, the same in both", async () => { + // fails without the fix: the cut took the turned layer's upright box, 167.4 or 173.2 px wide, not 179.9. + it("cuts a turned, scaled layer's crop at its own scale, along its own edges, the same in both", async () => { const [cos, sin] = [Math.cos(Math.PI / 6), Math.sin(Math.PI / 6)]; const [width, height] = [2 * (200 * cos + 100 * sin), 2 * (200 * sin + 100 * cos)]; const spun = sized(document.createElement("div"), [1000, 100, width, height]); @@ -249,7 +251,69 @@ describe("overlay rects on an opaque frame match a scriptable one", () => { const { group } = await settled( await overlayOn(frame(), { selection: null, group: ["grp", "spun"] }), ); - expect(group[1]!.width).toBeCloseTo((width - 100) / 2, 6); + const [cutW, cutH] = [2 * 150, 2 * 100]; + expect(group[1]!.width).toBeCloseTo((cutW * cos + cutH * sin) / 2, 6); + expect(group[1]!.height).toBeCloseTo((cutW * sin + cutH * cos) / 2, 6); + } + }); + + // fails without the fix: the crop was cut out of the upright box, 81.1 x 106.1 where the cut is 88.4 square. + const layer = (id: string, transform: string, clip: string, box = [1000, 100, 200, 100]) => { + const element = sized(document.createElement("div"), box); + element.id = id; + if (clip) element.style.setProperty("clip-path", clip); + if (transform) element.style.setProperty("transform", transform); + Object.defineProperty(element, "offsetWidth", { value: 200, configurable: true }); + Object.defineProperty(element, "offsetHeight", { value: 100, configurable: true }); + document.querySelector("[data-composition-id]")!.append(element); + }; + const pairIn = async (frame: () => HTMLIFrameElement, ids: [string, string]) => { + const { group } = await settled(await overlayOn(frame(), { selection: null, group: ids })); + return [group[0]!, group[1]!] as const; + }; + + // fails without the fix: a scaled layer's insets crossing past its width drew a box live, none sealed. + it("shrinks crossed insets until they meet, as CSS does, the same in both", async () => { + const half = "matrix(0.5, 0, 0, 0.5, 0, 0)"; + layer("whole", half, "", [1050, 125, 100, 50]); + layer("met", half, "inset(0px 300px 0px 100px)", [1050, 125, 100, 50]); + for (const frame of [liveFrame, opaqueFrame]) { + const [whole, met] = await pairIn(frame, ["whole", "met"]); + expect(met.width).toBeCloseTo(0, 6); + expect(met.left - whole.left).toBeCloseTo(((200 * 100) / 400) * 0.5 * 0.5, 6); + } + }); + + // fails without the fix: a mirrored layer's right inset cut its visual left live and its visual right sealed. + it("cuts a mirrored layer's right inset off its visual left, the same in both", async () => { + layer("plain", "", "inset(0px 50px 0px 0px)"); + layer("mirrored", "matrix(-1, 0, 0, 1, 0, 0)", "inset(0px 50px 0px 0px)"); + for (const frame of [liveFrame, opaqueFrame]) { + const [plain, mirrored] = await pairIn(frame, ["plain", "mirrored"]); + expect(mirrored.width).toBeCloseTo(plain.width, 6); + expect(mirrored.left - plain.left).toBeCloseTo(50 / 2, 6); + } + }); + + it("bounds a turned layer's cropped box by its cut corners, the same in both", async () => { + const half = Math.SQRT1_2; + const side = (200 + 100) * half; + const spun = sized(document.createElement("div"), [1000, 100, side, side]); + spun.id = "spun"; + spun.style.setProperty("clip-path", "inset(0px 50px 0px 0px)"); + spun.style.setProperty("transform", `matrix(${half}, ${half}, ${-half}, ${half}, 0, 0)`); + Object.defineProperty(spun, "offsetWidth", { value: 200, configurable: true }); + Object.defineProperty(spun, "offsetHeight", { value: 100, configurable: true }); + document.querySelector("[data-composition-id]")!.append(spun); + for (const frame of [liveFrame, opaqueFrame]) { + const { group } = await settled( + await overlayOn(frame(), { selection: null, group: ["grp", "spun"] }), + ); + const cut = ((150 + 100) * half) / 2; + expect(group[1]).toMatchObject({ + width: expect.closeTo(cut, 6), + height: expect.closeTo(cut, 6), + }); } }); diff --git a/packages/studio/src/components/editor/previewOverlayRects.ts b/packages/studio/src/components/editor/previewOverlayRects.ts index e00ebe75cf..a7ee35593b 100644 --- a/packages/studio/src/components/editor/previewOverlayRects.ts +++ b/packages/studio/src/components/editor/previewOverlayRects.ts @@ -35,7 +35,11 @@ function ownScaleOf(scale: OverlayRootScale, box: EditingElementBox) { const height = corners ? cornerEdgeLength(corners.nw, corners.sw) : box.rect.height * scale.rootScaleY; - return { x: width / layout.width, y: height / layout.height }; + return { + x: width / layout.width, + y: height / layout.height, + ...(corners && { corners }), + }; } /** `toOverlayRect`. */ From 196eff39eb05752b45d9e2f84fb20c1d530dc166 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 17:59:22 +0000 Subject: [PATCH 146/367] fix(studio): a sealed preview never keeps the keyboard, so no key it reports is acted on (#8521) * test(studio): a sealed preview's key reports never act, even right after a real press * fix(studio): a sealed preview never keeps the keyboard, so no key it reports is acted on * test(studio): in Chrome, a key after a sealed preview takes focus reaches Studio * fix(studio): take the keyboard back from a sealed preview once focus has settled in it * test(studio): the sealed keyboard walk presses Delete once the clip is picked --- .github/workflows/ci.yml | 6 +- .../studio/src/hooks/appHotkeysDispatch.ts | 39 +-- .../useAppHotkeys.previewForwarding.test.tsx | 241 +++++------------- packages/studio/src/hooks/useAppHotkeys.ts | 37 +-- .../player/hooks/usePlaybackKeyboard.test.ts | 91 ++----- .../src/player/hooks/usePlaybackKeyboard.ts | 42 +-- .../src/player/lib/sealedFrameKeyboard.ts | 16 ++ .../e2e/fixtures/sealed-keyboard/index.html | 46 ++++ .../tests/e2e/sealed-preview-keyboard.mjs | 78 ++++++ 9 files changed, 241 insertions(+), 355 deletions(-) create mode 100644 packages/studio/src/player/lib/sealedFrameKeyboard.ts create mode 100644 packages/studio/tests/e2e/fixtures/sealed-keyboard/index.html create mode 100644 packages/studio/tests/e2e/sealed-preview-keyboard.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7e1b3fad2..efa4cb1eb7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1239,7 +1239,7 @@ jobs: STUDIO_PROJECT_DIR="$PWD/packages/studio/data/projects/preview-video-regression" \ OUT_DIR=/tmp/preview-video-regression \ node packages/studio/tests/e2e/preview-video-regression.mjs - - name: Verify a sealed preview's proxy wait gets past its preflight + - name: Verify a sealed preview's proxy wait gets past its preflight, and that it never keeps the keyboard if: success() || failure() run: | set -euo pipefail @@ -1248,6 +1248,7 @@ jobs: cp packages/cli/src/templates/blank/index.html "$project/index.html" ffmpeg -hide_banner -loglevel error -y -f lavfi -i testsrc=size=320x180:rate=30 -t 1 \ -c:v libx264 -pix_fmt yuv420p "$project/clip.mov" + cp -R packages/studio/tests/e2e/fixtures/sealed-keyboard packages/studio/data/projects/sealed-keyboard VITE_STUDIO_OPAQUE_PREVIEW_ENABLED=1 NODE_ENV=production \ bun run --cwd packages/studio dev -- --port 5319 --strictPort & SERVER_PID=$! @@ -1258,6 +1259,9 @@ jobs: done STUDIO_URL="http://localhost:5319/#project/sealed-proxy" \ node packages/studio/tests/e2e/sealed-preview-proxy.mjs + STUDIO_URL="http://localhost:5319/#project/sealed-keyboard" \ + STUDIO_PROJECT_DIR="$PWD/packages/studio/data/projects/sealed-keyboard" \ + node packages/studio/tests/e2e/sealed-preview-keyboard.mjs - name: Upload gate evidence # The gate's whole output is machine-readable evidence, and a red run is # exactly when someone needs to read it. Keep it on failure too. diff --git a/packages/studio/src/hooks/appHotkeysDispatch.ts b/packages/studio/src/hooks/appHotkeysDispatch.ts index ee6e27f775..f3a7dd9e30 100644 --- a/packages/studio/src/hooks/appHotkeysDispatch.ts +++ b/packages/studio/src/hooks/appHotkeysDispatch.ts @@ -9,12 +9,7 @@ import { shouldIgnoreHistoryShortcut } from "../utils/studioHelpers"; import { canSplitElement } from "../utils/timelineElementSplit"; import { trackStudioEvent } from "../utils/studioTelemetry"; import { razorClaimsKey } from "../player/lib/playbackShortcuts"; -import { - getStudioKeys, - keyHint, - matchesKey, - type StudioKeyAction, -} from "../player/components/studioShortcuts"; +import { getStudioKeys, keyHint, matchesKey } from "../player/components/studioShortcuts"; import { zoomTimelineToSelectedClips } from "../player/components/timelineZoomInput"; import { openAudioGainDialog } from "../player/components/audioGainDialogStore"; import type { LinkShortcutCallbacks } from "./linkShortcuts"; @@ -124,38 +119,6 @@ function dispatchClipboardKey(event: KeyboardEvent, cb: HotkeyCallbacks): boolea return true; } -/** Every action the dispatchers here and dispatchLinkShortcut answer: what a sealed preview forwards to them. */ -export const APP_HOTKEY_ACTIONS = [ - "undo", - "redo", - "redoAlt", - "tabCompositions", - "tabAssets", - "group", - "ungroup", - "copy", - "paste", - "cut", - "duplicate", - "zoomSelection", - "fullscreen", - "split", - "audioGain", - "razorTool", - "selectTool", - "selectLeftward", - "selectRightward", - "cancel", - "deleteSelected", - "deleteSelectedAlt", - "resetKeyframes", - "record", - "linkToggle", - "detachAudio", - "deleteLinked", - "deleteLinkedAlt", -] as const satisfies readonly StudioKeyAction[]; - /** Exported for tests: the shortcuts that act on the editor, each read as a combo at event time. */ export function dispatchModifierKey( event: KeyboardEvent, diff --git a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx index a79f1bbc5c..c17c203ba2 100644 --- a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx +++ b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx @@ -1,6 +1,5 @@ // @vitest-environment happy-dom -import { readFileSync } from "node:fs"; import React, { act, useRef } from "react"; import type { Root } from "react-dom/client"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -9,8 +8,6 @@ import { usePlayerStore } from "../player/store/playerStore"; import { useAppHotkeys } from "./useAppHotkeys"; import { mountReactHarness } from "./domSelectionTestHarness"; import { trackStudioEvent } from "../utils/studioTelemetry"; -import { APP_HOTKEY_ACTIONS } from "./appHotkeysDispatch"; -import { PLAYBACK_ACTIONS } from "../player/hooks/usePlaybackKeyboard"; import { DEFAULT_STUDIO_KEYS } from "../player/components/studioShortcuts"; import { detachedFakeIframe, @@ -205,48 +202,31 @@ describe("preview iframe hotkey forwarding", () => { afterEach(() => closers.splice(0).forEach((close) => close())); // A frame whose document refuses Studio, reached only over the editing port it hands out per connect. - async function sealedFrame( - focus = { inPreview: true }, - { - inPlayer = false, - activation = { queued: [] as boolean[], otherwise: true, reads: 0 }, - } = {}, - ) { + async function sealedFrame() { const frame: Record = {}; const iframe = detachedFakeIframe(frame); const loaded = new Promise((resolve) => iframe.addEventListener("load", resolve, { once: true }), ); - const hasFocus = vi.spyOn(document, "hasFocus").mockImplementation(() => focus.inPreview); const player = document.createElement("div"); document.body.append(player); - if (!inPlayer) document.body.append(iframe); - if (inPlayer) { - const shadow = player.attachShadow({ mode: "open" }); - shadow.append(iframe); - Object.defineProperty(shadow, "activeElement", { - get: () => (focus.inPreview ? iframe : null), - }); - } - Object.defineProperty(document, "activeElement", { - configurable: true, - get: () => (!focus.inPreview ? document.body : inPlayer ? player : iframe), + const shadow = player.attachShadow({ mode: "open" }); + shadow.append(iframe); + const focus = { inPreview: true }; + Object.defineProperty(shadow, "activeElement", { + get: () => (focus.inPreview ? iframe : null), }); - // Studio's own window: active only after a real press or click, in the frame or out of it. + const blur = vi.spyOn(iframe, "blur").mockImplementation(() => { + focus.inPreview = false; + }); + // A real press or click just happened: Studio's window holds transient activation throughout. Object.defineProperty(window.navigator, "userActivation", { configurable: true, - get: () => { - activation.reads += 1; - const isActive = activation.queued.shift() ?? activation.otherwise; - return { isActive, hasBeenActive: isActive }; - }, + get: () => ({ isActive: true, hasBeenActive: true }), }); closers.push(() => { delete (window.navigator as { userActivation?: unknown }).userActivation; - hasFocus.mockRestore(); - delete (document as { activeElement?: unknown }).activeElement; player.remove(); - iframe.remove(); }); Object.defineProperty(iframe, "contentDocument", { value: null }); Object.defineProperty(frame, "document", { @@ -270,169 +250,82 @@ describe("preview iframe hotkey forwarding", () => { ); const report = (combo: string) => { const { mod, meta, ctrl, shift, alt, key } = parseCombo(combo)!; - ports.at(-1)!.postMessage({ - v: 1, - event: "key", - key: { - type: "keydown", - key, - code: "", - altKey: alt, - ctrlKey: ctrl, - metaKey: mod || meta, - shiftKey: shift, - repeat: false, - }, - }); + for (const port of ports) { + port.postMessage({ + v: 1, + event: "key", + key: { + type: "keydown", + key, + code: "", + altKey: alt, + ctrlKey: ctrl, + metaKey: mod || meta, + shiftKey: shift, + repeat: false, + }, + }); + } }; - const keyDown = (key: string, code: string) => - ports.at(-1)!.postMessage({ - v: 1, - event: "key", - key: { - type: "keydown", - key, - code, - altKey: false, - ctrlKey: false, - metaKey: false, - shiftKey: false, - repeat: false, - }, - }); + const answered = () => previewRequest(iframe, "max-z-index", {}, 1_000); await loaded; - return { iframe, watched, ports, keyDown, report, hasFocus }; + return { iframe, focus, blur, watched, report, answered }; } - it("leaves Studio's own reads of the preview answered while it forwards keys", async () => { - root = mountReactHarness(); - const { iframe, watched } = await sealedFrame(); - let read: Promise | undefined; - act(() => { - sync?.(iframe); - read = previewRequest(iframe, "max-z-index", {}, 1_000); - }); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - await expect(read).resolves.toEqual({ zIndex: 7 }); - }); - - it("deletes the selection on a Delete pressed inside the preview", async () => { - root = mountReactHarness(); - const { iframe, watched, keyDown } = await sealedFrame(); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - expect(new Set(watched[0])).toEqual( - new Set(APP_HOTKEY_ACTIONS.map((action) => DEFAULT_STUDIO_KEYS[action])), - ); - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(1)); - }); - - it("deletes the selection on a Delete pressed inside a preview held in the player's shadow root", async () => { - root = mountReactHarness(); - const { iframe, watched, keyDown } = await sealedFrame( - { inPreview: true }, - { inPlayer: true }, - ); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(1)); - }); - - it("ignores a key the preview reports while the person is not in the preview", async () => { - root = mountReactHarness(); - const focus = { inPreview: false }; - const { iframe, watched, keyDown, hasFocus } = await sealedFrame(focus); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(hasFocus).toHaveBeenCalledTimes(1)); - focus.inPreview = true; - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(1)); - expect(hasFocus).toHaveBeenCalledTimes(2); - }); - const changesMade = () => [domDelete, historyUndo, historyRedo, ...Object.values(changes)].reduce( (n, spy) => n + spy.mock.calls.length, 0, ); - // fails without the fix: focus in the frame was taken as a person's press, so every report below acted. - it.each([false, true])( - "acts on no app shortcut the frame reports with no real press (read-only preview: %s)", - async (readOnly) => { - readOnlyPreview = readOnly; - usePlayerStore.setState({ - selectedElementIds: new Set(["clip-a"]), - selectedElementId: "clip-a", - }); - root = mountReactHarness(); - // Each report Studio reads is unpressed, then the real Delete after them is pressed. - const activation = { - queued: APP_HOTKEY_ACTIONS.map(() => false), - otherwise: true, - reads: 0, - }; - const { iframe, watched, report, keyDown } = await sealedFrame( - { inPreview: true }, - { inPlayer: true, activation }, - ); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - for (const action of APP_HOTKEY_ACTIONS) report(DEFAULT_STUDIO_KEYS[action]); - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(activation.reads).toBe(APP_HOTKEY_ACTIONS.length + 1)); - await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(readOnly ? 0 : 1)); - expect(changesMade()).toBe(readOnly ? 0 : 1); - expect(usePlayerStore.getState().selectedElementId).toBe("clip-a"); - }, - ); - - // Known gap, by decision: a report forged within a real press's activation window (about 5 s) still acts. - it("still acts on a forged report while a real press's activation lasts", async () => { + // fails without the fix: a report the frame forged while a real press's activation lasted (about 5 s) acted. + it("acts on no key the frame reports, even right after a real press", async () => { + usePlayerStore.setState({ + selectedElementIds: new Set(["clip-a"]), + selectedElementId: "clip-a", + }); root = mountReactHarness(); - const { iframe, watched, report } = await sealedFrame( - { inPreview: true }, - { inPlayer: true }, - ); + const { iframe, watched, report, answered } = await sealedFrame(); act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - report(DEFAULT_STUDIO_KEYS.undo); - await vi.waitFor(() => expect(historyUndo).toHaveBeenCalledTimes(1)); + await answered(); + for (const combo of Object.values(DEFAULT_STUDIO_KEYS)) report(combo); + await answered(); + expect(watched).toEqual([]); + expect(changesMade()).toBe(0); }); - it("stops watching on the preview's next load, from a new port", async () => { + // fails without the fix: focus could stay in the frame, where Studio only had the frame's word for a key. + it("takes the keyboard back on the next task whenever focus moves into the frame", async () => { root = mountReactHarness(); - const { iframe, watched, ports } = await sealedFrame(); + const { iframe, focus, blur } = await sealedFrame(); act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(3)); - expect(watched.slice(1)).toContainEqual([]); - expect(ports).toHaveLength(2); + await vi.waitFor(() => expect(focus.inPreview).toBe(false)); + focus.inPreview = true; + window.dispatchEvent(new Event("blur")); + expect(focus.inPreview).toBe(true); + await vi.waitFor(() => expect(focus.inPreview).toBe(false)); + expect(blur).toHaveBeenCalledTimes(2); }); - it("watches every action the app's key dispatchers answer, so none is dead in a sealed preview", () => { - const read = (file: string) => readFileSync(new URL(file, import.meta.url), "utf8"); - const answered = new Set([ - ...[...read("./appHotkeysDispatch.ts").matchAll(/matchesKey\(\w+, "(\w+)"\)/g)].map( - (m) => m[1], - ), - ...[...read("./linkShortcuts.ts").matchAll(/\["(\w+)", "\w+"\]/g)].map((m) => m[1]), - ]); - expect(answered.size).toBeGreaterThan(20); - expect(new Set(APP_HOTKEY_ACTIONS)).toEqual(answered); + it("deletes the selection on a real Delete once Studio holds the keyboard", async () => { + root = mountReactHarness(); + const { iframe } = await sealedFrame(); + act(() => sync?.(iframe)); + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Delete", code: "Delete" })); + await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(1)); }); - it("watches no key the playback keys also watch, so the frame forwards each press once", () => { - const app = new Set(APP_HOTKEY_ACTIONS.map((action) => DEFAULT_STUDIO_KEYS[action])); - const shared = PLAYBACK_ACTIONS.map((action) => DEFAULT_STUDIO_KEYS[action]).filter((combo) => - app.has(combo), - ); - expect(shared).toEqual([]); + it("stops taking focus from the frame once the preview is gone", async () => { + root = mountReactHarness(); + const { iframe, focus, blur } = await sealedFrame(); + act(() => sync?.(iframe)); + await vi.waitFor(() => expect(blur).toHaveBeenCalledTimes(1)); + act(() => sync?.(null)); + focus.inPreview = true; + window.dispatchEvent(new Event("blur")); + // A task after the take-back would have run: it was queued first. + await new Promise((settled) => setTimeout(settled, 0)); + expect(blur).toHaveBeenCalledTimes(1); }); }); }); diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts index 185fe6ded4..207ba6b4c4 100644 --- a/packages/studio/src/hooks/useAppHotkeys.ts +++ b/packages/studio/src/hooks/useAppHotkeys.ts @@ -8,21 +8,15 @@ import { applyCaptionModelToIframe, isCaptionPreviewVisible, } from "../captions/components/CaptionOverlayUtils"; -import { - APP_HOTKEY_ACTIONS, - type HotkeyCallbacks, - dispatchModifierKey, - dispatchPlainKey, -} from "./appHotkeysDispatch"; +import { type HotkeyCallbacks, dispatchModifierKey, dispatchPlainKey } from "./appHotkeysDispatch"; import { useEditHistoryActions, type EditHistoryHandle, type UseEditHistoryActionsOptions, } from "./useEditHistoryActions"; import { useStableHandlers } from "./useStableHandlers"; -import { createEditingPortClient } from "@hyperframes/core/runtime/editing-port"; import { previewFrameOpaque } from "../player/lib/previewChannel"; -import { getStudioKey, subscribeStudioKeys } from "../player/components/studioShortcuts"; +import { keepKeyboardOutOfSealedFrame } from "../player/lib/sealedFrameKeyboard"; function iframeContentWindow(iframe: HTMLIFrameElement | null): Window | null { try { @@ -32,31 +26,6 @@ function iframeContentWindow(iframe: HTMLIFrameElement | null): Window | null { } } -// A port of its own: watch-keys replaces a port's whole list, and playback watches its keys on the shared one. -function forwardSealedFrameKeys(iframe: HTMLIFrameElement, onKeyDown: (e: KeyboardEvent) => void) { - const client = createEditingPortClient({ iframe }); - const watch = (combos: string[]) => void client.request("watch-keys", { combos }).catch(() => {}); - const watchApp = () => watch(APP_HOTKEY_ACTIONS.map(getStudioKey)); - watchApp(); - const stopRebinds = subscribeStudioKeys(watchApp); - // The frame can report keys and take focus, but only a real press or click activates Studio's own window. - const pressedByPerson = () => - iframe.ownerDocument.hasFocus() && - (iframe.getRootNode() as Document | ShadowRoot).activeElement === iframe && - iframe.ownerDocument.defaultView?.navigator.userActivation?.isActive === true; - const stopKeys = client.onKey((key) => { - if (key.type === "keydown" && pressedByPerson()) onKeyDown(new KeyboardEvent(key.type, key)); - }); - return () => { - stopRebinds(); - stopKeys(); - void client - .request("watch-keys", { combos: [] }) - .catch(() => {}) - .finally(() => client.dispose()); - }; -} - function safeAddListener(t: EventTarget | null, type: string, h: EventListener, capture = false) { try { t?.addEventListener(type, h, capture); @@ -281,7 +250,7 @@ export function useAppHotkeys({ previewHistoryCleanupRef.current?.(); previewHistoryCleanupRef.current = null; if (iframe && previewFrameOpaque(iframe)) { - previewHistoryCleanupRef.current = forwardSealedFrameKeys(iframe, handleAppKeyDown); + previewHistoryCleanupRef.current = keepKeyboardOutOfSealedFrame(iframe); return; } const win = iframeContentWindow(iframe); diff --git a/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts b/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts index b7b0e6d02c..3e379009ae 100644 --- a/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts +++ b/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts @@ -9,6 +9,7 @@ import { usePlayerStore } from "../store/playerStore"; import { setStudioKeys } from "../components/studioShortcuts"; import { useLinkedClipPreferences } from "../../utils/linkedClipPreferences"; import { detachedFakeIframe, serveEditingRequests } from "./timelinePlayerTestHarness"; +import { previewRequest } from "../lib/previewChannel"; globalThis.IS_REACT_ACT_ENVIRONMENT = true; @@ -487,11 +488,12 @@ describe("usePlaybackKeyboard: modifier combos and named keys", () => { }); }); +// fails without the fix: the sealed frame was asked to report playback keys, and every report it sent was acted on. describe("usePlaybackKeyboard: a sealed preview frame", () => { const closers: Array<() => void> = []; afterEach(() => closers.splice(0).forEach((close) => close())); - function sealedFrame() { + it("asks the frame for no keys and plays on none it reports", async () => { const frame: Record = {}; const iframe = detachedFakeIframe(frame); Object.defineProperty(iframe, "contentDocument", { value: null }); @@ -500,28 +502,30 @@ describe("usePlaybackKeyboard: a sealed preview frame", () => { throw new DOMException("blocked", "SecurityError"); }, }); - const watched: string[][] = []; - let port: MessagePort | null = null; + const watched: unknown[] = []; + const ports: MessagePort[] = []; closers.push( serveEditingRequests( frame, (kind, params) => { - if (kind !== "watch-keys") return null; - const { combos } = params as { combos: string[] }; - watched.push(combos); - return { watching: combos.length }; + if (kind === "max-z-index") return { zIndex: 1 }; + if (kind === "watch-keys") watched.push(params); + return null; }, - (framePort) => (port = framePort), + (port) => ports.push(port), ), ); - const forward = (type: "keydown" | "keyup", key: string, code: string) => - port!.postMessage({ + const { attach, spies } = setupHook(iframe); + attach(); + await previewRequest(iframe, "max-z-index", {}, 1_000); + for (const port of ports) { + port.postMessage({ v: 1, event: "key", key: { - type, - key, - code, + type: "keydown", + key: " ", + code: "Space", altKey: false, ctrlKey: false, metaKey: false, @@ -529,62 +533,9 @@ describe("usePlaybackKeyboard: a sealed preview frame", () => { repeat: false, }, }); - return { iframe, watched, forward }; - } - - it("asks the frame for exactly the playback keys, and again when they are remapped", async () => { - const { iframe, watched } = sealedFrame(); - setupHook(iframe).attach(); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - expect(new Set(watched[0])).toEqual( - new Set([ - "Space", - "ArrowLeft", - "ArrowRight", - "shift+ArrowLeft", - "shift+ArrowRight", - "m", - "shift+l", - "k", - "j", - "l", - "i", - "shift+i", - "o", - "shift+o", - "a", - "e", - ]), - ); - act(() => setStudioKeys({ playPause: "p" })); - await vi.waitFor(() => expect(watched).toHaveLength(2)); - expect(watched[1]).toContain("p"); - expect(watched[1]).not.toContain("Space"); - }); - - it("plays and steps from the keys the frame forwards, keyups included", async () => { - const { iframe, watched, forward } = sealedFrame(); - const { attach, spies } = setupHook(iframe); - attach(); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - forward("keydown", " ", "Space"); - await vi.waitFor(() => expect(spies.play).toHaveBeenCalledOnce()); - forward("keydown", "k", "KeyK"); - forward("keydown", "l", "KeyL"); - await vi.waitFor(() => expect(spies.seek).toHaveBeenCalledOnce()); - forward("keyup", "k", "KeyK"); - forward("keydown", "l", "KeyL"); - await vi.waitFor(() => expect(spies.play).toHaveBeenCalledTimes(2)); - }); - - it("stops watching when its listeners are replaced", async () => { - const { iframe, watched } = sealedFrame(); - const { attach } = setupHook(iframe); - attach(); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - attach(); - await vi.waitFor(() => expect(watched).toHaveLength(3)); - expect(watched[1]).toEqual([]); - expect(watched[2]).toEqual(watched[0]); + } + await previewRequest(iframe, "max-z-index", {}, 1_000); + expect(watched).toEqual([]); + expect(spies.play).not.toHaveBeenCalled(); }); }); diff --git a/packages/studio/src/player/hooks/usePlaybackKeyboard.ts b/packages/studio/src/player/hooks/usePlaybackKeyboard.ts index 8486cf7a83..f72975d3fc 100644 --- a/packages/studio/src/player/hooks/usePlaybackKeyboard.ts +++ b/packages/studio/src/player/hooks/usePlaybackKeyboard.ts @@ -15,13 +15,8 @@ import { } from "../lib/playbackShortcuts"; import { canvasNudgeKeysClaimed } from "../../utils/canvasNudgeGate"; import { usePlayerStore } from "../store/playerStore"; -import { - getStudioKey, - matchesKey, - subscribeStudioKeys, - type StudioKeyAction, -} from "../components/studioShortcuts"; -import { previewEditingClient, previewFrameOpaque } from "../lib/previewChannel"; +import { matchesKey, type StudioKeyAction } from "../components/studioShortcuts"; +import { previewFrameOpaque } from "../lib/previewChannel"; import { resolveCanvasNudgeDelta } from "../../components/editor/domEditNudge"; import { stepFrameTime } from "../lib/time"; import { useLinkedClipPreferences } from "../../utils/linkedClipPreferences"; @@ -45,7 +40,7 @@ const FRAME_STEPS = { frameBackTen: -10, frameForwardTen: 10, } as const; -export const PLAYBACK_ACTIONS = [ +const PLAYBACK_ACTIONS = [ "playPause", ...(Object.keys(FRAME_STEPS) as Array), "mute", @@ -73,28 +68,6 @@ function ignoresPlaybackKey(e: KeyboardEvent): boolean { }); } -type KeyHandlerRef = React.RefObject<(e: KeyboardEvent) => void>; - -function forwardSealedFrameKeys( - iframe: HTMLIFrameElement, - keyDown: KeyHandlerRef, - keyUp: KeyHandlerRef, -): () => void { - const client = previewEditingClient(iframe); - const watch = (combos: string[]) => void client.request("watch-keys", { combos }).catch(() => {}); - const watchPlayback = () => watch(PLAYBACK_ACTIONS.map(getStudioKey)); - watchPlayback(); - const stopRebinds = subscribeStudioKeys(watchPlayback); - const stopKeys = client.onKey((key) => - (key.type === "keydown" ? keyDown : keyUp).current(new KeyboardEvent(key.type, key)), - ); - return () => { - stopRebinds(); - stopKeys(); - watch([]); - }; -} - function handleWorkAreaKey( e: KeyboardEvent, action: PlaybackAction, @@ -227,14 +200,7 @@ export function usePlaybackKeyboard({ iframeShortcutCleanupRef.current?.(); iframeShortcutCleanupRef.current = null; const iframe = iframeRef.current; - if (iframe && previewFrameOpaque(iframe)) { - iframeShortcutCleanupRef.current = forwardSealedFrameKeys( - iframe, - playbackKeyDownRef, - playbackKeyUpRef, - ); - return; - } + if (iframe && previewFrameOpaque(iframe)) return; let iframeWin: Window | null = null; let iframeDoc: Document | null = null; diff --git a/packages/studio/src/player/lib/sealedFrameKeyboard.ts b/packages/studio/src/player/lib/sealedFrameKeyboard.ts new file mode 100644 index 0000000000..ebd6e08fd2 --- /dev/null +++ b/packages/studio/src/player/lib/sealedFrameKeyboard.ts @@ -0,0 +1,16 @@ +export function keepKeyboardOutOfSealedFrame(iframe: HTMLIFrameElement): () => void { + const studioWindow = iframe.ownerDocument.defaultView; + let attached = true; + // Chrome drops a blur while focus is still moving into the frame; on the next task the move has settled. + const reclaim = () => + studioWindow?.setTimeout(() => { + const holder = (iframe.getRootNode() as Document | ShadowRoot).activeElement; + if (attached && holder === iframe) iframe.blur(); + }, 0); + reclaim(); + studioWindow?.addEventListener("blur", reclaim); + return () => { + attached = false; + studioWindow?.removeEventListener("blur", reclaim); + }; +} diff --git a/packages/studio/tests/e2e/fixtures/sealed-keyboard/index.html b/packages/studio/tests/e2e/fixtures/sealed-keyboard/index.html new file mode 100644 index 0000000000..0e6a1a24e3 --- /dev/null +++ b/packages/studio/tests/e2e/fixtures/sealed-keyboard/index.html @@ -0,0 +1,46 @@ + + + + + Sealed keyboard + + + +
+
+ +
+ + diff --git a/packages/studio/tests/e2e/sealed-preview-keyboard.mjs b/packages/studio/tests/e2e/sealed-preview-keyboard.mjs new file mode 100644 index 0000000000..c05574d406 --- /dev/null +++ b/packages/studio/tests/e2e/sealed-preview-keyboard.mjs @@ -0,0 +1,78 @@ +// A sealed preview never keeps the keyboard: when its own script focuses an input in it, the next real key still +// reaches Studio; a real Delete after a canvas click deletes the picked clip. STUDIO_URL: a Studio started with +// VITE_STUDIO_OPAQUE_PREVIEW_ENABLED=1 on the sealed-keyboard fixture, whose folder is STUDIO_PROJECT_DIR. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { launchStudioChrome } from "./chrome-executable.mjs"; + +const url = process.env.STUDIO_URL; +const projectDir = process.env.STUDIO_PROJECT_DIR; +assert( + url && projectDir, + "STUDIO_URL and STUDIO_PROJECT_DIR must point at a sealed Studio's sealed-keyboard project", +); +const saved = () => readFileSync(join(projectDir, "index.html"), "utf8"); +/** A person's click on an element of the preview, mapped through the frame's on-screen scale. */ +async function clickInPreview(page, frame, selector) { + const inFrame = await frame.evaluate((s) => { + const b = document.querySelector(s).getBoundingClientRect(); + return { x: b.x + b.width / 2, y: b.y + b.height / 2, width: innerWidth }; + }, selector); + const iframe = await page.evaluateHandle(() => + document.querySelector("hyperframes-player").shadowRoot.querySelector("iframe"), + ); + const box = await iframe.boundingBox(); + const scale = box.width / inFrame.width; + await page.mouse.click(box.x + inFrame.x * scale, box.y + inFrame.y * scale, { delay: 120 }); +} +const { browser } = await launchStudioChrome(); +try { + const page = await browser.newPage(); + page.setDefaultTimeout(90_000); + await page.setViewport({ width: 1600, height: 1000 }); + await page.goto(url, { waitUntil: "domcontentloaded" }); + await page.waitForFunction(() => document.querySelector("hyperframes-player")?.painted === true); + const frame = page.frames().find((f) => /\/preview\/~[\w-]{43}/.test(f.url())); + assert.ok(frame, "the preview loads under its frame token"); + assert.equal( + await frame.evaluate(() => String(window.origin)), + "null", + "the preview frame is sealed", + ); + await page.evaluate(() => { + window.__studioKeys = []; + addEventListener("keydown", (e) => window.__studioKeys.push(e.key), true); + }); + const keyboardBackInStudio = () => + page.waitForFunction(() => { + let el = document.activeElement; + while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement; + return el?.tagName !== "IFRAME"; + }); + // The frame's own script puts focus on an ordinary input in it, as a composition may. + await frame.evaluate(() => document.getElementById("field").focus()); + await keyboardBackInStudio(); + await page.keyboard.press("y"); + await page.waitForFunction(() => window.__studioKeys.includes("y")); + assert.equal( + await frame.evaluate(() => document.getElementById("field").value), + "", + "the frame got no key", + ); + + // A clip picked on the canvas, then a real Delete: Studio deletes it. + assert.ok(saved().includes('id="plain"')); + await clickInPreview(page, frame, "#plain"); + await page.waitForFunction( + () => new URLSearchParams(location.hash.split("?")[1]).get("selId") === "plain", + ); + await keyboardBackInStudio(); + await page.keyboard.press("Delete"); + for (let i = 0; i < 100 && saved().includes('id="plain"'); i++) + await new Promise((r) => setTimeout(r, 100)); + assert.ok(!saved().includes('id="plain"'), "a real Delete after a canvas click deletes the clip"); + console.log(JSON.stringify({ studioKeys: await page.evaluate(() => window.__studioKeys) })); +} finally { + await browser.close(); +} From 4daeb78c3d8c2f7ab154613b13f6a1d74485d394 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 19:17:27 +0000 Subject: [PATCH 147/367] fix(producer): a film with many clips of one 4K video no longer freezes the render probe (#8284) --- .../services/render/stages/probeStage.test.ts | 72 +++++++++++++++++++ .../src/services/render/stages/probeStage.ts | 51 +++++++++++++ .../src/services/renderOrchestrator.ts | 10 ++- 3 files changed, 132 insertions(+), 1 deletion(-) diff --git a/packages/producer/src/services/render/stages/probeStage.test.ts b/packages/producer/src/services/render/stages/probeStage.test.ts index af6edfa189..a785db063e 100644 --- a/packages/producer/src/services/render/stages/probeStage.test.ts +++ b/packages/producer/src/services/render/stages/probeStage.test.ts @@ -20,6 +20,8 @@ import { hasRuntimeMediaChanges, hasScriptedAudioVolumeAutomation, hasVariableBoundMedia, + probeHoldFitsCapture, + probeVideoHold, reportedLengthSource, } from "./probeStage.js"; @@ -37,6 +39,8 @@ let afterMediaPreflight: (() => void) | null = null; let fileServerCloseCallCount = 0; let browserMediaResults: unknown[] = []; let browserMediaError: Error | null = null; +// Media sizes the mocked FFmpeg probe reports, by resolved path; any other path fails to probe. +const mediaSizes = new Map(); type MockSession = { id: number; @@ -95,6 +99,7 @@ function resetRetryMocks() { afterMediaPreflight = null; fileServerCloseCallCount = 0; browserMediaResults = []; + mediaSizes.clear(); } mock.module("../../assetMediaType.js", () => ({ @@ -116,6 +121,12 @@ mock.module("@hyperframes/engine", () => ({ parseImageElements, resolveReferencedStart, videoAudioId, + resolveProjectRelativeSrc: (src: string, projectDir: string) => `${projectDir}/${src}`, + extractMediaMetadata: async (path: string) => { + const size = mediaSizes.get(path); + if (!size) throw new Error(`ffprobe failed: ${path}`); + return size; + }, createCaptureSession: async ( _url: string, _dir: string, @@ -1630,6 +1641,67 @@ describe("runProbeStage — render variable threading", () => { }); }); +describe("probeVideoHold", () => { + it("holds each readable local video with its size, leaving runtime-set and remote sources live", async () => { + resetRetryMocks(); + mediaSizes.set("/p/4k.mp4", { width: 3840, height: 2160 }); + const html = ` + + + + + + `; + const videos = ["local", "bound", "sourced", "remote", "unreadable"].map((id) => ({ + id, + src: + id === "remote" + ? "https://cdn.example/4k.mp4" + : id === "unreadable" + ? "missing.mp4" + : "4k.mp4", + })); + + expect(await probeVideoHold(videos, html, "/p", "/p/compiled")).toEqual({ + skipReadinessVideoIds: ["local"], + videoMetadataHints: [{ id: "local", width: 3840, height: 2160 }], + }); + }); +}); + +describe("probeHoldFitsCapture", () => { + it("lets capture reuse the probe page only when capture holds every video the probe held", () => { + expect(probeHoldFitsCapture(["a", "b"], ["a", "b", "c"])).toBe(true); + expect(probeHoldFitsCapture(["a", "b"], ["a"])).toBe(false); + expect(probeHoldFitsCapture(undefined, [])).toBe(true); + }); +}); + +describe("runProbeStage — video hold", () => { + // fails without the fix: the probe page loaded every clip live, so 40 clips of one 4K file froze Chrome. + it("opens the probe page with the composition's local videos held at their FFmpeg size", async () => { + resetRetryMocks(); + capturedOptions.length = 0; + const { runProbeStage } = await import("./probeStage.js"); + const input = makeProbeInput({ stageForceScreenshot: false }); + mediaSizes.set(`${input.projectDir}/4k.mp4`, { width: 3840, height: 2160 }); + input.composition.videos = [ + { id: "c0", src: "4k.mp4", start: 0, end: 2, mediaStart: 0, hasAudio: false }, + { id: "c1", src: "4k.mp4", start: 2, end: 4, mediaStart: 30, hasAudio: false }, + ] as never[]; + + await runProbeStage(input); + + expect(capturedOptions[0]).toMatchObject({ + skipReadinessVideoIds: ["c0", "c1"], + videoMetadataHints: [ + { id: "c0", width: 3840, height: 2160 }, + { id: "c1", width: 3840, height: 2160 }, + ], + }); + }); +}); + describe("runProbeStage — page motion blur", () => { // The probe session is reused for capture, so it must carry the render's "off" like any session. it("passes pageMotionBlur to the probe session so a reused session installs the off global", async () => { diff --git a/packages/producer/src/services/render/stages/probeStage.ts b/packages/producer/src/services/render/stages/probeStage.ts index 3655e6cae4..0ac7847861 100644 --- a/packages/producer/src/services/render/stages/probeStage.ts +++ b/packages/producer/src/services/render/stages/probeStage.ts @@ -33,6 +33,7 @@ import { parseHTML } from "linkedom"; import { type CaptureOptions, type CaptureSession, + type CaptureVideoMetadataHint, type CompositionLengthSource, type EngineConfig, type SubTimelineWaitMemo, @@ -41,12 +42,14 @@ import { compositionRequiresWebGpu, createCaptureSession, deriveBeginFrameProbeTimeTicks, + extractMediaMetadata, getCompositionDuration, getCompositionLengthSource, initializeSession, isMemoryExhaustionError, isTransientBrowserError, probeBeginFrameLiveness, + resolveProjectRelativeSrc, videoAudioId, } from "@hyperframes/engine"; import { @@ -267,6 +270,48 @@ export function hasVariableBoundMedia( }); } +/** + * Videos the probe page holds at preload none with their FFmpeg size, as capture pages hold extracted ones: + * live, 40 clips of one 4K file stop Chrome answering. A runtime-set or sizeless source stays live. + */ +export async function probeVideoHold( + videos: readonly { id: string; src: string }[], + html: string, + projectDir: string, + compiledDir: string, +): Promise> { + const { document } = parseHTML(html); + const bound = new Set(); + for (const video of document.querySelectorAll("video")) { + if (!video.matches("[data-var-src]") && !video.querySelector("source[data-var-src]")) continue; + const id = video.getAttribute(MEDIA_RENDER_ID_ATTR) || video.getAttribute("id"); + if (id) bound.add(id); + } + const hints = await Promise.all( + videos.map(async ({ id, src }): Promise => { + if (bound.has(id) || /^https?:\/\//i.test(src)) return null; + try { + const path = resolveProjectRelativeSrc(src, projectDir, compiledDir); + const { width, height } = await extractMediaMetadata(path); + return width > 0 && height > 0 ? { id, width, height } : null; + } catch { + return null; + } + }), + ); + const held = hints.filter((hint): hint is CaptureVideoMetadataHint => hint !== null); + return { skipReadinessVideoIds: held.map((hint) => hint.id), videoMetadataHints: held }; +} + +/** A probe page can serve capture only when capture holds every video it held: an unextracted one needs Chrome. */ +export function probeHoldFitsCapture( + probeHeld: readonly string[] | undefined, + captureHeld: readonly string[], +): boolean { + const held = new Set(captureHeld); + return (probeHeld ?? []).every((id) => held.has(id)); +} + /** Each clip's own start point as the compiled markup gives it, keyed like the browser probe. */ function authoredMediaStarts(html: string): Map { const { document } = parseHTML(html); @@ -595,6 +640,12 @@ export async function runProbeStage(input: ProbeStageInput): Promise Date: Sun, 22 Nov 2026 20:31:38 +0000 Subject: [PATCH 148/367] fix(core): the motion path plugin loads from beside the page's own GSAP, never a CDN it did not name (#8523) * fix(core): the motion path plugin loads from beside the page's own GSAP, never a CDN it did not name * test(core): local root, revalidation and path-free preload rows * fix(core): the motion path plugin never falls back to jsDelivr, nor preloads for a page with none * fix(core): the plugin path beside GSAP is cut in linear time * test(core): the Desktop walk film's plugin request stays on its origin * fix(core): preload the motion path plugin only from the page's origin or a configured mirror * fix(core): the motion path preload compares with the preview document's own origin * fix(core): one rule decides the motion path plugin URL, bound to the document's own origin * fix(studio-server): the plugin tag sits beside the page's GSAP as the page wrote it * test(studio): the plugin-load fixtures name a page GSAP or a configured mirror --- packages/core/src/compiler/index.ts | 1 + packages/core/src/gsapCdn.ts | 36 ++++- .../src/runtime/editing/softReload.test.ts | 92 +++++++++++++ .../core/src/runtime/editing/softReload.ts | 38 +++++- .../core/src/runtime/editingAgent.test.ts | 19 +++ packages/core/src/runtime/editingAgent.ts | 3 +- .../src/helpers/gsapCoreScript.ts | 5 +- .../src/helpers/subCompositionBuild.ts | 7 +- .../studio-server/src/routes/preview.test.ts | 126 ++++++++++++++++-- packages/studio-server/src/routes/preview.ts | 92 +++++++++---- .../studio/src/utils/gsapSoftReload.test.ts | 28 ++-- .../utils/gsapSoftReloadWait.browser.test.ts | 5 +- 12 files changed, 395 insertions(+), 57 deletions(-) diff --git a/packages/core/src/compiler/index.ts b/packages/core/src/compiler/index.ts index 6c38f4e045..79669d7500 100644 --- a/packages/core/src/compiler/index.ts +++ b/packages/core/src/compiler/index.ts @@ -74,6 +74,7 @@ export { isAlwaysAppliedStyle, deferScriptsUntilFonts, headStyleRuns, + INLINED_FILE_ATTR, inlineScriptRuns, styleElementsFor, type CompositionStyle, diff --git a/packages/core/src/gsapCdn.ts b/packages/core/src/gsapCdn.ts index cd26c30a8e..29117bddf6 100644 --- a/packages/core/src/gsapCdn.ts +++ b/packages/core/src/gsapCdn.ts @@ -6,6 +6,18 @@ export const NO_PATH_TWEEN_META = "hf-no-path-tween"; export const namesMotionPath = (script: string) => /motionPath["']?\s*[:{]/.test(script); +const pathOf = (src: string) => + URL.canParse(src, "http://localhost/") ? new URL(src, "http://localhost/").pathname : null; + +export function isGsapCoreUrl(src: string): boolean { + return /\/gsap(-\d+(\.\d+)*)?(\.min)?\.js$/i.test(pathOf(src) ?? ""); +} + +export function motionPathBesideGsap(gsapFile: string): string { + const path = gsapFile.split(/[?#]/, 1)[0]!; + return `${path.slice(0, path.lastIndexOf("/") + 1)}MotionPathPlugin.min.js`; +} + function isLoopbackHost(hostname: string): boolean { return hostname === "localhost" || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(hostname); } @@ -51,7 +63,29 @@ export function gsapCdnDist(gsapVersion?: string, baseUrl?: string): string { return `${normalizeGsapBaseUrl(baseUrl)}/gsap@${version}/dist/`; } -/** MotionPathPlugin at the composition's own gsap version; a skew registers with a GSAP warning. */ export function motionPathPluginUrl(gsapVersion?: string, baseUrl?: string): string { return `${gsapCdnDist(gsapVersion, baseUrl)}MotionPathPlugin.min.js`; } + +const originOf = (url: string) => (URL.canParse(url) ? new URL(url).origin : "null"); + +/** The plugin a preview may load: an absolute mirror, the document's own origin, or (`pageOwned`) the page's GSAP. */ +export function previewMotionPathSrc(page: { + gsapFile: string | null; + mirror?: string | null; + version?: string; + documentUrl: string; + baseUrl: string; + pageOwned: boolean; +}): string | null { + const own = originOf(page.documentUrl); + const mirror = page.mirror?.trim(); + if (mirror?.startsWith("/")) { + return own === "null" ? null : new URL(motionPathPluginUrl(GSAP_CDN_VERSION, mirror), own).href; + } + const version = page.version ?? page.gsapFile?.match(/gsap@([\d.]+)/)?.[1]; + if (mirror) return motionPathPluginUrl(version, mirror); + if (!page.gsapFile || !URL.canParse(page.gsapFile, page.baseUrl)) return null; + const href = new URL(motionPathBesideGsap(page.gsapFile), page.baseUrl).href; + return page.pageOwned || (own !== "null" && originOf(href) === own) ? href : null; +} diff --git a/packages/core/src/runtime/editing/softReload.test.ts b/packages/core/src/runtime/editing/softReload.test.ts index a78eca199c..2ea3517901 100644 --- a/packages/core/src/runtime/editing/softReload.test.ts +++ b/packages/core/src/runtime/editing/softReload.test.ts @@ -4,6 +4,7 @@ import { parseRestoreAttributes } from "./restoreAttributes"; import { parseRestoreAttributesRerun, parseSoftReload, + preloadMotionPath, restoreAttributesOrRerun, softReload, type SoftReloadParams, @@ -167,6 +168,7 @@ describe("a re-run that waits for the MotionPath plugin", () => { document.body.innerHTML = `
` + `
` + + `` + ``; delete document.body.dataset.main; delete document.body.dataset.other; @@ -491,3 +493,93 @@ describe("parseSoftReload", () => { expect(parseSoftReload(request)).toBeNull(); }); }); + +describe("where the MotionPath plugin loads from", () => { + const pluginSrc = () => + document.head.querySelector("script[data-hf-gsap-plugin]")?.src ?? null; + const PATH_TWEEN = ''; + function preloadOn(markup: string, version?: string) { + document.body.innerHTML = markup; + win.gsap = { version, registerPlugin: () => {} }; + preloadMotionPath(win, document); + return pluginSrc(); + } + + // fails without the fix: the plugin came from jsDelivr whatever the page's GSAP was, so a preview with no + // network asked a third party for a script the page never named. + it.each([ + ['', "vendor/MotionPathPlugin.min.js"], + [ + '', + "vendor/MotionPathPlugin.min.js", + ], + ])("loads it from beside the page's own GSAP: %s", (tag, plugin) => { + expect(preloadOn(tag + PATH_TWEEN)).toBe(new URL(plugin, document.baseURI).href); + }); + + // fails without the fix: Desktop's walk film (project gsap.min.js at 3.12.5, no server meta) asked jsDelivr. + it("asks the page's own origin for a project GSAP's plugin, whatever its version", () => { + const src = preloadOn(`${PATH_TWEEN}`, "3.12.5"); + expect(src).toBe(new URL("MotionPathPlugin.min.js", document.baseURI).href); + expect(new URL(src!).origin).toBe(new URL(document.baseURI).origin); + }); + + it("requests nothing when the page names no GSAP file", () => { + expect(preloadOn(`${PATH_TWEEN}`)).toBeNull(); + }); + + // fails without the fix: a host's bundled root holds only its own GSAP version, so for another version the + // plugin came from jsDelivr though the page and the host named only same-origin files. + it("takes the host's bundled plugin for a page on another GSAP version, never the CDN", () => { + const meta = ''; + document.head.innerHTML = meta; + const src = preloadOn( + `${PATH_TWEEN}`, + "3.12.5", + ); + expect(src).toBe( + new URL("/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js", document.baseURI).href, + ); + }); + + // fails without the fix: with no server meta (Desktop), a film with GSAP from jsDelivr preloaded the plugin + // from there ahead of any path tween; an edit that adds one still loads it beside that GSAP. + it.each([ + ["no path tween", ""], + ["a path tween", PATH_TWEEN], + ])("never preloads from a CDN the host did not configure, with %s", (_, tween) => { + const cdn = ''; + expect(preloadOn(cdn + tween, "3.14.2")).toBeNull(); + }); + + // fails without the fix: rows "nothing, other site" and "local root, other site". The check read the + // page's base, so a on another site moved a "local" plugin there. + const LOCAL = "http://localhost:3000/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js"; + const MIRROR = "https://mirror.example/npm/gsap@3.12.5/dist/MotionPathPlugin.min.js"; + it.each<[string, string, string, string | null]>([ + ["nothing", "/film/", "", "http://localhost:3000/film/vendor/MotionPathPlugin.min.js"], + ["nothing", "https://assets.example/film/", "", null], + ["local root", "/film/", "/api/vendor/npm", LOCAL], + ["local root", "https://assets.example/film/", "/api/vendor/npm", LOCAL], + ["mirror", "/film/", "https://mirror.example/npm", MIRROR], + ["mirror", "https://assets.example/film/", "https://mirror.example/npm", MIRROR], + ])("preloads with %s configured under the base %s", (_, base, mirror, expected) => { + document.head.innerHTML = + `` + + (mirror ? `` : ""); + expect(preloadOn(`${PATH_TWEEN}`, "3.12.5")).toBe( + expected, + ); + }); + + // fails without the fix: a data: script threw out of the preload, and a project script beside GSAP was + // taken for GSAP's own and skipped it. + it.each([ + ["a project script beside GSAP", ''], + ["a data: script", ''], + ])("preloads the local plugin whatever else the page loads: %s", (_, other) => { + expect(preloadOn(`${other}`)).toBe( + new URL("vendor/MotionPathPlugin.min.js", document.baseURI).href, + ); + }); +}); diff --git a/packages/core/src/runtime/editing/softReload.ts b/packages/core/src/runtime/editing/softReload.ts index f4d7947b1b..989ef4785d 100644 --- a/packages/core/src/runtime/editing/softReload.ts +++ b/packages/core/src/runtime/editing/softReload.ts @@ -5,9 +5,11 @@ import { GSAP_BASE_URL_META, GSAP_PLUGIN_LOAD_ATTR, NO_PATH_TWEEN_META, - motionPathPluginUrl, + isGsapCoreUrl, + previewMotionPathSrc, namesMotionPath, } from "../../gsapCdn"; +import { INLINED_FILE_ATTR } from "../../compiler/scriptRuns"; import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading"; import { escapeCssString } from "../editingElement"; import { applyAuthoredTiming } from "../../studioPreviewMark"; @@ -337,11 +339,29 @@ export function finalizeSoftReload(win: SoftReloadWindow, currentTime: number): if (wasPlaying) win.__player?.play?.(); } -export function previewMotionPathUrl(doc: Document, version?: string): string { - const baseUrl = doc.head.querySelector( - `meta[name="${GSAP_BASE_URL_META}"]`, - )?.content; - return motionPathPluginUrl(version, baseUrl); +const scriptFile = (script: Element) => + script.getAttribute("src") ?? script.getAttribute(INLINED_FILE_ATTR); + +function pageGsapFile(doc: Document): string | null { + for (const script of doc.querySelectorAll(`script[src], script[${INLINED_FILE_ATTR}]`)) { + const file = scriptFile(script); + if (file && isGsapCoreUrl(file)) return file; + } + return null; +} + +const gsapMirror = (doc: Document) => + doc.head.querySelector(`meta[name="${GSAP_BASE_URL_META}"]`)?.content; + +function previewMotionPathUrl(doc: Document, version?: string, pageOwned = true): string | null { + return previewMotionPathSrc({ + gsapFile: pageGsapFile(doc), + mirror: gsapMirror(doc), + version, + documentUrl: doc.URL, + baseUrl: doc.baseURI, + pageOwned, + }); } function runSuppressed(win: SoftReloadWindow, reload: () => void): boolean { @@ -411,8 +431,10 @@ function whenMotionPathLoaded( win.__hfMotionPathWaiters = undefined; for (const [onReady, onFailed] of waiters) (loaded ? onReady : onFailed)(); }; + const src = previewMotionPathUrl(doc, win.gsap?.version); + if (!src) return settle(false); const pluginScript = doc.createElement("script"); - pluginScript.src = previewMotionPathUrl(doc, win.gsap?.version); + pluginScript.src = src; pluginScript.setAttribute(GSAP_PLUGIN_LOAD_ATTR, ""); pluginScript.onload = () => settle(Boolean(win.MotionPathPlugin)); // Running the script without the plugin would leave a motionPath tween that cannot play. @@ -469,6 +491,8 @@ export function preloadMotionPath( ): void { if (win.MotionPathPlugin || win.__hfMotionPathWaiters || !win.gsap) return; if (doc.querySelector(`meta[name="${NO_PATH_TWEEN_META}"]`)) return; + // Ahead of any path tween, only a request that stays local: the document's origin or the host's mirror. + if (!previewMotionPathUrl(doc, win.gsap.version, false)) return; const register = () => win.MotionPathPlugin && win.gsap?.registerPlugin?.(win.MotionPathPlugin); whenMotionPathLoaded(win, doc, register, () => {}); } diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index 4ceddef941..c16b4c8095 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -64,6 +64,25 @@ describe("installEditingAgent", () => { expect(transfer).toHaveLength(1); }); + // fails without the fix: the plugin preload ran before the handoff, so a page it threw on never got a port. + it("hands the port over before the optional plugin preload", () => { + Object.defineProperty(window, "gsap", { + configurable: true, + get: () => { + throw new Error("page gsap getter"); + }, + }); + const reported = (event: ErrorEvent) => event.preventDefault(); + window.addEventListener("error", reported); + try { + post(parent, CONNECT); + expect(handoff).toHaveBeenCalledOnce(); + } finally { + window.removeEventListener("error", reported); + Reflect.deleteProperty(window, "gsap"); + } + }); + it("hands a fresh port to each later connect from the parent and keeps the earlier one working", async () => { const old = connectedPort(); post(parent, CONNECT); diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts index 56649f9c4f..d1a4cfc3ce 100644 --- a/packages/core/src/runtime/editingAgent.ts +++ b/packages/core/src/runtime/editingAgent.ts @@ -303,7 +303,6 @@ export function installEditingAgent(parent: Window = window.parent): { dispose: const port = channel.port1; ports.add(port); serve(port); - preloadMotionPath(); try { // "*" as every runtime post does (bridge.ts): the frame is not told its parent's origin. parent.postMessage( @@ -315,7 +314,9 @@ export function installEditingAgent(parent: Window = window.parent): { dispose: swallow("editingAgent.handoff", err); port.close(); ports.delete(port); + return; } + preloadMotionPath(); }; window.addEventListener("message", onMessage); return { diff --git a/packages/studio-server/src/helpers/gsapCoreScript.ts b/packages/studio-server/src/helpers/gsapCoreScript.ts index d8acf3b04a..baf995d638 100644 --- a/packages/studio-server/src/helpers/gsapCoreScript.ts +++ b/packages/studio-server/src/helpers/gsapCoreScript.ts @@ -1,4 +1,5 @@ import { findStartTags, insertBeforeCloseTag } from "@hyperframes/core/compiler/html-document"; +import { isGsapCoreUrl } from "@hyperframes/core/gsap-cdn"; const URL_BASE = "http://localhost/"; @@ -6,9 +7,7 @@ function urlPath(src: string): string | null { return URL.canParse(src, URL_BASE) ? new URL(src, URL_BASE).pathname : null; } -export function isGsapCoreUrl(src: string): boolean { - return /\/gsap(-\d+(\.\d+)*)?(\.min)?\.js$/i.test(urlPath(src) ?? ""); -} +export { isGsapCoreUrl }; const GSAP_PLUGIN_FILE = /\/(\w+Plugin|CustomBounce|CustomEase|CustomWiggle|Draggable|EasePack|Flip|GSDevTools|MotionPathHelper|Observer|ScrollSmoother|ScrollTrigger|SplitText)(\.min)?\.js$/i; diff --git a/packages/studio-server/src/helpers/subCompositionBuild.ts b/packages/studio-server/src/helpers/subCompositionBuild.ts index 60fc370953..d4704f04d5 100644 --- a/packages/studio-server/src/helpers/subCompositionBuild.ts +++ b/packages/studio-server/src/helpers/subCompositionBuild.ts @@ -20,7 +20,12 @@ export interface FinishJob { signature: string; projectDir: string; compPath: string; - options: { capture: boolean; gsapBaseUrl: string; sandboxedCapture: boolean }; + options: { + capture: boolean; + gsapBaseUrl: string; + gsapMirror?: string | null; + sandboxedCapture: boolean; + }; variables?: Record; } diff --git a/packages/studio-server/src/routes/preview.test.ts b/packages/studio-server/src/routes/preview.test.ts index e9732f40d5..1c322fac51 100644 --- a/packages/studio-server/src/routes/preview.test.ts +++ b/packages/studio-server/src/routes/preview.test.ts @@ -818,6 +818,29 @@ describe("registerPreviewRoutes", () => { return [...parseHTML(html).document.querySelectorAll("script[src]")]; } + // fails without the fix: a page whose GSAP is the project's own file got the plugin from jsDelivr, a fetch + // a preview with no network cannot make and a script from a third party the page never named. + it.each([ + [ + "its own file", + '', + "vendor/MotionPathPlugin.min.js", + ], + [ + "a file the build inlined", + '', + "vendor/MotionPathPlugin.min.js", + ], + ])( + "loads the MotionPathPlugin from beside the page's GSAP when that is %s", + async (_, tag, plugin) => { + const scripts = await previewScriptSrcs(tag); + const srcs = scripts.map((el) => el.getAttribute("src") ?? ""); + expect(srcs).toContain(plugin); + expect(srcs.filter((src) => /jsdelivr|^https?:/.test(src))).toEqual([]); + }, + ); + it.each([ ["a query string", "https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js?v=1"], ["a hash", "https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.js#core"], @@ -3340,7 +3363,31 @@ describe("GSAP mirror configuration", () => { ); }); - it("preserves authored plugins and the default CDN when the override is unset", async () => { + // fails without the fix: an explicit jsDelivr mirror and no mirror shared an ETag, so after the mirror was + // removed a revalidation got a 304 and kept the cached page with the CDN plugin. + it.each(["", "/comp/scene.html"])( + "revalidates %s when the mirror setting changes", + async (suffix) => { + const projectDir = createProjectDir(); + const source = ``; + writeFileSync(join(projectDir, "index.html"), source); + writeFileSync(join(projectDir, "scene.html"), source); + const url = previewUrl + suffix; + const first = await appForMirror(projectDir, "https://cdn.jsdelivr.net/npm").request(url); + const etag = first.headers.get("ETag"); + expect(etag).toBeTruthy(); + const again = await appForMirror(projectDir, "").request(url, { + headers: { "If-None-Match": etag! }, + }); + expect(again.status).toBe(200); + const plugin = parseHTML(await again.text()).document.querySelector( + 'script[src*="MotionPathPlugin"]', + ); + expect(plugin?.getAttribute("src")).toBe("vendor/MotionPathPlugin.min.js"); + }, + ); + + it("preserves authored plugins, and names no plugin base when the override is unset", async () => { const projectDir = createProjectDir(); const plugin = "https://authored.example/MotionPathPlugin.min.js"; writeFileSync( @@ -3353,11 +3400,7 @@ describe("GSAP mirror configuration", () => { ).toHaveLength(1); expect(configured).toContain(`src="${plugin}"`); const defaults = await (await appForMirror(projectDir, "").request(previewUrl)).text(); - expect( - parseHTML(defaults) - .document.querySelector(`meta[name="${metaName}"]`) - ?.getAttribute("content"), - ).toBe("https://cdn.jsdelivr.net/npm"); + expect(parseHTML(defaults).document.querySelector(`meta[name="${metaName}"]`)).toBeNull(); expect(defaults).toContain('var cdnBase="https://cdn.jsdelivr.net/npm/gsap@3.15.0/dist/"'); }); @@ -3521,7 +3564,8 @@ describe("bundled GSAP local root", () => { expect(withPath).not.toContain("jsdelivr"); }); - it("loads a plugin for another GSAP version from jsDelivr", async () => { + // fails without the fix: the plugin for another GSAP version came from jsDelivr, a host the page never named. + it("loads the bundled plugin for another GSAP version, never jsDelivr", async () => { const projectDir = createProjectDir(); writeFileSync( join(projectDir, "index.html"), @@ -3532,7 +3576,8 @@ describe("bundled GSAP local root", () => { parseHTML(html) .document.querySelector('script[src*="MotionPathPlugin"]') ?.getAttribute("src"), - ).toBe("https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/MotionPathPlugin.min.js"); + ).toBe(`${localRoot}/gsap@3.15.0/dist/MotionPathPlugin.min.js`); + expect(html).not.toContain("jsdelivr"); }); it("prefers HYPERFRAMES_GSAP_BASE_URL over the bundled copy", async () => { @@ -3588,3 +3633,68 @@ describe("preview asset colour tags", () => { expect(response.headers.get("Content-Length") ?? String(body.length)).toBe(String(body.length)); }); }); + +describe("where the preview's MotionPathPlugin tag points", () => { + afterEach(() => vi.unstubAllEnvs()); + const pageUrl = "http://localhost/projects/demo/preview"; + const LOCAL = "http://localhost/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js"; + const MIRROR = "https://mirror.example/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js"; + + // fails without the fix: row "local root, other site". The bundled root was written as a path, which the + // page's on another site resolved there; the runtime now loads it on demand from the document. + it.each<[string, string | null, string | null]>([ + ["nothing", null, "http://localhost/api/projects/demo/preview/vendor/MotionPathPlugin.min.js"], + [ + "nothing", + "https://assets.example/film/", + "https://assets.example/film/vendor/MotionPathPlugin.min.js", + ], + ["local root", null, LOCAL], + ["local root", "https://assets.example/film/", null], + ["mirror", null, MIRROR], + ["mirror", "https://assets.example/film/", MIRROR], + ["nothing", "assets/", "http://localhost/projects/demo/assets/vendor/MotionPathPlugin.min.js"], + ["local root", "assets/", LOCAL], + ])("writes the tag with %s configured under the base %s", async (setup, base, expected) => { + const projectDir = createProjectDir(); + writeFileSync( + join(projectDir, "index.html"), + `${base ? `` : ""}
+ + + `, + ); + vi.stubEnv("HYPERFRAMES_GSAP_BASE_URL", setup === "mirror" ? "https://mirror.example/npm" : ""); + const app = new Hono(); + registerPreviewRoutes( + app, + createAdapter(projectDir, setup === "local root" ? { gsapLocalRoot: "/api/vendor/npm" } : {}), + ); + const doc = parseHTML(await (await app.request(pageUrl)).text()).document; + const src = doc.querySelector('script[src*="MotionPathPlugin"]')?.getAttribute("src"); + const baseUrl = new URL(doc.querySelector("base[href]")?.getAttribute("href") ?? "", pageUrl); + expect(src === undefined ? null : new URL(src, baseUrl).href).toBe(expected); + }); + + // fails without the fix: under the plugin was written from the site root, so it + // missed the folder the page's GSAP loads from and 404ed. + it("puts the plugin in the folder the page's GSAP loads from under a relative base", async () => { + const projectDir = createProjectDir(); + writeFileSync( + join(projectDir, "index.html"), + `
+ + + `, + ); + vi.stubEnv("HYPERFRAMES_GSAP_BASE_URL", ""); + const app = new Hono(); + registerPreviewRoutes(app, createAdapter(projectDir)); + const doc = parseHTML(await (await app.request(pageUrl)).text()).document; + const baseUrl = new URL(doc.querySelector("base[href]")?.getAttribute("href") ?? "", pageUrl); + const at = (selector: string) => + new URL(doc.querySelector(selector)?.getAttribute("src") ?? "missing", baseUrl).href; + const gsapFolder = at('script[src$="/gsap.min.js"]').replace(/gsap\.min\.js$/, ""); + expect(at('script[src*="MotionPathPlugin"]')).toBe(`${gsapFolder}MotionPathPlugin.min.js`); + }); +}); diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index 7d9f3c4d8b..6c4e4c8f29 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -8,6 +8,7 @@ import { join, resolve } from "node:path"; import { createHash } from "node:crypto"; import { AFTER_FONTS_SCRIPT_TYPE, + INLINED_FILE_ATTR, RUNTIME_BOOTSTRAP_ATTR, insertBeforeCloseTag, insertRuntimeTag, @@ -34,7 +35,8 @@ import { GSAP_PLUGIN_LOAD_ATTR, NO_PATH_TWEEN_META, gsapCdnDist, - motionPathPluginUrl, + motionPathBesideGsap, + previewMotionPathSrc, namesMotionPath, normalizeGsapBaseUrl, normalizeGsapLocalRoot, @@ -312,20 +314,38 @@ function htmlHasMotionPathPlugin(html: string): boolean { ); } -function injectMotionPathPluginIfNeeded(html: string, baseUrl: string): string { +// The plugin goes right after the page's GSAP, beside it as the page wrote it. The cached tag is the same for every +// visitor, so a local root's origin is a stand-in: written as a path, it holds only under a same-origin base. +const PREVIEW_DOCUMENT = "http://preview.invalid/preview"; + +function pluginTagSrc(html: string, gsapFile: string | null, mirror: string | null): string | null { + const baseHref = parseHTML(html).document.querySelector("base[href]")?.getAttribute("href"); + const baseUrl = new URL( + baseHref && URL.canParse(baseHref, PREVIEW_DOCUMENT) ? baseHref : "", + PREVIEW_DOCUMENT, + ); + const href = previewMotionPathSrc({ + gsapFile, + mirror, + documentUrl: PREVIEW_DOCUMENT, + baseUrl: baseUrl.href, + pageOwned: true, + }); + if (!href || !mirror) return href && gsapFile && motionPathBesideGsap(gsapFile); + const own = new URL(PREVIEW_DOCUMENT).origin; + if (new URL(href).origin !== own) return href; + return baseUrl.origin === own ? href.slice(own.length) : null; +} + +function injectMotionPathPluginIfNeeded(html: string, mirror: string | null = null): string { if (!htmlUsesMotionPath(html) || htmlHasMotionPathPlugin(html)) return html; - // The plugin registers onto an already-loaded gsap, so it must come AFTER the - // core gsap script — which often lives at body-end, not . Insert it - // directly after the gsap script tag; only fall back to if none is found - // (e.g. gsap is inlined). const gsap = findGsapCoreScript(html); - if (gsap) { - const version = gsap.src.match(/gsap@([\d.]+)/)?.[1]; - const ordering = `${gsap.type ? ` type="${gsap.type}"` : ""}${gsap.defer ? " defer" : ""}`; - const pluginTag = ``; - return html.slice(0, gsap.end) + "\n" + pluginTag + html.slice(gsap.end); - } - return injectScriptTagIntoHead(html, gsapScriptTag("MotionPathPlugin.min.js", baseUrl)); + const src = pluginTagSrc(html, gsap?.src ?? null, mirror); + if (!src) return html; + if (!gsap) return injectScriptTagIntoHead(html, ``); + const ordering = `${gsap.type ? ` type="${gsap.type}"` : ""}${gsap.defer ? " defer" : ""}`; + const pluginTag = ``; + return html.slice(0, gsap.end) + "\n" + pluginTag + html.slice(gsap.end); } type GsapCoreScript = { src: string; type: string | null; defer: boolean; end: number }; @@ -335,15 +355,15 @@ function findGsapCoreScript(html: string): GsapCoreScript | null { // The scanner skips comments, raw text and templates, so its ` - isGsapCoreUrl(lowerCaseAttributes(script).get("src") ?? ""), - ); + const fileOf = (attributes: Map) => + attributes.get("src") ?? attributes.get(INLINED_FILE_ATTR) ?? ""; + const at = scripts.findIndex((script) => isGsapCoreUrl(fileOf(lowerCaseAttributes(script)))); if (at === -1) return null; const attributes = lowerCaseAttributes(scripts[at]!); const end = scriptCloseEnd(html, starts[at]!); if (end === 0) return null; return { - src: attributes.get("src")!, + src: fileOf(attributes), type: attributes.get("type") ?? null, defer: attributes.has("defer"), end, @@ -499,7 +519,13 @@ export function injectStudioPreviewAugmentations( signature: string, projectDir: string, activeCompositionPath: string, - options: { capture: boolean; gsapBaseUrl: string; sandboxedCapture: boolean; pathFree?: boolean }, + options: { + capture: boolean; + gsapBaseUrl: string; + gsapMirror?: string | null; + sandboxedCapture: boolean; + pathFree?: boolean; + }, ): string { const studioMotion = readStudioMotion(projectDir, activeCompositionPath); const noTimelineToCome = @@ -519,8 +545,9 @@ export function injectStudioPreviewAugmentations( injectProjectSignature( injectTagsAtHeadStart( marked, - `` + - (!studioMotion && options.pathFree ? `` : ""), + (options.gsapMirror + ? `` + : "") + (!studioMotion && options.pathFree ? `` : ""), ), signature, ), @@ -534,7 +561,10 @@ export function injectStudioPreviewAugmentations( options.gsapBaseUrl, ) : withFallback; - const withPlugin = injectMotionPathPluginIfNeeded(withMotionDependencies, options.gsapBaseUrl); + const withPlugin = injectMotionPathPluginIfNeeded( + withMotionDependencies, + options.gsapMirror ?? null, + ); return studioMotion ? injectStudioMotionScript(withPlugin, studioMotion.script) : withPlugin; } @@ -601,11 +631,16 @@ export const withPreviewBase = (html: string, projectId: string) => { return hasBaseElement(mapped) ? mapped : injectTagsAtHeadStart(mapped, ``); }; -function resolvePreviewGsapBaseUrl(adapter: PreviewApiAdapter): string { +/** The GSAP root the preview rewrites to, and the same root when someone configured it (else null). */ +function resolvePreviewGsap(adapter: PreviewApiAdapter): { + gsapBaseUrl: string; + gsapMirror: string | null; +} { const configured = process.env.HYPERFRAMES_GSAP_BASE_URL; if (configured?.trim() || !adapter.gsapLocalRoot) { try { - return normalizeGsapBaseUrl(configured); + const gsapBaseUrl = normalizeGsapBaseUrl(configured); + return { gsapBaseUrl, gsapMirror: configured?.trim() ? gsapBaseUrl : null }; } catch (cause) { throw new Error( "Invalid HYPERFRAMES_GSAP_BASE_URL: use an absolute HTTPS npm mirror root (plain HTTP only for localhost) without credentials, query, or fragment", @@ -613,7 +648,8 @@ function resolvePreviewGsapBaseUrl(adapter: PreviewApiAdapter): string { ); } } - return normalizeGsapLocalRoot(adapter.gsapLocalRoot); + const gsapBaseUrl = normalizeGsapLocalRoot(adapter.gsapLocalRoot); + return { gsapBaseUrl, gsapMirror: gsapBaseUrl }; } export function registerPreviewRoutes( @@ -624,8 +660,9 @@ export function registerPreviewRoutes( subCompositionDeadlineMs, }: { sandboxThumbnailCaptures?: boolean; subCompositionDeadlineMs?: number } = {}, ): void { - const gsapBaseUrl = resolvePreviewGsapBaseUrl(adapter); - const gsapEtagSalt = `:gsap:${createHash("sha1").update(gsapBaseUrl).digest("hex").slice(0, 12)}`; + const { gsapBaseUrl, gsapMirror } = resolvePreviewGsap(adapter); + const gsapSource = `${gsapBaseUrl}|${gsapMirror ?? "unset"}`; + const gsapEtagSalt = `:gsap:${createHash("sha1").update(gsapSource).digest("hex").slice(0, 12)}`; const previewCacheHeaders = (etag: string) => ({ "Cache-Control": "private, no-cache", ETag: etag, @@ -695,6 +732,7 @@ export function registerPreviewRoutes( const options = { capture, gsapBaseUrl, + gsapMirror, sandboxedCapture: sandboxThumbnailCaptures, pathFree: await provesNoPathTween(transformed, project.dir, rootDeadline), }; @@ -759,6 +797,7 @@ export function registerPreviewRoutes( { capture, gsapBaseUrl, + gsapMirror, sandboxedCapture: sandboxThumbnailCaptures, pathFree: await provesNoPathTween(fallbackPage, project.dir), }, @@ -876,6 +915,7 @@ export function registerPreviewRoutes( const options = { capture, gsapBaseUrl, + gsapMirror, sandboxedCapture: sandboxThumbnailCaptures, pathFree: await provesNoPathTween(transformed, project.dir, deadline), }; diff --git a/packages/studio/src/utils/gsapSoftReload.test.ts b/packages/studio/src/utils/gsapSoftReload.test.ts index 22139ebf83..b51edd5804 100644 --- a/packages/studio/src/utils/gsapSoftReload.test.ts +++ b/packages/studio/src/utils/gsapSoftReload.test.ts @@ -25,6 +25,13 @@ tl.to("#box", { motionPath: { path: [{ x: 0, y: 0 }, { x: 100, y: 50 }] } }); window.__timelines["root"] = tl; `; +const PAGE = "http://localhost:3000/preview"; +/** The page's own GSAP file, which the plugin loads beside. */ +const pageGsap = () => + Object.assign(document.createElement("script"), { src: "vendor/gsap.min.js" }); +const pageScripts = (sel: string, inline: Element[] = []) => + sel === "script:not([src])" ? inline : sel.startsWith("script[src]") ? [pageGsap()] : []; + function buildMockIframe(overrides: Record = {}) { const scriptEl = document.createElement("script"); scriptEl.textContent = @@ -59,7 +66,9 @@ function buildMockIframe(overrides: Record = {}) { }; const contentDocument = { - querySelectorAll: (sel: string) => (sel === "script:not([src])" ? [scriptEl] : []), + URL: PAGE, + baseURI: PAGE, + querySelectorAll: (sel: string) => pageScripts(sel, [scriptEl]), createElement: (tag: string) => document.createElement(tag), body: container, head: document.createElement("div"), @@ -307,7 +316,7 @@ window.__timelines["root"] = tl;`; // script has NOT executed yet, so the timeline isn't rebound synchronously. expect(result).toBe("applied"); expect(appendedScripts).toHaveLength(1); - expect(appendedScripts[0]!.src).toContain("gsap@3.14.2/dist/MotionPathPlugin"); + expect(appendedScripts[0]!.src).toBe("http://localhost:3000/vendor/MotionPathPlugin.min.js"); expect(contentWindow.__hfForceTimelineRebind).not.toHaveBeenCalled(); // onerror must NOT run the script (that would reference a missing plugin) — @@ -478,6 +487,9 @@ function buildBootstrapIframe(overrides: Record = {}, pathFree ...overrides, }; const contentDocument = { + URL: PAGE, + baseURI: PAGE, + querySelectorAll: (sel: string) => pageScripts(sel), createElement: (tag: string) => document.createElement(tag), querySelector: (sel: string) => pathFree && sel === `meta[name="${NO_PATH_TWEEN_META}"]` @@ -574,14 +586,12 @@ describe("ensureMotionPathPluginLoaded", () => { expect(appendedScripts[0]!.hasAttribute(GSAP_PLUGIN_LOAD_ATTR)).toBe(true); }); - it("loads the plugin at the composition's own gsap version", () => { + it("loads the plugin from beside the page's own GSAP, whatever its version", () => { const { iframe, appendedScripts } = buildBootstrapIframe({ gsap: { version: "3.14.2", registerPlugin: vi.fn() }, }); ensureMotionPathPluginLoaded(iframe); - expect(appendedScripts[0]!.src).toBe( - "https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/MotionPathPlugin.min.js", - ); + expect(appendedScripts[0]!.src).toBe("http://localhost:3000/vendor/MotionPathPlugin.min.js"); }); it("preloads from the iframe mirror once, retaining the runtime version", () => { @@ -605,10 +615,10 @@ describe("ensureMotionPathPluginLoaded", () => { }); it.each([ - ["3.15.0", "/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js"], - ["3.14.2", "https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/MotionPathPlugin.min.js"], + ["3.15.0", "http://localhost:3000/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js"], + ["3.14.2", "http://localhost:3000/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js"], ])( - "preloads gsap %s from the host's bundled copy only when it holds that version", + "preloads gsap %s from the host's bundled copy at its own version, never the CDN", (version, url) => { const { iframe, appendedScripts } = buildBootstrapIframe({ gsap: { version, registerPlugin: vi.fn() }, diff --git a/packages/studio/src/utils/gsapSoftReloadWait.browser.test.ts b/packages/studio/src/utils/gsapSoftReloadWait.browser.test.ts index 47ea87306c..c055184b92 100644 --- a/packages/studio/src/utils/gsapSoftReloadWait.browser.test.ts +++ b/packages/studio/src/utils/gsapSoftReloadWait.browser.test.ts @@ -15,7 +15,10 @@ import { vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); const require = createRequire(import.meta.url); -const STUDIO_MARK = ''; +// A srcdoc preview has no origin of its own, so its plugin comes from a configured mirror, as Studio configures one. +const STUDIO_MARK = + '' + + ''; const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"]; let browser: Browser; let studioBundle: string; From 8c9c94572a148c62675a4e181cec1e3480e75bc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 20:32:43 +0000 Subject: [PATCH 149/367] fix(producer): a render serves every GSAP the CLI ships, and its own when the CDN is blocked (#8349) * test(producer): an older GSAP our templates name, or a blocked CDN's GSAP 3, renders offline * fix(producer): a render serves every GSAP the CLI ships, and its own when the CDN is blocked * fix(cli): the CLI's size limit covers the GSAP 3.14.2 files renders serve --- bun.lock | 3 + packages/cli/package.json | 1 + packages/cli/scripts/build-copy.mjs | 24 +++++-- packages/cli/src/server/gsapVendor.test.ts | 37 ++++++++++ .../src/services/bundledScripts.test.ts | 71 ++++++++++++++++--- .../producer/src/services/bundledScripts.ts | 25 +++++-- .../producer/src/services/htmlCompiler.ts | 17 ++++- scripts/package-size-budgets.json | 2 +- 8 files changed, 156 insertions(+), 24 deletions(-) diff --git a/bun.lock b/bun.lock index 9271fe2e2d..b827d49cf7 100644 --- a/bun.lock +++ b/bun.lock @@ -106,6 +106,7 @@ "@types/fontkit": "^2.0.9", "@types/node": "^25.0.10", "ajv": "^8.20.0", + "gsap-3.14.2": "npm:gsap@3.14.2", "linkedom": "^0.18.12", "onnxruntime-node": "1.21.1", "picocolors": "^1.1.1", @@ -1694,6 +1695,8 @@ "gsap": ["gsap@3.15.0", "", {}, "sha512-dMW4CWBTUK1AEEDeZc1g4xpPGIrSf9fJF960qbTZmN/QwZIWY5wgliS6JWl9/25fpTGJrMRtSjGtOmPnfjZB+A=="], + "gsap-3.14.2": ["gsap@3.14.2", "", {}, "sha512-P8/mMxVLU7o4+55+1TCnQrPmgjPKnwkzkXOK1asnR9Jg2lna4tEY5qBJjMmAaOBDDZWtlRjBXjLa0w53G/uBLA=="], + "gtoken": ["gtoken@7.1.0", "", { "dependencies": { "gaxios": "^6.0.0", "jws": "^4.0.0" } }, "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw=="], "happy-dom": ["happy-dom@21.0.4", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw=="], diff --git a/packages/cli/package.json b/packages/cli/package.json index c65bcdf161..bc2d815e1b 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -92,6 +92,7 @@ "@types/fontkit": "^2.0.9", "@types/node": "^25.0.10", "ajv": "^8.20.0", + "gsap-3.14.2": "npm:gsap@3.14.2", "linkedom": "^0.18.12", "onnxruntime-node": "1.21.1", "picocolors": "^1.1.1", diff --git a/packages/cli/scripts/build-copy.mjs b/packages/cli/scripts/build-copy.mjs index f7168db2d0..e5caf267e6 100644 --- a/packages/cli/scripts/build-copy.mjs +++ b/packages/cli/scripts/build-copy.mjs @@ -92,11 +92,25 @@ function copyGsapVendorFiles() { } const vendorDir = join(DIST, "vendor", "npm"); rmSync(vendorDir, { recursive: true, force: true }); - const dest = join(vendorDir, `gsap@${version}`, "dist"); - mkdirSync(dest, { recursive: true }); - for (const file of GSAP_VENDOR_FILES) { - copyFileSync(join(gsapRoot, "dist", file), join(dest, file)); - chmodSync(join(dest, file), 0o644); + // Older versions templates still name ship too, as the CDN's exact files: package.json's `gsap-` aliases + // (src/server/gsapVendor.test.ts pins their bytes). + const cliManifest = join(REPO_ROOT, "packages", "cli", "package.json"); + const cliRequire = createRequire(cliManifest); + const aliases = Object.keys(JSON.parse(readFileSync(cliManifest, "utf-8")).devDependencies ?? {}); + const roots = [ + gsapRoot, + ...aliases + .filter((name) => /^gsap-\d+\.\d+\.\d+$/.test(name)) + .map((name) => dirname(cliRequire.resolve(`${name}/package.json`))), + ]; + for (const root of roots) { + const { version: shipped } = JSON.parse(readFileSync(join(root, "package.json"), "utf-8")); + const dest = join(vendorDir, `gsap@${shipped}`, "dist"); + mkdirSync(dest, { recursive: true }); + for (const file of GSAP_VENDOR_FILES) { + copyFileSync(join(root, "dist", file), join(dest, file)); + chmodSync(join(dest, file), 0o644); + } } } diff --git a/packages/cli/src/server/gsapVendor.test.ts b/packages/cli/src/server/gsapVendor.test.ts index b00264d761..74c758523c 100644 --- a/packages/cli/src/server/gsapVendor.test.ts +++ b/packages/cli/src/server/gsapVendor.test.ts @@ -1,4 +1,7 @@ import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { describe, expect, it } from "vitest"; @@ -22,3 +25,37 @@ describe("resolveGsapVendorDir", () => { expect(out.trim()).toBe("ok"); }, 30_000); }); + +// The CDN's own files (jsDelivr's sha384, as a tag's integrity attribute would pin them). +const CDN_SHA384: Record> = { + "3.14.2": { + "gsap.min.js": "sG0Hv1tP1lZCk9KQmrIbY/XNwi+OY84GQqhMscbnsoBFqAz8KNCil1kvfL3Hbbk2", + "CustomEase.min.js": "Sjkr6w0fFKkxtEQY7MVGUGYK7lNjV5adCOLTzv8eBXdW2xDCLMNz5mo+iXchMXTh", + "MotionPathPlugin.min.js": "bRevQK3DiusS1XALpRyWfXNcSVNuNxBOUk12Tk44IsnfepFlBwFe8h/82zWbDxqi", + }, +}; + +describe("the older GSAP versions the CLI ships", () => { + const manifest = join(here, "..", "..", "package.json"); + const aliases = Object.keys(JSON.parse(readFileSync(manifest, "utf8")).devDependencies).filter( + (name) => /^gsap-\d+\.\d+\.\d+$/.test(name), + ); + + // fails without the fix: our own caption templates write gsap@3.14.2, which the CLI did not ship. + it("include 3.14.2, and each is the CDN's exact bytes", () => { + expect(aliases).toContain("gsap-3.14.2"); + const require = createRequire(manifest); + for (const alias of aliases) { + const version = alias.slice("gsap-".length); + const root = dirname(require.resolve(`${alias}/package.json`)); + expect(JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version).toBe(version); + expect(Object.keys(CDN_SHA384[version] ?? {})).toHaveLength(3); + for (const [file, sha] of Object.entries(CDN_SHA384[version] ?? {})) { + const got = createHash("sha384") + .update(readFileSync(join(root, "dist", file))) + .digest("base64"); + expect(`${version}/${file} ${got}`).toBe(`${version}/${file} ${sha}`); + } + } + }); +}); diff --git a/packages/producer/src/services/bundledScripts.test.ts b/packages/producer/src/services/bundledScripts.test.ts index 8b92f91473..9a85e25767 100644 --- a/packages/producer/src/services/bundledScripts.test.ts +++ b/packages/producer/src/services/bundledScripts.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test"; import { createHash } from "node:crypto"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { gsapCdnDist } from "@hyperframes/core/gsap-cdn"; +import { GSAP_CDN_VERSION, gsapCdnDist } from "@hyperframes/core/gsap-cdn"; import { _setDownloadFetchForTests } from "@hyperframes/engine"; import { inlineExternalScripts } from "./htmlCompiler.js"; import { GSAP_VENDOR_DIR_ENV } from "./bundledScripts.js"; @@ -17,18 +17,25 @@ const failingFetch = () => throw new TypeError("net::ERR_INTERNET_DISCONNECTED"); }) as unknown as typeof fetch; -let dir: string; +/** The host's copy of `version`, laid out as the CLI ships it: `/gsap@/dist`. */ +const ship = (version: string, file: string, bytes: string) => { + const at = join(root, `gsap@${version}`, "dist"); + mkdirSync(at, { recursive: true }); + writeFileSync(join(at, file), bytes); + return at; +}; + +let root: string; const realEnv = process.env[GSAP_VENDOR_DIR_ENV]; beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), "gsap-vendor-")); - writeFileSync(join(dir, "gsap.min.js"), BYTES); - process.env[GSAP_VENDOR_DIR_ENV] = dir; + root = mkdtempSync(join(tmpdir(), "gsap-vendor-")); + process.env[GSAP_VENDOR_DIR_ENV] = ship(GSAP_CDN_VERSION, "gsap.min.js", BYTES); }); afterEach(() => { _setDownloadFetchForTests(); if (realEnv === undefined) delete process.env[GSAP_VENDOR_DIR_ENV]; else process.env[GSAP_VENDOR_DIR_ENV] = realEnv; - rmSync(dir, { recursive: true, force: true }); + rmSync(root, { recursive: true, force: true }); }); describe("the host's own GSAP needs no network", () => { @@ -46,16 +53,60 @@ describe("the host's own GSAP needs no network", () => { expect(await inlineExternalScripts(page(URL_))).toContain("var net = 1;"); }); - it("leaves any other URL, including a mirror's, to the network", async () => { + it("leaves a version the host does not ship, and a mirror's URL, to the network", async () => { _setDownloadFetchForTests(mock(async () => new Response("var net = 1;"))); for (const other of [ - "https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js", - "https://mirror.example.com/gsap@3.15.0/dist/gsap.min.js", + "https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js", + `https://mirror.example.com/gsap@${GSAP_CDN_VERSION}/dist/gsap.min.js`, ]) { expect(await inlineExternalScripts(page(other))).toContain("var net = 1;"); } }); + // fails without the fix: our caption templates write gsap@3.14.2, and with jsDelivr blocked every export failed. + it("inlines another version the host ships, and its plugins, with no network", async () => { + ship("3.14.2", "gsap.min.js", "var gsap = 3142;"); + ship("3.14.2", "CustomEase.min.js", "var ease = 3142;"); + const fetch = failingFetch(); + _setDownloadFetchForTests(fetch); + const old = "https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/"; + const html = await inlineExternalScripts( + ``, + ); + expect(html).toContain("var gsap = 3142;"); + expect(html).toContain("var ease = 3142;"); + expect(fetch).not.toHaveBeenCalled(); + }); +}); + +describe("a GSAP 3 file the CDN cannot bring", () => { + const other = "https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js"; + + // fails without the fix: the tag stayed external, so the render browser failed on the blocked CDN too. + it("is inlined as the host's own GSAP", async () => { + _setDownloadFetchForTests(failingFetch()); + expect(await inlineExternalScripts(page(other))).toContain(BYTES); + }); + + it("stays the CDN's file when the CDN answers", async () => { + _setDownloadFetchForTests(mock(async () => new Response("var gsap = 3125;"))); + const html = await inlineExternalScripts(page(other)); + expect(html).toContain("var gsap = 3125;"); + expect(html).not.toContain(BYTES); + }); + + it("is never replaced when its tag pins its bytes, nor when it is not GSAP 3 from the default CDN", async () => { + _setDownloadFetchForTests(failingFetch()); + for (const html of [ + page(other, ' integrity="sha384-AAAA"'), + page("https://cdn.jsdelivr.net/npm/gsap@2.1.3/dist/gsap.min.js"), + page("https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js"), + page(`https://mirror.example.com/gsap@3.12.5/dist/gsap.min.js`), + ]) { + expect(await inlineExternalScripts(html)).not.toContain(BYTES); + } + }); + it("downloads when the host's copy fails the tag's integrity metadata", async () => { const fresh = "var fresh = 2;"; const digest = `sha256-${createHash("sha256").update(fresh).digest("base64")}`; diff --git a/packages/producer/src/services/bundledScripts.ts b/packages/producer/src/services/bundledScripts.ts index 43a2c07f9c..3e76d1e2eb 100644 --- a/packages/producer/src/services/bundledScripts.ts +++ b/packages/producer/src/services/bundledScripts.ts @@ -1,14 +1,27 @@ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; -import { gsapCdnDist } from "@hyperframes/core/gsap-cdn"; +import { GSAP_CDN_VERSION } from "@hyperframes/core/gsap-cdn"; -/** The folder a host that ships its own GSAP names, so a render needs no network for it. */ +/** The host's GSAP_CDN_VERSION files; other versions it ships sit beside them at `../../gsap@/dist`. */ export const GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR"; -/** The host's bytes for exactly the default CDN's GSAP file; a mirror's URL differs, so it never matches. */ +const DEFAULT_CDN_GSAP_3 = + /^https:\/\/cdn\.jsdelivr\.net\/npm\/gsap@(3\.\d+\.\d+)\/dist\/([A-Za-z]+\.min\.js)$/; + +const read = (file: string) => (existsSync(file) ? readFileSync(file) : null); + +/** The host's bytes for exactly this default-CDN GSAP file, at any version the host ships. */ export function bundledScript(url: string): Uint8Array | null { const dir = process.env[GSAP_VENDOR_DIR_ENV]; - if (!dir || url !== `${gsapCdnDist()}gsap.min.js`) return null; - const file = join(dir, "gsap.min.js"); - return existsSync(file) ? readFileSync(file) : null; + const [, version, file] = DEFAULT_CDN_GSAP_3.exec(url) ?? []; + if (!dir || !version || !file) return null; + const at = version === GSAP_CDN_VERSION ? dir : join(dir, "..", "..", `gsap@${version}`, "dist"); + return read(join(at, file)); +} + +/** The same file at the host's own GSAP version, for one the network could not bring. */ +export function bundledGsapStandIn(url: string): Uint8Array | null { + const dir = process.env[GSAP_VENDOR_DIR_ENV]; + const [, , file] = DEFAULT_CDN_GSAP_3.exec(url) ?? []; + return dir && file ? read(join(dir, file)) : null; } diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 86caffceb5..f9eb357ce0 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -28,7 +28,7 @@ import { createHash } from "node:crypto"; import { createReadStream, existsSync, mkdirSync, readFileSync, statSync } from "fs"; import { join, dirname, resolve, basename, relative, sep } from "path"; import { parseHTML } from "linkedom"; -import { bundledScript } from "./bundledScripts.js"; +import { bundledGsapStandIn, bundledScript } from "./bundledScripts.js"; import { inlineScriptBlocks, remoteSrcUrls, @@ -1659,6 +1659,9 @@ export async function inlineExternalScripts( }); const remote = new Set(externalScripts.filter((_, i) => !local[i]).map(({ src }) => src)); assertRemoteFetchCount("scripts", remote.size); + const pinned = new Set( + externalScripts.filter(({ el }) => el.getAttribute("integrity")).map(({ src }) => src), + ); const mirror = operatorGsapMirror(); const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES); @@ -1683,7 +1686,17 @@ export async function inlineExternalScripts( if (!bytes) { bytes = limit(async () => { fetchSignal.throwIfAborted(); - const downloaded = await downloadScript(src, mirror, fetchSignal); + const downloaded = await downloadScript(src, mirror, fetchSignal).catch( + (error: unknown) => { + // GSAP keeps its API within a major version, so a blocked CDN's 3.x file runs as the host's 3.x. + const standIn = pinned.has(src) || fetchSignal.aborted ? null : bundledGsapStandIn(src); + if (!standIn) throw error; + defaultLogger.warn( + `[Compiler] Could not download ${src} (${error}); using the host's own GSAP instead.`, + ); + return standIn; + }, + ); charge(downloaded.byteLength); return downloaded; }, fetchSignal); diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index 81b612772d..5497555bb7 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -5,7 +5,7 @@ }, "@hyperframes/cli": { "packed": 8577627, - "unpacked": 25500000 + "unpacked": 25830000 }, "@hyperframes/core": { "packed": 1948041, From 02450e3e2e9f9792589399d3a10b7a4ae34f6f2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 20:57:01 +0000 Subject: [PATCH 150/367] fix(studio-server): a sandboxed history read no longer fails with EPERM while the app holds it (#8529) A process that may only read the history folder now finds a live owner's lock busy at once instead of reporting the refused claim write, so readers show the history quietly. --- packages/cli/src/commands/history.test.ts | 18 +++++++++++ .../src/history/ownerLock.test.ts | 30 +++++++++++++++++++ .../studio-server/src/history/ownerLock.ts | 17 ++++++++++- 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/commands/history.test.ts b/packages/cli/src/commands/history.test.ts index 63132c87b5..25d5b7308a 100644 --- a/packages/cli/src/commands/history.test.ts +++ b/packages/cli/src/commands/history.test.ts @@ -826,6 +826,24 @@ describe.skipIf(process.platform === "win32" || process.getuid?.() === 0)( expect(listed.err).toMatch(/could not write this project's history/i); }); + // fails without the fix: the refused claim draft (EPERM in a macOS sandbox, EACCES here) is warned on stderr. + it("lists a history another app holds quietly when its folder cannot be written", async () => { + const { hf, turn } = project(); + await hf(); + const entry = await turn("claude", "Retitle", "index.html", "A2"); + const [id] = readdirSync(historyDeps.historyRoot).filter((name) => + existsSync(join(historyDeps.historyRoot, name, "log.jsonl")), + ); + writeFileSync(join(historyDeps.historyRoot, id!, "owner.pid"), String(process.ppid)); + lock(0o555); + const listed = await hf("--json"); + expect(listed.code).toBe(0); + expect(JSON.parse(listed.out).entries.map((item: { id: string }) => item.id)).toContain( + entry.id, + ); + expect(listed.err).not.toMatch(/could not write/i); + }); + it("lists the history when its log can be read but not appended to", async () => { const { hf, write, turn } = project(); await hf(); diff --git a/packages/studio-server/src/history/ownerLock.test.ts b/packages/studio-server/src/history/ownerLock.test.ts index d3d5b9bf44..d628e45dd6 100644 --- a/packages/studio-server/src/history/ownerLock.test.ts +++ b/packages/studio-server/src/history/ownerLock.test.ts @@ -91,6 +91,36 @@ function newHome(): string { return home; } +describe("takeHistoryOwnership where every write is refused (the desktop app's sandboxed agents)", () => { + const refuseWrites = () => + vi.mocked(writeFileSync).mockImplementation((path) => { + throw Object.assign(new Error(`EPERM: operation not permitted, open '${String(path)}'`), { + code: "EPERM", + syscall: "open", + }); + }); + + // fails without the fix: EPERM writing the claim draft, though the lock was plainly held. Windows retries these + // codes as a file locked for a moment, so it waits out the deadline as before. + it.skipIf(platform === "win32")( + "finds a live owner's lock busy at once, since it could never take it", + async () => { + const home = newHome(); + writeFileSync(join(home, "owner.pid"), String(process.ppid)); + refuseWrites(); + // A wait for the owner would outlast the test's own timeout. + await expect(takeHistoryOwnership(home, 60_000)).rejects.toThrow(HistoryBusyError); + }, + ); + + it("still fails with the refused write when no live owner holds the lock", async () => { + const home = newHome(); + writeFileSync(join(home, "owner.pid"), "2147483646"); + refuseWrites(); + await expect(takeHistoryOwnership(home, 100)).rejects.toMatchObject({ code: "EPERM" }); + }); +}); + function withoutHardLinks(code = "ENOTSUP"): void { vi.mocked(linkSync).mockImplementation(() => { throw Object.assign(new Error("hard links are not supported"), { code }); diff --git a/packages/studio-server/src/history/ownerLock.ts b/packages/studio-server/src/history/ownerLock.ts index 6a13c1a421..5347e5ef5a 100644 --- a/packages/studio-server/src/history/ownerLock.ts +++ b/packages/studio-server/src/history/ownerLock.ts @@ -32,6 +32,7 @@ const BOOT_SLACK_MS = 60_000; const NO_FOLLOW = constants.O_NOFOLLOW ?? 0; const NON_BLOCK = constants.O_NONBLOCK ?? 0; const LINKED = new Set(["ELOOP", "EMLINK"]); +const WRITE_REFUSED = new Set(["EPERM", "EACCES", "EROFS"]); function busyOnWindows(error: unknown): boolean { return ( @@ -39,6 +40,10 @@ function busyOnWindows(error: unknown): boolean { ); } +function mayOnlyRead(error: unknown): boolean { + return !busyOnWindows(error) && WRITE_REFUSED.has((error as NodeJS.ErrnoException).code ?? ""); +} + function alive(pid: number): boolean { if (!Number.isInteger(pid) || pid <= 0) return false; try { @@ -225,8 +230,18 @@ function servedBy(file: string, urlFile: string, pid: number): string | undefine type Attempt = "claimed" | "retry" | "wait"; +function claimOrBusy(file: string, urlFile: string): boolean { + try { + return claim(file); + } catch (error) { + const pid = mayOnlyRead(error) ? ownerOf(file) : null; + if (pid === null || deadHolder(file, pid)) throw error; + throw new HistoryBusyError(pid, servedBy(file, urlFile, pid)); + } +} + function attemptClaim(file: string, urlFile: string, deadline: number): Attempt { - if (claim(file)) return "claimed"; + if (claimOrBusy(file, urlFile)) return "claimed"; const pid = ownerOf(file); if (pid === null) return "retry"; if (deadHolder(file, pid) && evictDeadOwner(file)) return "retry"; From 2e1cd032379a34563142c69a31ba874c76e47003 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 21:07:50 +0000 Subject: [PATCH 151/367] chore: release v0.9.82 (#8531) --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- docs/changelog.mdx | 42 ++++++++++++++++++++++++ gemini-extension.json | 2 +- 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/inspector/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/share/package.json | 2 +- packages/studio-server/package.json | 2 +- packages/studio/package.json | 2 +- plugin.json | 2 +- releases/v0.9.82.md | 41 +++++++++++++++++++++++ 22 files changed, 103 insertions(+), 20 deletions(-) create mode 100644 releases/v0.9.82.md diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 4439acdde4..004f303c0c 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 capture for HyperFrames.", - "version": "0.9.81", + "version": "0.9.82", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 54195a93ad..8845e781a1 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "hyperframes", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.", - "version": "0.9.81", + "version": "0.9.82", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 33c0a0f0be..ddc4b45ec1 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -3,7 +3,7 @@ "name": "hyperframes", "displayName": "HyperFrames by HeyGen", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.", - "version": "0.9.81", + "version": "0.9.82", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com" diff --git a/docs/changelog.mdx b/docs/changelog.mdx index 01fea7f766..da731a2577 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -8,6 +8,48 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio {/* New release entries are prepended by `bun run changelog:draft --write`. */} + +A preview loads GSAP's motion path plugin from the page's own GSAP folder or the host's copy, so it works with no network. Sealed previews get more fixes, from sound and the keyboard to moves inside nested compositions. + +## Fixes + +- **Producer:** A render serves every GSAP the CLI ships, and its own when the CDN is blocked ([8c9c94572](https://github.com/heygen-com/hyperframes/commit/8c9c94572a148c62675a4e181cec1e3480e75bc4), [#8349](https://github.com/heygen-com/hyperframes/pull/8349)). +- **Core:** The motion path plugin loads from beside the page's own GSAP, never a CDN it did not name ([80f45de33](https://github.com/heygen-com/hyperframes/commit/80f45de33da92c8f765fd184a0ac4cb8e2ade261), [#8523](https://github.com/heygen-com/hyperframes/pull/8523)). +- **Producer:** A film with many clips of one 4K video no longer freezes the render probe ([4daeb78c3](https://github.com/heygen-com/hyperframes/commit/4daeb78c3d8c2f7ab154613b13f6a1d74485d394), [#8284](https://github.com/heygen-com/hyperframes/pull/8284)). +- **Studio:** A sealed preview never keeps the keyboard, so no key it reports is acted on ([196eff39e](https://github.com/heygen-com/hyperframes/commit/196eff39eb05752b45d9e2f84fb20c1d530dc166), [#8521](https://github.com/heygen-com/hyperframes/pull/8521)). +- **Studio:** A turned layer's cropped box is the bounds of its cut corners ([e5e360154](https://github.com/heygen-com/hyperframes/commit/e5e360154e08cf39b2e1bca3d95c5bfc0bbb2da9), [#8502](https://github.com/heygen-com/hyperframes/pull/8502)). +- **Player:** A sealed film is heard when its frame may not start sound ([87fddbc1a](https://github.com/heygen-com/hyperframes/commit/87fddbc1a1c5b745be0f1bbae59e37639a3f5d92), [#8495](https://github.com/heygen-com/hyperframes/pull/8495)). +- **Core:** Pasted or written markup never carries a composition source from elsewhere ([2425df5f4](https://github.com/heygen-com/hyperframes/commit/2425df5f4d8a94a1923cb11d76a97bba9f6e0d8f), [#8520](https://github.com/heygen-com/hyperframes/pull/8520)). +- **CLI:** Pinned-file downloaders check the cache folder is private before reading or writing it ([675e3a876](https://github.com/heygen-com/hyperframes/commit/675e3a876e550a5e5850b0b0123ffffec8be7cce), [#8486](https://github.com/heygen-com/hyperframes/pull/8486)). +- **Studio:** Paste and duplicate check the file they write, after every edit to it ([bd7a8402d](https://github.com/heygen-com/hyperframes/commit/bd7a8402db87662cf256c4e2e29212c03b48b7de), [#8519](https://github.com/heygen-com/hyperframes/pull/8519)). +- **CLI:** Publish updates a committed project only when this machine linked the folder ([886f609c4](https://github.com/heygen-com/hyperframes/commit/886f609c43b3e622402d2856ba5e63165e248f76), [#8487](https://github.com/heygen-com/hyperframes/pull/8487)). +- **CLI:** Print project file names in check's stderr notes as visible escapes ([4202462ca](https://github.com/heygen-com/hyperframes/commit/4202462ca5549738c044ce45f09d27fb409a01db), [#8485](https://github.com/heygen-com/hyperframes/pull/8485)). +- **Player:** A late timeline from the old film no longer keeps a switched player ready ([c19d98d9a](https://github.com/heygen-com/hyperframes/commit/c19d98d9a15ed060ae1a7c989c7ca10c75bf3488), [#8500](https://github.com/heygen-com/hyperframes/pull/8500)). +- **Core:** A sealed move inside a nested composition shows where it was dropped ([ec9a3a8ef](https://github.com/heygen-com/hyperframes/commit/ec9a3a8ef2b73e35fddea9a94e6fa474cf73e09a), [#8517](https://github.com/heygen-com/hyperframes/pull/8517)). +- **Studio Server:** A page with thousands of script tags no longer stalls the preview ([0bc7963ff](https://github.com/heygen-com/hyperframes/commit/0bc7963ffd836fe262bfce8b9422f53dc4b06b8a), [#8518](https://github.com/heygen-com/hyperframes/pull/8518)). +- **Producer:** A probe step's out-of-memory error keeps its words, so it still reads as memory ([258a3cf4e](https://github.com/heygen-com/hyperframes/commit/258a3cf4ea1a2b9c9d9305809be52a960b7e880e), [#8513](https://github.com/heygen-com/hyperframes/pull/8513)). +- **CLI:** Cloudrun and lambda say a usage error before loading their cloud SDK ([fbd1cd4bc](https://github.com/heygen-com/hyperframes/commit/fbd1cd4bcf8b5888c0dd21b62a637a7b2143abac), [#8510](https://github.com/heygen-com/hyperframes/pull/8510)). +- **Core:** A timeline whose labels throw no longer empties the clip list ([5d4420fee](https://github.com/heygen-com/hyperframes/commit/5d4420fee1bae9ca9cd0b157e33c7de2680be906), [#8512](https://github.com/heygen-com/hyperframes/pull/8512)). +- **Studio:** Vitest exits when a project is open in the dev data folder ([b3d37f948](https://github.com/heygen-com/hyperframes/commit/b3d37f948cabec76e187bed2f2fbb1336da5ae3e), [#8514](https://github.com/heygen-com/hyperframes/pull/8514)). +- **Studio:** The viewport gate tells a virtualized timeline by its mounted rows, not its clips ([dd7799037](https://github.com/heygen-com/hyperframes/commit/dd7799037396404e4e9b7f2803072ac87dc2fcc4), [#8511](https://github.com/heygen-com/hyperframes/pull/8511)). +- **Studio:** A cropped layer's outline is cut at the layer's own scale, sealed or not ([2b1495f7a](https://github.com/heygen-com/hyperframes/commit/2b1495f7aff642e23a571217ad7f8bdc7d5533fe), [#8496](https://github.com/heygen-com/hyperframes/pull/8496)). +- **Core:** A far clip whose source is swapped learns its new length ([4a47c33ea](https://github.com/heygen-com/hyperframes/commit/4a47c33ea36970ac288662ac40ec7790590ce9d8), [#8509](https://github.com/heygen-com/hyperframes/pull/8509)). +- **Studio Server:** Previewing a page with thousands of media files no longer stalls the app ([f03233ab4](https://github.com/heygen-com/hyperframes/commit/f03233ab4d1efcaaa677fd82fcad3a96bb46f9ac), [#8505](https://github.com/heygen-com/hyperframes/pull/8505)). +- **Producer:** A render that stops while preparing names the step it stopped in ([852611378](https://github.com/heygen-com/hyperframes/commit/85261137849f8e050c904e508810e7d8292b00d1), [#8506](https://github.com/heygen-com/hyperframes/pull/8506)). + +## Internal + +- **CLI:** The diagnostic test's ffmpeg stand-in answers the demuxer listing, writing no file ([f38a4e367](https://github.com/heygen-com/hyperframes/commit/f38a4e3675a76d8742acf8843fd6f909e2a0e96b), [#8515](https://github.com/heygen-com/hyperframes/pull/8515)). +- **Studio:** A failed walk in the viewport gate job names itself on the check ([086948766](https://github.com/heygen-com/hyperframes/commit/086948766477b8ae4c4fa1be0b4215a627e1062b), [#8516](https://github.com/heygen-com/hyperframes/pull/8516)). +- **CLI:** The sign-in return test waits for each window's navigation instead of one second ([20a91dd5f](https://github.com/heygen-com/hyperframes/commit/20a91dd5f1092e3b1709f20886cc16bcf2c53c39), [#8507](https://github.com/heygen-com/hyperframes/pull/8507)). + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.9.81...v0.9.82). + + Date: Sun, 22 Nov 2026 21:14:59 +0000 Subject: [PATCH 152/367] perf(producer): compile time stays linear on pages with thousands of clips or style rules (#8528) * perf(producer): compile time stays linear on pages with thousands of clips or style rules * perf(producer): each background rule's selector matches in bounded time, :has() included * fix(producer): a wrapper's escaped class selector still finds its background --- .../core/src/compiler/timingCompiler.test.ts | 36 +++++ packages/core/src/compiler/timingCompiler.ts | 80 ++++++------ .../src/services/htmlCompiler.test.ts | 65 +++++++++ .../producer/src/services/htmlCompiler.ts | 123 ++++++++++++++++-- 4 files changed, 256 insertions(+), 48 deletions(-) diff --git a/packages/core/src/compiler/timingCompiler.test.ts b/packages/core/src/compiler/timingCompiler.test.ts index 13f73fe0c8..e43aaad969 100644 --- a/packages/core/src/compiler/timingCompiler.test.ts +++ b/packages/core/src/compiler/timingCompiler.test.ts @@ -396,6 +396,16 @@ describe("compileTimingAttrs", () => { }); }); +// 5,000 clips: main rescanned the page once per clip, about a minute for this page. +const CLIPS = 5_000; +const manyClips = (attrs: string) => + Array.from( + { length: CLIPS }, + (_, i) => `
', + '
', + ])("writes no comment from the copy %s", (html) => { + for (const readFrom of [null, "compositions/recv.html"]) { + const pasted = pasteElementHtml(FILE, { html, readFrom }, false, "index.html"); + const clip = { html, readFrom, start: 0, duration: 1, track: 1 }; + const placed = pasteTimelineClips(FILE, [clip], 0, [], false, "index.html").content; + for (const file of [pasted, placed]) { + expect(file).not.toContain("b", parse)).toBe("ab"); }); diff --git a/packages/core/src/utils/richTextSanitize.ts b/packages/core/src/utils/richTextSanitize.ts index 4afaeab0c1..dc21b69dde 100644 --- a/packages/core/src/utils/richTextSanitize.ts +++ b/packages/core/src/utils/richTextSanitize.ts @@ -85,7 +85,8 @@ const OPAQUE_TAGS = new Set([ ]); /** Anything that reaches out of the stylesheet, in a property that should not. */ -const UNSAFE_VALUE = /url\(|expression\(|javascript:|vbscript:|@import|<\//i; +const UNSAFE_VALUE = /javascript:|vbscript:|@import|<\//i; +const RESOURCE_FUNCTION = /(?:url|src|image|image-set|cross-fade|element|expression)\(/i; const ELEMENT_NODE = 1; const TEXT_NODE = 3; @@ -108,7 +109,8 @@ export function isRichTextFormattingStyle(property: string, value: string): bool return ( FORMATTING_STYLE_PROPS.has(property.toLowerCase()) && value.length > 0 && - !UNSAFE_VALUE.test(value) + !UNSAFE_VALUE.test(value) && + !RESOURCE_FUNCTION.test(withoutPlainStrings(value)) ); } @@ -190,7 +192,7 @@ function stripAttributes(element: Element): void { /** Keep only the allowlisted declarations, and only if their values are inert. */ function filterStyle(style: string): string { - return splitDeclarations(style) + return (splitDeclarations(style) ?? []) .map((declaration) => { const colon = declaration.indexOf(":"); if (colon === -1) return null; @@ -203,42 +205,32 @@ function filterStyle(style: string): string { .join("; "); } -function isQuoteDelimiter(char: string): char is "'" | '"' { - return char === "'" || char === '"'; -} +const PLAIN_STRING = /"[^"\\\n\r\f]*"|'[^'\\\n\r\f]*'/g; +const withoutPlainStrings = (text: string) => + text.replace(PLAIN_STRING, (string) => "_".repeat(string.length)); +// Outside plain strings: an escape, a stray or broken quote, a comment, a bracket no formatting value needs. +const READ_UNLIKE_CSS = /[\\"'{}[\]]|\/\*/; -function nextParenthesisDepth(depth: number, char: string): number { - if (char === "(") return depth + 1; - if (char === ")") return Math.max(0, depth - 1); - return depth; -} - -function isDeclarationSeparator(char: string, depth: number, quote: "'" | '"' | null): boolean { - return char === ";" && depth === 0 && quote === null; -} - -/** - * Split on the semicolons that separate declarations, not the ones inside a - * value. `color: rgb(1, 2, 3)` is one declaration however many separators its - * value contains. - */ -function splitDeclarations(style: string): string[] { +/** Declarations split where a browser splits them, or null for text this split could read differently from CSS. */ +function splitDeclarations(style: string): string[] | null { + const bare = withoutPlainStrings(style); + if (READ_UNLIKE_CSS.test(bare) || !bracketsCloseWithoutSemicolon(bare)) return null; const declarations: string[] = []; - let current = ""; - let depth = 0; - let quote: "'" | '"' | null = null; - for (const char of style) { - if (char === quote) quote = null; - else if (quote === null && isQuoteDelimiter(char)) quote = char; - else if (isDeclarationSeparator(char, depth, quote)) { - declarations.push(current); - current = ""; - continue; - } else if (quote === null) { - depth = nextParenthesisDepth(depth, char); - } - current += char; + let start = 0; + for (let end = bare.indexOf(";"); end !== -1; end = bare.indexOf(";", start)) { + declarations.push(style.slice(start, end)); + start = end + 1; } - if (current.trim()) declarations.push(current); - return declarations; + declarations.push(style.slice(start)); + return declarations.filter((declaration) => declaration.trim()); +} + +function bracketsCloseWithoutSemicolon(bare: string): boolean { + let depth = 0; + for (const char of bare) { + if (char === "(") depth++; + else if (char === ")") depth--; + if (depth < 0 || (depth > 0 && char === ";")) return false; + } + return depth === 0; } From f43c35c21de1ad63fb638261947afd0abc25551a Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Tue, 24 Nov 2026 08:27:19 +0000 Subject: [PATCH 247/367] fix(engine): read playlists in linear time and bound the whole walk (#8653) * fix(engine): read playlists in linear time and bound the whole walk The trailing-blank trim and the ffconcat file pattern backtracked, so one very long line took quadratic time on the event loop. Both are now single scans. A line longer than ffmpeg reads (4095 bytes) refuses the list before it is parsed, and the walk refuses past 16 MiB of list text or 50,000 entries across all nested lists. * test(engine): playlist walks finish in milliseconds and stop at their budget Covers a single 8 MiB line in both list shapes, the 4095-byte line limit, ffconcat file lines read as before, and the entry and byte budgets across nested lists. * refactor(engine): keep the playlist parser at its comment share --- .../engine/src/utils/notMediaPayload.test.ts | 68 ++++++++++++++- packages/engine/src/utils/notMediaPayload.ts | 82 ++++++++++++++----- 2 files changed, 129 insertions(+), 21 deletions(-) diff --git a/packages/engine/src/utils/notMediaPayload.test.ts b/packages/engine/src/utils/notMediaPayload.test.ts index 3a4719b1a6..ebe8f4fc08 100644 --- a/packages/engine/src/utils/notMediaPayload.test.ts +++ b/packages/engine/src/utils/notMediaPayload.test.ts @@ -389,6 +389,72 @@ describe("playlistLeavesItsFolder", () => { }); }); +describe("playlistLeavesItsFolder takes time linear in the list, and bounds the walk", () => { + // Just under the size the walk reads whole, so the list is parsed rather than refused for its size. + const FILL = 8 * 1024 * 1024 - 64; + const segments = (...names: string[]) => + `#EXTM3U\n${names.map((n) => `#EXTINF:1,\n${n}\n`).join("")}`; + + it.each([ + ["an HLS line of blanks ending in one other character", `#EXTM3U\n${" ".repeat(FILL)}x\n`], + [ + "an ffconcat file line of blanks with a lone carriage return inside", + `ffconcat version 1.0\nfile${" ".repeat(FILL)}x\ry\n`, + ], + ])("refuses %s in milliseconds", async (_name, contents) => { + const file = writeFixture("photo.png", contents); + const started = performance.now(); + expect(await playlistLeavesItsFolder(file)).toBe(true); + expect(performance.now() - started).toBeLessThan(1000); + }); + + it("reads a line as long as ffmpeg reads, and refuses one byte longer", async () => { + // 4095 bytes is ffmpeg's line limit; neither name exists, so only the length decides. + const atLimit = writeFixture("clip.m3u8", segments(`${"a".repeat(4092)}.ts`)); + expect(await playlistLeavesItsFolder(atLimit)).toBe(false); + const over = writeFixture("clip.m3u8", segments(`${"a".repeat(4093)}.ts`)); + expect(await playlistLeavesItsFolder(over)).toBe(true); + const concatOver = writeFixture( + "clip.ffconcat", + `ffconcat version 1.0\nfile ${"a".repeat(4091)}\n`, + ); + expect(await playlistLeavesItsFolder(concatOver)).toBe(true); + }); + + it("reads an ffconcat file line as before: blanks and carriage returns between file and the name", async () => { + const list = (line: string) => writeFixture("clip.ffconcat", `ffconcat version 1.0\n${line}\n`); + expect(await playlistLeavesItsFolder(list(" file \r\t../other/out.mp4"))).toBe(true); + expect(await playlistLeavesItsFolder(list("file\t'../other/out.mp4' "))).toBe(true); + expect(await playlistLeavesItsFolder(list("file'../other/out.mp4'"))).toBe(false); + expect(await playlistLeavesItsFolder(list("files ../other/out.mp4"))).toBe(false); + expect(await playlistLeavesItsFolder(list("file part.mp4"))).toBe(false); + }); + + it("refuses a walk past its entry budget, before it opens any entry", async () => { + const names = Array.from({ length: 50_001 }, (_, i) => `s${i}.ts`); + expect(await playlistLeavesItsFolder(writeFixture("clip.m3u8", segments(...names)))).toBe(true); + expect( + await playlistLeavesItsFolder(writeFixture("clip.m3u8", segments(...names.slice(0, 1000)))), + ).toBe(false); + }); + + it("refuses a walk past its byte budget across nested lists", async () => { + // Three nested lists of 6 MiB each: every one is readable alone, together they pass 16 MiB. + const padding = `#${"x".repeat(4000)}\n`.repeat(Math.ceil((6 * 1024 * 1024) / 4002)); + const files: Record = { + "master.m3u8": + "#EXTM3U\n" + + ["a", "b", "c"].map((n) => `#EXT-X-STREAM-INF:BANDWIDTH=1\n${n}.m3u8\n`).join(""), + }; + for (const n of ["a", "b", "c"]) files[`${n}.m3u8`] = `#EXTM3U\n${padding}#EXTINF:1,\nseg.ts\n`; + expect(await playlistLeavesItsFolder(writeTree(files))).toBe(true); + delete files["c.m3u8"]; + files["master.m3u8"] = + "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\na.m3u8\n#EXT-X-STREAM-INF:BANDWIDTH=1\nb.m3u8\n"; + expect(await playlistLeavesItsFolder(writeTree(files))).toBe(false); + }); +}); + describe("playlistLeavesItsFolder reads entries and folders as ffmpeg resolves them", () => { const hls = (...lines: string[]) => ["#EXTM3U", ...lines, "#EXT-X-ENDLIST"].join("\n"); const listIn = (folder: string, contents: string | Buffer, name = "list.m3u8"): string => { @@ -528,8 +594,6 @@ describe("playlistLeavesItsFolder reads a list as ffprobe does", () => { expect(await playlistLeavesItsFolder(unreadable)).toBe(true); const missing = writeTree({ "clip.m3u8": list("gone.ts") }); expect(await playlistLeavesItsFolder(missing)).toBe(false); - const tooLong = writeTree({ "clip.m3u8": list("a".repeat(5000)) }); - expect(await playlistLeavesItsFolder(tooLong)).toBe(false); }); it.skipIf(process.platform !== "linux")( diff --git a/packages/engine/src/utils/notMediaPayload.ts b/packages/engine/src/utils/notMediaPayload.ts index 132cd3d2a5..3d0258fd43 100644 --- a/packages/engine/src/utils/notMediaPayload.ts +++ b/packages/engine/src/utils/notMediaPayload.ts @@ -313,30 +313,53 @@ export async function isNotImagePayload(filePath: string): Promise { const MAX_PLAYLIST_BYTES = 8 * 1024 * 1024; const MAX_PLAYLIST_DEPTH = 8; +// The whole walk, nested lists included, is refused past these, so its cost never depends on what a list holds. +const MAX_WALK_BYTES = 2 * MAX_PLAYLIST_BYTES; +const MAX_WALK_ENTRIES = 50_000; const HTTP_URL = /^https?:\/\//i; const COLON_IN_FIRST_SEGMENT = /^[^/\\?#]*:/; const FOLDER_CUT_AT_QUERY_OR_FRAGMENT = /[?#]/; -// ffmpeg reads a playlist line into a 4096-byte buffer and drops the rest of it. -const MAX_HLS_LINE_BYTES = 4095; +// ffmpeg reads a list line into a 4096-byte buffer, so a longer line would name something else: it is refused unread. +const MAX_LIST_LINE_BYTES = 4095; const ATTRIBUTE_GAP = /[\t\n\v\f\r ,]/; +const SPACE = /\s/; +const TRAILING_HLS_BLANK = /[\t\v\f ]/; + +function withoutTrailing(line: string, isBlank: RegExp): string { + let end = line.length; + while (end > 0 && isBlank.test(line[end - 1]!)) end--; + return line.slice(0, end); +} /** - * Every name an HLS list can open, read as ffmpeg's hls demuxer reads it and also as written. - * The text is latin1, one character per byte, so a line is cut where ffmpeg cuts it. + * Every name an HLS list can open, read as ffmpeg's hls demuxer reads it; true when a line is too long to read + * whole. The text is latin1, one character per byte, so a line's length is its length in bytes. */ -function hlsEntries(body: string): string[] { +function hlsEntries(body: string): string[] | true { const names = new Set(); for (const raw of body.replaceAll("\0", "\n").split(/[\r\n]/)) { - for (const whole of new Set([raw, raw.slice(0, MAX_HLS_LINE_BYTES)])) { - const line = whole.replace(/[\t\v\f ]+$/, ""); - const found = line.startsWith("#") ? attributeUris(line) : [line, line.trim()]; - for (const name of found) if (name) names.add(name); - } + if (raw.length > MAX_LIST_LINE_BYTES) return true; + const line = withoutTrailing(raw, TRAILING_HLS_BLANK); + const found = line.startsWith("#") ? attributeUris(line) : [line, line.trim()]; + for (const name of found) if (name) names.add(name); } return [...names]; } +/** The name an ffconcat `file` line gives, as `/^\s*file\s+(.*)$/` would match it, in one pass; undefined for any other line. */ +function concatFileName(raw: string): string | undefined { + let at = 0; + while (at < raw.length && SPACE.test(raw[at]!)) at++; + if (!raw.startsWith("file", at)) return undefined; + let rest = at + 4; + while (rest < raw.length && SPACE.test(raw[rest]!)) rest++; + // `\s+` needs one blank, and `.` matches no carriage return, so one left past the blanks fails the match. + if (rest === at + 4 || raw.includes("\r", rest)) return undefined; + const value = raw.slice(rest).trim(); + return value.startsWith("'") ? value.slice(1, -1).replace(/\\(.)/g, "$1") : value; +} + /** `URI=` values of a tag, split as ffmpeg's `ff_parse_key_value` splits them. */ function attributeUris(line: string): string[] { const uris: string[] = []; @@ -373,16 +396,18 @@ function attributeValue(line: string, at: number): [string, number] { const UTF8_BOM = "\xEF\xBB\xBF"; -function playlistEntries(text: string): string[] | undefined { +/** The names a list can open; true when a line is too long to read whole; undefined when the text is no list. */ +function playlistEntries(text: string): string[] | true | undefined { const body = (text.startsWith(UTF8_BOM) ? text.slice(UTF8_BOM.length) : text).trimStart(); if (body.startsWith("#EXTM3U")) return hlsEntries(body); if (/^ffconcat\s+version/i.test(body)) { - return body.split(/\r?\n/).flatMap((raw) => { - const match = /^\s*file\s+(.*)$/.exec(raw); - if (!match) return []; - const value = match[1]!.trim(); - return [value.startsWith("'") ? value.slice(1, -1).replace(/\\(.)/g, "$1") : value]; - }); + const names: string[] = []; + for (const raw of body.split(/\r?\n/)) { + if (raw.length > MAX_LIST_LINE_BYTES) return true; + const name = concatFileName(raw); + if (name !== undefined) names.push(name); + } + return names; } return undefined; } @@ -414,6 +439,8 @@ interface Walk { folder: string; seen: Set; verdicts: Map; + bytes: number; + entries: number; } /** @@ -425,7 +452,13 @@ export async function playlistLeavesItsFolder( placedAt = filePath, ): Promise { const placed = asBytes(resolve(placedAt)); - const walk: Walk = { folder: dirname(placed), seen: new Set(), verdicts: new Map() }; + const walk: Walk = { + folder: dirname(placed), + seen: new Set(), + verdicts: new Map(), + bytes: 0, + entries: 0, + }; try { return await listLeaves(asBytes(resolve(filePath)), placed, walk, 0); } catch { @@ -495,6 +528,15 @@ const isMissing = (error: unknown): boolean => (error as NodeJS.ErrnoException | null)?.code ?? "", ); +/** A list's entries, counted against the walk's budget; true when the list or the walk must be refused. */ +function budgetedEntries(text: string, walk: Walk): string[] | true { + walk.bytes += text.length; + const entries = playlistEntries(text) ?? []; + if (entries === true) return true; + walk.entries += entries.length; + return walk.bytes > MAX_WALK_BYTES || walk.entries > MAX_WALK_ENTRIES ? true : entries; +} + /** Every list a list names is read too, against the top list's folder. A nested file that exists but cannot be read is refused. */ async function listLeaves( readPath: string, @@ -509,7 +551,9 @@ async function listLeaves( if (text === true || depth >= MAX_PLAYLIST_DEPTH) return true; if (walk.seen.has(path)) return false; walk.seen.add(path); - for (const entry of playlistEntries(text) ?? []) { + const entries = budgetedEntries(text, walk); + if (entries === true) return true; + for (const entry of entries) { if (await entryLeaves(entry, dirname(path), walk, depth)) return true; } return false; From bfadf5b2b32814c36ada261428fb4e2d9c1317f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 08:31:39 +0000 Subject: [PATCH 248/367] fix(cli): lambda deploy and destroy use only the checkout the CLI itself is in (#8664) A folder above the CLI's own package that holds packages/aws-lambda no longer counts as a checkout, and a source checkout is named before it is built or deployed from. --- .../cli/src/commands/lambda/deploy.test.ts | 3 + packages/cli/src/commands/lambda/deploy.ts | 1 + .../cli/src/commands/lambda/destroy.test.ts | 16 ++++- packages/cli/src/commands/lambda/destroy.ts | 1 + .../cli/src/commands/lambda/repoRoot.test.ts | 69 ++++++++++++++++++- packages/cli/src/commands/lambda/repoRoot.ts | 51 ++++++++++---- 6 files changed, 122 insertions(+), 19 deletions(-) diff --git a/packages/cli/src/commands/lambda/deploy.test.ts b/packages/cli/src/commands/lambda/deploy.test.ts index baddc13524..de49e52c46 100644 --- a/packages/cli/src/commands/lambda/deploy.test.ts +++ b/packages/cli/src/commands/lambda/deploy.test.ts @@ -69,6 +69,9 @@ describe("runDeploy", () => { await runDeploy({ skipBuild: true, videoArch: "x86_64" }); expect(vi.mocked(samDeploy).mock.calls[0]?.[0]).toMatchObject({ samDir }); + expect(vi.mocked(console.log).mock.calls.flat().join("\n")).toContain( + `Using the source checkout at ${dir}`, + ); expect(vi.mocked(samDeploy).mock.calls[0]?.[0].videoImageUri).toBeUndefined(); expect(pushVideoImage).not.toHaveBeenCalled(); }); diff --git a/packages/cli/src/commands/lambda/deploy.ts b/packages/cli/src/commands/lambda/deploy.ts index 375bd72662..84125ff964 100644 --- a/packages/cli/src/commands/lambda/deploy.ts +++ b/packages/cli/src/commands/lambda/deploy.ts @@ -153,6 +153,7 @@ function warmVideoFunction(functionName: string | undefined, args: DeployArgs): /** Checkout: build the ZIP from source. Otherwise: stage the adapter's pinned prebuilt ZIP. */ async function prepareSamDir(root: string | undefined, args: DeployArgs): Promise { if (!root) return stagePrebuiltHandler(); + console.log(c.dim(terminalText(`→ Using the source checkout at ${root}`))); const samDir = dirname(locateSamTemplate(root)); if (!args.skipBuild) { console.log(c.dim("→ Building handler ZIP")); diff --git a/packages/cli/src/commands/lambda/destroy.test.ts b/packages/cli/src/commands/lambda/destroy.test.ts index dc2fcc6089..4f0d27a6c2 100644 --- a/packages/cli/src/commands/lambda/destroy.test.ts +++ b/packages/cli/src/commands/lambda/destroy.test.ts @@ -5,7 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { stateFilePath, writeStackOutputs } from "./state.js"; const samDirs = vi.hoisted(() => [] as string[]); -vi.mock("./repoRoot.js", () => ({ repoRoot: () => undefined })); +const root = vi.hoisted(() => ({ value: undefined as string | undefined })); +vi.mock("./repoRoot.js", () => ({ repoRoot: () => root.value })); vi.mock("./sam.js", () => ({ samDelete: vi.fn((opts: { samDir: string }) => { samDirs.push(opts.samDir); @@ -36,6 +37,7 @@ beforeEach(() => { afterEach(() => { quiet.mockRestore(); + root.value = undefined; process.chdir(previousCwd); rmSync(cwd, { recursive: true, force: true }); }); @@ -62,6 +64,18 @@ describe("runDestroy", () => { expect(existsSync(stateFilePath("Demo", cwd))).toBe(false); }); + it("in a source checkout, says which checkout it deletes from and runs sam there", async () => { + writeStackOutputs(stack, cwd); + root.value = cwd; + + await runDestroy({ stackName: "Demo" }); + + expect(samDirs).toEqual([join(cwd, "examples", "aws-lambda")]); + expect(vi.mocked(console.log).mock.calls.flat().join("\n")).toContain( + `Using the source checkout at ${cwd}`, + ); + }); + it("deletes the stack's own video repository, whatever name the state file records", async () => { writeStackOutputs({ ...stack, videoRepository: "someone-elses-repo" }, cwd); diff --git a/packages/cli/src/commands/lambda/destroy.ts b/packages/cli/src/commands/lambda/destroy.ts index 821655a647..5e54b1010b 100644 --- a/packages/cli/src/commands/lambda/destroy.ts +++ b/packages/cli/src/commands/lambda/destroy.ts @@ -30,6 +30,7 @@ export async function runDestroy(args: DestroyArgs): Promise { c.dim(terminalText(`→ sam delete (stack=${stack.stackName} region=${stack.region})`)), ); const root = repoRoot(); + if (root) console.log(c.dim(terminalText(`→ Using the source checkout at ${root}`))); const awsProfile = args.awsProfile ?? process.env.AWS_PROFILE; // Mirror deploy.ts's AWS_PROFILE env fallback — `AWS_PROFILE=prod // hyperframes lambda destroy` should hit the same account `deploy` diff --git a/packages/cli/src/commands/lambda/repoRoot.test.ts b/packages/cli/src/commands/lambda/repoRoot.test.ts index 9642c69b89..fc915e0f6f 100644 --- a/packages/cli/src/commands/lambda/repoRoot.test.ts +++ b/packages/cli/src/commands/lambda/repoRoot.test.ts @@ -1,6 +1,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; import { afterEach, describe, expect, it, vi } from "vitest"; import { repoRoot } from "./repoRoot.js"; @@ -17,10 +18,20 @@ describe("repoRoot", () => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); + const writePackage = (dir: string, name: string) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "package.json"), JSON.stringify({ name })); + }; + // A tree that looks like a checkout: the adapter package and its SAM template. + const plantCheckout = (root: string) => { + writePackage(join(root, "packages", "aws-lambda"), "@hyperframes/aws-lambda"); + mkdirSync(join(root, "examples", "aws-lambda"), { recursive: true }); + writeFileSync(join(root, "examples", "aws-lambda", "template.yaml"), "Resources: {}\n"); + }; + it("returns HYPERFRAMES_REPO_ROOT when it is a hyperframes checkout", () => { const root = tempDir(); - mkdirSync(join(root, "packages", "aws-lambda"), { recursive: true }); - writeFileSync(join(root, "packages", "aws-lambda", "package.json"), "{}"); + writePackage(join(root, "packages", "aws-lambda"), "@hyperframes/aws-lambda"); vi.stubEnv("HYPERFRAMES_REPO_ROOT", root); expect(repoRoot()).toBe(root); }); @@ -31,4 +42,56 @@ describe("repoRoot", () => { expect(() => repoRoot()).toThrow("HYPERFRAMES_REPO_ROOT is not a hyperframes checkout"); expect(() => repoRoot()).not.toThrow(root); }); + + it("throws on a HYPERFRAMES_REPO_ROOT whose packages/aws-lambda is another package", () => { + const root = tempDir(); + writePackage(join(root, "packages", "aws-lambda"), "not-hyperframes"); + vi.stubEnv("HYPERFRAMES_REPO_ROOT", root); + expect(() => repoRoot()).toThrow("HYPERFRAMES_REPO_ROOT is not a hyperframes checkout"); + }); + + // fails without the fix: the old walk took the planted folder above the install as the checkout. + it("ignores a checkout planted in a folder above an installed CLI", () => { + const drive = tempDir(); + plantCheckout(drive); + const cli = join(drive, "Users", "me", "npm", "node_modules", "@hyperframes", "cli"); + writePackage(cli, "@hyperframes/cli"); + mkdirSync(join(cli, "dist"), { recursive: true }); + expect(repoRoot(join(cli, "dist"))).toBeUndefined(); + }); + + it("ignores an adapter package two folders above a CLI that is not under packages/", () => { + const drive = tempDir(); + plantCheckout(drive); + const cli = join(drive, "tools", "cli"); + writePackage(cli, "@hyperframes/cli"); + expect(repoRoot(join(cli, "dist"))).toBeUndefined(); + }); + + it("ignores a checkout when this module is bundled into another package", () => { + const root = tempDir(); + plantCheckout(root); + writePackage(join(root, "packages", "app"), "someone-elses-app"); + expect(repoRoot(join(root, "packages", "app", "dist"))).toBeUndefined(); + }); + + it("returns the checkout the CLI's own package sits in", () => { + const root = tempDir(); + plantCheckout(root); + writePackage(join(root, "packages", "cli"), "@hyperframes/cli"); + mkdirSync(join(root, "packages", "cli", "dist"), { recursive: true }); + expect(repoRoot(join(root, "packages", "cli", "dist"))).toBe(root); + }); + + it("returns undefined when the CLI's checkout has no adapter package", () => { + const root = tempDir(); + writePackage(join(root, "packages", "cli"), "@hyperframes/cli"); + writePackage(join(root, "packages", "aws-lambda"), "something-else"); + expect(repoRoot(join(root, "packages", "cli", "src"))).toBeUndefined(); + }); + + it("finds this repository from its own source", () => { + const here = dirname(fileURLToPath(import.meta.url)); + expect(repoRoot()).toBe(resolve(here, "..", "..", "..", "..", "..")); + }); }); diff --git a/packages/cli/src/commands/lambda/repoRoot.ts b/packages/cli/src/commands/lambda/repoRoot.ts index 13de3aac17..ecc5e2f5ea 100644 --- a/packages/cli/src/commands/lambda/repoRoot.ts +++ b/packages/cli/src/commands/lambda/repoRoot.ts @@ -3,32 +3,53 @@ * to find `examples/aws-lambda/template.yaml` and the handler ZIP build * script. * - * Walks up from this file's location until it finds a directory that - * contains `packages/aws-lambda/`. Undefined outside a checkout (the - * published CLI), where deploy uses the adapter's prebuilt handler. + * Only the checkout this CLI itself sits in counts: `/packages/cli` + * must be the running CLI's own package, and `/packages/aws-lambda` + * must be the adapter package. Undefined for a published install, where + * deploy uses the adapter's prebuilt handler. */ -import { existsSync } from "node:fs"; -import { dirname, resolve } from "node:path"; +import { existsSync, readFileSync } from "node:fs"; +import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -export function repoRoot(): string | undefined { +const CLI_PACKAGE = "@hyperframes/cli"; +const LAMBDA_PACKAGE = "@hyperframes/aws-lambda"; + +export function repoRoot( + moduleDir: string = dirname(fileURLToPath(import.meta.url)), +): string | undefined { const override = process.env.HYPERFRAMES_REPO_ROOT; if (override) { - if (existsSync(resolve(override, "packages", "aws-lambda", "package.json"))) return override; + if (packageName(resolve(override, "packages", "aws-lambda")) === LAMBDA_PACKAGE) + return override; throw new Error( "[hyperframes lambda] HYPERFRAMES_REPO_ROOT is not a hyperframes checkout " + - "(no packages/aws-lambda/package.json there). Point it at the repo root, or unset it.", + `(no ${LAMBDA_PACKAGE} package at packages/aws-lambda there). Point it at the repo root, or unset it.`, ); } - let dir = dirname(fileURLToPath(import.meta.url)); - for (let depth = 0; depth < 12; depth++) { - if (existsSync(resolve(dir, "packages", "aws-lambda", "package.json"))) { - return dir; - } + const cliDir = ownPackageDir(moduleDir); + if (!cliDir || packageName(cliDir) !== CLI_PACKAGE) return undefined; + const packagesDir = dirname(cliDir); + if (basename(packagesDir) !== "packages") return undefined; + const root = dirname(packagesDir); + return packageName(join(root, "packages", "aws-lambda")) === LAMBDA_PACKAGE ? root : undefined; +} + +/** The nearest folder at or above `dir` holding a package.json: this module's own package. */ +function ownPackageDir(dir: string): string | undefined { + for (;;) { + if (existsSync(join(dir, "package.json"))) return dir; const parent = dirname(dir); - if (parent === dir) break; + if (parent === dir) return undefined; dir = parent; } - return undefined; +} + +function packageName(dir: string): unknown { + try { + return (JSON.parse(readFileSync(join(dir, "package.json"), "utf8")) as { name?: unknown }).name; + } catch { + return undefined; + } } From e6ba081bb964db593b82ac0cec146f34611b0f3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 08:36:39 +0000 Subject: [PATCH 249/367] fix(studio): property panel corner radius and copied source line read a sealed preview (#8662) * test(studio): property panel corner radii and source line read the same sealed * fix(studio): property panel corner radius and copied source line read a sealed preview * refactor(studio): the panel's sealed reads live in their own module, under the file-size cap --- .../src/components/editor/PropertyPanel.tsx | 22 ++- .../components/editor/propertyPanelHelpers.ts | 85 ----------- .../propertyPanelSealedReads.browser.test.ts | 93 ++++++++++++ .../editor/propertyPanelSealedReads.ts | 136 ++++++++++++++++++ .../studio/src/player/lib/previewChannel.ts | 16 ++- 5 files changed, 257 insertions(+), 95 deletions(-) create mode 100644 packages/studio/src/components/editor/propertyPanelSealedReads.browser.test.ts create mode 100644 packages/studio/src/components/editor/propertyPanelSealedReads.ts diff --git a/packages/studio/src/components/editor/PropertyPanel.tsx b/packages/studio/src/components/editor/PropertyPanel.tsx index 645b4988d5..b561a29b56 100644 --- a/packages/studio/src/components/editor/PropertyPanel.tsx +++ b/packages/studio/src/components/editor/PropertyPanel.tsx @@ -7,13 +7,11 @@ import { useStudioShellContext } from "../../contexts/StudioContext"; import { readStudioBoxSize } from "./manualEdits"; import { readMoveOffset, readShownRotation } from "./plainTranslate"; import { - buildElementInfoText, EMPTY_STYLES, formatPxMetricValue, parsePxMetricValue, RESPONSIVE_GRID, readGsapRuntimeValuesForPanel, - readGsapBorderRadiusForPanel, isSelectedElementHidden, selectionIdentityKey, } from "./propertyPanelHelpers"; @@ -37,6 +35,11 @@ import { TimingSection } from "./propertyPanelTimingSection"; import { type PropertyPanelProps } from "./propertyPanelHelpers"; import { GestureRecordPanelButton } from "./GestureRecordControl"; import { PropertyPanelEmptyState } from "./PropertyPanelEmptyState"; +import { + readElementInfoText, + readGsapBorderRadiusForPanel, + useAnswered, +} from "./propertyPanelSealedReads"; import { DesignPanelInputProvider } from "../../contexts/DesignPanelInputContext"; import { isAudioDomElement } from "../../utils/timelineInspector"; import { useManualEditDisabledFlags } from "./previewReadOnlyContext"; @@ -144,14 +147,20 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelPro // eslint-disable-next-line react-hooks/exhaustive-deps -- iframeRef is stable; currentTime drives re-reads during playback [gsapAnimIdForMemo, gsapAnimations, element, currentTime, sealedReads], ); - const gsapBorderRadius = useMemo( + const borderRadiusRead = useMemo( () => element - ? readGsapBorderRadiusForPanel(gsapRuntimeValues, gsapAnimations, element, iframeRef) + ? readGsapBorderRadiusForPanel( + gsapRuntimeValues, + gsapAnimations, + element, + iframeRef.current, + ) : null, // eslint-disable-next-line react-hooks/exhaustive-deps [gsapRuntimeValues, gsapAnimations, element, currentTime], ); + const gsapBorderRadius = useAnswered(borderRadiusRead, element); // The 3D Transform panel should be reachable on ANY element, not only ones GSAP is // already animating — otherwise you can't add depth/rotation to a fresh static // element (the panel never appears, the classic chicken-and-egg). Default to @@ -236,11 +245,10 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelPro const displayR = gsapRuntimeValues?.rotation ?? manualRotation.angle; const handleCopyElementInfo = () => { - const text = buildElementInfoText(element, sourceLabel, gsapAnimations, previewIframeRef); // Claim the copy only once the write actually lands — a denied clipboard // permission otherwise reports a copy that never happened. - navigator.clipboard - .writeText(text) + void readElementInfoText(element, sourceLabel, gsapAnimations, previewIframeRef?.current) + .then((text) => navigator.clipboard.writeText(text)) .then(() => { showToast(`Copied element info for ${element.label}. Paste it into any AI agent`, "info"); setClipboardCopied(true); diff --git a/packages/studio/src/components/editor/propertyPanelHelpers.ts b/packages/studio/src/components/editor/propertyPanelHelpers.ts index c0e341f7c1..75c5371878 100644 --- a/packages/studio/src/components/editor/propertyPanelHelpers.ts +++ b/packages/studio/src/components/editor/propertyPanelHelpers.ts @@ -506,88 +506,3 @@ export function readGsapRuntimeValuesForPanel( return null; } } - -export function readGsapBorderRadiusForPanel( - gsapRuntimeValues: Record | null, - gsapAnimations: GsapAnimation[], - element: DomEditSelection, - previewIframeRef: React.RefObject, -): { tl: number; tr: number; br: number; bl: number } | null { - if (!gsapRuntimeValues || !("borderRadius" in gsapRuntimeValues)) { - const hasBRProp = gsapAnimations.some( - (a) => - "borderRadius" in a.properties || - a.keyframes?.keyframes.some((kf) => "borderRadius" in kf.properties), - ); - if (!hasBRProp) return null; - } - const iframe = previewIframeRef?.current; - if (!iframe?.contentDocument) return null; - try { - const el = findPreviewNode(iframe.contentDocument, element); - if (!el || !iframe.contentWindow) return null; - const cs = iframe.contentWindow.getComputedStyle(el); - const parse = (v: string) => Number.parseFloat(v) || 0; - return { - tl: parse(cs.borderTopLeftRadius), - tr: parse(cs.borderTopRightRadius), - br: parse(cs.borderBottomRightRadius), - bl: parse(cs.borderBottomLeftRadius), - }; - } catch { - return null; - } -} - -/** - * Builds the multi-line "element info" text copied to the clipboard for an AI - * agent. Shared by both the legacy and flat inspector headers (the flat split - * needs the same string), so it lives here rather than as a PropertyPanel - * closure. Pure — the caller owns the clipboard write, toast, and copied state. - */ -// fallow-ignore-next-line complexity -export function buildElementInfoText( - element: DomEditSelection, - sourceLabel: string, - gsapAnimations: GsapAnimation[], - previewIframeRef?: React.RefObject, -): string { - const file = element.sourceFile ?? "index.html"; - let lineNum: number | null = null; - try { - const src = previewIframeRef?.current?.contentDocument?.documentElement?.outerHTML ?? ""; - if (src && element.id) { - const idx = src.indexOf(`id="${element.id}"`); - if (idx > -1) lineNum = src.slice(0, idx).split("\n").length; - } - if (!lineNum && element.selector) { - const tag = element.tagName.toLowerCase(); - const cls = element.selector.startsWith(".") ? element.selector.slice(1).split(".")[0] : null; - const search = cls ? `class="${cls}` : `<${tag}`; - const idx = src.indexOf(search); - if (idx > -1) lineNum = src.slice(0, idx).split("\n").length; - } - } catch {} - const fileLoc = lineNum ? `${file}:${lineNum}` : file; - const lines = [ - `Element: ${element.label} (${sourceLabel})`, - `File: ${fileLoc}`, - `Position: x=${Math.round(element.boundingBox.x)}, y=${Math.round(element.boundingBox.y)}`, - `Size: ${Math.round(element.boundingBox.width)}×${Math.round(element.boundingBox.height)}`, - `Tag: <${element.tagName}>`, - ]; - if (element.computedStyles["z-index"] && element.computedStyles["z-index"] !== "auto") { - lines.push(`Z-index: ${element.computedStyles["z-index"]}`); - } - if (gsapAnimations.length > 0) { - const anim = gsapAnimations[0]; - lines.push( - `Animation: ${anim.method}() ${anim.duration}s at ${anim.position}s, ease: ${anim.ease ?? "default"}`, - ); - const props = Object.entries(anim.properties) - .map(([k, v]) => `${k}: ${v}`) - .join(", "); - if (props) lines.push(`Properties: ${props}`); - } - return lines.join("\n"); -} diff --git a/packages/studio/src/components/editor/propertyPanelSealedReads.browser.test.ts b/packages/studio/src/components/editor/propertyPanelSealedReads.browser.test.ts new file mode 100644 index 0000000000..9d381f5317 --- /dev/null +++ b/packages/studio/src/components/editor/propertyPanelSealedReads.browser.test.ts @@ -0,0 +1,93 @@ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import type { Browser } from "puppeteer-core"; +import { afterAll, beforeAll, expect, it, vi } from "vitest"; +import { closeTestChrome, launchTestChrome } from "../../../tests/chromeTestUtils"; +import { buildStudioBundle, openPreview } from "../../../tests/sealedPreviewHarness"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); +const require = createRequire(import.meta.url); +const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"]; +let browser: Browser; +let studioBundle: string; + +beforeAll(async () => { + browser = await launchTestChrome(); + studioBundle = await buildStudioBundle([ + `export { readElementInfoText, readGsapBorderRadiusForPanel } from "./components/editor/propertyPanelSealedReads";`, + ]); +}); + +afterAll(() => closeTestChrome(browser)); + +function previewHtml(): string { + const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8"); + const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); + return ` + + + +
+
Intro
+
+
+ + + `; +} + +async function panelReads(mode: string) { + const preview = await openPreview(browser, studioBundle, previewHtml(), mode); + try { + await preview.seek(2); + return await preview.page.evaluate(async () => { + type Studio = { + previewRequest( + iframe: HTMLIFrameElement, + kind: "query", + params: { selector: string }, + ): Promise<{ matches: Array<{ handle: string }> } | null>; + readGsapBorderRadiusForPanel(...args: unknown[]): unknown; + readElementInfoText(...args: unknown[]): Promise; + }; + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const iframe = document.querySelector("iframe")!; + const query = await studio.previewRequest(iframe, "query", { selector: "#card" }); + const element = { + element: null, + handle: query?.matches[0]?.handle, + id: "card", + selector: "#card", + sourceFile: "index.html", + tagName: "div", + label: "card", + boundingBox: { x: 0, y: 0, width: 400, height: 300 }, + computedStyles: {}, + }; + const animations = [{ properties: { borderRadius: "40px 80px 120px 20px" } }]; + const radius = await studio.readGsapBorderRadiusForPanel(null, animations, element, iframe); + const info = await studio.readElementInfoText(element, "#card", [], iframe); + return { radius, file: info.split("\n").find((line) => line.startsWith("File:")) }; + }); + } finally { + await preview.page.close(); + } +} + +it.each(MODES)( + "the property panel reads corner radii and the source line in a %s preview", + async (mode) => { + const reads = await panelReads(mode); + expect(reads.radius).toEqual({ tl: 20, tr: 40, br: 60, bl: 10 }); + expect(reads.file).toMatch(/^File: index\.html:\d+$/); + expect(reads.file).not.toBe("File: index.html:1"); + expect(reads).toEqual(await panelReads("unsealed")); + }, +); diff --git a/packages/studio/src/components/editor/propertyPanelSealedReads.ts b/packages/studio/src/components/editor/propertyPanelSealedReads.ts new file mode 100644 index 0000000000..277f8fe0f6 --- /dev/null +++ b/packages/studio/src/components/editor/propertyPanelSealedReads.ts @@ -0,0 +1,136 @@ +import { useEffect, useState } from "react"; +import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser"; +import type { DomEditSelection } from "./domEditing"; +import { findPreviewNode } from "./domEditingElement"; +import { + previewComputedStyles, + previewDocumentMarkup, + previewFrameOpaque, +} from "../../player/lib/previewChannel"; + +type PanelBorderRadius = { tl: number; tr: number; br: number; bl: number }; + +const RADIUS_CORNERS = [ + "border-top-left-radius", + "border-top-right-radius", + "border-bottom-right-radius", + "border-bottom-left-radius", +] as const; + +function cornerRadii(read: (corner: string) => string | undefined): PanelBorderRadius { + const [tl, tr, br, bl] = RADIUS_CORNERS.map( + (corner) => Number.parseFloat(read(corner) ?? "") || 0, + ); + return { tl: tl!, tr: tr!, br: br!, bl: bl! }; +} + +/** The element's computed corner radii while GSAP animates them: at once from a readable frame, else asked of it. */ +export function readGsapBorderRadiusForPanel( + gsapRuntimeValues: Record | null, + gsapAnimations: GsapAnimation[], + element: DomEditSelection, + iframe: HTMLIFrameElement | null, +): PanelBorderRadius | Promise | null { + if (!gsapRuntimeValues || !("borderRadius" in gsapRuntimeValues)) { + const hasBRProp = gsapAnimations.some( + (a) => + "borderRadius" in a.properties || + a.keyframes?.keyframes.some((kf) => "borderRadius" in kf.properties), + ); + if (!hasBRProp) return null; + } + if (!iframe) return null; + if (previewFrameOpaque(iframe)) { + if (!element.handle) return null; + return previewComputedStyles(iframe, { handle: element.handle }, [...RADIUS_CORNERS]).then( + (styles) => styles && cornerRadii((corner) => styles[corner]), + ); + } + try { + const el = iframe.contentDocument && findPreviewNode(iframe.contentDocument, element); + if (!el || !iframe.contentWindow) return null; + const cs = iframe.contentWindow.getComputedStyle(el); + return cornerRadii((corner) => cs.getPropertyValue(corner)); + } catch { + return null; + } +} + +/** + * The "element info" text copied for an AI agent, its line found in the frame's markup `src`; both inspector + * headers share it. Pure — the caller owns the clipboard write, toast, and copied state. + */ +// fallow-ignore-next-line complexity +function buildElementInfoText( + element: DomEditSelection, + sourceLabel: string, + gsapAnimations: GsapAnimation[], + src: string, +): string { + const file = element.sourceFile ?? "index.html"; + let lineNum: number | null = null; + if (src && element.id) { + const idx = src.indexOf(`id="${element.id}"`); + if (idx > -1) lineNum = src.slice(0, idx).split("\n").length; + } + if (!lineNum && element.selector) { + const tag = element.tagName.toLowerCase(); + const cls = element.selector.startsWith(".") ? element.selector.slice(1).split(".")[0] : null; + const search = cls ? `class="${cls}` : `<${tag}`; + const idx = src.indexOf(search); + if (idx > -1) lineNum = src.slice(0, idx).split("\n").length; + } + const fileLoc = lineNum ? `${file}:${lineNum}` : file; + const lines = [ + `Element: ${element.label} (${sourceLabel})`, + `File: ${fileLoc}`, + `Position: x=${Math.round(element.boundingBox.x)}, y=${Math.round(element.boundingBox.y)}`, + `Size: ${Math.round(element.boundingBox.width)}×${Math.round(element.boundingBox.height)}`, + `Tag: <${element.tagName}>`, + ]; + if (element.computedStyles["z-index"] && element.computedStyles["z-index"] !== "auto") { + lines.push(`Z-index: ${element.computedStyles["z-index"]}`); + } + if (gsapAnimations.length > 0) { + const anim = gsapAnimations[0]; + lines.push( + `Animation: ${anim.method}() ${anim.duration}s at ${anim.position}s, ease: ${anim.ease ?? "default"}`, + ); + const props = Object.entries(anim.properties) + .map(([k, v]) => `${k}: ${v}`) + .join(", "); + if (props) lines.push(`Properties: ${props}`); + } + return lines.join("\n"); +} + +export async function readElementInfoText( + element: DomEditSelection, + sourceLabel: string, + gsapAnimations: GsapAnimation[], + iframe: HTMLIFrameElement | null | undefined, +): Promise { + let src = ""; + try { + if (iframe && previewFrameOpaque(iframe)) src = (await previewDocumentMarkup(iframe)) ?? ""; + else src = iframe?.contentDocument?.documentElement?.outerHTML ?? ""; + } catch {} + return buildElementInfoText(element, sourceLabel, gsapAnimations, src); +} + +export function useAnswered( + read: T | Promise | null, + owner: unknown, +): T | null { + const [answered, setAnswered] = useState<{ owner: unknown; value: T | null } | null>(null); + useEffect(() => { + if (!(read instanceof Promise)) return; + let current = true; + void read.then((value) => current && setAnswered({ owner, value })); + return () => { + current = false; + }; + }, [read, owner]); + if (!(read instanceof Promise)) return read; + return answered && answered.owner === owner ? answered.value : null; +} diff --git a/packages/studio/src/player/lib/previewChannel.ts b/packages/studio/src/player/lib/previewChannel.ts index 4cfaecba90..8f8834d31d 100644 --- a/packages/studio/src/player/lib/previewChannel.ts +++ b/packages/studio/src/player/lib/previewChannel.ts @@ -177,12 +177,22 @@ export async function previewAssetsUnloaded(iframe: HTMLIFrameElement): Promise< return typeof reply?.unloaded === "boolean" ? reply.unloaded : null; } -export async function previewDocumentCopy(iframe: HTMLIFrameElement): Promise { +async function documentMarkup(iframe: HTMLIFrameElement) { const reply = await previewRequest(iframe, "document-markup", {}); if (typeof reply?.html !== "string" || typeof reply.baseURI !== "string") return null; - const doc = new DOMParser().parseFromString(reply.html, "text/html"); + return { html: reply.html, baseURI: reply.baseURI }; +} + +export async function previewDocumentMarkup(iframe: HTMLIFrameElement): Promise { + return (await documentMarkup(iframe))?.html ?? null; +} + +export async function previewDocumentCopy(iframe: HTMLIFrameElement): Promise { + const markup = await documentMarkup(iframe); + if (!markup) return null; + const doc = new DOMParser().parseFromString(markup.html, "text/html"); const base = doc.createElement("base"); - base.setAttribute("href", reply.baseURI); + base.setAttribute("href", markup.baseURI); doc.head.prepend(base); return doc; } From 3ce07d4b1f56dbd22e0dde06e31c6bdcb8cc8641 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 08:38:53 +0000 Subject: [PATCH 250/367] fix(studio): element picker style, data and text edits draw in a sealed preview (#8663) --- .../hooks/elementPickerWrites.browser.test.ts | 88 ++++++++++++ .../studio/src/hooks/elementPickerWrites.ts | 52 +++++++ packages/studio/src/hooks/useElementPicker.ts | 132 +++++++----------- 3 files changed, 189 insertions(+), 83 deletions(-) create mode 100644 packages/studio/src/hooks/elementPickerWrites.browser.test.ts create mode 100644 packages/studio/src/hooks/elementPickerWrites.ts diff --git a/packages/studio/src/hooks/elementPickerWrites.browser.test.ts b/packages/studio/src/hooks/elementPickerWrites.browser.test.ts new file mode 100644 index 0000000000..9aa6692966 --- /dev/null +++ b/packages/studio/src/hooks/elementPickerWrites.browser.test.ts @@ -0,0 +1,88 @@ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import type { Browser } from "puppeteer-core"; +import { afterAll, beforeAll, expect, it, vi } from "vitest"; +import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils"; +import { buildStudioBundle, openPreview } from "../../tests/sealedPreviewHarness"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); +const require = createRequire(import.meta.url); +const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"]; +let browser: Browser; +let studioBundle: string; + +beforeAll(async () => { + browser = await launchTestChrome(); + studioBundle = await buildStudioBundle([ + `export { writePicked } from "./hooks/elementPickerWrites";`, + ]); +}); + +afterAll(() => closeTestChrome(browser)); + +function previewHtml(): string { + const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); + return ` + + +
+

Hello

+
+ `; +} + +async function pickerWrites(mode: string) { + const preview = await openPreview(browser, studioBundle, previewHtml(), mode); + try { + const sources = await preview.page.evaluate(async () => { + type Studio = { + writePicked(iframe: HTMLIFrameElement, selector: string, write: unknown): unknown; + }; + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const iframe = document.querySelector("iframe")!; + return [ + await studio.writePicked(iframe, ".title", { + live: (el: HTMLElement) => el.style.setProperty("color", "rgb(0, 128, 0)"), + sealed: { styles: [["color", "rgb(0, 128, 0)"]] }, + }), + await studio.writePicked(iframe, ".title", { + live: (el: HTMLElement) => el.setAttribute("data-mood", "calm"), + sealed: { attributes: [["data-mood", "calm"]] }, + }), + await studio.writePicked(iframe, ".title", { + live: (el: HTMLElement) => { + el.textContent = "Hi & you"; + }, + sealed: { html: "Hi <there> & you" }, + }), + await studio.writePicked(iframe, ".missing", { + live: () => {}, + sealed: { styles: [["color", "red"]] }, + }), + ]; + }); + const drawn = await preview.frame.evaluate(() => { + const title = document.querySelector(".title")!; + return { + color: getComputedStyle(title).color, + mood: title.getAttribute("data-mood"), + text: title.textContent, + }; + }); + return { sources, drawn }; + } finally { + await preview.page.close(); + } +} + +it.each(MODES)( + "the element picker's style, data and text edits draw in a %s preview", + async (mode) => { + const writes = await pickerWrites(mode); + const source = { hfId: "t1", ownFile: "index.html" }; + expect(writes).toEqual({ + sources: [source, source, source, null], + drawn: { color: "rgb(0, 128, 0)", mood: "calm", text: "Hi & you" }, + }); + }, +); diff --git a/packages/studio/src/hooks/elementPickerWrites.ts b/packages/studio/src/hooks/elementPickerWrites.ts new file mode 100644 index 0000000000..ae13372532 --- /dev/null +++ b/packages/studio/src/hooks/elementPickerWrites.ts @@ -0,0 +1,52 @@ +import { compositionPathOfPreviewUrl } from "../player/components/CompositionThumbnail"; +import { previewFrameOpaque } from "../player/lib/previewChannel"; +import { + describePreviewElements, + editPreviewElement, + previewElementSourceFile, + queryPreviewElements, +} from "../player/lib/previewElements"; +import { getSourceFileForElement } from "../components/editor/domEditingDom"; + +const previewedPath = (iframe: HTMLIFrameElement) => + compositionPathOfPreviewUrl(iframe.getAttribute("src") ?? ""); + +export interface PickedSource { + hfId: string | null; + ownFile: string; +} + +export interface PickedWrite { + live: (el: HTMLElement) => void; + sealed: Parameters[2]; +} + +/** Draws `write` on the frame's first `selector` match; the element's source, or null when nothing was drawn. */ +export function writePicked( + iframe: HTMLIFrameElement, + selector: string, + write: PickedWrite, +): PickedSource | null | Promise { + if (previewFrameOpaque(iframe)) return writeSealedPicked(iframe, selector, write.sealed); + try { + const el = iframe.contentDocument?.querySelector(selector); + if (!el) return null; + write.live(el); + const ownFile = getSourceFileForElement(el, previewedPath(iframe)).sourceFile; + return { hfId: el.getAttribute("data-hf-id"), ownFile }; + } catch { + return null; + } +} + +async function writeSealedPicked( + iframe: HTMLIFrameElement, + selector: string, + edit: PickedWrite["sealed"], +): Promise { + const handle = (await queryPreviewElements(iframe, selector))?.matches[0]?.handle; + const [element] = (handle && (await describePreviewElements(iframe, [handle]))) || []; + if (!element || !(await editPreviewElement(iframe, element.handle, edit).drawn)) return null; + const hfId = element.attributes.find(([name]) => name === "data-hf-id")?.[1] ?? null; + return { hfId, ownFile: previewElementSourceFile(element, previewedPath(iframe)) }; +} diff --git a/packages/studio/src/hooks/useElementPicker.ts b/packages/studio/src/hooks/useElementPicker.ts index 3398e8090d..4dcbcf1c8c 100644 --- a/packages/studio/src/hooks/useElementPicker.ts +++ b/packages/studio/src/hooks/useElementPicker.ts @@ -11,11 +11,11 @@ import { acceptStudioRuntimeMessage, postRuntimeControlMessage, } from "../player/lib/runtimeProtocol"; -import { compositionPathOfPreviewUrl } from "../player/components/CompositionThumbnail"; import { frameOrigins } from "../player/lib/bridgePlayback"; import { previewComputedStyles, previewFrameOpaque } from "../player/lib/previewChannel"; +import { escapeHtmlText } from "../components/editor/domEditingLayers"; +import { writePicked, type PickedSource, type PickedWrite } from "./elementPickerWrites"; import { PICKED_STYLE_PROPERTIES, readComputedStyles } from "./elementPickerStyles"; -import { getSourceFileForElement } from "../components/editor/domEditingDom"; import { createElementPickerHoverLabel, type ElementPickerHoverInfo, @@ -298,17 +298,16 @@ export function useElementPicker( settlePendingWrites(pendingWritesRef.current, options?.workspaceFiles); const syncToSource = useCallback( - (picked: PickedElement, live: HTMLElement, iframe: HTMLIFrameElement, op: PatchOperation) => { + (picked: PickedElement, source: PickedSource, op: PatchOperation) => { const opts = optionsRef.current; if (!opts?.workspaceFiles || !opts.onSyncFiles) return; // No id: the preview's hf-id names the element, in the file it was served from. - const hfId = live.getAttribute("data-hf-id"); const pending = pendingWritesRef.current; const files = withPendingWrites(opts.workspaceFiles, pending); const patch = picked.id ? patchById(files, picked.id, picked.selector, op) - : hfId - ? patchByHfId(files, hfId, ownSourceFile(live, iframe), op) + : source.hfId + ? patchByHfId(files, source.hfId, source.ownFile, op) : null; if (!patch || patch.after === patch.before) return; recordPendingWrite(pending, patch.path, opts.workspaceFiles[patch.path], patch.after); @@ -317,87 +316,59 @@ export function useElementPicker( [], ); - const setStyle = useCallback( - (prop: string, value: string) => { + const writePickedElement = useCallback( + (write: PickedWrite, shown: (prev: PickedElement) => PickedElement, op: PatchOperation) => { const activeIframe = getActiveIframe(); - if (!pickedElement?.selector || !activeIframe) return; - try { - const doc = activeIframe.contentDocument; - const el = doc?.querySelector(pickedElement.selector) as HTMLElement | null; - if (el) { - el.style.setProperty(prop, value); - setPickedElement((prev) => - prev - ? { - ...prev, - computedStyles: { ...prev.computedStyles, [prop]: value }, - } - : null, - ); - syncToSource(pickedElement, el, activeIframe, { - type: "inline-style", - property: prop, - value, - }); - } - } catch { - /* cross-origin */ - } + const picked = pickedElement; + if (!picked?.selector || !activeIframe) return; + const saved = (source: PickedSource | null) => { + if (!source) return; + setPickedElement((prev) => (prev ? shown(prev) : null)); + syncToSource(picked, source, op); + }; + const source = writePicked(activeIframe, picked.selector, write); + if (source instanceof Promise) void source.then(saved); + else saved(source); }, [pickedElement, getActiveIframe, setPickedElement, syncToSource], ); + const setStyle = useCallback( + (prop: string, value: string) => + writePickedElement( + { live: (el) => el.style.setProperty(prop, value), sealed: { styles: [[prop, value]] } }, + (prev) => ({ ...prev, computedStyles: { ...prev.computedStyles, [prop]: value } }), + { type: "inline-style", property: prop, value }, + ), + [writePickedElement], + ); + const setDataAttr = useCallback( - (attr: string, value: string) => { - const activeIframe = getActiveIframe(); - if (!pickedElement?.selector || !activeIframe) return; - try { - const doc = activeIframe.contentDocument; - const el = doc?.querySelector(pickedElement.selector); - if (el) { - el.setAttribute(`data-${attr}`, value); - setPickedElement((prev) => - prev - ? { - ...prev, - dataAttributes: { ...prev.dataAttributes, [attr]: value }, - } - : null, - ); - syncToSource(pickedElement, el as HTMLElement, activeIframe, { - type: "attribute", - property: attr, - value, - }); - } - } catch { - /* cross-origin */ - } - }, - [pickedElement, getActiveIframe, setPickedElement, syncToSource], + (attr: string, value: string) => + writePickedElement( + { + live: (el) => el.setAttribute(`data-${attr}`, value), + sealed: { attributes: [[`data-${attr}`, value]] }, + }, + (prev) => ({ ...prev, dataAttributes: { ...prev.dataAttributes, [attr]: value } }), + { type: "attribute", property: attr, value }, + ), + [writePickedElement], ); const setTextContent = useCallback( - (text: string) => { - const activeIframe = getActiveIframe(); - if (!pickedElement?.selector || !activeIframe) return; - try { - const doc = activeIframe.contentDocument; - const el = doc?.querySelector(pickedElement.selector); - if (el) { - el.textContent = text; - setPickedElement((prev) => (prev ? { ...prev, textContent: text } : null)); - syncToSource(pickedElement, el as HTMLElement, activeIframe, { - type: "text-content", - property: "textContent", - value: text, - }); - } - } catch { - /* cross-origin */ - } - }, - [pickedElement, getActiveIframe, setPickedElement, syncToSource], + (text: string) => + writePickedElement( + { + live: (el) => { + el.textContent = text; + }, + sealed: { html: escapeHtmlText(text) }, + }, + (prev) => ({ ...prev, textContent: text }), + { type: "text-content", property: "textContent", value: text }, + ), + [writePickedElement], ); return { @@ -543,11 +514,6 @@ function patchById( return path && before ? { path, before, after: applyPatch(before, id, op) } : null; } -function ownSourceFile(live: HTMLElement, iframe: HTMLIFrameElement): string { - const previewed = compositionPathOfPreviewUrl(iframe.getAttribute("src") ?? ""); - return getSourceFileForElement(live, previewed).sourceFile; -} - function patchByHfId( files: Record, hfId: string, From 0ee98f87d0ec87482bd65ddaeba982ab0ecfc274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 08:39:00 +0000 Subject: [PATCH 251/367] fix(studio): sealed keyframe edits save the same values as a regular preview (#8668) * test(studio): sealed rotation commit reads only its own tween's channels * fix(studio): sealed keyframe commits compare GSAP values with the frame's CSS --- .../src/hooks/gsapRuntimeReaders.test.ts | 8 +-- .../studio/src/hooks/gsapRuntimeReaders.ts | 47 +++++++------ .../src/hooks/gsapSealedReads.browser.test.ts | 67 +++++++++++++++++++ .../src/hooks/useAnimatedPropertyCommit.ts | 2 +- 4 files changed, 100 insertions(+), 24 deletions(-) create mode 100644 packages/studio/src/hooks/gsapSealedReads.browser.test.ts diff --git a/packages/studio/src/hooks/gsapRuntimeReaders.test.ts b/packages/studio/src/hooks/gsapRuntimeReaders.test.ts index 2162a2ab8a..451ce4540d 100644 --- a/packages/studio/src/hooks/gsapRuntimeReaders.test.ts +++ b/packages/studio/src/hooks/gsapRuntimeReaders.test.ts @@ -49,7 +49,7 @@ afterEach(() => { }); describe("readAllAnimatedProperties group filter", () => { - it("keeps other tweens' out-of-group properties out of a grouped resolve", () => { + it("keeps other tweens' out-of-group properties out of a grouped resolve", async () => { const el = document.createElement("div"); el.id = "clip"; document.body.appendChild(el); @@ -58,7 +58,7 @@ describe("readAllAnimatedProperties group filter", () => { otherTweenVars: { opacity: 0, rotationX: 52, rotationY: -47 }, }); - const result = readAllAnimatedProperties(iframe, "#clip", rotationSetAnim(), "rotation"); + const result = await readAllAnimatedProperties(iframe, "#clip", rotationSetAnim(), "rotation"); expect(result).toEqual({ rotation: -28.1 }); }); @@ -77,7 +77,7 @@ describe("color-grading opacity truth", () => { }); describe("readAllAnimatedProperties with a sibling tween", () => { - it("leaves a sibling tween's rotation to that tween after an opacity keyframe edit", () => { + it("leaves a sibling tween's rotation to that tween after an opacity keyframe edit", async () => { const el = document.createElement("div"); el.id = "clip"; document.body.appendChild(el); @@ -107,7 +107,7 @@ describe("readAllAnimatedProperties with a sibling tween", () => { } as unknown as GsapAnimation; // commitKeyframeProps: these values plus the edit at the playhead, and backfilled into the rest. - const read = readAllAnimatedProperties(iframe, "#clip", anim); + const read = await readAllAnimatedProperties(iframe, "#clip", anim); live.kill(); gsap.set(el, { clearProps: "all" }); const edited = build({ diff --git a/packages/studio/src/hooks/gsapRuntimeReaders.ts b/packages/studio/src/hooks/gsapRuntimeReaders.ts index ac1feeb437..93012b68a1 100644 --- a/packages/studio/src/hooks/gsapRuntimeReaders.ts +++ b/packages/studio/src/hooks/gsapRuntimeReaders.ts @@ -4,6 +4,8 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import { classifyPropertyGroup, type PropertyGroupName } from "@hyperframes/core/gsap-parser"; import { getIframeGsap, queryIframeElement } from "./gsapShared"; +import { settleGsapSnapshot } from "./gsapFrameSnapshot"; +import { previewComputedStyles, previewFrameOpaque } from "../player/lib/previewChannel"; import { gsapWritesChannels } from "./gsapRuntimeKeyframes"; import { roundTo3 } from "../utils/rounding"; @@ -27,24 +29,19 @@ export function readGsapProperty( } export const POSITION_PROPS = new Set(["x", "y", "xPercent", "yPercent"]); -export function readAllAnimatedProperties( +export async function readAllAnimatedProperties( iframe: HTMLIFrameElement | null, selector: string, anim: GsapAnimation, group?: PropertyGroupName, -): Record { +): Promise> { const result: Record = {}; if (!iframe) return result; + await settleGsapSnapshot(iframe); const gsap = getIframeGsap(iframe); if (!gsap) return result; const el = queryIframeElement(iframe, selector); if (!el) return result; - let doc: Document | null = null; - try { - doc = iframe?.contentDocument ?? null; - } catch { - /* cross-origin guard — doc stays null */ - } const propKeys = new Set(); if (anim.keyframes) { @@ -91,23 +88,14 @@ export function readAllAnimatedProperties( "backgroundPositionX", "backgroundPositionY", ]; - let computedStyle: CSSStyleDeclaration | null = null; - try { - computedStyle = doc?.defaultView?.getComputedStyle(el) ?? null; - } catch {} + const css = await computedCss(iframe, el, selector, COMPUTED_BASELINE.map(kebabCase)); for (const prop of COMPUTED_BASELINE) { if (prop in result) continue; if (!inGroup(prop)) continue; if (gsapWritesChannels(el, [prop])) continue; const gsapVal = Number(gsap.getProperty(el, prop)); if (!Number.isFinite(gsapVal)) continue; - let cssVal = NaN; - if (computedStyle) { - const raw = computedStyle.getPropertyValue( - prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`), - ); - cssVal = parseFloat(raw); - } + const cssVal = parseFloat(css[kebabCase(prop)] ?? ""); if (Number.isFinite(cssVal) && Math.round(gsapVal * 1000) === Math.round(cssVal * 1000)) continue; result[prop] = roundTo3(gsapVal); @@ -115,3 +103,24 @@ export function readAllAnimatedProperties( return result; } + +const kebabCase = (prop: string) => prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`); + +/** The element's computed CSS for `names`: over the port for a sealed frame, as the live element answers. */ +async function computedCss( + iframe: HTMLIFrameElement, + el: Element, + selector: string, + names: string[], +): Promise> { + if (previewFrameOpaque(iframe)) + return (await previewComputedStyles(iframe, selector, names)) ?? {}; + try { + const style = iframe.contentDocument?.defaultView?.getComputedStyle(el); + return style + ? Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name)])) + : {}; + } catch { + return {}; + } +} diff --git a/packages/studio/src/hooks/gsapSealedReads.browser.test.ts b/packages/studio/src/hooks/gsapSealedReads.browser.test.ts new file mode 100644 index 0000000000..c67a3d5337 --- /dev/null +++ b/packages/studio/src/hooks/gsapSealedReads.browser.test.ts @@ -0,0 +1,67 @@ +// Real Chrome: what a commit reads of an element's GSAP values, in a sealed preview and a same-origin one. +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import type { Browser } from "puppeteer-core"; +import { afterAll, beforeAll, expect, it, vi } from "vitest"; +import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils"; +import { buildStudioBundle, openPreview, type Studio } from "../../tests/sealedPreviewHarness"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); +const require = createRequire(import.meta.url); +const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"]; +type Reads = Studio & { + readAllAnimatedProperties: typeof import("./gsapRuntimeReaders").readAllAnimatedProperties; + settleGsapSnapshot: typeof import("./gsapFrameSnapshot").settleGsapSnapshot; +}; +let browser: Browser; +let studioBundle: string; + +beforeAll(async () => { + browser = await launchTestChrome(); + studioBundle = await buildStudioBundle([ + `export { readAllAnimatedProperties } from "./hooks/gsapRuntimeReaders";`, + `export { settleGsapSnapshot } from "./hooks/gsapFrameSnapshot";`, + ]); +}); + +afterAll(() => closeTestChrome(browser)); + +/** #box turns in one tween and rounds its corners in another, both over 0-2 s. */ +function previewHtml(): string { + const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8"); + const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); + return ` + + + +
+
+
+ + + `; +} + +// fails without the fix: a sealed read saw no tween writing borderRadius and copied it into the rotation commit. +it.each(MODES)("a rotation commit reads only the rotation tween's channels (%s)", async (mode) => { + const preview = await openPreview(browser, studioBundle, previewHtml(), mode); + await preview.seek(1); + const read = await preview.page.evaluate(async () => { + const studio = (window as unknown as { hfStudio: Reads }).hfStudio; + const iframe = document.querySelector("iframe")!; + studio.usePlayerStore.setState({ currentTime: 1, isPlaying: false }); + await studio.settleGsapSnapshot(iframe); + return studio.readAllAnimatedProperties(iframe, "#box", { + properties: { rotation: 20 }, + } as never); + }); + expect(read).toEqual({ rotation: 10 }); + await preview.page.close(); +}); diff --git a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts b/packages/studio/src/hooks/useAnimatedPropertyCommit.ts index a5521f681f..5020d4a3c7 100644 --- a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts +++ b/packages/studio/src/hooks/useAnimatedPropertyCommit.ts @@ -339,7 +339,7 @@ async function commitKeyframeProps( ); } const ct = usePlayerStore.getState().currentTime; - const runtimeProps = selector ? readAllAnimatedProperties(iframe, selector, anim) : {}; + const runtimeProps = selector ? await readAllAnimatedProperties(iframe, selector, anim) : {}; const properties: Record = { ...runtimeProps, ...props }; const backfillDefaults: Record = { ...runtimeProps }; From 5e1a490c800646c99b7a8442d297198f554b0803 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 08:39:25 +0000 Subject: [PATCH 252/367] fix(cli): check keeps copy windows for videos with #, ? or % in the name (#8669) --- packages/cli/src/utils/checkBrowser.test.ts | 28 +++++++++++++++++++++ packages/cli/src/utils/checkBrowser.ts | 3 ++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/utils/checkBrowser.test.ts b/packages/cli/src/utils/checkBrowser.test.ts index 0af1041803..c59c7b82ba 100644 --- a/packages/cli/src/utils/checkBrowser.test.ts +++ b/packages/cli/src/utils/checkBrowser.test.ts @@ -2554,6 +2554,34 @@ describe("finding frame capture", () => { } }); + // fails without the fix: the name was decoded twice, so these files got no copy window + it("keeps the copy window of a video whose name has #, ? or %", async () => { + const dir = mkdtempSync(join(tmpdir(), "finding-windows-names-")); + // Windows refuses ? in a file name. + const names = [ + "clip #1.mov", + "50% off.mov", + ...(process.platform === "win32" ? [] : ["a?b.mov"]), + ]; + for (const name of names) writeFileSync(join(dir, name), ""); + installSessionMock(fakePage()); + mocks.bundleWithLocalizedFonts.mockResolvedValueOnce( + `${names.map((name) => ``).join("")}`, + ); + mocks.proxyWindowSeconds.mockClear(); + mocks.proxyWindowSeconds.mockResolvedValue(30); + try { + await captureFindingFrames({ ...PROJECT, dir }, DEFAULT_CHECK_OPTIONS, [ + { time: 1, filename: "a.png" }, + ]); + expect(vi.mocked(serveStaticProjectHtml).mock.calls.at(-1)?.[5]).toEqual( + new Map(names.map((name) => [join(dir, name), 30])), + ); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + it("closes the session when a later screenshot fails", async () => { const dir = mkdtempSync(join(tmpdir(), "finding-frames-failure-")); const page = fakePage(); diff --git a/packages/cli/src/utils/checkBrowser.ts b/packages/cli/src/utils/checkBrowser.ts index b59f970b6a..24b5926e6e 100644 --- a/packages/cli/src/utils/checkBrowser.ts +++ b/packages/cli/src/utils/checkBrowser.ts @@ -45,6 +45,7 @@ import { import { resolveAutoProxy } from "./projectConfig.js"; import { findStageProxyBox } from "./compositionViewport.js"; import { mediaUsedSeconds } from "./mediaUsedSeconds.js"; +import { encodeUrlPath } from "@hyperframes/parsers"; import type { PreviewProxyBox } from "@hyperframes/core"; import { terminalText } from "@hyperframes/core/terminal-text"; import { injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document"; @@ -223,7 +224,7 @@ async function copyWindows( [...pathnames].map(async (pathname) => { const seconds = used.get(pathname); if (seconds === undefined) return; - const sourcePath = projectLocalFile(projectDir, pathname); + const sourcePath = projectLocalFile(projectDir, encodeUrlPath(pathname)); if (!sourcePath) return; const window = await proxyWindowSeconds(sourcePath, seconds); if (window !== undefined) windows.set(sourcePath, window); From 5f0fe71cc1abf36805d2b9a65b80771d0e4ffe95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 08:42:33 +0000 Subject: [PATCH 253/367] fix(aws-lambda): the handler ZIP ships ffmpeg only when it matches its pinned digest (#8665) build-zip accepted whatever ffmpeg-static's install script downloaded as long as it had a Linux x86-64 ELF header. It now compares the binary's sha256 with the one pinned for the installed ffmpeg-static version and stops before the ZIP is built when they differ, or when a version has no pinned digest. --- .github/workflows/lambda-arm64-image.yml | 1 + packages/aws-lambda/README.md | 3 +- packages/aws-lambda/scripts/_ffmpeg.ts | 143 ++++++++++++++++++ packages/aws-lambda/scripts/build-zip.test.ts | 63 ++++++++ packages/aws-lambda/scripts/build-zip.ts | 105 +------------ 5 files changed, 213 insertions(+), 102 deletions(-) create mode 100644 packages/aws-lambda/scripts/_ffmpeg.ts diff --git a/.github/workflows/lambda-arm64-image.yml b/.github/workflows/lambda-arm64-image.yml index 12e4dd820b..cd1648e427 100644 --- a/.github/workflows/lambda-arm64-image.yml +++ b/.github/workflows/lambda-arm64-image.yml @@ -14,6 +14,7 @@ on: # A dependency bump or a ZIP layout change must re-stage the image. - "packages/aws-lambda/package.json" - "packages/aws-lambda/scripts/build-zip.ts" + - "packages/aws-lambda/scripts/_ffmpeg.ts" - "packages/aws-lambda/scripts/runtimeLock.ts" - "packages/aws-lambda/scripts/runtime-lock/**" - ".github/workflows/lambda-arm64-image.yml" diff --git a/packages/aws-lambda/README.md b/packages/aws-lambda/README.md index b27bd9cfd0..a3347261bc 100644 --- a/packages/aws-lambda/README.md +++ b/packages/aws-lambda/README.md @@ -149,7 +149,8 @@ bun run --cwd packages/aws-lambda verify:zip-size # CI gate The build script bundles `src/handler.ts` via esbuild, stages `@sparticuz/chromium` and `puppeteer-core` under `node_modules/`, copies -ffmpeg-static into `bin/`, and zips the result. The unzipped layout is +ffmpeg-static into `bin/` once its sha256 matches the one pinned for that +ffmpeg-static version in `scripts/_ffmpeg.ts`, and zips the result. The unzipped layout is designed to extract cleanly into Lambda's `/var/task/`. `verify:zip-size` enforces: diff --git a/packages/aws-lambda/scripts/_ffmpeg.ts b/packages/aws-lambda/scripts/_ffmpeg.ts new file mode 100644 index 0000000000..14b967e67e --- /dev/null +++ b/packages/aws-lambda/scripts/_ffmpeg.ts @@ -0,0 +1,143 @@ +import { createHash } from "node:crypto"; +import { + chmodSync, + closeSync, + cpSync, + existsSync, + mkdirSync, + openSync, + readFileSync, + readSync, +} from "node:fs"; +import { join } from "node:path"; + +/** + * sha256 of the linux-x64 ffmpeg each `ffmpeg-static` version downloads at install time. The lockfile + * pins the package, not that download, so a version bump needs its binary's digest added here. + */ +export const PINNED_FFMPEG_STATIC_SHA256: Readonly> = { + "5.3.0": "e7e7fb30477f717e6f55f9180a70386c62677ef8a4d4d1a5d948f4098aa3eb99", +}; + +function assertPinnedFfmpeg( + ffmpegModule: string, + binary: string, + pinned: Readonly>, +): void { + const { version } = JSON.parse(readFileSync(join(ffmpegModule, "package.json"), "utf-8")) as { + version: string; + }; + const expected = pinned[version]; + if (!expected) { + throw new Error( + `[build-zip] ffmpeg-static ${version} has no pinned sha256. Add the digest of the linux-x64 ` + + `binary it downloads to PINNED_FFMPEG_STATIC_SHA256 in scripts/_ffmpeg.ts.`, + ); + } + const actual = createHash("sha256").update(readFileSync(binary)).digest("hex"); + if (actual !== expected) { + throw new Error( + `[build-zip] ffmpeg-static ${version} binary at ${binary} has sha256 ${actual}, ` + + `not the pinned ${expected}. Delete node_modules/ffmpeg-static and install it again.`, + ); + } +} + +// ELF header constants used by `assertLinuxX86_64Elf`. Header layout: +// bytes 0..3 magic `0x7F 'E' 'L' 'F'`, byte 4 EI_CLASS (`2` = ELFCLASS64), +// bytes 18..19 e_machine little-endian (`0x3E` = EM_X86_64). +const ELF_MAGIC = Buffer.from([0x7f, 0x45, 0x4c, 0x46]); +const ELF_CLASS_64 = 2; +const ELF_MACHINE_X86_64 = 0x3e; +const ELF_HEADER_BYTES = 20; + +/** + * Verify the binary at `path` is a Linux x86-64 ELF executable, the only + * shape the Lambda runtime can exec. Throws with the canonical workaround + * (Docker `--platform=linux/amd64` or `npm_config_platform` / + * `npm_config_arch` overrides) so the build doesn't ship a silently + * broken zip when a non-Linux host's postinstall fetched the wrong arch. + */ +function assertLinuxX86_64Elf(path: string, label: string): void { + const head = readFileHead(path, ELF_HEADER_BYTES, label); + const isElf = head.subarray(0, 4).equals(ELF_MAGIC); + const isElf64 = head[4] === ELF_CLASS_64; + const machine = head.readUInt16LE(18); + if (isElf && isElf64 && machine === ELF_MACHINE_X86_64) return; + + const magicHex = head.subarray(0, 4).toString("hex"); + throw new Error( + `[build-zip] ${label} at ${path} is not a Linux x86-64 ELF executable ` + + `(magic=0x${magicHex}, ei_class=${head[4]}, e_machine=0x${machine.toString(16)}). ` + + `This usually means the deploy host's postinstall fetched a host-platform binary ` + + `(e.g. macOS arm64 ffmpeg) instead of the linux/x64 binary Lambda needs. ` + + `Re-run the build inside a linux/amd64 container, or pre-install with ` + + `\`npm_config_platform=linux npm_config_arch=x64\` so the package fetches the right binary.`, + ); +} + +function readFileHead(path: string, byteCount: number, label: string): Buffer { + const fd = openSync(path, "r"); + try { + const buf = Buffer.alloc(byteCount); + const bytesRead = readSync(fd, buf, 0, byteCount, 0); + if (bytesRead < byteCount) { + throw new Error( + `[build-zip] ${label} at ${path} is too short — read ${bytesRead} of ${byteCount} bytes.`, + ); + } + return buf; + } finally { + closeSync(fd); + } +} + +export function stageFfmpeg( + stagingDir: string, + ffmpegModule: string, + ffprobeModule: string, + pinned: Readonly> = PINNED_FFMPEG_STATIC_SHA256, +): void { + const binDir = join(stagingDir, "bin"); + mkdirSync(binDir, { recursive: true }); + + // ffmpeg from `ffmpeg-static`. The package only ships the encoder + // binary; the audio pad/trim path also needs ffprobe, which comes + // from `ffprobe-static`. + // + // `ffmpeg-static`'s postinstall fetches a binary for the host platform + // (e.g. arm64 Mach-O on Apple Silicon macOS). Lambda runs Linux x86-64, + // so a build from a non-Linux host silently produces a zip that boots + // but fails at first ffmpeg invocation with `cannot execute binary file`. + // Verify the ELF header up front and bail with a clear message instead. + const ffmpegBinary = join(ffmpegModule, "ffmpeg"); + if (!existsSync(ffmpegBinary)) { + throw new Error( + `[build-zip] ffmpeg-static binary missing at ${ffmpegBinary}. Did postinstall run?`, + ); + } + assertLinuxX86_64Elf(ffmpegBinary, "ffmpeg-static binary"); + assertPinnedFfmpeg(ffmpegModule, ffmpegBinary, pinned); + const ffmpegDest = join(binDir, "ffmpeg"); + cpSync(ffmpegBinary, ffmpegDest); + chmodSync(ffmpegDest, 0o755); + + // ffprobe lives at `ffprobe-static/bin///ffprobe`. + // The producer's `audioPadTrim` spawns `ffprobe` from PATH so we need + // it alongside ffmpeg under /var/task/bin/. + const ffprobeCandidates = [ + join(ffprobeModule, "bin", "linux", "x64", "ffprobe"), + join(ffprobeModule, "bin", "linux", "arm64", "ffprobe"), + ]; + const ffprobeBinary = ffprobeCandidates.find((p) => existsSync(p)); + if (!ffprobeBinary) { + throw new Error( + `[build-zip] ffprobe-static binary not found under ${ffprobeModule}/bin/linux/. Did postinstall run?`, + ); + } + const ffprobeDest = join(binDir, "ffprobe"); + cpSync(ffprobeBinary, ffprobeDest); + chmodSync(ffprobeDest, 0o755); + + console.log(`[build-zip] staged ffmpeg + ffprobe → bin/`); +} diff --git a/packages/aws-lambda/scripts/build-zip.test.ts b/packages/aws-lambda/scripts/build-zip.test.ts index 2f1f73fb87..827b9e4b4e 100644 --- a/packages/aws-lambda/scripts/build-zip.test.ts +++ b/packages/aws-lambda/scripts/build-zip.test.ts @@ -9,6 +9,7 @@ import { statSync, writeFileSync, } from "node:fs"; +import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { pathToFileURL } from "node:url"; @@ -16,6 +17,7 @@ import { headlessShellDigest, managedChromeVersion } from "@hyperframes/engine/c import * as esbuild from "esbuild"; import { BUNDLED_SHELL_DIR } from "../src/chromium.js"; import { stageChromeHeadlessShell } from "./_chromeHeadlessShell.js"; +import { stageFfmpeg } from "./_ffmpeg.js"; import { HANDLER_BANNER } from "./_handlerBanner.js"; // The handler ships as ESM (.mjs) but inlines CJS deps that assume Node's CJS @@ -184,3 +186,64 @@ describe("build-zip chrome-headless-shell staging", () => { } }); }); + +describe("build-zip ffmpeg staging", () => { + // A Linux x86-64 ELF header, so only the digest can tell this binary from the real one. + const elfX64 = (tail: string) => { + const head = Buffer.alloc(20); + Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2]).copy(head); + head.writeUInt16LE(0x3e, 18); + return Buffer.concat([head, Buffer.from(tail)]); + }; + function modules(ffmpeg: Buffer, version = "5.3.0") { + const root = mkdtempSync(join(tmpdir(), "hf-ffmpeg-modules-")); + const ffmpegModule = join(root, "ffmpeg-static"); + const ffprobeModule = join(root, "ffprobe-static"); + mkdirSync(ffmpegModule, { recursive: true }); + writeFileSync(join(ffmpegModule, "package.json"), JSON.stringify({ version })); + writeFileSync(join(ffmpegModule, "ffmpeg"), ffmpeg); + mkdirSync(join(ffprobeModule, "bin/linux/x64"), { recursive: true }); + writeFileSync(join(ffprobeModule, "bin/linux/x64/ffprobe"), "probe"); + return { root, ffmpegModule, ffprobeModule }; + } + const sha256 = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex"); + + it("refuses an ffmpeg whose bytes differ from the pinned digest", () => { + // fails without the fix: any file with a Linux x86-64 ELF header was copied into bin/ffmpeg. + const { root, ffmpegModule, ffprobeModule } = modules(elfX64("swapped")); + try { + expect(() => stageFfmpeg(root, ffmpegModule, ffprobeModule)).toThrow( + /ffmpeg-static 5\.3\.0 binary .* has sha256 [0-9a-f]{64}, not the pinned e7e7fb30/, + ); + expect(existsSync(join(root, "bin/ffmpeg"))).toBe(false); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("refuses an ffmpeg-static version with no pinned digest", () => { + const binary = elfX64("next"); + const { root, ffmpegModule, ffprobeModule } = modules(binary, "5.4.0"); + try { + expect(() => + stageFfmpeg(root, ffmpegModule, ffprobeModule, { "5.3.0": sha256(binary) }), + ).toThrow(/ffmpeg-static 5\.4\.0 has no pinned sha256/); + expect(existsSync(join(root, "bin/ffmpeg"))).toBe(false); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("stages an ffmpeg that matches its version's pinned digest", () => { + const binary = elfX64("real"); + const { root, ffmpegModule, ffprobeModule } = modules(binary); + try { + stageFfmpeg(root, ffmpegModule, ffprobeModule, { "5.3.0": sha256(binary) }); + expect(readFileSync(join(root, "bin/ffmpeg")).equals(binary)).toBe(true); + expect(statSync(join(root, "bin/ffmpeg")).mode & 0o111).not.toBe(0); + expect(readFileSync(join(root, "bin/ffprobe"), "utf-8")).toBe("probe"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/aws-lambda/scripts/build-zip.ts b/packages/aws-lambda/scripts/build-zip.ts index 1807857704..20e0414e93 100644 --- a/packages/aws-lambda/scripts/build-zip.ts +++ b/packages/aws-lambda/scripts/build-zip.ts @@ -33,15 +33,11 @@ import { spawnSync } from "node:child_process"; import { - chmodSync, - closeSync, copyFileSync, cpSync, existsSync, mkdirSync, - openSync, readdirSync, - readSync, rmSync, statSync, writeFileSync, @@ -51,6 +47,7 @@ import { fileURLToPath } from "node:url"; import * as esbuild from "esbuild"; import { BUNDLED_SHELL_DIR } from "../src/chromium.js"; import { stageChromeHeadlessShell } from "./_chromeHeadlessShell.js"; +import { stageFfmpeg } from "./_ffmpeg.js"; import { formatBytes } from "./_formatBytes.js"; import { HANDLER_BANNER } from "./_handlerBanner.js"; import { RUNTIME_LOCK_DIR, assertRuntimeLockCurrent } from "./runtimeLock.js"; @@ -132,7 +129,7 @@ async function main(): Promise { stageRuntimeModules(stagingDir, opts.source); // 3. Stage the ffmpeg binary. - stageFfmpeg(stagingDir); + stageFfmpeg(stagingDir, resolveModuleDir("ffmpeg-static"), resolveModuleDir("ffprobe-static")); // 3b. Stage the hyperframe runtime manifest + IIFE as siblings of // handler.mjs. The producer's `hyperframeRuntimeLoader` checks @@ -280,8 +277,8 @@ function stageRuntimeModules(stagingDir: string, source: BuildOptions["source"]) function resolveModuleDir(moduleName: string): string { // Walk up from packageRoot to find a matching node_modules entry. - // Used by stageFfmpeg below; the @sparticuz/chromium + puppeteer-core - // paths now go through npm install instead. + // Used for ffmpeg-static and ffprobe-static; the @sparticuz/chromium + + // puppeteer-core paths go through npm install instead. let dir = packageRoot; for (let i = 0; i < 5; i++) { const candidate = join(dir, "node_modules", moduleName); @@ -308,100 +305,6 @@ function stageHyperframeRuntime(stagingDir: string): void { console.log(`[build-zip] staged hyperframe.manifest.json + hyperframe.runtime.iife.js`); } -// ELF header constants used by `assertLinuxX86_64Elf`. Header layout: -// bytes 0..3 magic `0x7F 'E' 'L' 'F'`, byte 4 EI_CLASS (`2` = ELFCLASS64), -// bytes 18..19 e_machine little-endian (`0x3E` = EM_X86_64). -const ELF_MAGIC = Buffer.from([0x7f, 0x45, 0x4c, 0x46]); -const ELF_CLASS_64 = 2; -const ELF_MACHINE_X86_64 = 0x3e; -const ELF_HEADER_BYTES = 20; - -/** - * Verify the binary at `path` is a Linux x86-64 ELF executable, the only - * shape the Lambda runtime can exec. Throws with the canonical workaround - * (Docker `--platform=linux/amd64` or `npm_config_platform` / - * `npm_config_arch` overrides) so the build doesn't ship a silently - * broken zip when a non-Linux host's postinstall fetched the wrong arch. - */ -function assertLinuxX86_64Elf(path: string, label: string): void { - const head = readFileHead(path, ELF_HEADER_BYTES, label); - const isElf = head.subarray(0, 4).equals(ELF_MAGIC); - const isElf64 = head[4] === ELF_CLASS_64; - const machine = head.readUInt16LE(18); - if (isElf && isElf64 && machine === ELF_MACHINE_X86_64) return; - - const magicHex = head.subarray(0, 4).toString("hex"); - throw new Error( - `[build-zip] ${label} at ${path} is not a Linux x86-64 ELF executable ` + - `(magic=0x${magicHex}, ei_class=${head[4]}, e_machine=0x${machine.toString(16)}). ` + - `This usually means the deploy host's postinstall fetched a host-platform binary ` + - `(e.g. macOS arm64 ffmpeg) instead of the linux/x64 binary Lambda needs. ` + - `Re-run the build inside a linux/amd64 container, or pre-install with ` + - `\`npm_config_platform=linux npm_config_arch=x64\` so the package fetches the right binary.`, - ); -} - -function readFileHead(path: string, byteCount: number, label: string): Buffer { - const fd = openSync(path, "r"); - try { - const buf = Buffer.alloc(byteCount); - const bytesRead = readSync(fd, buf, 0, byteCount, 0); - if (bytesRead < byteCount) { - throw new Error( - `[build-zip] ${label} at ${path} is too short — read ${bytesRead} of ${byteCount} bytes.`, - ); - } - return buf; - } finally { - closeSync(fd); - } -} - -function stageFfmpeg(stagingDir: string): void { - const binDir = join(stagingDir, "bin"); - mkdirSync(binDir, { recursive: true }); - - // ffmpeg from `ffmpeg-static`. The package only ships the encoder - // binary; the audio pad/trim path also needs ffprobe, which comes - // from `ffprobe-static`. - // - // `ffmpeg-static`'s postinstall fetches a binary for the host platform - // (e.g. arm64 Mach-O on Apple Silicon macOS). Lambda runs Linux x86-64, - // so a build from a non-Linux host silently produces a zip that boots - // but fails at first ffmpeg invocation with `cannot execute binary file`. - // Verify the ELF header up front and bail with a clear message instead. - const ffmpegBinary = join(resolveModuleDir("ffmpeg-static"), "ffmpeg"); - if (!existsSync(ffmpegBinary)) { - throw new Error( - `[build-zip] ffmpeg-static binary missing at ${ffmpegBinary}. Did postinstall run?`, - ); - } - assertLinuxX86_64Elf(ffmpegBinary, "ffmpeg-static binary"); - const ffmpegDest = join(binDir, "ffmpeg"); - cpSync(ffmpegBinary, ffmpegDest); - chmodSync(ffmpegDest, 0o755); - - // ffprobe lives at `ffprobe-static/bin///ffprobe`. - // The producer's `audioPadTrim` spawns `ffprobe` from PATH so we need - // it alongside ffmpeg under /var/task/bin/. - const ffprobeModule = resolveModuleDir("ffprobe-static"); - const ffprobeCandidates = [ - join(ffprobeModule, "bin", "linux", "x64", "ffprobe"), - join(ffprobeModule, "bin", "linux", "arm64", "ffprobe"), - ]; - const ffprobeBinary = ffprobeCandidates.find((p) => existsSync(p)); - if (!ffprobeBinary) { - throw new Error( - `[build-zip] ffprobe-static binary not found under ${ffprobeModule}/bin/linux/. Did postinstall run?`, - ); - } - const ffprobeDest = join(binDir, "ffprobe"); - cpSync(ffprobeBinary, ffprobeDest); - chmodSync(ffprobeDest, 0o755); - - console.log(`[build-zip] staged ffmpeg + ffprobe → bin/`); -} - function zipDirectory(sourceDir: string, zipPath: string): void { const result = spawnSync("zip", ["-rq", zipPath, "."], { cwd: sourceDir, stdio: "inherit" }); if (result.status !== 0) { From 8c9e9521624eb1e501595bae11976ee4e5a92d9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 08:43:08 +0000 Subject: [PATCH 254/367] fix(producer): a remote font stylesheet's text stays CSS when inlined (#8671) --- .../htmlCompiler.remoteFontText.test.ts | 68 +++++++++++++++++++ .../producer/src/services/htmlCompiler.ts | 3 +- 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 packages/producer/src/services/htmlCompiler.remoteFontText.test.ts diff --git a/packages/producer/src/services/htmlCompiler.remoteFontText.test.ts b/packages/producer/src/services/htmlCompiler.remoteFontText.test.ts new file mode 100644 index 0000000000..52ffaf6147 --- /dev/null +++ b/packages/producer/src/services/htmlCompiler.remoteFontText.test.ts @@ -0,0 +1,68 @@ +// @vitest-environment node +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { parseHTML } from "linkedom"; +import { compileForRender } from "./htmlCompiler.js"; + +const SHEET = "https://fonts.example.com/brand.css"; +const requested = vi.hoisted(() => [] as string[]); + +vi.mock("../utils/urlDownloader.js", async (importOriginal) => ({ + ...(await importOriginal()), + downloadToTemp: async (url: string) => { + requested.push(url); + throw new Error("offline test"); + }, + fetchPublicHttpsText: async (url: string) => { + requested.push(url); + if (url !== SHEET) throw new Error("offline test"); + return ( + `@font-face { font-family: "Brand` + + `` + + ``; + const fontCssWithLtAsCssEscape = fontFaceBlocks.join("\n").replace(//* Inlined external font stylesheet */\n${fontCssWithLtAsCssEscape}\n`; try { budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length); } catch (error) { From 928f9eabb3dbbe5196be9f3b18d897cd781f9c51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 08:54:32 +0000 Subject: [PATCH 255/367] fix(core): sub-compositions load only from inside the project (#8670) * fix(core): sub-compositions load only from inside the project * fix(core): fetch the authored sub-composition source the check resolved --- .../src/runtime/compositionLoader.test.ts | 86 +++++++++++++++++-- .../core/src/runtime/compositionLoader.ts | 14 ++- packages/core/src/runtime/init.test.ts | 4 +- 3 files changed, 93 insertions(+), 11 deletions(-) diff --git a/packages/core/src/runtime/compositionLoader.test.ts b/packages/core/src/runtime/compositionLoader.test.ts index 6bd260258c..4192593274 100644 --- a/packages/core/src/runtime/compositionLoader.test.ts +++ b/packages/core/src/runtime/compositionLoader.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, afterEach, beforeAll } from "vitest"; +import { describe, it, expect, vi, afterEach, beforeAll, beforeEach } from "vitest"; import { loadCompositions } from "./compositionLoader"; type LoaderParams = Parameters[0]; @@ -45,6 +45,18 @@ beforeAll(() => { } }); +// Studio pins a preview page's project root with ; these fixtures live under it. +function useProjectBase(href = "https://example.com/") { + beforeEach(() => { + const base = document.createElement("base"); + base.href = href; + document.head.prepend(base); + }); + afterEach(() => document.head.querySelectorAll("base").forEach((base) => base.remove())); +} + +useProjectBase(); + describe("loadCompositions external hosts", () => { afterEach(() => { document.body.innerHTML = ""; @@ -456,6 +468,61 @@ describe("loadCompositions external hosts", () => { }, ); + describe("a project under /api/projects/p1/preview/", () => { + beforeEach(() => { + document.querySelector("base")!.href = "https://example.com/api/projects/p1/preview/"; + }); + + it.each([ + "https://elsewhere.example/x.html", + "//elsewhere.example/x.html", + "/api/projects/p2/preview/x.html", + "../p2/preview/x.html", + ])("never fetches or mounts a data-composition-src outside it: %s", async (src) => { + const host = appendExternalHost(src, "x"); + const fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue( + new Response( + `

off

`, + ), + ); + const onDiagnostic = vi.fn(); + const { injectedScripts } = await loadFixture({ onDiagnostic }); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(host.innerHTML).toBe(""); + expect(injectedScripts).toHaveLength(0); + expect(onDiagnostic).toHaveBeenCalledWith({ + code: "external_composition_load_failed", + details: expect.objectContaining({ + hostCompositionSrc: src, + errorMessage: "data-composition-src must name a file inside the project", + }), + }); + }); + + it("mounts a project-relative sub-composition and its script", async () => { + const host = appendExternalHost("compositions/sub.html", "sub"); + const fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue( + new Response( + `

in

`, + ), + ); + const onDiagnostic = vi.fn(); + const { injectedScripts } = await loadFixture({ onDiagnostic }); + expect(new URL(String(fetchSpy.mock.calls[0]?.[0]), document.baseURI).href).toBe( + "https://example.com/api/projects/p1/preview/compositions/sub.html", + ); + expect(host.textContent).toContain("in"); + expect(injectedScripts.map((script) => script.textContent).join("")).toContain( + "window.__in = 1;", + ); + expect(onDiagnostic).not.toHaveBeenCalled(); + }); + }); + it("calls onDiagnostic when HTTP response is not ok", async () => { const host = document.createElement("div"); host.setAttribute("data-composition-src", "https://example.com/404.html"); @@ -897,6 +964,9 @@ describe("loadCompositions external hosts", () => { */ const FRAME_URL = "http://localhost:5190/api/projects/demo/preview/compositions/frames/scene.html"; + beforeEach(() => { + document.querySelector("base")!.href = "http://localhost:5190/api/projects/demo/preview/"; + }); it("rewrites `../`-traversing src on elements inside