Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): save moves in GSAP-free files without a 2 s wait for a warm parse (#4770)
Miguel Ángel8d537dea9f7c
diff --git a/packages/studio/src/hooks/useCommitPreflightCapabilities.ts b/packages/studio/src/hooks/useCommitPreflightCapabilities.tsindex e1b1664213..3fea264e80 100644--- a/packages/studio/src/hooks/useCommitPreflightCapabilities.ts+++ b/packages/studio/src/hooks/useCommitPreflightCapabilities.ts@@ -5,10 +5,8 @@ import { dragEditOutcome, preflightGsapRotationIntercept } from "./gsapRuntimeBrimport { preflightGsapResizeIntercept } from "./gsapResizePreflight";import { GSAP_EDIT_BLOCK_COPY, type GsapEditOutcome } from "./gsapEditOutcome";import { fetchParsedAnimations, parseCacheKey } from "./keyframeCacheAstLoad";-import {- gsapSourceFileForSelection,- selectElementAnimationsOrRetry,-} from "./useGsapAnimationFetchFallback";+import { getAnimationsForElement } from "./gsapElementMatch";+import { gsapSourceFileForSelection } from "./useGsapAnimationFetchFallback";interface CommitPreflight {offset: GsapEditOutcome;@@ -23,13 +21,7 @@ function runCommitPreflights(group: boolean,): CommitPreflight {const target = { id: selection.id ?? null, selector: selection.selector ?? null };- const matched = selectElementAnimationsOrRetry(- { animations: fileAnimations },- target,- selection.element,- );- // A file the server parsed with no tweens at all is a definitive answer here.- const animations = matched.kind === "resolved" ? matched.animations : [];+ const animations = getAnimationsForElement(fileAnimations, target, selection.element);return {offset: dragEditOutcome(selection, animations, iframe, [], group),size: preflightGsapResizeIntercept(selection, animations, iframe),diff --git a/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.ts b/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.tsindex 95e882a951..ef5e5e8181 100644--- a/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.ts+++ b/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.ts@@ -1,13 +1,24 @@// @vitest-environment happy-dom-import { describe, expect, it } from "vitest";+import React, { act } from "react";+import { createRoot } from "react-dom/client";+import { describe, expect, it, vi } from "vitest";import type { GsapAnimation, ParsedGsap } from "@hyperframes/core/gsap-parser";import {gsapSourceFileForSelection,selectElementAnimationsOrRetry,+ useGsapAnimationFetchFallback,} from "./useGsapAnimationFetchFallback";+import { fetchParsedAnimations } from "./useGsapTweenCache";import type { DomEditSelection } from "../components/editor/domEditingTypes";+vi.mock("./useGsapTweenCache", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./useGsapTweenCache")>()),+ fetchParsedAnimations: vi.fn(),+}));++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+describe("gsapSourceFileForSelection", () => {it("uses the explicit target source instead of ambient selection state", () => {expect(@@ -28,8 +39,11 @@ describe("selectElementAnimationsOrRetry", () => {expect(selectElementAnimationsOrRetry(null, target)).toEqual({ kind: "fetch-error" });});- it("signals cold (full retry budget) when the parse is reachable but has zero total animations", () => {- expect(selectElementAnimationsOrRetry(parsed([]), target)).toEqual({ kind: "cold" });+ it("resolves to [] for a file with no tweens at all: the endpoint parses the file per request", () => {+ expect(selectElementAnimationsOrRetry(parsed([]), target)).toEqual({+ kind: "resolved",+ animations: [],+ });});it("resolves the matching animations from a warm parse", () => {@@ -58,3 +72,30 @@ describe("selectElementAnimationsOrRetry", () => {expect(outcome).toEqual({ kind: "resolved", animations: [] });});});++describe("useGsapAnimationFetchFallback", () => {+ const fetchFor = (projectId: string) => {+ let fetcher: ReturnType<typeof useGsapAnimationFetchFallback> | null = null;+ function Probe() {+ fetcher = useGsapAnimationFetchFallback(projectId);+ return null;+ }+ const root = createRoot(document.createElement("div"));+ act(() => root.render(React.createElement(Probe)));+ act(() => root.unmount());+ const element = document.createElement("div");+ return fetcher!({ id: "puck-a", selector: "#puck-a", element } as unknown as DomEditSelection);+ };++ it("answers a GSAP-free file with one parse request, no retries", async () => {+ vi.mocked(fetchParsedAnimations).mockReset().mockResolvedValue(parsed([]));+ await expect(fetchFor("demo")()).resolves.toEqual([]);+ expect(fetchParsedAnimations).toHaveBeenCalledTimes(1);+ });++ it("retries a failed fetch once, then reports no animation", async () => {+ vi.mocked(fetchParsedAnimations).mockReset().mockResolvedValue(null);+ await expect(fetchFor("demo")()).resolves.toEqual([]);+ expect(fetchParsedAnimations).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/studio/src/hooks/useGsapAnimationFetchFallback.ts b/packages/studio/src/hooks/useGsapAnimationFetchFallback.tsindex 8f4382d529..5376d19398 100644--- a/packages/studio/src/hooks/useGsapAnimationFetchFallback.ts+++ b/packages/studio/src/hooks/useGsapAnimationFetchFallback.ts@@ -3,13 +3,8 @@ import type { GsapAnimation, ParsedGsap } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditing";import { fetchParsedAnimations, getAnimationsForElement } from "./useGsapTweenCache";-// A cold parse is the initial-load race: the endpoint is reachable but its parse-// isn't warm yet (zero total animations). It's worth waiting out (~600ms).-const COLD_PARSE_RETRIES = 5;-const COLD_PARSE_DELAY_MS = 120;// A hard fetch error (404/403/network/JSON failure → `fetchParsedAnimations`-// returns null) is NOT a parse-warming race, so it shouldn't burn the full-// cold-parse budget. One short retry covers a transient blip; beyond that the+// returns null) gets one short retry for a transient blip; beyond that the// endpoint genuinely isn't serving this file, so fall through to "no animation".const FETCH_ERROR_RETRIES = 1;const FETCH_ERROR_DELAY_MS = 120;@@ -18,17 +13,14 @@ const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve,/*** Outcome of resolving an element's animations from a single parse result.- * - `resolved`: a definitive answer (matched animations, or `[]` when the parse- * is warm but this element has no animation — create a new one, don't retry).+ * - `resolved`: a definitive answer. The endpoint parses the file on disk per request,+ * so no match, or a file with no tweens at all, means the element has no animation.* - `fetch-error`: `fetchParsedAnimations` returned null (HTTP/network/JSON- * failure) — retry briefly, not for the full cold-parse budget.- * - `cold`: the parse came back reachable but with zero total animations — the- * initial-load warming race, worth the full cold-parse retry budget.+ * failure) — retry briefly.*/export type ElementAnimationsOutcome =| { kind: "resolved"; animations: GsapAnimation[] }- | { kind: "fetch-error" }- | { kind: "cold" };+ | { kind: "fetch-error" };export interface GsapAnimationFetchOptions {/** Refuse the edit when the parse endpoint is unavailable instead of treating it as no motion. */@@ -41,26 +33,19 @@ export function gsapSourceFileForSelection(selection: DomEditSelection): stringreturn selection.sourceFile || "index.html";}-/**- * Classify a parse result for one element. Differentiates a hard fetch failure- * (`parsed === null`) from a warm-but-empty cold parse (`animations.length === 0`)- * so the caller can apply the right retry budget to each.- */+/** Classify a parse result for one element: a hard fetch failure (`parsed === null`) or its animations. */export function selectElementAnimationsOrRetry(parsed: Pick<ParsedGsap, "animations"> | null,target: { id: string | null; selector: string | null },element?: Element | null,): ElementAnimationsOutcome {if (!parsed) return { kind: "fetch-error" };- if (parsed.animations.length === 0) return { kind: "cold" };return {kind: "resolved",animations: getAnimationsForElement(parsed.animations, target, element),};}-// Retry policy deliberately distinguishes cold parses from hard fetch errors.-// fallow-ignore-next-line complexityasync function fetchElementAnimationsWithRetry(projectId: string,gsapSourceFile: string,@@ -69,25 +54,16 @@ async function fetchElementAnimationsWithRetry(failOnFetchError: boolean,fresh: boolean,): Promise<GsapAnimation[]> {- let coldAttempts = 0;- let errorAttempts = 0;- for (;;) {+ for (let errorAttempts = 0; ; errorAttempts++) {const parsed = await fetchParsedAnimations(projectId, gsapSourceFile, { fresh });fresh = false;const outcome = selectElementAnimationsOrRetry(parsed, target, element);if (outcome.kind === "resolved") return outcome.animations;- if (outcome.kind === "fetch-error") {- if (errorAttempts >= FETCH_ERROR_RETRIES) {- if (failOnFetchError) throw new Error("GSAP animation ownership could not be verified");- return [];- }- errorAttempts++;- await delay(FETCH_ERROR_DELAY_MS);- continue;+ if (errorAttempts >= FETCH_ERROR_RETRIES) {+ if (failOnFetchError) throw new Error("GSAP animation ownership could not be verified");+ return [];}- if (coldAttempts >= COLD_PARSE_RETRIES) return [];- coldAttempts++;- await delay(COLD_PARSE_DELAY_MS);+ await delay(FETCH_ERROR_DELAY_MS);}}diff --git a/packages/studio/src/hooks/useGsapTweenCache.element.test.tsx b/packages/studio/src/hooks/useGsapTweenCache.element.test.tsxindex 67f05f49b6..e389198c8b 100644--- a/packages/studio/src/hooks/useGsapTweenCache.element.test.tsx+++ b/packages/studio/src/hooks/useGsapTweenCache.element.test.tsx@@ -16,9 +16,10 @@ const dotTween = {} as GsapAnimation;vi.mock("./keyframeCacheAstLoad", async (importOriginal) => ({...(await importOriginal<typeof import("./keyframeCacheAstLoad")>()),- fetchParsedAnimations: async () => ({ animations: [dotTween] }),+ fetchParsedAnimations: vi.fn(async () => ({ animations: [dotTween] })),}));const { useGsapAnimationsForElement } = await import("./useGsapTweenCache");+const { fetchParsedAnimations } = await import("./keyframeCacheAstLoad");it("attributes a class tween by the selected element, not an earlier same-id copy in a sub-composition", async () => {document.body.innerHTML =@@ -37,3 +38,24 @@ it("attributes a class tween by the selected element, not an earlier same-id copexpect(animations.map((animation) => animation.id)).toEqual(["dots"]);act(() => root.unmount());});++it("reads a file with no tweens once: the parse endpoint answers from the file on disk", async () => {+ vi.useFakeTimers();+ vi.mocked(fetchParsedAnimations)+ .mockClear()+ .mockResolvedValue({ animations: [] } as never);+ const selection = { id: "card", sourceFile: "index.html" } as DomEditSelection;+ function Harness() {+ useGsapAnimationsForElement("p", "index.html", selection, 0);+ return null;+ }+ const root = mountReactHarness(<Harness />);+ try {+ await act(async () => {});+ await act(async () => vi.advanceTimersByTime(2000));+ expect(fetchParsedAnimations).toHaveBeenCalledTimes(1);+ } finally {+ act(() => root.unmount());+ vi.useRealTimers();+ }+});diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.tsindex 255fd886d1..b21d826add 100644--- a/packages/studio/src/hooks/useGsapTweenCache.ts+++ b/packages/studio/src/hooks/useGsapTweenCache.ts@@ -41,7 +41,6 @@ export function useGsapAnimationsForElement(const [multipleTimelines, setMultipleTimelines] = useState(false);const [unsupportedTimelinePattern, setUnsupportedTimelinePattern] = useState(false);const lastFetchKeyRef = useRef("");- const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);// Re-run the per-element cache populate when sub-comp DOM children appear, so a// sub-comp element gets its host-relative keyframe percentages (not elDuration=1).const domClipChildrenKey = usePlayerStore((s) =>@@ -54,11 +53,6 @@ export function useGsapAnimationsForElement(if (fetchKey === lastFetchKeyRef.current) return;lastFetchKeyRef.current = fetchKey;- if (retryTimerRef.current) {- clearTimeout(retryTimerRef.current);- retryTimerRef.current = null;- }-if (!projectId) {setAllAnimations([]);setMultipleTimelines(false);@@ -80,28 +74,10 @@ export function useGsapAnimationsForElement(setAllAnimations(parsed.animations);setMultipleTimelines(parsed.multipleTimelines === true);setUnsupportedTimelinePattern(parsed.unsupportedTimelinePattern === true);-- // Retry once if initial fetch returned 0 animations — handles- // cold-load race where the sourceFile isn't resolved yet.- if (parsed.animations.length === 0 && targetKey) {- retryTimerRef.current = setTimeout(() => {- if (cancelled) return;- fetchParsedAnimations(projectId, sourceFile).then((retryParsed) => {- if (cancelled) return;- if (retryParsed && retryParsed.animations.length > 0) {- setAllAnimations(retryParsed.animations);- }- });- }, 800);- }});return () => {cancelled = true;- if (retryTimerRef.current) {- clearTimeout(retryTimerRef.current);- retryTimerRef.current = null;- }};}, [projectId, sourceFile, version, target?.id, target?.selector]);