From e33dd14026fda2d40ccbbbb2a65e6f5cd1765802 Mon Sep 17 00:00:00 2001 From: Vance Ingalls Date: Sun, 14 Jun 2026 18:39:00 -0700 Subject: [PATCH] fix(sdk,studio): 14 code-review correctness fixes from stage 7 review - http adapter: throw on 5xx instead of silently returning undefined - fs adapter: serialize appendVersion to prevent concurrent pruning race - mutate: GSAP handlers throw (not silent EMPTY) when no GSAP script block - mutate: selectorMatchesId supports scoped hf-HOST/hf-LEAF ids - sdkShadow: fix double data- prefix on attribute patch ops - sdkShadow: call onDomEditPersisted on SDK cutover success path - useSdkSession: fix compRef closure race on dispose; suppress self-write echo - App.tsx: pass domEditSaveTimestampRef to useSdkSession for echo suppression - examples: fix dead !comp.can(op) guard (needs .ok); remove stale id field Co-Authored-By: Claude Sonnet 4.6 --- packages/sdk/examples/headless-agent.ts | 5 +- packages/sdk/examples/react-embed.ts | 4 +- packages/sdk/examples/vanilla-editor.ts | 4 +- packages/sdk/src/adapters/fs.ts | 10 +++- packages/sdk/src/adapters/http.test.ts | 8 ++- packages/sdk/src/adapters/http.ts | 3 +- packages/sdk/src/engine/mutate.gsap.test.ts | 53 ++++++++++++++++--- packages/sdk/src/engine/mutate.test.ts | 16 +++--- packages/sdk/src/engine/mutate.ts | 13 ++++- packages/studio/src/App.tsx | 3 ++ .../studio/src/hooks/useDomEditCommits.ts | 11 ++-- packages/studio/src/hooks/useSdkSession.ts | 23 +++++--- packages/studio/src/utils/sdkShadow.test.ts | 14 +++++ packages/studio/src/utils/sdkShadow.ts | 15 +++--- 14 files changed, 139 insertions(+), 43 deletions(-) diff --git a/packages/sdk/examples/headless-agent.ts b/packages/sdk/examples/headless-agent.ts index 95f450c6a2..6308ca86ad 100644 --- a/packages/sdk/examples/headless-agent.ts +++ b/packages/sdk/examples/headless-agent.ts @@ -121,10 +121,7 @@ export async function addStaggeredEntrance(html: string, staggerDelay = 0.15): P fromProperties: { opacity: 0, y: 30 }, } as const; const first = textEls[0]; - if ( - !first || - !comp.can({ type: "addGsapTween", target: first, id: "preflight", tween: probeTween }) - ) { + if (!first || !comp.can({ type: "addGsapTween", target: first, tween: probeTween }).ok) { return comp.serialize(); } diff --git a/packages/sdk/examples/react-embed.ts b/packages/sdk/examples/react-embed.ts index 69798276bc..34db25ef3d 100644 --- a/packages/sdk/examples/react-embed.ts +++ b/packages/sdk/examples/react-embed.ts @@ -98,12 +98,12 @@ export function addBounceIn(comp: Composition, targetId: string): string | null ease: "bounce.out", fromProperties: { y: 40, opacity: 0 }, } as const; - if (!comp.can({ type: "addGsapTween", target: targetId, id: "preflight", tween })) return null; + if (!comp.can({ type: "addGsapTween", target: targetId, tween }).ok) return null; return comp.addGsapTween(targetId, tween); } export function updateEase(comp: Composition, animationId: string, ease: string): void { - if (!comp.can({ type: "setGsapTween", animationId, properties: { ease } })) return; + if (!comp.can({ type: "setGsapTween", animationId, properties: { ease } }).ok) return; comp.setGsapTween(animationId, { ease }); } diff --git a/packages/sdk/examples/vanilla-editor.ts b/packages/sdk/examples/vanilla-editor.ts index bcd5f472b9..a2a1aa07a5 100644 --- a/packages/sdk/examples/vanilla-editor.ts +++ b/packages/sdk/examples/vanilla-editor.ts @@ -113,7 +113,7 @@ export function addFadeIn(comp: Composition, targetId: string, delay = 0): strin ease: "power2.out", fromProperties: { opacity: 0 }, }; - if (!comp.can({ type: "addGsapTween", target: targetId, id: "preflight", tween })) return null; + if (!comp.can({ type: "addGsapTween", target: targetId, tween }).ok) return null; return comp.addGsapTween(targetId, tween); } @@ -130,7 +130,7 @@ export function addBounce( fromProperties: { y: 60, opacity: 0 }, ...overrides, }; - if (!comp.can({ type: "addGsapTween", target: targetId, id: "preflight", tween })) return null; + if (!comp.can({ type: "addGsapTween", target: targetId, tween }).ok) return null; return comp.addGsapTween(targetId, tween); } diff --git a/packages/sdk/src/adapters/fs.ts b/packages/sdk/src/adapters/fs.ts index 76d09edbed..7f13606edd 100644 --- a/packages/sdk/src/adapters/fs.ts +++ b/packages/sdk/src/adapters/fs.ts @@ -18,6 +18,7 @@ class FsAdapter implements PersistAdapter { private errorHandlers: Array<(e: PersistErrorEvent) => void> = []; private readonly inflightWrites = new Set>(); private versionCounter = 0; + private appendVersionQueue = Promise.resolve(); constructor(opts: FsAdapterOptions) { this.root = opts.root; @@ -109,7 +110,14 @@ class FsAdapter implements PersistAdapter { return join(this.root, ".hf-versions", path); } - private async appendVersion(path: string, content: string): Promise { + private appendVersion(path: string, content: string): Promise { + this.appendVersionQueue = this.appendVersionQueue.then(() => + this.doAppendVersion(path, content), + ); + return this.appendVersionQueue; + } + + private async doAppendVersion(path: string, content: string): Promise { const dir = this.versionsDir(path); await mkdir(dir, { recursive: true }); // Pad counter to 6 digits so lexicographic sort = insertion order within same ms. diff --git a/packages/sdk/src/adapters/http.test.ts b/packages/sdk/src/adapters/http.test.ts index 19c39bb989..b3a8786ce5 100644 --- a/packages/sdk/src/adapters/http.test.ts +++ b/packages/sdk/src/adapters/http.test.ts @@ -59,11 +59,17 @@ describe("read()", () => { expect(await adapter.read("missing.html")).toBeUndefined(); }); - it("returns undefined on non-ok response", async () => { + it("returns undefined on 404 response", async () => { stubFetch(() => ({ ok: false, status: 404 })); const adapter = createHttpAdapter({ projectFilesUrl: BASE }); expect(await adapter.read("gone.html")).toBeUndefined(); }); + + it("throws on 5xx server error", async () => { + stubFetch(() => ({ ok: false, status: 503 })); + const adapter = createHttpAdapter({ projectFilesUrl: BASE }); + await expect(adapter.read("comp.html")).rejects.toThrow("HTTP 503"); + }); }); // ── write() ─────────────────────────────────────────────────────────────────── diff --git a/packages/sdk/src/adapters/http.ts b/packages/sdk/src/adapters/http.ts index ed50a17fe1..8bdad04be2 100644 --- a/packages/sdk/src/adapters/http.ts +++ b/packages/sdk/src/adapters/http.ts @@ -30,7 +30,8 @@ class HttpAdapter implements PersistAdapter { async read(path: string): Promise { const url = `${this.baseUrl}/files/${encodeURIComponent(path)}?optional=1`; const res = await fetch(url); - if (!res.ok) return undefined; + if (res.status === 404) return undefined; + if (!res.ok) throw new Error(`HTTP ${res.status}`); const data = (await res.json()) as { content?: string }; return typeof data.content === "string" ? data.content : undefined; } diff --git a/packages/sdk/src/engine/mutate.gsap.test.ts b/packages/sdk/src/engine/mutate.gsap.test.ts index 4e2596714a..5e19ca8d8f 100644 --- a/packages/sdk/src/engine/mutate.gsap.test.ts +++ b/packages/sdk/src/engine/mutate.gsap.test.ts @@ -177,16 +177,17 @@ describe("addGsapTween", () => { expect(newScript).toContain("opacity: 1"); }); - it("returns EMPTY when no GSAP script", () => { + it("throws when no GSAP script block exists in composition", () => { const noScript = parseMutable( `
`, ); - const result = applyOp(noScript, { - type: "addGsapTween", - target: "hf-box", - tween: { method: "to", properties: { x: 1 } }, - }); - expect(result.forward).toHaveLength(0); + expect(() => + applyOp(noScript, { + type: "addGsapTween", + target: "hf-box", + tween: { method: "to", properties: { x: 1 } }, + }), + ).toThrow("No GSAP script block found"); }); }); @@ -477,3 +478,41 @@ window.__timelines["t"] = tl;`; expect(newScript).toContain("hf-stage"); }); }); + +// ─── GSAP ops on composition with no script block ──────────────────────────── + +const NO_SCRIPT_HTML = `
+
+
`.trim(); + +describe("GSAP ops on composition with no GSAP script block", () => { + function freshNoScript() { + return parseMutable(NO_SCRIPT_HTML); + } + + it("addGsapTween throws instead of silent no-op", () => { + expect(() => + applyOp(freshNoScript(), { + type: "addGsapTween", + target: "hf-box", + tween: { method: "to", properties: { x: 100 } }, + }), + ).toThrow(); + }); + + it("setGsapTween throws instead of silent no-op", () => { + expect(() => + applyOp(freshNoScript(), { + type: "setGsapTween", + animationId: "anim-1", + properties: { ease: "power2.out" }, + }), + ).toThrow(); + }); + + it("removeGsapTween throws instead of silent no-op", () => { + expect(() => + applyOp(freshNoScript(), { type: "removeGsapTween", animationId: "anim-1" }), + ).toThrow(); + }); +}); diff --git a/packages/sdk/src/engine/mutate.test.ts b/packages/sdk/src/engine/mutate.test.ts index 89be75d2a0..5323cdd501 100644 --- a/packages/sdk/src/engine/mutate.test.ts +++ b/packages/sdk/src/engine/mutate.test.ts @@ -389,14 +389,14 @@ describe("validateOp", () => { // ─── Phase 3b ops — graceful when no GSAP script, feature-detectable ──────── describe("Phase 3b ops", () => { - it("applyOp returns EMPTY when no GSAP script is present", () => { - const result = applyOp(fresh(), { - type: "addGsapTween", - target: "hf-title", - tween: { method: "from", properties: { opacity: 0 } }, - }); - expect(result.forward).toHaveLength(0); - expect(result.inverse).toHaveLength(0); + it("applyOp throws when no GSAP script block is present", () => { + expect(() => + applyOp(fresh(), { + type: "addGsapTween", + target: "hf-title", + tween: { method: "from", properties: { opacity: 0 } }, + }), + ).toThrow("No GSAP script block found"); }); it("validateOp returns ok:false / E_NO_GSAP_SCRIPT when no GSAP script present", () => { diff --git a/packages/sdk/src/engine/mutate.ts b/packages/sdk/src/engine/mutate.ts index d6015ce160..d18c622de1 100644 --- a/packages/sdk/src/engine/mutate.ts +++ b/packages/sdk/src/engine/mutate.ts @@ -509,10 +509,15 @@ function handleSetVariableValue( // ─── GSAP selector helpers ─────────────────────────────────────────────────── function selectorMatchesId(selector: string, id: HfId): boolean { + const bareId = id.includes("/") ? id.split("/").pop()! : id; return ( selector === `[data-hf-id="${id}"]` || selector === `[data-hf-id='${id}']` || - selector === `#${id}` + selector === `#${id}` || + (bareId !== id && + (selector === `[data-hf-id="${bareId}"]` || + selector === `[data-hf-id='${bareId}']` || + selector === `#${bareId}`)) ); } @@ -585,6 +590,8 @@ function handleAddGsapTween( tween: GsapTweenSpec, ): MutationResult { const script = getGsapScript(parsed.document); + if (script === null) + throw new Error("No GSAP script block found. Use comp.can(op) to check first."); if (!script) return EMPTY; const extras: Record = {}; @@ -623,6 +630,8 @@ function handleSetGsapTween( properties: Partial, ): MutationResult { const script = getGsapScript(parsed.document); + if (script === null) + throw new Error("No GSAP script block found. Use comp.can(op) to check first."); if (!script) return EMPTY; const updates: Partial = {}; @@ -649,6 +658,8 @@ function handleSetGsapTween( function handleRemoveGsapTween(parsed: ParsedDocument, animationId: string): MutationResult { const script = getGsapScript(parsed.document); + if (script === null) + throw new Error("No GSAP script block found. Use comp.can(op) to check first."); if (!script) return EMPTY; const newScript = removeAnimationFromScript(script, animationId); if (newScript === script) return EMPTY; diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx index 783d18753d..5c587e8278 100644 --- a/packages/studio/src/App.tsx +++ b/packages/studio/src/App.tsx @@ -152,6 +152,9 @@ export function StudioApp() { domEditSaveTimestampRef, setRefreshKey, }); + + const sdkSession = useSdkSession(projectId, activeCompPath, domEditSaveTimestampRef); + useEffect(() => { if (activeCompPathHydrated) return; if (!fileManager.fileTreeLoaded) return; diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.ts index 51931b012b..d2fa24562b 100644 --- a/packages/studio/src/hooks/useDomEditCommits.ts +++ b/packages/studio/src/hooks/useDomEditCommits.ts @@ -134,7 +134,6 @@ export function useDomEditCommits({ if (options?.shouldSave && !options.shouldSave()) return; const targetPath = selection.sourceFile || activeCompPath || "index.html"; - const readResponse = await fetch( `/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`, ); @@ -146,9 +145,14 @@ export function useDomEditCommits({ if (typeof originalContent !== "string") { throw new Error(`Missing file contents for ${targetPath}`); } - if (options?.shouldSave && !options.shouldSave()) return; - + if ( + onTrySdkPersist && + (await onTrySdkPersist(selection, operations, originalContent, targetPath)) + ) { + onDomEditPersisted?.(selection, operations); + return; + } const patchTarget = buildDomEditPatchTarget(selection); const patchBody = { target: patchTarget, operations }; const unsafeFields = findUnsafeDomPatchValues(patchBody); @@ -162,7 +166,6 @@ export function useDomEditCommits({ // handler suppresses the reload even if the event arrives before the // response (the server writes the file and emits SSE during the fetch). domEditSaveTimestampRef.current = Date.now(); - const patchResponse = await fetch( `/api/projects/${pid}/file-mutations/patch-element/${encodeURIComponent(targetPath)}`, { diff --git a/packages/studio/src/hooks/useSdkSession.ts b/packages/studio/src/hooks/useSdkSession.ts index 7a3fbf1ee8..e99ede9731 100644 --- a/packages/studio/src/hooks/useSdkSession.ts +++ b/packages/studio/src/hooks/useSdkSession.ts @@ -1,4 +1,5 @@ import { useState, useEffect } from "react"; +import type { MutableRefObject } from "react"; import { openComposition } from "@hyperframes/sdk"; import { createHttpAdapter } from "@hyperframes/sdk/adapters/http"; import type { Composition } from "@hyperframes/sdk"; @@ -27,9 +28,12 @@ export function shouldReloadSdkSession(payload: unknown, activeCompPath: string * is therefore purely additive — no SDK self-write exists yet, so there is no * persist echo. Step 3c must add self-write suppression once dispatch writes. */ +const SELF_WRITE_SUPPRESS_MS = 2000; + export function useSdkSession( projectId: string | null, activeCompPath: string | null, + domEditSaveTimestampRef?: MutableRefObject, ): Composition | null { const [session, setSession] = useState(null); const [reloadToken, setReloadToken] = useState(0); @@ -38,9 +42,14 @@ export function useSdkSession( useEffect(() => { if (!activeCompPath) return; const handler = (payload?: unknown) => { - if (shouldReloadSdkSession(payload, activeCompPath)) { - setReloadToken((t) => t + 1); - } + if (!shouldReloadSdkSession(payload, activeCompPath)) return; + // Suppress reload triggered by our own SDK cutover write. + if ( + domEditSaveTimestampRef && + Date.now() - domEditSaveTimestampRef.current < SELF_WRITE_SUPPRESS_MS + ) + return; + setReloadToken((t) => t + 1); }; if (import.meta.hot) { import.meta.hot.on("hf:file-change", handler); @@ -50,6 +59,7 @@ export function useSdkSession( const es = new EventSource("/api/events"); es.addEventListener("file-change", handler); return () => es.close(); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeCompPath]); // ── Open / re-open the session ── @@ -60,7 +70,7 @@ export function useSdkSession( } let cancelled = false; - let comp: Composition | null = null; + const compRef = { current: null as Composition | null }; const adapter = createHttpAdapter({ projectFilesUrl: `/api/projects/${projectId}`, @@ -69,7 +79,7 @@ export function useSdkSession( .read(activeCompPath) .then(async (content) => { if (cancelled || typeof content !== "string") return; - comp = await openComposition(content, { + const comp = await openComposition(content, { persist: adapter, persistPath: activeCompPath, }); @@ -81,6 +91,7 @@ export function useSdkSession( comp.dispose(); return; } + compRef.current = comp; setSession(comp); }) .catch(() => { @@ -89,7 +100,7 @@ export function useSdkSession( return () => { cancelled = true; - const c = comp; + const c = compRef.current; if (c) void c.flush().finally(() => c.dispose()); }; }, [projectId, activeCompPath, reloadToken]); diff --git a/packages/studio/src/utils/sdkShadow.test.ts b/packages/studio/src/utils/sdkShadow.test.ts index 637ab9ba53..7f367e62a3 100644 --- a/packages/studio/src/utils/sdkShadow.test.ts +++ b/packages/studio/src/utils/sdkShadow.test.ts @@ -42,6 +42,20 @@ describe("patchOpsToSdkEditOps", () => { }); }); + it("does not double-prefix attribute op whose property already starts with data-", () => { + const ops: PatchOperation[] = [ + { type: "attribute", property: "data-hf-studio-path-offset", value: "true" }, + ]; + const result = patchOpsToSdkEditOps("hf-box", ops); + expect(result).toHaveLength(1); + expect(result[0]).toEqual({ + type: "setAttribute", + target: "hf-box", + name: "data-hf-studio-path-offset", + value: "true", + }); + }); + it("maps html-attribute op to setAttribute without prefix", () => { const ops: PatchOperation[] = [ { type: "html-attribute", property: "contenteditable", value: "true" }, diff --git a/packages/studio/src/utils/sdkShadow.ts b/packages/studio/src/utils/sdkShadow.ts index 6167039ad1..7a8d799d8d 100644 --- a/packages/studio/src/utils/sdkShadow.ts +++ b/packages/studio/src/utils/sdkShadow.ts @@ -38,7 +38,7 @@ export function patchOpsToSdkEditOps(hfId: string, ops: PatchOperation[]): EditO result.push({ type: "setAttribute", target: hfId, - name: `data-${op.property}`, + name: op.property.startsWith("data-") ? op.property : `data-${op.property}`, value: op.value, }); } else if (op.type === "html-attribute") { @@ -105,11 +105,14 @@ const OP_FIELD_RESOLVERS: Record = { actual: flat.styles[op.property] ?? null, }), "text-content": (op, flat) => ({ property: "text", expected: op.value ?? "", actual: flat.text }), - attribute: (op, flat) => ({ - property: `data-${op.property}`, - expected: op.value ?? null, - actual: flat.attrs[`data-${op.property}`] ?? null, - }), + attribute: (op, flat) => { + const attrName = op.property.startsWith("data-") ? op.property : `data-${op.property}`; + return { + property: attrName, + expected: op.value ?? null, + actual: flat.attrs[attrName] ?? null, + }; + }, "html-attribute": (op, flat) => ({ property: op.property, expected: op.value ?? null,