Skip to content

Write HTML. Render video. Built for agents.

fix(studio): make sdk cutover transactional (#2155)

James Russo42055296ee71
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index 9098891dcb..e82357a54c 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -227,8 +227,10 @@ function foldElementPatches(
/**
* The single commit owner for element patch batches. All files are resolved,
* read, and folded before the first write; any unmatched target refuses the
- * whole request. The final snapshots/writes are synchronous, so another route
- * cannot interleave once the commit section begins.
+ * whole request. Studio Server is intentionally single-process; within that
+ * process the final snapshots/writes are synchronous, so another route cannot
+ * interleave once the commit section begins. A multi-process deployment must
+ * replace this process-local guarantee with a shared per-project file lock.
*/
export function commitElementPatchBatches(
projectDir: string,
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx
index 52048298fb..51df24c444 100644
--- a/packages/studio/src/App.tsx
+++ b/packages/studio/src/App.tsx
@@ -71,14 +71,12 @@ export function StudioApp() {
const { projectId, resolving, waitingForServer } = useServerConnection();
const initialUrlStateRef = useRef(readStudioUrlStateFromWindow());
const viewModeValue = useViewModeState();
-
useEffect(() => {
if (resolving || waitingForServer) return;
if (hasFiredSessionStart()) return;
markSessionStartFired();
trackStudioSessionStart({ has_project: projectId != null });
}, [projectId, resolving, waitingForServer]);
-
const [activeCompPath, setActiveCompPath] = useState<string | null>(null);
const [activeCompPathHydrated, setActiveCompPathHydrated] = useState(
() => initialUrlStateRef.current.activeCompPath == null,
@@ -176,6 +174,7 @@ export function StudioApp() {
uploadProjectFiles: fileManager.uploadProjectFiles,
isRecordingRef: isGestureRecordingRef,
sdkSession: editFlowSdkSession,
+ publishSdkSession: sdkHandle.publish,
forceReloadSdkSession: sdkHandle.forceReload,
handleDomZIndexReorderCommitRef,
});
@@ -317,6 +316,7 @@ export function StudioApp() {
selectSidebarTab: sidebarTabRef.current.select,
getSidebarTab: sidebarTabRef.current.get,
sdkSession: editFlowSdkSession,
+ publishSdkSession: sdkHandle.publish,
forceReloadSdkSession: sdkHandle.forceReload,
});
domEditSelectionBridgeRef.current = domEditSession.domEditSelection;
@@ -331,7 +331,6 @@ export function StudioApp() {
domEditSession.domEditSelection,
domEditSession.domEditGroupSelections,
);
-
useCaptionDetection({
projectId,
activeCompPath,
@@ -533,6 +532,7 @@ export function StudioApp() {
recordingDuration={gestureRecording.recordingDuration}
onToggleRecording={recordingToggle}
sdkSession={sdkHandle.session}
+ publishSdkSession={sdkHandle.publish}
reloadPreview={reloadPreview}
domEditSaveTimestampRef={domEditSaveTimestampRef}
recordEdit={editHistory.recordEdit}
diff --git a/packages/studio/src/components/DesignPanelPromoteProvider.tsx b/packages/studio/src/components/DesignPanelPromoteProvider.tsx
index 80b523955f..4213f13104 100644
--- a/packages/studio/src/components/DesignPanelPromoteProvider.tsx
+++ b/packages/studio/src/components/DesignPanelPromoteProvider.tsx
@@ -9,11 +9,12 @@
* composition, so behavior there is unchanged.
*/
-import type { ReactNode } from "react";
+import { useCallback, type ReactNode } from "react";
import type { DomEditSelection } from "./editor/domEditingTypes";
import { useSdkSession } from "../hooks/useSdkSession";
import { useVariablesPersist, type UseVariablesPersistParams } from "../hooks/useVariablesPersist";
import { VariablePromoteProvider } from "../contexts/VariablePromoteContext";
+import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics";
/** Persist wiring minus the target — this provider derives the target from the selection. */
type PersistDeps = Omit<UseVariablesPersistParams, "sdkSession" | "activeCompPath">;
@@ -22,12 +23,14 @@ export function DesignPanelPromoteProvider({
selection,
projectId,
activeCompPath,
+ showToast,
children,
...persistDeps
}: PersistDeps & {
selection: DomEditSelection | null;
projectId: string | null;
activeCompPath: string | null;
+ showToast: (message: string, tone?: "error" | "info") => void;
children: ReactNode;
}) {
const targetPath = selection?.sourceFile || activeCompPath || "index.html";
@@ -35,10 +38,20 @@ export function DesignPanelPromoteProvider({
const persist = useVariablesPersist({
...persistDeps,
sdkSession: handle.session,
+ publishSdkSession: handle.publish,
activeCompPath: targetPath,
});
+ const handlePersistError = useCallback(
+ (error: unknown) => showToast(getStudioSaveErrorMessage(error), "error"),
+ [showToast],
+ );
return (
- <VariablePromoteProvider session={handle.session} selection={selection} persist={persist}>
+ <VariablePromoteProvider
+ session={handle.session}
+ selection={selection}
+ persist={persist}
+ onPersistError={handlePersistError}
+ >
{children}
</VariablePromoteProvider>
);
diff --git a/packages/studio/src/components/StudioRightPanel.tsx b/packages/studio/src/components/StudioRightPanel.tsx
index ed17525c14..cac09bc944 100644
--- a/packages/studio/src/components/StudioRightPanel.tsx
+++ b/packages/studio/src/components/StudioRightPanel.tsx
@@ -15,7 +15,7 @@ import type { IframeWindow } from "../player/lib/playbackTypes";
import { STUDIO_INSPECTOR_PANELS_ENABLED } from "./editor/manualEditingAvailability";
import type { Composition } from "@hyperframes/sdk";
import type { EditHistoryKind } from "../utils/editHistory";
-import { useSlideshowPersist } from "../hooks/useSlideshowPersist";
+import { useSlideshowPersist, type UseSlideshowPersistParams } from "../hooks/useSlideshowPersist";
import { DesignPanelPromoteProvider } from "./DesignPanelPromoteProvider";
import { useStudioPlaybackContext, useStudioShellContext } from "../contexts/StudioContext";
@@ -47,6 +47,7 @@ export interface StudioRightPanelProps {
onToggleRecording?: () => void;
/** Dependencies for the Slideshow persist callback, threaded from App.tsx. */
sdkSession: Composition | null;
+ publishSdkSession: NonNullable<UseSlideshowPersistParams["publishSdkSession"]>;
reloadPreview: () => void;
domEditSaveTimestampRef: MutableRefObject<number>;
recordEdit: (entry: {
@@ -66,6 +67,7 @@ export function StudioRightPanel({
recordingDuration,
onToggleRecording,
sdkSession,
+ publishSdkSession,
reloadPreview,
domEditSaveTimestampRef,
recordEdit,
@@ -160,6 +162,7 @@ export function StudioRightPanel({
recordEdit,
reloadPreview,
domEditSaveTimestampRef,
+ publishSdkSession,
});
// Notes path: persists are debounced in SlideshowPanel; coalesceKey ensures
@@ -172,6 +175,7 @@ export function StudioRightPanel({
recordEdit,
reloadPreview,
domEditSaveTimestampRef,
+ publishSdkSession,
coalesceKey: activeCompPath ? `slideshow-notes:${activeCompPath}` : "slideshow-notes",
});
@@ -305,7 +309,6 @@ export function StudioRightPanel({
},
[projectId, refreshFileTree, showToast],
);
-
const handleHideAllSelected = () => {
const { elements } = usePlayerStore.getState();
const keys = timelineKeysForSelections(domEditGroupSelections, elements, activeCompPath);
@@ -316,6 +319,7 @@ export function StudioRightPanel({
selection={domEditGroupSelections.length > 1 ? null : domEditSelection}
projectId={projectId}
activeCompPath={activeCompPath}
+ showToast={showToast}
readProjectFile={readProjectFile}
writeProjectFile={writeProjectFile}
recordEdit={recordEdit}
@@ -507,6 +511,7 @@ export function StudioRightPanel({
) : rightPanelTab === "variables" ? (
<VariablesPanel
sdkSession={sdkSession}
+ publishSdkSession={publishSdkSession}
reloadPreview={reloadPreview}
domEditSaveTimestampRef={domEditSaveTimestampRef}
recordEdit={recordEdit}
diff --git a/packages/studio/src/components/panels/VariablesPanel.tsx b/packages/studio/src/components/panels/VariablesPanel.tsx
index fce436e633..73139a847e 100644
--- a/packages/studio/src/components/panels/VariablesPanel.tsx
+++ b/packages/studio/src/components/panels/VariablesPanel.tsx
@@ -6,6 +6,7 @@ import type {
VariableValidationIssue,
} from "@hyperframes/sdk";
import type { EditHistoryKind } from "../../utils/editHistory";
+import type { PublishSdkSession } from "../../utils/sdkCutover";
import { useStudioPlaybackContext, useStudioShellContext } from "../../contexts/StudioContext";
import { useDomEditContext } from "../../contexts/DomEditContext";
import { useFileManagerContext } from "../../contexts/FileManagerContext";
@@ -32,6 +33,7 @@ function shellSingleQuote(value: string): string {
interface VariablesPanelProps {
sdkSession: Composition | null;
+ publishSdkSession: PublishSdkSession;
reloadPreview: () => void;
domEditSaveTimestampRef: MutableRefObject<number>;
recordEdit: (entry: {
@@ -247,6 +249,7 @@ const EMPTY_STATE = (
// fallow-ignore-next-line complexity
export const VariablesPanel = memo(function VariablesPanel({
sdkSession,
+ publishSdkSession,
reloadPreview,
domEditSaveTimestampRef,
recordEdit,
@@ -285,6 +288,7 @@ export const VariablesPanel = memo(function VariablesPanel({
recordEdit,
reloadPreview,
domEditSaveTimestampRef,
+ publishSdkSession,
});
const declarations = useMemo(
diff --git a/packages/studio/src/contexts/VariablePromoteContext.test.tsx b/packages/studio/src/contexts/VariablePromoteContext.test.tsx
new file mode 100644
index 0000000000..812f5718ea
--- /dev/null
+++ b/packages/studio/src/contexts/VariablePromoteContext.test.tsx
@@ -0,0 +1,67 @@
+// @vitest-environment happy-dom
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vitest";
+import type { Composition } from "@hyperframes/sdk";
+import type { DomEditSelection } from "../components/editor/domEditingTypes";
+import {
+ VariablePromoteProvider,
+ useVariablePromoteChannel,
+ type ChannelPromote,
+} from "./VariablePromoteContext";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("VariablePromoteProvider save failures", () => {
+ it("reports a rejected promote instead of leaving an unhandled promise", async () => {
+ const snapshot = {
+ attributes: { id: "box" },
+ inlineStyles: {},
+ text: "",
+ children: [],
+ };
+ const session = {
+ getElement: vi.fn().mockReturnValue(snapshot),
+ getVariableDeclarations: vi.fn().mockReturnValue([]),
+ on: vi.fn().mockReturnValue(() => {}),
+ } as unknown as Composition;
+ const selection = {
+ hfId: "hf-box",
+ tagName: "div",
+ label: "Box",
+ capabilities: { canEditStyles: true },
+ computedStyles: { color: "rgb(255, 0, 0)" },
+ } as unknown as DomEditSelection;
+ const error = new Error("write failed");
+ const persist = vi.fn().mockRejectedValue(error);
+ const onPersistError = vi.fn();
+ let channel: ChannelPromote | null = null;
+
+ function Consumer() {
+ channel = useVariablePromoteChannel({ kind: "style", prop: "color" });
+ return null;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ act(() => {
+ root.render(
+ <VariablePromoteProvider
+ session={session}
+ selection={selection}
+ persist={persist}
+ onPersistError={onPersistError}
+ >
+ <Consumer />
+ </VariablePromoteProvider>,
+ );
+ });
+ act(() => channel?.promote());
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(persist).toHaveBeenCalledOnce();
+ expect(onPersistError).toHaveBeenCalledWith(error);
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/contexts/VariablePromoteContext.tsx b/packages/studio/src/contexts/VariablePromoteContext.tsx
index 31b244ca9a..18fac0cb54 100644
--- a/packages/studio/src/contexts/VariablePromoteContext.tsx
+++ b/packages/studio/src/contexts/VariablePromoteContext.tsx
@@ -44,6 +44,7 @@ interface VariablePromoteContextValue {
actions: BindAction[];
declarations: CompositionVariable[];
persist: (label: string, mutate: (session: Composition) => void) => Promise<boolean>;
+ onPersistError: (error: unknown) => void;
}
const VariablePromoteContext = createContext<VariablePromoteContextValue | null>(null);
@@ -58,11 +59,13 @@ export function VariablePromoteProvider({
session,
selection,
persist,
+ onPersistError,
children,
}: {
session: Composition | null;
selection: DomEditSelection | null;
persist: (label: string, mutate: (session: Composition) => void) => Promise<boolean>;
+ onPersistError: (error: unknown) => void;
children: React.ReactNode;
}) {
// Re-derive actions/bindings after each persisted schema edit.
@@ -85,8 +88,8 @@ export function VariablePromoteProvider({
}, [session, revision]);
const value = useMemo<VariablePromoteContextValue>(
- () => ({ session, selection, actions, declarations, persist }),
- [session, selection, actions, declarations, persist],
+ () => ({ session, selection, actions, declarations, persist, onPersistError }),
+ [session, selection, actions, declarations, persist, onPersistError],
);
return (
@@ -105,7 +108,7 @@ export function useVariablePromoteChannel(channel: PromoteChannel): ChannelPromo
return useMemo(() => {
if (!ctx || !ctx.session || !ctx.selection?.hfId) return null;
- const { session, selection, actions, declarations, persist } = ctx;
+ const { session, selection, actions, declarations, persist, onPersistError } = ctx;
const hfId = selection.hfId!;
const action = matchAction(actions, channel);
const boundId = readBinding(session, hfId, channel);
@@ -125,12 +128,14 @@ export function useVariablePromoteChannel(channel: PromoteChannel): ChannelPromo
const id = uniqueId(action.suggestedId, declarations);
void persist(`Bind ${action.label.toLowerCase()} to variable "${id}"`, (s) =>
applyBind(s, hfId, action, id),
- );
+ ).catch(onPersistError);
},
setDefault: (raw: string) => {
if (!boundId || !declaration) return;
const next = declaration.type === "color" ? rgbToHex(raw) : raw;
- void persist(`Set default for "${boundId}"`, (s) => s.setVariableValue(boundId, next));
+ void persist(`Set default for "${boundId}"`, (s) =>
+ s.setVariableValue(boundId, next),
+ ).catch(onPersistError);
},
};
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/packages/studio/src/hooks/gsapScriptCommitTypes.ts b/packages/studio/src/hooks/gsapScriptCommitTypes.ts
index 4de90da3d0..137dc2af18 100644
--- a/packages/studio/src/hooks/gsapScriptCommitTypes.ts
+++ b/packages/studio/src/hooks/gsapScriptCommitTypes.ts
@@ -2,6 +2,7 @@ import type { ParsedGsap } from "@hyperframes/core/gsap-parser";
import type { Composition } from "@hyperframes/sdk";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import type { EditHistoryKind } from "../utils/editHistory";
+import type { PublishSdkSession } from "../utils/sdkCutover";
import type { RuntimeTweenChange } from "./gsapRuntimePatch";
export interface MutationResult {
@@ -22,10 +23,9 @@ export interface CommitMutationOptions {
beforeReload?: () => void;
/**
* Serialize this commit against others sharing the same key. Used to chain
- * per-animationId GSAP meta updates so overlapping read-modify-write POSTs to
- * one file can't interleave — which would pair the shadow fidelity diff with a
- * stale server result and report false ease mismatches. Commits without a key
- * (and under distinct keys) run concurrently as before.
+ * per-animationId GSAP meta updates. Every commit independently takes the
+ * project/file mutation lock, so this key only adds ordering and can never
+ * bypass whole-file serialization.
*/
serializeKey?: string;
/**
@@ -87,6 +87,8 @@ export interface GsapScriptCommitsParams {
showToast: (message: string, tone?: "error" | "info") => void;
/** Stage 7 §3.5: SDK session for routing GSAP tween ops through addGsapTween/setGsapTween/removeGsapTween. */
sdkSession?: Composition | null;
+ /** Publish a fully persisted candidate SDK session. */
+ publishSdkSession?: PublishSdkSession;
writeProjectFile?: (path: string, content: string) => Promise<void>;
/** Resync the in-memory SDK session after a server-authoritative write. */
forceReloadSdkSession?: () => void;
diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts
index 165bab8e69..8d18a76399 100644
--- a/packages/studio/src/hooks/useAppHotkeys.ts
+++ b/packages/studio/src/hooks/useAppHotkeys.ts
@@ -9,6 +9,7 @@ import { shouldIgnoreHistoryShortcut } from "../utils/studioHelpers";
import { canSplitElement } from "../utils/timelineElementSplit";
import { STUDIO_RAZOR_TOOL_ENABLED } from "../components/editor/manualEditingAvailability";
import { trackStudioEvent } from "../utils/studioTelemetry";
+import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
function iframeContentWindow(iframe: HTMLIFrameElement | null): Window | null {
try {
@@ -87,6 +88,7 @@ interface HistoryResult {
interface HistoryFileCallbacks {
readFile: (path: string) => Promise<string>;
writeFile: (path: string, content: string) => Promise<void>;
+ serialize?: <T>(paths: readonly string[], task: () => Promise<T>) => Promise<T>;
}
interface EditHistoryHandle {
undo: (cb: HistoryFileCallbacks) => Promise<HistoryResult>;
@@ -367,6 +369,11 @@ export function useAppHotkeys({
},
[domEditSaveTimestampRef, writeProjectFile],
);
+ const serializeHistoryFiles = useCallback(
+ <T>(paths: readonly string[], task: () => Promise<T>) =>
+ serializeStudioFileMutations(writeProjectFile, paths, task),
+ [writeProjectFile],
+ );
const applyHistory = useCallback(
async (direction: "undo" | "redo") => {
@@ -377,6 +384,7 @@ export function useAppHotkeys({
const result = await editHistory[direction]({
readFile: readHistoryFile,
writeFile: writeHistoryFile,
+ serialize: serializeHistoryFiles,
});
if (!result.ok && result.reason === "content-mismatch") {
showToast(
@@ -406,6 +414,7 @@ export function useAppHotkeys({
syncHistoryPreviewAfterApply,
waitForPendingDomEditSaves,
writeHistoryFile,
+ serializeHistoryFiles,
onAfterUndoRedo,
activeCompPath,
forceReloadSdkSession,
diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.ts
index 2f8e435d9f..c9fec08076 100644
--- a/packages/studio/src/hooks/useDomEditCommits.ts
+++ b/packages/studio/src/hooks/useDomEditCommits.ts
@@ -32,7 +32,7 @@ import {
patchElementBatches,
readErrorResponseBody,
} from "./useDomEditCommitsHelpers";
-
+import { cutoverCommittedOrThrow, type CutoverResult } from "../utils/sdkCutover";
interface RecordEditInput {
label: string;
kind: EditHistoryKind;
@@ -71,16 +71,20 @@ export interface UseDomEditCommitsParams {
* path, whose session is already current) so a later SDK edit doesn't
* serialize the pre-write doc and revert the server's change. */
forceReloadSdkSession?: () => void;
- /** Stage 7 Step 3c: called before the server-side patch path; returns true if SDK handled it. */
+ /** Stage 7 Step 3c: called before the server-side patch path. */
onTrySdkPersist?: (
selection: DomEditSelection,
operations: PatchOperation[],
originalContent: string,
targetPath: string,
options?: { label?: string; coalesceKey?: string; skipRefresh?: boolean },
- ) => Promise<boolean>;
- /** Stage 7 §3.1: called before the server-side delete path; returns true if SDK handled it. */
- onTrySdkDelete?: (hfId: string, originalContent: string, targetPath: string) => Promise<boolean>;
+ ) => Promise<CutoverResult>;
+ /** Stage 7 §3.1: called before the server-side delete path. */
+ onTrySdkDelete?: (
+ hfId: string,
+ originalContent: string,
+ targetPath: string,
+ ) => Promise<CutoverResult>;
/** Resolver-shadow tripwire for z-index reorder targets (telemetry-only, decoupled from cutover). */
onReorderShadow?: (targets: string[]) => void;
}
@@ -175,18 +179,17 @@ export function useDomEditCommits({
// Skip the SDK path when prepareContent is set (e.g. @font-face injection
// for a custom font): sdkCutoverPersist serializes only the patched DOM
// and would drop the injected content. Let the server path run prepareContent.
- if (
- onTrySdkPersist &&
- !options?.prepareContent &&
- (await onTrySdkPersist(selection, operations, originalContent, targetPath, {
+ if (onTrySdkPersist && !options?.prepareContent) {
+ const cutover = await onTrySdkPersist(selection, operations, originalContent, targetPath, {
label: options?.label,
coalesceKey: options?.coalesceKey,
skipRefresh: options?.skipRefresh,
- }))
- ) {
- // SDK handled it — its in-memory doc is already current, so do NOT
- // forceReload (that would echo-reload the session we just wrote).
- return;
+ });
+ if (cutoverCommittedOrThrow(cutover)) {
+ // SDK handled it — its in-memory doc is already current, so do NOT
+ // forceReload (that would echo-reload the session we just wrote).
+ return;
+ }
}
// Mark the save timestamp before the file write so the SSE file-change
diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.ts
index ee1a3ea52f..d84cf823a7 100644
--- a/packages/studio/src/hooks/useDomEditSession.ts
+++ b/packages/studio/src/hooks/useDomEditSession.ts
@@ -7,7 +7,7 @@ import type { RightPanelTab } from "../utils/studioHelpers";
import type { PatchTarget } from "../utils/sourcePatcher";
import type { SidebarTab } from "../components/sidebar/LeftSidebar";
import type { Composition } from "@hyperframes/sdk";
-import { sdkCutoverPersist, sdkDeletePersist } from "../utils/sdkCutover";
+import { sdkCutoverPersist, sdkDeletePersist, type PublishSdkSession } from "../utils/sdkCutover";
import { runResolverShadow, recordResolverParity } from "../utils/sdkResolverShadow";
import { useAskAgentModal } from "./useAskAgentModal";
import { useDomSelection } from "./useDomSelection";
@@ -67,6 +67,7 @@ export interface UseDomEditSessionParams {
selectSidebarTab?: (tab: SidebarTab) => void;
getSidebarTab?: () => SidebarTab;
sdkSession?: Composition | null;
+ publishSdkSession?: PublishSdkSession;
forceReloadSdkSession?: () => void;
}
@@ -108,10 +109,10 @@ export function useDomEditSession({
selectSidebarTab,
getSidebarTab,
sdkSession,
+ publishSdkSession,
forceReloadSdkSession,
}: UseDomEditSessionParams) {
void _setRefreshKey;
-
// ── Selection ──
const {
@@ -178,7 +179,6 @@ export function useDomEditSession({
previewDocumentVersion,
refreshDomEditSelectionFromPreview,
});
-
// ── GSAP cache (hoisted so both useGsapScriptCommits and useDomEditWiring share the same instance) ──
const { version: gsapCacheVersion, bump: bumpGsapCache } = useGsapCacheVersion();
@@ -217,6 +217,7 @@ export function useDomEditSession({
onFileContentChanged: updateEditingFileContent,
showToast,
sdkSession,
+ publishSdkSession,
writeProjectFile,
forceReloadSdkSession,
});
@@ -280,6 +281,8 @@ export function useDomEditSession({
reloadPreview,
domEditSaveTimestampRef,
compositionPath: activeCompPath,
+ readProjectFile,
+ publishSession: publishSdkSession,
},
options,
);
@@ -293,6 +296,8 @@ export function useDomEditSession({
reloadPreview,
domEditSaveTimestampRef,
compositionPath: activeCompPath,
+ readProjectFile,
+ publishSession: publishSdkSession,
})
: undefined,
// Resolver shadow for the z-index reorder edit: it takes the server path (no
diff --git a/packages/studio/src/hooks/useDomEditWiring.ts b/packages/studio/src/hooks/useDomEditWiring.ts
index f598cb54e3..19e21d29b6 100644
--- a/packages/studio/src/hooks/useDomEditWiring.ts
+++ b/packages/studio/src/hooks/useDomEditWiring.ts
@@ -55,24 +55,24 @@ export interface UseDomEditWiringParams {
sel: DomEditSelection,
animId: string,
updates: { duration?: number; ease?: string; position?: number },
- ) => void;
- deleteGsapAnimation: (sel: DomEditSelection, animId: string) => void;
- deleteAllForSelector: (sel: DomEditSelection, targetSelector: string) => void;
+ ) => Promise<void>;
+ deleteGsapAnimation: (sel: DomEditSelection, animId: string) => Promise<void>;
+ deleteAllForSelector: (sel: DomEditSelection, targetSelector: string) => Promise<void>;
addGsapAnimation: (
sel: DomEditSelection,
method: "to" | "from" | "set" | "fromTo",
time: number,
) => Promise<void>;
- addGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
- removeGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
+ addGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => Promise<void>;
+ removeGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => Promise<void>;
updateGsapFromProperty: (
sel: DomEditSelection,
animId: string,
prop: string,
value: number | string,
- ) => void;
- addGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
- removeGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
+ ) => Promise<void>;
+ addGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => Promise<void>;
+ removeGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => Promise<void>;
addKeyframe: (
sel: DomEditSelection,
animId: string,
@@ -105,7 +105,7 @@ export interface UseDomEditWiringParams {
animId: string,
resolvedFromValues?: Record<string, number | string>,
) => Promise<void>;
- removeAllKeyframes: (sel: DomEditSelection, animId: string) => void;
+ removeAllKeyframes: (sel: DomEditSelection, animId: string) => Promise<void>;
handleDomManualEditsReset: (sel: DomEditSelection) => void;
}
@@ -245,6 +245,7 @@ export function useDomEditWiring({
removeAllKeyframes,
handleDomManualEditsReset,
selectedGsapAnimations,
+ showToast,
});
// ── Preview sync side-effects ──
diff --git a/packages/studio/src/hooks/useElementLifecycleOps.ts b/packages/studio/src/hooks/useElementLifecycleOps.ts
index 4eb8110c96..4e17c5af36 100644
--- a/packages/studio/src/hooks/useElementLifecycleOps.ts
+++ b/packages/studio/src/hooks/useElementLifecycleOps.ts
@@ -20,10 +20,15 @@ import {
type LayerRevealCommitOwnership,
} from "../components/editor/useLayerRevealOverride";
import type { CommitDomEditPatchBatches, DomEditPatchBatch } from "./domEditCommitTypes";
+import { cutoverCommittedOrThrow, type CutoverResult } from "../utils/sdkCutover";
interface UseElementLifecycleOpsParams extends DomEditCommitBaseParams {
- /** Route delete through SDK when session resolves the hf-id; returns true if handled. */
- onTrySdkDelete?: (hfId: string, originalContent: string, targetPath: string) => Promise<boolean>;
+ /** Route delete through SDK when session resolves the hf-id. */
+ onTrySdkDelete?: (
+ hfId: string,
+ originalContent: string,
+ targetPath: string,
+ ) => Promise<CutoverResult>;
/** Resolver-shadow tripwire for the reordered targets (telemetry-only, decoupled from cutover). */
onReorderShadow?: (targets: string[]) => void;
/** Resync the SDK session after a server-fallback delete. */
@@ -97,7 +102,7 @@ export function useElementLifecycleOps({
if (onTrySdkDelete && selection.hfId) {
const handled = await onTrySdkDelete(selection.hfId, originalContent, targetPath);
- if (handled) {
+ if (cutoverCommittedOrThrow(handled)) {
clearDomSelection();
usePlayerStore.getState().setSelectedElementId(null);
showToast(`Deleted ${label}. Use Undo to restore it.`, "info");
diff --git a/packages/studio/src/hooks/useFileManager.projectOwnership.test.tsx b/packages/studio/src/hooks/useFileManager.projectOwnership.test.tsx
new file mode 100644
index 0000000000..89ce79ee4e
--- /dev/null
+++ b/packages/studio/src/hooks/useFileManager.projectOwnership.test.tsx
@@ -0,0 +1,98 @@
+// @vitest-environment happy-dom
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("./useFileTree", () => ({
+ useFileTree: () => ({
+ projectDir: "",
+ fileTree: [],
+ setFileTree: vi.fn(),
+ fileTreeLoaded: true,
+ refreshFileTree: vi.fn(async () => {}),
+ compositions: [],
+ assets: [],
+ fontAssets: [],
+ }),
+}));
+
+vi.mock("./useEditorSave", () => ({
+ useEditorSave: () => ({
+ saveRafRef: { current: null },
+ handleContentChange: vi.fn(),
+ }),
+}));
+
+import { useFileManager } from "./useFileManager";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("useFileManager project ownership", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("keeps delayed callbacks bound to the project that created them", async () => {
+ let resolveProjectARead: ((value: Response) => void) | undefined;
+ const projectARead = new Promise<Response>((resolve) => {
+ resolveProjectARead = resolve;
+ });
+ const fetchMock = vi.fn((url: string, init?: RequestInit) => {
+ if (url.includes("project-a") && !init?.method) return projectARead;
+ if (!init?.method) {
+ return Promise.resolve({
+ ok: true,
+ json: async () => ({ content: "PROJECT_B" }),
+ } as Response);
+ }
+ return Promise.resolve({ ok: true } as Response);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const captured: { manager: ReturnType<typeof useFileManager> | null } = { manager: null };
+ function Probe({ projectId }: { projectId: string }) {
+ captured.manager = useFileManager({
+ projectId,
+ showToast: vi.fn(),
+ recordEdit: vi.fn(async () => {}),
+ domEditSaveTimestampRef: { current: 0 },
+ setRefreshKey: vi.fn(),
+ });
+ return null;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(<Probe projectId="project-a/../other?x=1" />));
+ const managerA = captured.manager;
+ if (!managerA) throw new Error("project A manager did not render");
+ const delayedRead = managerA.readProjectFile("index.html");
+
+ await act(async () => root.render(<Probe projectId="project-b#fragment" />));
+ const managerB = captured.manager;
+ if (!managerB) throw new Error("project B manager did not render");
+ expect(managerB.writeProjectFile).not.toBe(managerA.writeProjectFile);
+
+ resolveProjectARead?.({
+ ok: true,
+ json: async () => ({ content: "PROJECT_A" }),
+ } as Response);
+ await expect(delayedRead).resolves.toBe("PROJECT_A");
+ await managerA.writeProjectFile("index.html", "A_AFTER");
+ await expect(managerB.readProjectFile("index.html")).resolves.toBe("PROJECT_B");
+ await expect(managerB.readOptionalProjectFile("index.html")).resolves.toBe("PROJECT_B");
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/projects/project-a%2F..%2Fother%3Fx%3D1/files/index.html",
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/projects/project-a%2F..%2Fother%3Fx%3D1/files/index.html",
+ expect.objectContaining({ method: "PUT", body: "A_AFTER" }),
+ );
+ expect(fetchMock).toHaveBeenCalledWith("/api/projects/project-b%23fragment/files/index.html");
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/projects/project-b%23fragment/files/index.html?optional=1",
+ );
+
+ await act(async () => root.unmount());
+ });
+});
diff --git a/packages/studio/src/hooks/useFileManager.ts b/packages/studio/src/hooks/useFileManager.ts
index 9fbc8cc20f..452196384f 100644
--- a/packages/studio/src/hooks/useFileManager.ts
+++ b/packages/studio/src/hooks/useFileManager.ts
@@ -66,38 +66,48 @@ export function useFileManager({
// ── Core file I/O ──
- const readProjectFile = useCallback(async (path: string): Promise<string> => {
- const pid = projectIdRef.current;
- if (!pid) throw new Error("No active project");
- const response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`);
- if (!response.ok) throw new Error(`Failed to read ${path}`);
- const data = (await response.json()) as { content?: string };
- if (typeof data.content !== "string") throw new Error(`Missing file contents for ${path}`);
- return data.content;
- }, []);
+ const readProjectFile = useCallback(
+ async (path: string): Promise<string> => {
+ if (!projectId) throw new Error("No active project");
+ const response = await fetch(
+ `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}`,
+ );
+ if (!response.ok) throw new Error(`Failed to read ${path}`);
+ const data = (await response.json()) as { content?: string };
+ if (typeof data.content !== "string") throw new Error(`Missing file contents for ${path}`);
+ return data.content;
+ },
+ [projectId],
+ );
- const writeProjectFile = useCallback(async (path: string, content: string): Promise<void> => {
- const pid = projectIdRef.current;
- if (!pid) throw new Error("No active project");
- await retryStudioSave(async () => {
- let response: Response;
- try {
- response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`, {
- method: "PUT",
- headers: { "Content-Type": "text/plain" },
- body: content,
- });
- } catch (error) {
- throw new StudioSaveNetworkError(`Failed to save ${path}: network error`, {
- cause: error,
- });
+ const writeProjectFile = useCallback(
+ async (path: string, content: string): Promise<void> => {
+ if (!projectId) throw new Error("No active project");
+ const writeProjectId = projectId;
+ await retryStudioSave(async () => {
+ let response: Response;
+ try {
+ response = await fetch(
+ `/api/projects/${encodeURIComponent(writeProjectId)}/files/${encodeURIComponent(path)}`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "text/plain" },
+ body: content,
+ },
+ );
+ } catch (error) {
+ throw new StudioSaveNetworkError(`Failed to save ${path}: network error`, {
+ cause: error,
+ });
+ }
+ if (!response.ok) throw await createStudioSaveHttpError(response, `Failed to save ${path}`);
+ });
+ if (projectIdRef.current === writeProjectId && editingPathRef.current === path) {
+ setEditingFile({ path, content });
}
- if (!response.ok) throw await createStudioSaveHttpError(response, `Failed to save ${path}`);
- });
- if (editingPathRef.current === path) {
- setEditingFile({ path, content });
- }
- }, []);
+ },
+ [projectId],
+ );
const updateEditingFileContent = useCallback((path: string, content: string) => {
if (editingPathRef.current === path) {
@@ -105,16 +115,18 @@ export function useFileManager({
}
}, []);
- const readOptionalProjectFile = useCallback(async (path: string): Promise<string> => {
- const pid = projectIdRef.current;
- if (!pid) throw new Error("No active project");
- const response = await fetch(
- `/api/projects/${pid}/files/${encodeURIComponent(path)}?optional=1`,
- );
- if (!response.ok) throw new Error(`Failed to read ${path}`);
- const data = (await response.json()) as { content?: string };
- return typeof data.content === "string" ? data.content : "";
- }, []);
+ const readOptionalProjectFile = useCallback(
+ async (path: string): Promise<string> => {
+ if (!projectId) throw new Error("No active project");
+ const response = await fetch(
+ `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}?optional=1`,
+ );
+ if (!response.ok) throw new Error(`Failed to read ${path}`);
+ const data = (await response.json()) as { content?: string };
+ return typeof data.content === "string" ? data.content : "";
+ },
+ [projectId],
+ );
// ── Editor save (debounced content change) ──
@@ -146,7 +158,7 @@ export function useFileManager({
setEditingFile({ path, content: null });
return;
}
- fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`)
+ fetch(`/api/projects/${encodeURIComponent(pid)}/files/${encodeURIComponent(path)}`)
.then((r) => {
if (!r.ok) throw new Error(`Failed to load ${path} (${r.status})`);
return r.json();
@@ -179,7 +191,7 @@ export function useFileManager({
const requestId = ++revealRequestIdRef.current;
const controller = new AbortController();
revealAbortRef.current = controller;
- fetch(`/api/projects/${pid}/files/${encodeURIComponent(sourceFile)}`, {
+ fetch(`/api/projects/${encodeURIComponent(pid)}/files/${encodeURIComponent(sourceFile)}`, {
signal: controller.signal,
})
.then((r) => r.json())
@@ -211,7 +223,7 @@ export function useFileManager({
const qs = dir ? `?dir=${encodeURIComponent(dir)}` : "";
try {
- const res = await fetch(`/api/projects/${pid}/upload${qs}`, {
+ const res = await fetch(`/api/projects/${encodeURIComponent(pid)}/upload${qs}`, {
method: "POST",
body: formData,
});
@@ -251,11 +263,14 @@ export function useFileManager({
content =
'<!DOCTYPE html>\n<html>\n<head>\n <meta charset="UTF-8">\n</head>\n<body>\n\n</body>\n</html>\n';
}
- const res = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`, {
- method: "POST",
- headers: { "Content-Type": "text/plain" },
- body: content,
- });
+ const res = await fetch(
+ `/api/projects/${encodeURIComponent(pid)}/files/${encodeURIComponent(path)}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "text/plain" },
+ body: content,
+ },
+ );
if (res.ok) {
await refreshFileTree();
handleFileSelect(path);
@@ -273,7 +288,7 @@ export function useFileManager({
const pid = projectIdRef.current;
if (!pid) return;
const res = await fetch(
- `/api/projects/${pid}/files/${encodeURIComponent(path + "/.gitkeep")}`,
+ `/api/projects/${encodeURIComponent(pid)}/files/${encodeURIComponent(path + "/.gitkeep")}`,
{
method: "POST",
headers: { "Content-Type": "text/plain" },
@@ -295,9 +310,12 @@ export function useFileManager({
async (path: string) => {
const pid = projectIdRef.current;
if (!pid) return;
- const res = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`, {
- method: "DELETE",
- });
+ const res = await fetch(
+ `/api/projects/${encodeURIComponent(pid)}/files/${encodeURIComponent(path)}`,
+ {
+ method: "DELETE",
+ },
+ );
if (res.ok) {
if (editingPathRef.current === path) setEditingFile(null);
await refreshFileTree();
@@ -314,11 +332,14 @@ export function useFileManager({
async (oldPath: string, newPath: string) => {
const pid = projectIdRef.current;
if (!pid) return;
- const res = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(oldPath)}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ newPath }),
- });
+ const res = await fetch(
+ `/api/projects/${encodeURIComponent(pid)}/files/${encodeURIComponent(oldPath)}`,
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ newPath }),
+ },
+ );
if (res.ok) {
if (editingPathRef.current === oldPath) {
handleFileSelect(newPath);
@@ -338,7 +359,7 @@ export function useFileManager({
async (path: string) => {
const pid = projectIdRef.current;
if (!pid) return;
- const res = await fetch(`/api/projects/${pid}/duplicate-file`, {
+ const res = await fetch(`/api/projects/${encodeURIComponent(pid)}/duplicate-file`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ path }),
@@ -367,17 +388,18 @@ export function useFileManager({
const handleImportFonts = useCallback(
async (files: FileList | File[]): Promise<ImportedFontAsset[]> => {
+ const pid = projectIdRef.current;
+ if (!pid) return [];
const uploaded = await uploadProjectFiles(
Array.from(files).filter((file) => FONT_EXT.test(file.name)),
"assets/fonts",
);
- const pid = projectIdRef.current;
const imported = uploaded
.filter((asset) => FONT_EXT.test(asset))
.map((asset) => ({
family: fontFamilyFromAssetPath(asset),
path: asset,
- url: `/api/projects/${pid}/preview/${asset}`,
+ url: `/api/projects/${encodeURIComponent(pid)}/preview/${asset}`,
}));
importedFontAssetsRef.current = [
...imported,
diff --git a/packages/studio/src/hooks/useGsapAnimationOps.ts b/packages/studio/src/hooks/useGsapAnimationOps.ts
index 4eef046a87..260c5cac1c 100644
--- a/packages/studio/src/hooks/useGsapAnimationOps.ts
+++ b/packages/studio/src/hooks/useGsapAnimationOps.ts
@@ -7,6 +7,7 @@ import {
sdkGsapDeleteAllForSelectorPersist,
sdkAddWithKeyframesPersist,
sdkReplaceWithKeyframesPersist,
+ cutoverCommittedOrThrow,
type CutoverDeps,
} from "../utils/sdkCutover";
import {
@@ -52,7 +53,7 @@ export function useGsapAnimationOps({
sdkDeps,
{ label: "Edit GSAP animation", coalesceKey: `gsap:${animationId}:meta` },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
commitMutationSafely(
selection,
@@ -74,7 +75,7 @@ export function useGsapAnimationOps({
sdkDeps,
{ label: "Delete GSAP animation" },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
commitMutationSafely(
selection,
@@ -96,7 +97,7 @@ export function useGsapAnimationOps({
sdkDeps,
{ label: "Delete all animations for element" },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
void commitMutation(
selection,
@@ -162,7 +163,7 @@ export function useGsapAnimationOps({
sdkDeps,
{ label: `Add GSAP ${method} animation` },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
await commitMutation(
@@ -213,7 +214,7 @@ export function useGsapAnimationOps({
sdkDeps,
{ label },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
void commitMutation(
selection,
@@ -256,7 +257,7 @@ export function useGsapAnimationOps({
sdkDeps,
{ label },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
void commitMutation(
selection,
diff --git a/packages/studio/src/hooks/useGsapKeyframeOps.ts b/packages/studio/src/hooks/useGsapKeyframeOps.ts
index 63fa8ca0e4..fdaebc7551 100644
--- a/packages/studio/src/hooks/useGsapKeyframeOps.ts
+++ b/packages/studio/src/hooks/useGsapKeyframeOps.ts
@@ -8,6 +8,7 @@ import {
sdkGsapRemoveKeyframePersist,
sdkGsapRemoveAllKeyframesPersist,
sdkGsapConvertToKeyframesPersist,
+ cutoverCommittedOrThrow,
type CutoverDeps,
} from "../utils/sdkCutover";
import type { KeyframeCacheEntry } from "../player/store/playerStore";
@@ -136,7 +137,7 @@ export function useGsapKeyframeOps({
coalesceKey: `gsap:${animationId}:kf:${percentage}`,
},
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
await commitMutation(selection, mutation, {
label: `Add keyframe at ${percentage}%`,
@@ -169,7 +170,7 @@ export function useGsapKeyframeOps({
sdkDeps,
toSdkPersistOptions(`Add keyframe at ${percentage}%`, commitOverrides),
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
return commitMutation(
selection,
@@ -218,7 +219,7 @@ export function useGsapKeyframeOps({
sdkDeps,
toSdkPersistOptions(label, commitOverrides),
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
const commitOptions = commitOverrides?.skipReload
? { label, ...commitOverrides }
@@ -300,7 +301,7 @@ export function useGsapKeyframeOps({
sdkDeps,
toSdkPersistOptions("Convert to keyframes", commitOverrides),
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
return commitMutation(
selection,
@@ -329,7 +330,7 @@ export function useGsapKeyframeOps({
sdkDeps,
{ label: "Remove all keyframes" },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
commitMutationSafely(
selection,
diff --git a/packages/studio/src/hooks/useGsapPropertyDebounce.ts b/packages/studio/src/hooks/useGsapPropertyDebounce.ts
index 3b59609ce3..a57e6c5954 100644
--- a/packages/studio/src/hooks/useGsapPropertyDebounce.ts
+++ b/packages/studio/src/hooks/useGsapPropertyDebounce.ts
@@ -5,6 +5,7 @@ import type { DomEditSelection } from "../components/editor/domEditingTypes";
import {
sdkGsapTweenPersist,
sdkGsapRemovePropertyPersist,
+ cutoverCommittedOrThrow,
type CutoverDeps,
} from "../utils/sdkCutover";
import { extractGsapScriptText } from "../utils/gsapSoftReload";
@@ -45,6 +46,12 @@ interface SdkPropertyDeps {
sdkSession?: Composition | null;
sdkDeps?: CutoverDeps | null;
activeCompPath?: string | null;
+ onFlushError?: (
+ error: unknown,
+ selection: DomEditSelection,
+ mutation: Record<string, unknown>,
+ label: string,
+ ) => void;
}
export function useGsapPropertyDebounce(
@@ -68,38 +75,46 @@ export function useGsapPropertyDebounce(
const sdkRef = useRef(sdk);
sdkRef.current = sdk;
+ // fallow-ignore-next-line complexity
const flushPendingPropertyEdit = useCallback(async () => {
const pending = pendingPropertyEditRef.current;
if (!pending) return;
pendingPropertyEditRef.current = null;
const { selection, animationId, property, value } = pending;
- const { sdkSession, sdkDeps, activeCompPath } = sdkRef.current ?? {};
- if (sdkSession && sdkDeps) {
- const targetPath = selection.sourceFile || activeCompPath || "index.html";
- const handled = await sdkGsapTweenPersist(
- targetPath,
- {
- kind: "set",
- animationId,
- properties: {
- properties: mergeTweenProperties(sdkSession, animationId, { [property]: value }, "to"),
+ const mutation = { type: "update-property", animationId, property, value };
+ const label = `Edit GSAP ${property}`;
+ try {
+ const { sdkSession, sdkDeps, activeCompPath } = sdkRef.current ?? {};
+ if (sdkSession && sdkDeps) {
+ const targetPath = selection.sourceFile || activeCompPath || "index.html";
+ const handled = await sdkGsapTweenPersist(
+ targetPath,
+ {
+ kind: "set",
+ animationId,
+ properties: {
+ properties: mergeTweenProperties(
+ sdkSession,
+ animationId,
+ { [property]: value },
+ "to",
+ ),
+ },
},
- },
- sdkSession,
- sdkDeps,
- { label: `Edit GSAP ${property}`, coalesceKey: `gsap:${animationId}:${property}` },
- );
- if (handled) return;
- }
- commitMutationSafely(
- selection,
- { type: "update-property", animationId, property, value },
- {
- label: `Edit GSAP ${property}`,
+ sdkSession,
+ sdkDeps,
+ { label, coalesceKey: `gsap:${animationId}:${property}` },
+ );
+ if (cutoverCommittedOrThrow(handled)) return;
+ }
+ await commitMutationSafely(selection, mutation, {
+ label,
coalesceKey: `gsap:${animationId}:${property}`,
softReload: true,
- },
- );
+ });
+ } catch (error) {
+ sdkRef.current?.onFlushError?.(error, selection, mutation, label);
+ }
}, [commitMutationSafely]);
const updateGsapProperty = useCallback(
@@ -162,7 +177,7 @@ export function useGsapPropertyDebounce(
sdkDeps,
{ label: `Add GSAP ${property}` },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
commitMutationSafely(
selection,
@@ -187,7 +202,7 @@ export function useGsapPropertyDebounce(
sdkDeps,
{ label: `Remove GSAP ${from ? `from-${property}` : property}` },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
if (from) {
commitMutationSafely(
@@ -247,7 +262,7 @@ export function useGsapPropertyDebounce(
coalesceKey: `gsap:${animationId}:from:${property}`,
},
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
commitMutationSafely(
selection,
@@ -285,7 +300,7 @@ export function useGsapPropertyDebounce(
sdkDeps,
{ label: `Add GSAP from-${property}` },
);
- if (handled) return;
+ if (cutoverCommittedOrThrow(handled)) return;
}
commitMutationSafely(
selection,
diff --git a/packages/studio/src/hooks/useGsapPropertyDebounceFlush.test.ts b/packages/studio/src/hooks/useGsapPropertyDebounceFlush.test.ts
index 7890f0d007..64dd929a66 100644
--- a/packages/studio/src/hooks/useGsapPropertyDebounceFlush.test.ts
+++ b/packages/studio/src/hooks/useGsapPropertyDebounceFlush.test.ts
@@ -82,4 +82,39 @@ describe("useGsapPropertyDebounce flush stability (finding #7)", () => {
root.unmount();
});
});
+
+ it("reports a rejected debounced flush instead of leaking an unhandled rejection", async () => {
+ const error = new Error("save failed");
+ const commitMutationSafely = vi.fn().mockRejectedValue(error);
+ const onFlushError = vi.fn();
+ let queueEdit: (() => void) | null = null;
+
+ function Harness() {
+ const ops = useGsapPropertyDebounce(commitMutationSafely, {
+ sdkSession: null,
+ sdkDeps: null,
+ activeCompPath: "index.html",
+ onFlushError,
+ });
+ queueEdit = () => ops.updateGsapProperty(selection, "tw-1", "x", 42);
+ return null;
+ }
+
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(React.createElement(Harness));
+ });
+ act(() => queueEdit?.());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(200);
+ });
+
+ expect(onFlushError).toHaveBeenCalledWith(
+ error,
+ selection,
+ { type: "update-property", animationId: "tw-1", property: "x", value: 42 },
+ "Edit GSAP x",
+ );
+ act(() => root.unmount());
+ });
});
diff --git a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx
index 26ea7aff2e..76ae4930b7 100644
--- a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx
+++ b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx
@@ -28,6 +28,7 @@ vi.mock("../utils/studioTelemetry", () => ({
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import type { MutationResult } from "./gsapScriptCommitTypes";
+import { persistSdkSerialize } from "../utils/sdkCutover";
import { applyPreviewSync, useGsapScriptCommits } from "./useGsapScriptCommits";
// ── applyPreviewSync (pure preview-sync decision) ────────────────────────────
@@ -214,7 +215,11 @@ type HookApi = ReturnType<typeof useGsapScriptCommits>;
let cleanup: (() => void) | null = null;
-function renderCommitHook() {
+function renderCommitHook(
+ options: {
+ writeProjectFile?: (path: string, content: string) => Promise<void>;
+ } = {},
+) {
const reloadPreview = vi.fn();
const onCacheInvalidate = vi.fn();
const onFileContentChanged = vi.fn();
@@ -235,7 +240,7 @@ function renderCommitHook() {
onFileContentChanged,
showToast,
sdkSession: null,
- writeProjectFile: undefined,
+ writeProjectFile: options.writeProjectFile,
forceReloadSdkSession,
});
return null;
@@ -422,4 +427,45 @@ describe("runCommit — instantPatch wiring", () => {
expect(applySoftReload).toHaveBeenCalledTimes(1);
expect(deps.onCacheInvalidate).toHaveBeenCalledTimes(1);
});
+
+ it("serializes a legacy fallback request behind an in-flight SDK whole-file edit", async () => {
+ let releaseSdkWrite: (() => void) | undefined;
+ const sdkWriteGate = new Promise<void>((resolve) => {
+ releaseSdkWrite = resolve;
+ });
+ let notifySdkWriteStarted: (() => void) | undefined;
+ const sdkWriteStarted = new Promise<void>((resolve) => {
+ notifySdkWriteStarted = resolve;
+ });
+ const writeProjectFile = vi.fn(async () => {
+ notifySdkWriteStarted?.();
+ await sdkWriteGate;
+ });
+ const deps = renderCommitHook({ writeProjectFile });
+ const sdkEdit = persistSdkSerialize(() => "SDK_AFTER", "index.html", "BEFORE", {
+ editHistory: { recordEdit: deps.recordEdit },
+ writeProjectFile,
+ readProjectFile: vi.fn(async () => "BEFORE"),
+ reloadPreview: deps.reloadPreview,
+ domEditSaveTimestampRef: { current: 0 },
+ });
+ await sdkWriteStarted;
+
+ mockFetchResult();
+ let legacyEdit: Promise<void> | undefined;
+ act(() => {
+ legacyEdit = deps.api.commitMutation(selection, { x: 10 }, { label: "Legacy fallback" });
+ });
+ await Promise.resolve();
+ expect(fetch).not.toHaveBeenCalled();
+
+ releaseSdkWrite?.();
+ await act(async () => {
+ await Promise.all([sdkEdit, legacyEdit]);
+ });
+ expect(fetch).toHaveBeenCalledWith(
+ "/api/projects/proj-1/gsap-mutations/index.html",
+ expect.objectContaining({ method: "POST" }),
+ );
+ });
});
diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.ts
index 2afe9f27cd..1ad71c7e73 100644
--- a/packages/studio/src/hooks/useGsapScriptCommits.ts
+++ b/packages/studio/src/hooks/useGsapScriptCommits.ts
@@ -6,6 +6,12 @@ import { usePlayerStore } from "../player/store/playerStore";
import { applySoftReload, extractGsapScriptText } from "../utils/gsapSoftReload";
import type { SoftReloadResult } from "../utils/gsapSoftReload";
import { trackStudioEvent } from "../utils/studioTelemetry";
+import { serializeStudioFileMutation } from "../utils/studioFileMutationCoordinator";
+import {
+ getStudioSaveErrorMessage,
+ isStudioSaveErrorAlreadyToasted,
+ markStudioSaveErrorAlreadyToasted,
+} from "../utils/studioSaveDiagnostics";
import type { CutoverDeps } from "../utils/sdkCutover";
import { updateKeyframeCacheFromParsed } from "./gsapKeyframeCacheHelpers";
import { patchRuntimeTweenInPlace } from "./gsapRuntimePatch";
@@ -81,15 +87,19 @@ async function runMutationRequest(
if (unsafeFields.length > 0) {
showToast?.("Couldn't read element layout — try again at a different playhead time", "error");
if (options.skipReload) return;
- throw new Error(
- `Mutation contains unsafe values: ${unsafeFields.map((field) => field.path).join(", ")}`,
+ throw markStudioSaveErrorAlreadyToasted(
+ new Error(
+ `Mutation contains unsafe values: ${unsafeFields.map((field) => field.path).join(", ")}`,
+ ),
);
}
try {
return await request();
} catch (error) {
- if (error instanceof GsapMutationHttpError)
+ if (error instanceof GsapMutationHttpError) {
showToast?.(formatGsapMutationRejectionToast(error), "error");
+ markStudioSaveErrorAlreadyToasted(error);
+ }
if (options.skipReload) return;
throw error;
}
@@ -120,6 +130,54 @@ function refreshMutationPreview(
onCacheInvalidate();
}
+function isActiveCommitTarget(
+ projectIdRef: { current: string | null },
+ activeCompPathRef: { current: string | null },
+ projectId: string,
+ compositionPath: string | null,
+): boolean {
+ return projectIdRef.current === projectId && activeCompPathRef.current === compositionPath;
+}
+
+function syncCommittedGsapMutation({
+ iframe,
+ selection,
+ mutation,
+ targetPath,
+ result,
+ options,
+ onFileContentChanged,
+ forceReloadSdkSession,
+ reloadPreview,
+ onCacheInvalidate,
+}: {
+ iframe: HTMLIFrameElement | null;
+ selection: DomEditSelection;
+ mutation: Record<string, unknown>;
+ targetPath: string;
+ result: MutationResult;
+ options: CommitMutationOptions;
+ onFileContentChanged?: (path: string, content: string) => void;
+ forceReloadSdkSession?: () => void;
+ reloadPreview: () => void;
+ onCacheInvalidate: () => void;
+}): void {
+ if (result.after != null) onFileContentChanged?.(targetPath, result.after);
+ // Server wrote the file; the in-memory SDK doc is now stale. Resync it so a
+ // later SDK-routed edit doesn't serialize the pre-write doc and revert this.
+ forceReloadSdkSession?.();
+ if (options.skipReload) return;
+ if (result.parsed?.animations) {
+ updateKeyframeCacheFromParsed(
+ result.parsed.animations,
+ targetPath,
+ selection.id ?? undefined,
+ mutation,
+ );
+ }
+ refreshMutationPreview(iframe, result, options, reloadPreview, onCacheInvalidate);
+}
+
/**
* Apply a soft reload and enforce the U4 invariant via the richer
* `SoftReloadResult`, with telemetry on every non-success path so the invariant
@@ -208,7 +266,10 @@ export function applyPreviewSync(
// oxfmt-ignore
// fallow-ignore-next-line complexity
-export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIframeRef, editHistory, domEditSaveTimestampRef, reloadPreview, onCacheInvalidate, onFileContentChanged, showToast, sdkSession, writeProjectFile, forceReloadSdkSession }: GsapScriptCommitsParams) {
+export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIframeRef, editHistory, domEditSaveTimestampRef, reloadPreview, onCacheInvalidate, onFileContentChanged, showToast, sdkSession, publishSdkSession, writeProjectFile, forceReloadSdkSession }: GsapScriptCommitsParams) {
+ const activeProjectId = projectIdRef.current;
+ const activeCompPathRef = useRef(activeCompPath);
+ activeCompPathRef.current = activeCompPath;
// Serializer for per-key commits (options.serializeKey). Keyed by
// `gsap:${animationId}:meta`, it chains a meta commit onto the prior one for
// the same animationId so their POSTs can't interleave. Held in a ref so the
@@ -225,69 +286,115 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
});
}, [editHistory]);
- const finalizeSuccessfulMutation = useCallback(async (selection: DomEditSelection, mutation: Record<string, unknown>, targetPath: string, result: MutationResult, options: CommitMutationOptions) => {
+ const finalizeSuccessfulMutation = useCallback(async (projectId: string, compositionPath: string | null, selection: DomEditSelection, mutation: Record<string, unknown>, targetPath: string, result: MutationResult, options: CommitMutationOptions) => {
+ if (projectIdRef.current !== projectId) return;
+ const previewIsActive = isActiveCommitTarget(
+ projectIdRef,
+ activeCompPathRef,
+ projectId,
+ compositionPath,
+ );
// A no-op file write may still owe the runtime a deferred instant patch.
- if (finishUnchangedMutation(previewIframeRef.current, result, options, reloadPreview)) return;
- domEditSaveTimestampRef.current = Date.now();
+ if (result.changed === false) {
+ if (previewIsActive) {
+ finishUnchangedMutation(previewIframeRef.current, result, options, reloadPreview);
+ }
+ return;
+ }
+ if (previewIsActive) domEditSaveTimestampRef.current = Date.now();
await recordMutationEdit(targetPath, result, options);
- if (result.after != null) onFileContentChanged?.(targetPath, result.after);
- // Server wrote the file; the in-memory SDK doc is now stale. Resync it so a
- // later SDK-routed edit doesn't serialize the pre-write doc and revert this.
- forceReloadSdkSession?.();
- if (options.skipReload) return;
- if (result.parsed?.animations) updateKeyframeCacheFromParsed(result.parsed.animations, targetPath, selection.id ?? undefined, mutation);
- refreshMutationPreview(
- previewIframeRef.current,
+ // The durable mutation belongs to the project captured when it was queued.
+ // A later project must never receive its file state or preview refresh.
+ if (!isActiveCommitTarget(projectIdRef, activeCompPathRef, projectId, compositionPath)) return;
+ syncCommittedGsapMutation({
+ iframe: previewIframeRef.current,
+ selection,
+ mutation,
+ targetPath,
result,
options,
+ onFileContentChanged,
+ forceReloadSdkSession,
reloadPreview,
onCacheInvalidate,
- );
- }, [previewIframeRef, domEditSaveTimestampRef, reloadPreview, onCacheInvalidate, onFileContentChanged, forceReloadSdkSession, recordMutationEdit]);
+ });
+ }, [projectIdRef, previewIframeRef, domEditSaveTimestampRef, reloadPreview, onCacheInvalidate, onFileContentChanged, forceReloadSdkSession, recordMutationEdit]);
- const runCommit = useCallback(async (selection: DomEditSelection, mutation: Record<string, unknown>, options: CommitMutationOptions) => {
- const pid = projectIdRef.current;
- if (!pid) return;
- const targetPath = selection.sourceFile || activeCompPath || "index.html";
+ const runCommit = useCallback(async (pid: string, compositionPath: string | null, targetPath: string, selection: DomEditSelection, mutation: Record<string, unknown>, options: CommitMutationOptions) => {
const result = await runMutationRequest([mutation], options, showToast, () =>
mutateGsapScript(pid, targetPath, mutation),
);
if (!result) return;
- await finalizeSuccessfulMutation(selection, mutation, targetPath, result, options);
- }, [projectIdRef, activeCompPath, showToast, finalizeSuccessfulMutation]);
+ await finalizeSuccessfulMutation(pid, compositionPath, selection, mutation, targetPath, result, options);
+ }, [showToast, finalizeSuccessfulMutation]);
- const runBatchCommit = useCallback(async (calls: CommitMutationCall[], options: CommitMutationOptions) => {
- const pid = projectIdRef.current;
+ const runBatchCommit = useCallback(async (pid: string, compositionPath: string | null, targetPath: string, calls: CommitMutationCall[], options: CommitMutationOptions) => {
const first = calls[0];
const last = calls.at(-1);
- if (!pid || !first || !last) return;
- const targetPath = first.selection.sourceFile || activeCompPath || "index.html";
+ if (!first || !last) return;
const mutations = calls.map(({ mutation }) => mutation);
const result = await runMutationRequest(mutations, options, showToast, () =>
mutateGsapScriptBatch(pid, targetPath, mutations),
);
if (!result) return;
- await finalizeSuccessfulMutation(last.selection, last.mutation, targetPath, result, options);
- }, [projectIdRef, activeCompPath, showToast, finalizeSuccessfulMutation]);
+ await finalizeSuccessfulMutation(pid, compositionPath, last.selection, last.mutation, targetPath, result, options);
+ }, [showToast, finalizeSuccessfulMutation]);
// Every GSAP-script commit is a read-modify-write of one file. Overlapping
// commits to the SAME file (any op type, any animation) interleave server-side,
- // so serialize per target file by default; an explicit serializeKey overrides.
+ // so every legacy request takes the same project/file lock as SDK writes. An
+ // explicit key adds ordering for related calls but never replaces the file lock.
const commitMutation = useMemo<CommitMutation>(() => {
+ const serializeFile = <T,>(file: string, task: () => Promise<T>): Promise<T> => {
+ if (writeProjectFile) {
+ return serializeStudioFileMutation(writeProjectFile, file, task);
+ }
+ return serializerRef.current(`gsap-file:${file}`, task);
+ };
+ const serializeCommit = <T,>(
+ file: string,
+ serializeKey: string | undefined,
+ task: () => Promise<T>,
+ ): Promise<T> => {
+ const fileKey = `gsap-file:${file}`;
+ const run = () => serializeFile(file, task);
+ if (serializeKey && (writeProjectFile || serializeKey !== fileKey)) {
+ return serializerRef.current(serializeKey, run);
+ }
+ return run();
+ };
const commit: CommitMutation = (selection, mutation, options) => {
+ if (!activeProjectId) return Promise.resolve();
const file = selection.sourceFile || activeCompPath || "index.html";
- const key = options.serializeKey ?? `gsap-file:${file}`;
- return serializerRef.current(key, () => runCommit(selection, mutation, options));
+ return serializeCommit(file, options.serializeKey, () =>
+ runCommit(activeProjectId, activeCompPath, file, selection, mutation, options),
+ );
};
commit.batch = (calls, options) => {
+ if (!activeProjectId) return Promise.resolve();
const file = calls[0]?.selection.sourceFile || activeCompPath || "index.html";
- const key = options.serializeKey ?? `gsap-file:${file}`;
- return serializerRef.current(key, () => runBatchCommit(calls, options));
+ return serializeCommit(file, options.serializeKey, () =>
+ runBatchCommit(activeProjectId, activeCompPath, file, calls, options),
+ );
};
return commit;
- }, [runCommit, runBatchCommit, activeCompPath]);
+ }, [runCommit, runBatchCommit, activeCompPath, activeProjectId, writeProjectFile]);
const trackGsapSaveFailure = useGsapSaveFailureTelemetry(activeCompPath);
- const commitMutationSafely = useSafeGsapCommitMutation(commitMutation, trackGsapSaveFailure, showToast);
+ const handleGsapSaveFailure = useCallback(
+ (
+ error: unknown,
+ selection: DomEditSelection,
+ mutation: Record<string, unknown>,
+ label?: string,
+ ) => {
+ trackGsapSaveFailure(error, selection, mutation, label);
+ if (!isStudioSaveErrorAlreadyToasted(error)) {
+ showToast?.(`Couldn't save animation: ${getStudioSaveErrorMessage(error)}`, "error");
+ }
+ },
+ [showToast, trackGsapSaveFailure],
+ );
+ const commitMutationSafely = useSafeGsapCommitMutation(commitMutation, handleGsapSaveFailure);
// One stable SDK-deps object shared by all GSAP child hooks. Memoized so the
// hooks' callbacks keep a stable identity (an inline literal here re-fired the
@@ -315,23 +422,15 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
},
[previewIframeRef, reloadPreview, onCacheInvalidate],
);
- // Reuse the SAME per-file serializer the legacy commitMutation path uses, so
- // SDK gsap-write flushes serialize against legacy commits AND each other —
- // overlapping same-file read-modify-writes can't interleave and lose an edit.
- const serializeByFile = useCallback(
- <T>(key: string, task: () => Promise<T>): Promise<T> => serializerRef.current(key, task),
- [],
- );
// Read the on-disk bytes of targetPath so the SDK GSAP persist captures the
// exact prior content as its undo `before` (matching the style/delete paths),
// instead of a normalized full-DOM re-emit that would reformat the whole file.
const readProjectFileContent = useCallback(
(path: string): Promise<string> => {
- const pid = projectIdRef.current;
- if (!pid) throw new Error("No active project");
- return readSharedProjectFileContent(pid, path);
+ if (!activeProjectId) throw new Error("No active project");
+ return readSharedProjectFileContent(activeProjectId, path);
},
- [projectIdRef],
+ [activeProjectId],
);
const sdkDeps = useMemo<CutoverDeps | null>(
() =>
@@ -343,8 +442,8 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
domEditSaveTimestampRef,
refresh: sdkRefresh,
compositionPath: activeCompPath,
- serialize: serializeByFile,
readProjectFile: readProjectFileContent,
+ publishSession: publishSdkSession,
}
: null,
[
@@ -354,8 +453,8 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
domEditSaveTimestampRef,
sdkRefresh,
activeCompPath,
- serializeByFile,
readProjectFileContent,
+ publishSdkSession,
],
);
@@ -363,6 +462,7 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
sdkSession,
sdkDeps,
activeCompPath,
+ onFlushError: handleGsapSaveFailure,
});
const animationOps = useGsapAnimationOps({
projectIdRef,
@@ -377,7 +477,7 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
activeCompPath,
commitMutation,
commitMutationSafely,
- trackGsapSaveFailure,
+ trackGsapSaveFailure: handleGsapSaveFailure,
sdkSession,
sdkDeps,
});
diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx b/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx
new file mode 100644
index 0000000000..f1ae419ec9
--- /dev/null
+++ b/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment happy-dom
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vitest";
+import type { DomEditSelection } from "../components/editor/domEditingTypes";
+import { useGsapSelectionHandlers } from "./useGsapSelectionHandlers";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+type Params = Parameters<typeof useGsapSelectionHandlers>[0];
+type Handlers = ReturnType<typeof useGsapSelectionHandlers>;
+
+function makeSelection(): DomEditSelection {
+ return {
+ id: "box",
+ hfId: "hf-box",
+ selector: "#box",
+ sourceFile: "index.html",
+ element: document.createElement("div"),
+ } as unknown as DomEditSelection;
+}
+
+function makeParams(overrides: Partial<Params> = {}): Params {
+ const resolved = () => vi.fn().mockResolvedValue(undefined);
+ return {
+ domEditSelection: makeSelection(),
+ updateGsapProperty: vi.fn(),
+ updateGsapMeta: resolved(),
+ deleteGsapAnimation: resolved(),
+ deleteAllForSelector: resolved(),
+ addGsapAnimation: resolved(),
+ addGsapProperty: resolved(),
+ removeGsapProperty: resolved(),
+ updateGsapFromProperty: resolved(),
+ addGsapFromProperty: resolved(),
+ removeGsapFromProperty: resolved(),
+ addKeyframe: vi.fn(),
+ addKeyframeBatch: resolved(),
+ removeKeyframe: vi.fn(),
+ moveKeyframe: vi.fn(),
+ resizeKeyframedTween: vi.fn(),
+ convertToKeyframes: resolved(),
+ removeAllKeyframes: resolved(),
+ handleDomManualEditsReset: vi.fn(),
+ selectedGsapAnimations: [],
+ showToast: vi.fn(),
+ ...overrides,
+ };
+}
+
+function renderHandlers(params: Params): { handlers: () => Handlers; unmount: () => void } {
+ let current: Handlers | undefined;
+ function Probe() {
+ current = useGsapSelectionHandlers(params);
+ return null;
+ }
+ const root = createRoot(document.createElement("div"));
+ act(() => root.render(<Probe />));
+ return {
+ handlers: () => {
+ if (!current) throw new Error("Hook did not render");
+ return current;
+ },
+ unmount: () => act(() => root.unmount()),
+ };
+}
+
+async function flushRejection(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve();
+ });
+}
+
+describe("useGsapSelectionHandlers save failures", () => {
+ it("surfaces a rejected animation metadata save", async () => {
+ const error = new Error("write failed");
+ const showToast = vi.fn();
+ const rendered = renderHandlers(
+ makeParams({ updateGsapMeta: vi.fn().mockRejectedValue(error), showToast }),
+ );
+
+ act(() => rendered.handlers().handleGsapUpdateMeta("anim-1", { duration: 2 }));
+ await flushRejection();
+
+ expect(showToast).toHaveBeenCalledWith("Couldn't save animation: write failed", "error");
+ rendered.unmount();
+ });
+
+ it("surfaces a rejected non-debounced property save", async () => {
+ const error = new Error("write failed");
+ const showToast = vi.fn();
+ const rendered = renderHandlers(
+ makeParams({ addGsapProperty: vi.fn().mockRejectedValue(error), showToast }),
+ );
+
+ act(() => rendered.handlers().handleGsapAddProperty("anim-1", "opacity"));
+ await flushRejection();
+
+ expect(showToast).toHaveBeenCalledWith("Couldn't save animation: write failed", "error");
+ rendered.unmount();
+ });
+
+ it("does not duplicate a toast already emitted by the mutation request", async () => {
+ const error = Object.assign(new Error("write failed"), { alreadyToasted: true });
+ const showToast = vi.fn();
+ const rendered = renderHandlers(
+ makeParams({ addGsapAnimation: vi.fn().mockRejectedValue(error), showToast }),
+ );
+
+ act(() => rendered.handlers().handleGsapAddAnimation("to"));
+ await flushRejection();
+
+ expect(showToast).not.toHaveBeenCalled();
+ rendered.unmount();
+ });
+});
diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.ts b/packages/studio/src/hooks/useGsapSelectionHandlers.ts
index 191fd3a64d..0b11d760de 100644
--- a/packages/studio/src/hooks/useGsapSelectionHandlers.ts
+++ b/packages/studio/src/hooks/useGsapSelectionHandlers.ts
@@ -3,7 +3,11 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditing";
import { usePlayerStore } from "../player";
import { computeCurrentPercentage } from "./gsapDragCommit";
-import { trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";
+import {
+ getStudioSaveErrorMessage,
+ isStudioSaveErrorAlreadyToasted,
+ trackStudioSaveFailure,
+} from "../utils/studioSaveDiagnostics";
import { trackStudioEvent } from "../utils/studioTelemetry";
import type { CommitMutationOptions } from "./gsapScriptCommitTypes";
@@ -34,6 +38,7 @@ export function useGsapSelectionHandlers({
removeAllKeyframes,
handleDomManualEditsReset,
selectedGsapAnimations,
+ showToast,
}: {
domEditSelection: DomEditSelection | null;
updateGsapProperty: (
@@ -46,24 +51,24 @@ export function useGsapSelectionHandlers({
sel: DomEditSelection,
animId: string,
updates: { duration?: number; ease?: string; position?: number },
- ) => void;
- deleteGsapAnimation: (sel: DomEditSelection, animId: string) => void;
- deleteAllForSelector: (sel: DomEditSelection, targetSelector: string) => void;
+ ) => Promise<void>;
+ deleteGsapAnimation: (sel: DomEditSelection, animId: string) => Promise<void>;
+ deleteAllForSelector: (sel: DomEditSelection, targetSelector: string) => Promise<void>;
addGsapAnimation: (
sel: DomEditSelection,
method: "to" | "from" | "set" | "fromTo",
time: number,
) => Promise<void>;
- addGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
- removeGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
+ addGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => Promise<void>;
+ removeGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => Promise<void>;
updateGsapFromProperty: (
sel: DomEditSelection,
animId: string,
prop: string,
value: number | string,
- ) => void;
- addGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
- removeGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
+ ) => Promise<void>;
+ addGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => Promise<void>;
+ removeGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => Promise<void>;
addKeyframe: (
sel: DomEditSelection,
animId: string,
@@ -104,10 +109,11 @@ export function useGsapSelectionHandlers({
duration?: number,
commitOverrides?: Partial<CommitMutationOptions>,
) => Promise<void>;
- removeAllKeyframes: (sel: DomEditSelection, animId: string) => void;
+ removeAllKeyframes: (sel: DomEditSelection, animId: string) => Promise<void>;
handleDomManualEditsReset: (sel: DomEditSelection) => void;
selectedGsapAnimations: GsapAnimation[];
+ showToast: (message: string, tone?: "error" | "info") => void;
}) {
const lastSelectionRef = useRef<DomEditSelection | null>(null);
if (domEditSelection) lastSelectionRef.current = domEditSelection;
@@ -124,8 +130,20 @@ export function useGsapSelectionHandlers({
targetSelector: selection.selector,
targetSourceFile: selection.sourceFile,
});
+ if (!isStudioSaveErrorAlreadyToasted(error)) {
+ showToast(`Couldn't save animation: ${getStudioSaveErrorMessage(error)}`, "error");
+ }
+ },
+ [showToast],
+ );
+
+ const observeGsapMutation = useCallback(
+ (mutation: Promise<void>, selection: DomEditSelection, mutationType: string, label: string) => {
+ void mutation.catch((error) => {
+ trackGsapHandlerFailure(error, selection, mutationType, label);
+ });
},
- [],
+ [trackGsapHandlerFailure],
);
const handleGsapUpdateProperty = useCallback(
@@ -144,18 +162,23 @@ export function useGsapSelectionHandlers({
) => {
const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current;
if (!sel) return;
- updateGsapMeta(sel, animId, updates);
+ observeGsapMutation(
+ updateGsapMeta(sel, animId, updates),
+ sel,
+ "update-meta",
+ "Edit GSAP animation",
+ );
},
- [domEditSelection, updateGsapMeta],
+ [domEditSelection, observeGsapMutation, updateGsapMeta],
);
const handleGsapDeleteAnimation = useCallback(
(animId: string) => {
const sel = domEditSelection ?? lastSelectionRef.current;
if (!sel) return;
- deleteGsapAnimation(sel, animId);
+ observeGsapMutation(deleteGsapAnimation(sel, animId), sel, "delete", "Delete GSAP animation");
},
- [domEditSelection, deleteGsapAnimation],
+ [domEditSelection, deleteGsapAnimation, observeGsapMutation],
);
const handleGsapDeleteAllForElement = useCallback(
@@ -163,9 +186,14 @@ export function useGsapSelectionHandlers({
const sel = domEditSelection ?? lastSelectionRef.current;
if (!sel) return;
trackStudioEvent("keyframe", { action: "delete_all" });
- deleteAllForSelector(sel, targetSelector);
+ observeGsapMutation(
+ deleteAllForSelector(sel, targetSelector),
+ sel,
+ "delete-all-for-selector",
+ "Delete all animations for element",
+ );
},
- [domEditSelection, deleteAllForSelector],
+ [domEditSelection, deleteAllForSelector, observeGsapMutation],
);
const handleGsapAddAnimation = useCallback(
@@ -186,41 +214,66 @@ export function useGsapSelectionHandlers({
const handleGsapAddProperty = useCallback(
(animId: string, prop: string) => {
if (!domEditSelection) return;
- addGsapProperty(domEditSelection, animId, prop);
+ observeGsapMutation(
+ addGsapProperty(domEditSelection, animId, prop),
+ domEditSelection,
+ "add-property",
+ `Add GSAP ${prop}`,
+ );
},
- [domEditSelection, addGsapProperty],
+ [domEditSelection, addGsapProperty, observeGsapMutation],
);
const handleGsapRemoveProperty = useCallback(
(animId: string, prop: string) => {
if (!domEditSelection) return;
- removeGsapProperty(domEditSelection, animId, prop);
+ observeGsapMutation(
+ removeGsapProperty(domEditSelection, animId, prop),
+ domEditSelection,
+ "remove-property",
+ `Remove GSAP ${prop}`,
+ );
},
- [domEditSelection, removeGsapProperty],
+ [domEditSelection, observeGsapMutation, removeGsapProperty],
);
const handleGsapUpdateFromProperty = useCallback(
(animId: string, prop: string, value: number | string) => {
if (!domEditSelection) return;
- updateGsapFromProperty(domEditSelection, animId, prop, value);
+ observeGsapMutation(
+ updateGsapFromProperty(domEditSelection, animId, prop, value),
+ domEditSelection,
+ "update-from-property",
+ `Edit GSAP from-${prop}`,
+ );
},
- [domEditSelection, updateGsapFromProperty],
+ [domEditSelection, observeGsapMutation, updateGsapFromProperty],
);
const handleGsapAddFromProperty = useCallback(
(animId: string, prop: string) => {
if (!domEditSelection) return;
- addGsapFromProperty(domEditSelection, animId, prop);
+ observeGsapMutation(
+ addGsapFromProperty(domEditSelection, animId, prop),
+ domEditSelection,
+ "add-from-property",
+ `Add GSAP from-${prop}`,
+ );
},
- [domEditSelection, addGsapFromProperty],
+ [domEditSelection, addGsapFromProperty, observeGsapMutation],
);
const handleGsapRemoveFromProperty = useCallback(
(animId: string, prop: string) => {
if (!domEditSelection) return;
- removeGsapFromProperty(domEditSelection, animId, prop);
+ observeGsapMutation(
+ removeGsapFromProperty(domEditSelection, animId, prop),
+ domEditSelection,
+ "remove-from-property",
+ `Remove GSAP from-${prop}`,
+ );
},
- [domEditSelection, removeGsapFromProperty],
+ [domEditSelection, observeGsapMutation, removeGsapFromProperty],
);
const handleGsapAddKeyframe = useCallback(
@@ -354,18 +407,28 @@ export function useGsapSelectionHandlers({
const handleGsapRemoveAllKeyframes = useCallback(
(animId: string) => {
if (!domEditSelection) return;
- removeAllKeyframes(domEditSelection, animId);
+ observeGsapMutation(
+ removeAllKeyframes(domEditSelection, animId),
+ domEditSelection,
+ "remove-all-keyframes",
+ "Remove all keyframes",
+ );
},
- [domEditSelection, removeAllKeyframes],
+ [domEditSelection, observeGsapMutation, removeAllKeyframes],
);
const handleResetSelectedElementKeyframes = useCallback((): boolean => {
if (!domEditSelection) return false;
const withKeyframes = selectedGsapAnimations.find((a) => a.keyframes);
if (!withKeyframes) return false;
- removeAllKeyframes(domEditSelection, withKeyframes.id);
+ observeGsapMutation(
+ removeAllKeyframes(domEditSelection, withKeyframes.id),
+ domEditSelection,
+ "remove-all-keyframes",
+ "Remove all keyframes",
+ );
return true;
- }, [domEditSelection, selectedGsapAnimations, removeAllKeyframes]);
+ }, [domEditSelection, observeGsapMutation, removeAllKeyframes, selectedGsapAnimations]);
return {
handleGsapUpdateProperty,
diff --git a/packages/studio/src/hooks/usePersistentEditHistory.projectOwnership.test.tsx b/packages/studio/src/hooks/usePersistentEditHistory.projectOwnership.test.tsx
new file mode 100644
index 0000000000..3491be5a5b
--- /dev/null
+++ b/packages/studio/src/hooks/usePersistentEditHistory.projectOwnership.test.tsx
@@ -0,0 +1,60 @@
+// @vitest-environment happy-dom
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it } from "vitest";
+import { createMemoryEditHistoryStorage } from "../utils/editHistoryStorage";
+import { usePersistentEditHistory } from "./usePersistentEditHistory";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushAsyncEffects(): Promise<void> {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
+describe("usePersistentEditHistory project ownership", () => {
+ it("rejects a delayed project A recorder after project B becomes active", async () => {
+ const storage = createMemoryEditHistoryStorage();
+ const now = () => 100;
+ const captured: { history: ReturnType<typeof usePersistentEditHistory> | null } = {
+ history: null,
+ };
+
+ function Probe({ projectId }: { projectId: string }) {
+ captured.history = usePersistentEditHistory({ projectId, storage, now });
+ return null;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(<Probe projectId="project-a" />));
+ await flushAsyncEffects();
+ const recordProjectA = captured.history?.recordEdit;
+ if (!recordProjectA) throw new Error("project A history did not load");
+
+ await act(async () => root.render(<Probe projectId="project-b" />));
+ await expect(
+ recordProjectA({
+ label: "Delayed A edit",
+ kind: "manual",
+ files: { "index.html": { before: "A", after: "A2" } },
+ }),
+ ).rejects.toThrow("inactive project project-a");
+ await flushAsyncEffects();
+
+ const recordProjectB = captured.history?.recordEdit;
+ if (!recordProjectB) throw new Error("project B history did not load");
+ await act(async () => {
+ await recordProjectB({
+ label: "B edit",
+ kind: "manual",
+ files: { "index.html": { before: "B", after: "B2" } },
+ });
+ });
+
+ expect(await storage.get("project-a")).toBeNull();
+ expect((await storage.get("project-b"))?.undo.map((entry) => entry.label)).toEqual(["B edit"]);
+
+ await act(async () => root.unmount());
+ });
+});
diff --git a/packages/studio/src/hooks/usePersistentEditHistory.test.ts b/packages/studio/src/hooks/usePersistentEditHistory.test.ts
index 8b14c4605f..76c9a8b549 100644
--- a/packages/studio/src/hooks/usePersistentEditHistory.test.ts
+++ b/packages/studio/src/hooks/usePersistentEditHistory.test.ts
@@ -1,7 +1,11 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { createEmptyEditHistory } from "../utils/editHistory";
import type { EditHistoryStorageAdapter } from "../utils/editHistoryStorage";
import { createMemoryEditHistoryStorage } from "../utils/editHistoryStorage";
+import {
+ serializeStudioFileMutation,
+ serializeStudioFileMutations,
+} from "../utils/studioFileMutationCoordinator";
import {
createPersistentEditHistoryController,
createPersistentEditHistoryStore,
@@ -213,6 +217,50 @@ describe("createPersistentEditHistoryController", () => {
expect(store.snapshot().canRedo).toBe(true);
});
+ it("waits for same-file mutations before checking an undo hash", async () => {
+ const storage = createMemoryEditHistoryStorage();
+ const store = createPersistentEditHistoryStore({
+ projectId: "project-1",
+ storage,
+ initialState: createEmptyEditHistory(),
+ now: () => 100,
+ onChange: () => {},
+ });
+ await store.recordEdit({
+ label: "Edit source",
+ kind: "source",
+ files: { "index.html": { before: "before", after: "after" } },
+ });
+
+ let disk = "after";
+ let release!: () => void;
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const writeFile = vi.fn(async (_path: string, content: string) => {
+ disk = content;
+ });
+ const priorMutation = serializeStudioFileMutation(writeFile, "index.html", async () => {
+ await blocked;
+ disk = "newer-edit";
+ });
+ const readFile = vi.fn(async () => disk);
+ const undo = store.undo({
+ readFile,
+ writeFile,
+ serialize: (paths, task) => serializeStudioFileMutations(writeFile, paths, task),
+ });
+
+ await Promise.resolve();
+ expect(readFile).not.toHaveBeenCalled();
+ release();
+ await priorMutation;
+ await expect(undo).resolves.toMatchObject({ ok: false, reason: "content-mismatch" });
+ expect(disk).toBe("newer-edit");
+ expect(writeFile).not.toHaveBeenCalled();
+ expect(store.snapshot().canUndo).toBe(true);
+ });
+
it("returns per-file restored/previous content so the preview can soft-apply", async () => {
const storage = createMemoryEditHistoryStorage();
const store = createPersistentEditHistoryStore({
diff --git a/packages/studio/src/hooks/usePersistentEditHistory.ts b/packages/studio/src/hooks/usePersistentEditHistory.ts
index 61779eddec..5c87ca2616 100644
--- a/packages/studio/src/hooks/usePersistentEditHistory.ts
+++ b/packages/studio/src/hooks/usePersistentEditHistory.ts
@@ -30,6 +30,7 @@ interface RecordEditInput {
interface ApplyCallbacks {
readFile: (path: string) => Promise<string>;
writeFile: (path: string, content: string) => Promise<void>;
+ serialize?: <T>(paths: readonly string[], task: () => Promise<T>) => Promise<T>;
}
interface UsePersistentEditHistoryOptions {
@@ -167,31 +168,32 @@ async function applyHistoryStep(
if (!entry) {
return { state: currentState, result: { ok: false, reason: "empty" } };
}
- const { currentFiles, currentHashes } = await readCurrentFileHashes(
- Object.keys(entry.files),
- callbacks.readFile,
- );
- const result = transition(currentState, currentHashes, now());
- if (!result.ok) {
+ const paths = Object.keys(entry.files);
+ const apply = async (): Promise<{ state: EditHistoryState; result: ApplyResult }> => {
+ const { currentFiles, currentHashes } = await readCurrentFileHashes(paths, callbacks.readFile);
+ const result = transition(currentState, currentHashes, now());
+ if (!result.ok) {
+ return {
+ state: currentState,
+ result: { ok: false, reason: result.reason },
+ };
+ }
+ await writeFilesWithRollback({
+ files: result.filesToWrite,
+ rollbackFiles: currentFiles,
+ writeFile: callbacks.writeFile,
+ });
return {
- state: currentState,
- result: { ok: false, reason: result.reason },
+ state: result.state,
+ result: {
+ ok: true,
+ label: result.entry.label,
+ paths: Object.keys(result.entry.files),
+ files: restoredFilesMap(result.filesToWrite, currentFiles),
+ },
};
- }
- await writeFilesWithRollback({
- files: result.filesToWrite,
- rollbackFiles: currentFiles,
- writeFile: callbacks.writeFile,
- });
- return {
- state: result.state,
- result: {
- ok: true,
- label: result.entry.label,
- paths: Object.keys(result.entry.files),
- files: restoredFilesMap(result.filesToWrite, currentFiles),
- },
};
+ return callbacks.serialize ? callbacks.serialize(paths, apply) : apply();
}
export function createPersistentEditHistoryStore({
@@ -305,11 +307,15 @@ export function usePersistentEditHistory(options: UsePersistentEditHistoryOption
const [loaded, setLoaded] = useState(false);
const projectId = options.projectId;
const storeRef = useRef<ReturnType<typeof createPersistentEditHistoryStore> | null>(null);
+ const storeProjectIdRef = useRef<string | null>(null);
+ const activeProjectIdRef = useRef(projectId);
+ activeProjectIdRef.current = projectId;
useEffect(() => {
let cancelled = false;
const emptyState = createEmptyEditHistory();
storeRef.current = null;
+ storeProjectIdRef.current = null;
setState(emptyState);
setLoaded(false);
if (!projectId) {
@@ -327,6 +333,7 @@ export function usePersistentEditHistory(options: UsePersistentEditHistoryOption
now,
onChange: setState,
});
+ storeProjectIdRef.current = projectId;
setState(loadedState);
})
.catch(() => {
@@ -338,6 +345,7 @@ export function usePersistentEditHistory(options: UsePersistentEditHistoryOption
now,
onChange: setState,
});
+ storeProjectIdRef.current = projectId;
setState(emptyState);
})
.finally(() => {
@@ -349,17 +357,49 @@ export function usePersistentEditHistory(options: UsePersistentEditHistoryOption
};
}, [now, projectId, storage]);
- const recordEdit = useCallback(async (input: RecordEditInput) => {
- await storeRef.current?.recordEdit(input);
- }, []);
+ const recordEdit = useCallback(
+ async (input: RecordEditInput) => {
+ if (!projectId) return;
+ if (activeProjectIdRef.current !== projectId) {
+ throw new Error(`Cannot record an edit for inactive project ${projectId}`);
+ }
+ const store = storeRef.current;
+ if (!store) return;
+ if (storeProjectIdRef.current !== projectId) {
+ throw new Error(`Edit history store does not belong to project ${projectId}`);
+ }
+ await store.recordEdit(input);
+ },
+ [projectId],
+ );
- const undo = useCallback(async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {
- return storeRef.current?.undo(callbacks) ?? { ok: false, reason: "empty" };
- }, []);
+ const undo = useCallback(
+ async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {
+ if (
+ !projectId ||
+ activeProjectIdRef.current !== projectId ||
+ storeProjectIdRef.current !== projectId
+ ) {
+ return { ok: false, reason: "empty" };
+ }
+ return storeRef.current?.undo(callbacks) ?? { ok: false, reason: "empty" };
+ },
+ [projectId],
+ );
- const redo = useCallback(async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {
- return storeRef.current?.redo(callbacks) ?? { ok: false, reason: "empty" };
- }, []);
+ const redo = useCallback(
+ async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {
+ if (
+ !projectId ||
+ activeProjectIdRef.current !== projectId ||
+ storeProjectIdRef.current !== projectId
+ ) {
+ return { ok: false, reason: "empty" };
+ }
+ return storeRef.current?.redo(callbacks) ?? { ok: false, reason: "empty" };
+ },
+ [projectId],
+ );
return {
loaded,
diff --git a/packages/studio/src/hooks/useProjectCompositionVariables.ts b/packages/studio/src/hooks/useProjectCompositionVariables.ts
index 61928c9d6c..f419a8b17b 100644
--- a/packages/studio/src/hooks/useProjectCompositionVariables.ts
+++ b/packages/studio/src/hooks/useProjectCompositionVariables.ts
@@ -103,17 +103,16 @@ export function useEditVariablesInFile(deps: EditVariablesDeps) {
return useCallback(
async (path: string, label: string, mutate: (session: Composition) => void): Promise<void> => {
const originalContent = await readProjectFile(path);
- const comp = await openComposition(originalContent, { history: false });
- let after: string;
- try {
- mutate(comp);
- after = comp.serialize();
- } finally {
- comp.dispose();
- }
- if (after === originalContent) return;
await persistSdkSerialize(
- after,
+ async (onDiskBefore) => {
+ const comp = await openComposition(onDiskBefore, { history: false });
+ try {
+ mutate(comp);
+ return comp.serialize();
+ } finally {
+ comp.dispose();
+ }
+ },
path,
originalContent,
{
@@ -122,6 +121,7 @@ export function useEditVariablesInFile(deps: EditVariablesDeps) {
reloadPreview,
domEditSaveTimestampRef,
compositionPath: path,
+ readProjectFile,
},
{ label },
);
diff --git a/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx b/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx
new file mode 100644
index 0000000000..7719b6d883
--- /dev/null
+++ b/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx
@@ -0,0 +1,137 @@
+// @vitest-environment happy-dom
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const openComposition = vi.fn();
+
+vi.mock("@hyperframes/sdk", () => ({
+ openComposition: (...args: unknown[]) => openComposition(...args),
+}));
+
+import type { Composition } from "@hyperframes/sdk";
+import { useSdkSession, type SdkSessionHandle } from "./useSdkSession";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+function fakeSession(): Composition {
+ return { dispose: vi.fn() } as unknown as Composition;
+}
+
+function response(content: string): Response {
+ return { ok: true, json: async () => ({ content }) } as Response;
+}
+
+async function flushAsyncEffects(): Promise<void> {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
+describe("useSdkSession ownership", () => {
+ beforeEach(() => {
+ openComposition.mockReset();
+ class FakeEventSource {
+ addEventListener(): void {}
+ close(): void {}
+ }
+ vi.stubGlobal("EventSource", FakeEventSource);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("hides project A immediately while project B with the same path is still opening", async () => {
+ const sessionA = fakeSession();
+ const publishedA = fakeSession();
+ const sessionB = fakeSession();
+ let resolveProjectB: ((value: Response) => void) | undefined;
+ const projectBResponse = new Promise<Response>((resolve) => {
+ resolveProjectB = resolve;
+ });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn((url: string) =>
+ url.includes("project-b") ? projectBResponse : Promise.resolve(response("PROJECT_A")),
+ ),
+ );
+ openComposition.mockImplementation(async (content: string) =>
+ content === "PROJECT_A" ? sessionA : sessionB,
+ );
+
+ const captured: { handle: SdkSessionHandle | null } = { handle: null };
+ function Probe({ projectId }: { projectId: string }) {
+ captured.handle = useSdkSession(projectId, "index.html");
+ return null;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(<Probe projectId="project-a" />));
+ await flushAsyncEffects();
+ expect(captured.handle?.session).toBe(sessionA);
+
+ let publication: ReturnType<SdkSessionHandle["publish"]> | undefined;
+ await act(async () => {
+ publication = captured.handle?.publish({
+ candidate: publishedA,
+ expectedSession: sessionA,
+ targetPath: "index.html",
+ });
+ });
+ expect(publication).toBe("published");
+ expect(captured.handle?.session).toBe(publishedA);
+
+ await act(async () => root.render(<Probe projectId="project-b" />));
+ expect(captured.handle?.session).toBeNull();
+ expect(publishedA.dispose).toHaveBeenCalledOnce();
+ expect(
+ captured.handle?.publish({
+ candidate: fakeSession(),
+ expectedSession: publishedA,
+ targetPath: "index.html",
+ }),
+ ).toBe("rejected-inactive-target");
+
+ resolveProjectB?.(response("PROJECT_B"));
+ await flushAsyncEffects();
+ expect(captured.handle?.session).toBe(sessionB);
+
+ await act(async () => root.unmount());
+ expect(sessionB.dispose).toHaveBeenCalledOnce();
+ });
+
+ it("disposes the currently published candidate when its owner unmounts", async () => {
+ const opened = fakeSession();
+ const published = fakeSession();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => response("PROJECT_A")),
+ );
+ openComposition.mockResolvedValue(opened);
+
+ const captured: { handle: SdkSessionHandle | null } = { handle: null };
+ function Probe() {
+ captured.handle = useSdkSession("project-a", "index.html");
+ return null;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(<Probe />));
+ await flushAsyncEffects();
+ expect(captured.handle?.session).toBe(opened);
+ let publication: ReturnType<SdkSessionHandle["publish"]> | undefined;
+ await act(async () => {
+ publication = captured.handle?.publish({
+ candidate: published,
+ expectedSession: opened,
+ targetPath: "index.html",
+ });
+ });
+ expect(publication).toBe("published");
+ expect(opened.dispose).toHaveBeenCalledOnce();
+
+ await act(async () => root.unmount());
+ expect(published.dispose).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/studio/src/hooks/useSdkSession.ts b/packages/studio/src/hooks/useSdkSession.ts
index 9f3a79943a..31886433e3 100644
--- a/packages/studio/src/hooks/useSdkSession.ts
+++ b/packages/studio/src/hooks/useSdkSession.ts
@@ -1,9 +1,11 @@
-import { useState, useEffect, useCallback } from "react";
+import { useState, useEffect, useCallback, useRef } from "react";
import type { MutableRefObject } from "react";
import { openComposition } from "@hyperframes/sdk";
import type { Composition } from "@hyperframes/sdk";
import { readStudioFileChangePath } from "../components/editor/manualEdits";
import { isSelfWriteEcho } from "./sdkSelfWriteRegistry";
+import { trackStudioEvent } from "../utils/studioTelemetry";
+import type { PublishSdkSession } from "../utils/sdkCutover";
/**
* Read a project file's content, or undefined on a non-2xx (optional read).
@@ -82,6 +84,8 @@ export function shouldReloadOnFileChange(
export interface SdkSessionHandle {
session: Composition | null;
+ /** Atomically publish a fully persisted candidate session. */
+ publish: PublishSdkSession;
/**
* Force a session reload immediately, bypassing the self-write suppress
* window. Call after undo/redo writes the active composition file so the
@@ -90,13 +94,82 @@ export interface SdkSessionHandle {
forceReload: () => void;
}
+interface SdkSessionOwner {
+ projectId: string;
+ path: string;
+ reloadToken: number;
+ generation: number;
+}
+
+interface OwnedSdkSession extends SdkSessionOwner {
+ session: Composition;
+}
+
+function isSessionOwnerActive(
+ owner: SdkSessionOwner | undefined,
+ projectId: string | null,
+ path: string | null,
+ targetPath: string,
+): owner is SdkSessionOwner {
+ if (!owner) return false;
+ return owner.projectId === projectId && owner.path === path && owner.path === targetPath;
+}
+
+function isSessionOwnerCurrent(
+ owner: SdkSessionOwner,
+ generation: number,
+ projectId: string | null,
+ path: string | null,
+ reloadToken: number,
+): boolean {
+ return (
+ owner.generation === generation &&
+ owner.projectId === projectId &&
+ owner.path === path &&
+ owner.reloadToken === reloadToken
+ );
+}
+
+function ownsExpectedSession(
+ current: OwnedSdkSession | null,
+ expectedOwner: SdkSessionOwner,
+ expectedSession: Composition,
+ reloadToken: number,
+): current is OwnedSdkSession {
+ if (!current) return false;
+ return (
+ current.session === expectedSession &&
+ current.generation === expectedOwner.generation &&
+ current.reloadToken === reloadToken
+ );
+}
+
+function disposeSdkSession(session: Composition): void {
+ try {
+ session.dispose();
+ } catch (error) {
+ trackStudioEvent("sdk_session_dispose_failed", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
export function useSdkSession(
projectId: string | null,
activeCompPath: string | null,
domEditSaveTimestampRef?: MutableRefObject<number>,
): SdkSessionHandle {
- const [session, setSession] = useState<Composition | null>(null);
+ const [ownedSession, setOwnedSession] = useState<OwnedSdkSession | null>(null);
+ const ownedSessionRef = useRef<OwnedSdkSession | null>(null);
+ const sessionOwnersRef = useRef(new WeakMap<Composition, SdkSessionOwner>());
+ const generationRef = useRef(0);
+ const projectIdRef = useRef(projectId);
+ projectIdRef.current = projectId;
+ const activeCompPathRef = useRef(activeCompPath);
+ activeCompPathRef.current = activeCompPath;
const [reloadToken, setReloadToken] = useState(0);
+ const reloadTokenRef = useRef(reloadToken);
+ reloadTokenRef.current = reloadToken;
// ── Re-open on external change to the active composition ──
useEffect(() => {
@@ -135,13 +208,28 @@ export function useSdkSession(
// ── Open / re-open the session ──
useEffect(() => {
+ const generation = ++generationRef.current;
+ let cancelled = false;
+
+ // The preceding effect normally released its generation first. Clear any
+ // remaining owner defensively so an invalid project/path cannot retain it.
+ const previous = ownedSessionRef.current;
+ ownedSessionRef.current = null;
+ setOwnedSession(null);
+ if (previous) disposeSdkSession(previous.session);
+
if (!projectId || !activeCompPath) {
- setSession(null);
- return;
+ return () => {
+ cancelled = true;
+ };
}
- let cancelled = false;
- const compRef = { current: null as Composition | null };
+ const owner: SdkSessionOwner = {
+ projectId,
+ path: activeCompPath,
+ reloadToken,
+ generation,
+ };
readProjectFileOptional(projectId, activeCompPath)
.then(async (content) => {
@@ -157,24 +245,77 @@ export function useSdkSession(
const comp = await openComposition(content, { history: false });
// Cleanup may have fired while openComposition was awaited; dispose immediately.
if (cancelled) {
- comp.dispose();
+ disposeSdkSession(comp);
+ return;
+ }
+ if (
+ !isSessionOwnerCurrent(
+ owner,
+ generationRef.current,
+ projectIdRef.current,
+ activeCompPathRef.current,
+ reloadTokenRef.current,
+ )
+ ) {
+ disposeSdkSession(comp);
return;
}
- compRef.current = comp;
- setSession(comp);
+ const displaced = ownedSessionRef.current;
+ const installed = { ...owner, session: comp };
+ sessionOwnersRef.current.set(comp, owner);
+ ownedSessionRef.current = installed;
+ setOwnedSession(installed);
+ if (displaced && displaced.session !== comp) disposeSdkSession(displaced.session);
})
.catch(() => {
- if (!cancelled) setSession(null);
+ if (!cancelled && generationRef.current === generation) setOwnedSession(null);
});
return () => {
cancelled = true;
- // No queue to flush; dispose only. (Flushing here would serialize the
- // pre-undo in-memory doc and race the revert write on undo/redo reload.)
- compRef.current?.dispose();
+ // Publication preserves this generation, so cleanup releases whichever
+ // session it currently owns (the initially opened one or its candidate).
+ const owned = ownedSessionRef.current;
+ if (owned?.generation === generation) {
+ ownedSessionRef.current = null;
+ disposeSdkSession(owned.session);
+ }
};
}, [projectId, activeCompPath, reloadToken]);
const forceReload = useCallback(() => setReloadToken((t) => t + 1), []);
- return { session, forceReload };
+ const publish = useCallback<PublishSdkSession>(({ candidate, expectedSession, targetPath }) => {
+ const expectedOwner = sessionOwnersRef.current.get(expectedSession);
+ const current = ownedSessionRef.current;
+ if (
+ !isSessionOwnerActive(
+ expectedOwner,
+ projectIdRef.current,
+ activeCompPathRef.current,
+ targetPath,
+ )
+ ) {
+ return "rejected-inactive-target";
+ }
+ if (!ownsExpectedSession(current, expectedOwner, expectedSession, reloadTokenRef.current)) {
+ // The durable write won, but another session was installed for this same
+ // path before publication. Its self-write echo will be suppressed, so
+ // explicitly re-open it from disk instead of leaving it stale.
+ setReloadToken((t) => t + 1);
+ return "rejected-active-target";
+ }
+ const next: OwnedSdkSession = { ...current, session: candidate };
+ sessionOwnersRef.current.set(candidate, current);
+ ownedSessionRef.current = next;
+ setOwnedSession(next);
+ if (current.session !== candidate) disposeSdkSession(current.session);
+ return "published";
+ }, []);
+ const session =
+ ownedSession?.projectId === projectId &&
+ ownedSession.path === activeCompPath &&
+ ownedSession.reloadToken === reloadToken
+ ? ownedSession.session
+ : null;
+ return { session, publish, forceReload };
}
diff --git a/packages/studio/src/hooks/useSlideshowPersist.ts b/packages/studio/src/hooks/useSlideshowPersist.ts
index b4a525946e..5ccc56f31d 100644
--- a/packages/studio/src/hooks/useSlideshowPersist.ts
+++ b/packages/studio/src/hooks/useSlideshowPersist.ts
@@ -2,6 +2,7 @@ import { useCallback, type MutableRefObject } from "react";
import type { Composition } from "@hyperframes/sdk";
import type { SlideshowManifest } from "@hyperframes/core/slideshow";
import type { EditHistoryKind } from "../utils/editHistory";
+import type { PublishSdkSession } from "../utils/sdkCutover";
import { persistSlideshowManifest } from "../utils/setSlideshowManifest";
export interface UseSlideshowPersistParams {
@@ -16,6 +17,8 @@ export interface UseSlideshowPersistParams {
}) => Promise<void>;
reloadPreview: () => void;
domEditSaveTimestampRef: MutableRefObject<number>;
+ /** Publish a fully persisted candidate SDK session. */
+ publishSdkSession?: PublishSdkSession;
/**
* When provided, rapid writes with the same key coalesce through the
* save-queue infra (via recordEdit's coalesceKey) so back-to-back persists
@@ -33,6 +36,7 @@ export function useSlideshowPersist({
recordEdit,
reloadPreview,
domEditSaveTimestampRef,
+ publishSdkSession,
coalesceKey,
}: UseSlideshowPersistParams): (manifest: SlideshowManifest) => Promise<void> {
return useCallback(
@@ -42,7 +46,6 @@ export function useSlideshowPersist({
const originalContent = await readProjectFile(path);
await persistSlideshowManifest({
manifest,
- sdkSession,
originalContent,
targetPath: path,
deps: {
@@ -50,6 +53,8 @@ export function useSlideshowPersist({
writeProjectFile,
reloadPreview,
domEditSaveTimestampRef,
+ readProjectFile,
+ publishSession: publishSdkSession,
},
coalesceKey,
});
@@ -62,6 +67,7 @@ export function useSlideshowPersist({
recordEdit,
reloadPreview,
domEditSaveTimestampRef,
+ publishSdkSession,
coalesceKey,
],
);
diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx
index 491d13f071..33525d1a5f 100644
--- a/packages/studio/src/hooks/useTimelineEditing.test.tsx
+++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx
@@ -1108,6 +1108,7 @@ describe("useTimelineEditing duration rollback on failed persist", () => {
stubProjectFetch(ROLLBACK_SOURCE);
usePlayerStore.getState().setDuration(4);
vi.spyOn(console, "error").mockImplementation(() => {});
+ const showToast = vi.fn();
const hook = renderTimelineEditingHook({
timelineElements: [clip],
iframe,
@@ -1116,8 +1117,9 @@ describe("useTimelineEditing duration rollback on failed persist", () => {
writeProjectFile,
recordEdit: vi.fn(async () => {}),
reloadPreview: vi.fn(),
+ showToast,
});
- return { iframe, clip, hook, writeError };
+ return { iframe, clip, hook, showToast, writeError };
}
/**
@@ -1137,6 +1139,7 @@ describe("useTimelineEditing duration rollback on failed persist", () => {
await flushAsyncWork();
});
expect(rejection).toBe(ctx.writeError);
+ expect(ctx.showToast).toHaveBeenCalledWith("write failed", "error");
expect(usePlayerStore.getState().duration).toBe(4);
expect(rootDurationAttr(ctx.iframe)).toBe("4");
}
diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts
index b2c316eea1..f6bc0885ba 100644
--- a/packages/studio/src/hooks/useTimelineEditing.ts
+++ b/packages/studio/src/hooks/useTimelineEditing.ts
@@ -32,8 +32,9 @@ import {
} from "./timelineTrackVisibility";
import { useTimelineGroupEditing } from "./useTimelineGroupEditing";
import { serializeZLaneGesture } from "../components/nle/zLaneGesture";
-import { sdkTimingPersist } from "../utils/sdkCutover";
+import { cutoverCommittedOrThrow, sdkTimingPersist } from "../utils/sdkCutover";
import type { UseTimelineEditingOptions } from "./useTimelineEditingTypes";
+import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics";
type TimelineMoveUpdates = Pick<TimelineElement, "start" | "track"> & {
stackingReorder?: TimelineStackingReorderIntent | null;
@@ -53,6 +54,7 @@ export function useTimelineEditing({
uploadProjectFiles,
isRecordingRef,
sdkSession,
+ publishSdkSession,
forceReloadSdkSession,
handleDomZIndexReorderCommitRef,
}: UseTimelineEditingOptions) {
@@ -121,10 +123,10 @@ export function useTimelineEditing({
recordEdit,
reloadPreview,
sdkSession,
+ publishSdkSession,
showToast,
writeProjectFile,
});
-
const handleTimelineElementMove = useCallback(
// fallow-ignore-next-line complexity
(element: TimelineElement, updates: TimelineMoveUpdates) => {
@@ -215,10 +217,11 @@ export function useTimelineEditing({
// 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(projectIdRef.current ?? "", path),
+ publishSession: publishSdkSession,
},
{ label: "Move timeline clip", coalesceKey },
- ).then((handled) => {
- if (!handled) return moveFallback();
+ ).then((result) => {
+ if (!cutoverCommittedOrThrow(result)) return moveFallback();
});
}
return moveFallback();
@@ -226,6 +229,7 @@ export function useTimelineEditing({
.catch((error) => {
// Failed persist: revert the optimistic duration readout + live root.
rollbackDuration();
+ showToast(getStudioSaveErrorMessage(error), "error");
throw error;
});
};
@@ -236,12 +240,14 @@ export function useTimelineEditing({
enqueueEdit,
activeCompPath,
sdkSession,
+ publishSdkSession,
recordEdit,
writeProjectFile,
reloadPreview,
domEditSaveTimestampRef,
timelineElements,
handleDomZIndexReorderCommitRef,
+ showToast,
],
);
@@ -255,9 +261,6 @@ export function useTimelineEditing({
["data-start", formatTimelineAttributeNumber(updates.start)],
["data-duration", formatTimelineAttributeNumber(updates.duration)],
];
- // Patch the live playback-start/media-start attr too, or a resize that
- // trims the playback start leaves the preview showing the old in-point
- // until the next reload (the persisted patch handles it via pbs below).
if (updates.playbackStart != null) {
const liveAttr =
element.playbackStartAttr === "playback-start"
@@ -319,15 +322,17 @@ export function useTimelineEditing({
// 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(projectIdRef.current ?? "", path),
+ publishSession: publishSdkSession,
},
{ label: "Resize timeline clip", coalesceKey },
- ).then((handled) => {
- if (!handled) return resizeFallback();
+ ).then((result) => {
+ if (!cutoverCommittedOrThrow(result)) return resizeFallback();
})
: resizeFallback();
return persistDone.catch((error) => {
// Failed persist: revert the optimistic duration readout + live root.
rollbackDuration();
+ showToast(getStudioSaveErrorMessage(error), "error");
throw error;
});
},
@@ -336,10 +341,12 @@ export function useTimelineEditing({
enqueueEdit,
activeCompPath,
sdkSession,
+ publishSdkSession,
recordEdit,
writeProjectFile,
reloadPreview,
domEditSaveTimestampRef,
+ showToast,
],
);
diff --git a/packages/studio/src/hooks/useTimelineEditingTypes.ts b/packages/studio/src/hooks/useTimelineEditingTypes.ts
index a8660cc707..6bda862632 100644
--- a/packages/studio/src/hooks/useTimelineEditingTypes.ts
+++ b/packages/studio/src/hooks/useTimelineEditingTypes.ts
@@ -2,6 +2,7 @@ import type { MutableRefObject, RefObject } from "react";
import type { Composition } from "@hyperframes/sdk";
import type { TimelineElement } from "../player";
import type { EditHistoryKind } from "../utils/editHistory";
+import type { PublishSdkSession } from "../utils/sdkCutover";
interface RecordEditInput {
label: string;
@@ -40,6 +41,8 @@ export interface UseTimelineEditingOptions {
isRecordingRef?: RefObject<boolean>;
/** Stage 7 §3.2: SDK session for routing timing ops through setTiming. */
sdkSession?: Composition | null;
+ /** Publish a fully persisted candidate SDK session. */
+ publishSdkSession?: PublishSdkSession;
/** Resync the SDK session after a server-authoritative timeline write. */
forceReloadSdkSession?: () => void;
handleDomZIndexReorderCommitRef?: MutableRefObject<TimelineZIndexReorderCommit | null>;
diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts
index 71e37a5616..7938624c0c 100644
--- a/packages/studio/src/hooks/useTimelineGroupEditing.ts
+++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts
@@ -1,7 +1,11 @@
import { useCallback, type MutableRefObject, type RefObject } from "react";
import type { Composition } from "@hyperframes/sdk";
import type { TimelineElement } from "../player";
-import { sdkTimingBatchPersist } from "../utils/sdkCutover";
+import {
+ cutoverCommittedOrThrow,
+ sdkTimingBatchPersist,
+ type PublishSdkSession,
+} from "../utils/sdkCutover";
import {
buildTimelineMoveTimingPatch,
buildTimelineResizeTimingPatch,
@@ -20,6 +24,7 @@ import {
shiftGsapPositions,
syncPreviewContentDuration,
} from "./timelineTimingSync";
+import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics";
export interface TimelineGroupMoveChange {
element: TimelineElement;
@@ -53,6 +58,7 @@ interface UseTimelineGroupEditingOptions {
recordEdit: (input: RecordEditInput) => Promise<void>;
reloadPreview: () => void;
sdkSession?: Composition | null;
+ publishSdkSession?: PublishSdkSession;
showToast: (message: string, tone?: "error" | "info") => void;
writeProjectFile: (path: string, content: string) => Promise<void>;
}
@@ -108,6 +114,7 @@ export function useTimelineGroupEditing({
recordEdit,
reloadPreview,
sdkSession,
+ publishSdkSession,
showToast,
writeProjectFile,
}: UseTimelineGroupEditingOptions) {
@@ -189,7 +196,7 @@ export function useTimelineGroupEditing({
input.eligible &&
input.sdkChanges.every((change) => change !== null);
if (!canUseSdk) return false;
- return sdkTimingBatchPersist(
+ const result = await sdkTimingBatchPersist(
input.sdkChanges.filter((change): change is NonNullable<typeof change> => change !== null),
sharedPath,
sdkSession,
@@ -200,14 +207,17 @@ export function useTimelineGroupEditing({
domEditSaveTimestampRef,
compositionPath: activeCompPath,
readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),
+ publishSession: publishSdkSession,
},
{ label: input.label, coalesceKey: input.coalesceKey, coalesceMs: input.coalesceMs },
);
+ return cutoverCommittedOrThrow(result);
},
[
activeCompPath,
domEditSaveTimestampRef,
projectIdRef,
+ publishSdkSession,
recordEdit,
reloadPreview,
sdkSession,
@@ -313,6 +323,7 @@ export function useTimelineGroupEditing({
// Failed persist: revert the optimistic duration readout + live root
// alongside the gesture owner's store rollback.
rollbackDuration();
+ showToast(getStudioSaveErrorMessage(error), "error");
throw error;
});
},
@@ -324,6 +335,7 @@ export function useTimelineGroupEditing({
recordEdit,
reloadPreview,
trySdkBatchPersist,
+ showToast,
],
);
@@ -419,6 +431,7 @@ export function useTimelineGroupEditing({
// Failed persist: revert the optimistic duration readout + live root
// alongside the gesture owner's store rollback.
rollbackDuration();
+ showToast(getStudioSaveErrorMessage(error), "error");
throw error;
});
},
@@ -430,6 +443,7 @@ export function useTimelineGroupEditing({
recordEdit,
reloadPreview,
trySdkBatchPersist,
+ showToast,
],
);
diff --git a/packages/studio/src/hooks/useVariablesPersist.ts b/packages/studio/src/hooks/useVariablesPersist.ts
index 7d148d9294..7d42a72487 100644
--- a/packages/studio/src/hooks/useVariablesPersist.ts
+++ b/packages/studio/src/hooks/useVariablesPersist.ts
@@ -1,6 +1,6 @@
import { useCallback } from "react";
import type { Composition } from "@hyperframes/sdk";
-import { persistSdkSerialize } from "../utils/sdkCutover";
+import { cutoverCommittedOrThrow, persistSdkCandidateMutation } from "../utils/sdkCutover";
import type { UseSlideshowPersistParams } from "./useSlideshowPersist";
/** Same single-writer dependency set the slideshow persist path uses. */
@@ -21,6 +21,7 @@ export function useVariablesPersist({
recordEdit,
reloadPreview,
domEditSaveTimestampRef,
+ publishSdkSession,
}: UseVariablesPersistParams): (
label: string,
mutate: (session: Composition) => void,
@@ -30,11 +31,8 @@ export function useVariablesPersist({
if (!sdkSession) return false;
const path = activeCompPath ?? "index.html";
const originalContent = await readProjectFile(path);
- mutate(sdkSession);
- const after = sdkSession.serialize();
- if (after === originalContent) return false;
- await persistSdkSerialize(
- after,
+ const result = await persistSdkCandidateMutation(
+ sdkSession,
path,
originalContent,
{
@@ -43,10 +41,13 @@ export function useVariablesPersist({
reloadPreview,
domEditSaveTimestampRef,
compositionPath: activeCompPath,
+ readProjectFile,
+ publishSession: publishSdkSession,
},
+ mutate,
{ label },
);
- return true;
+ return cutoverCommittedOrThrow(result);
},
[
sdkSession,
@@ -56,6 +57,7 @@ export function useVariablesPersist({
recordEdit,
reloadPreview,
domEditSaveTimestampRef,
+ publishSdkSession,
],
);
}
diff --git a/packages/studio/src/utils/sdkCutover.gate.test.ts b/packages/studio/src/utils/sdkCutover.gate.test.ts
index e5d122cc92..d5672ab9fc 100644
--- a/packages/studio/src/utils/sdkCutover.gate.test.ts
+++ b/packages/studio/src/utils/sdkCutover.gate.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from "vitest";
// Dark-launch contract: with STUDIO_SDK_CUTOVER_ENABLED=false, EVERY cutover
-// persist chokepoint must return false so the caller takes the legacy server
+// persist chokepoint must explicitly decline so the caller takes the legacy server
// path — even when a valid SDK session exists (one always does, for
// shadow/selection). This is the contract the prod flag-flip rests on; a future
// refactor of the gate guards that silently re-enables cutover on flag-off
@@ -31,12 +31,12 @@ const makeDeps = () =>
domEditSaveTimestampRef: { current: 0 },
}) as never;
-describe("dark-launch gate — STUDIO_SDK_CUTOVER_ENABLED=false ⇒ persist returns false", () => {
+describe("dark-launch gate — STUDIO_SDK_CUTOVER_ENABLED=false ⇒ persist declines", () => {
it("sdkTimingPersist falls back without writing", async () => {
const deps = makeDeps();
- expect(await sdkTimingPersist("hf-a", "/c.html", { start: 1 }, makeSession(), deps)).toBe(
- false,
- );
+ expect(
+ await sdkTimingPersist("hf-a", "/c.html", { start: 1 }, makeSession(), deps),
+ ).toMatchObject({ status: "declined", reason: "feature_disabled" });
expect(
(deps as unknown as { writeProjectFile: ReturnType<typeof vi.fn> }).writeProjectFile,
).not.toHaveBeenCalled();
@@ -50,12 +50,12 @@ describe("dark-launch gate — STUDIO_SDK_CUTOVER_ENABLED=false ⇒ persist retu
makeSession(),
makeDeps(),
),
- ).toBe(false);
+ ).toMatchObject({ status: "declined", reason: "feature_disabled" });
});
it("sdkDeletePersist falls back", async () => {
expect(
await sdkDeletePersist("hf-a", "<html></html>", "/c.html", makeSession(), makeDeps()),
- ).toBe(false);
+ ).toMatchObject({ status: "declined", reason: "feature_disabled" });
});
});
diff --git a/packages/studio/src/utils/sdkCutover.test.ts b/packages/studio/src/utils/sdkCutover.test.ts
index 5b0bf6e7a7..78099232de 100644
--- a/packages/studio/src/utils/sdkCutover.test.ts
+++ b/packages/studio/src/utils/sdkCutover.test.ts
@@ -6,6 +6,9 @@ import {
sdkTimingPersist,
sdkGsapTweenPersist,
sdkGsapKeyframePersist,
+ cutoverCommittedOrThrow,
+ persistSdkCandidateMutation,
+ persistSdkSerialize,
} from "./sdkCutover";
import { openComposition } from "@hyperframes/sdk";
import { createMemoryAdapter } from "@hyperframes/sdk/adapters/memory";
@@ -44,6 +47,14 @@ const htmlAttrOp = (property: string, value: string): PatchOperation => ({
value,
});
+const candidateTestDeps = () => ({
+ publishSession: vi.fn(),
+ createCandidateSession: async (
+ _serialized: string,
+ live: Parameters<typeof sdkCutoverPersist>[4],
+ ) => live!,
+});
+
describe("shouldUseSdkCutover", () => {
it("returns false when flag disabled", () => {
expect(shouldUseSdkCutover(false, true, "hf-abc", [styleOp("color", "red")])).toBe(false);
@@ -148,6 +159,7 @@ describe("sdkCutoverPersist", () => {
writeProjectFile: vi.fn().mockResolvedValue(undefined),
reloadPreview: vi.fn(),
domEditSaveTimestampRef: makeRef(0),
+ ...candidateTestDeps(),
...overrides,
});
@@ -175,7 +187,7 @@ describe("sdkCutoverPersist", () => {
null,
deps,
);
- expect(result).toBe(false);
+ expect(result.status).toBe("declined");
});
it("returns false when element not found in session", async () => {
@@ -190,7 +202,7 @@ describe("sdkCutoverPersist", () => {
session,
deps,
);
- expect(result).toBe(false);
+ expect(result.status).toBe("declined");
});
it("dispatches setStyle for inline-style ops", async () => {
@@ -205,7 +217,7 @@ describe("sdkCutoverPersist", () => {
session,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.dispatch).toHaveBeenCalledWith({
type: "setStyle",
target: "hf-abc",
@@ -227,7 +239,7 @@ describe("sdkCutoverPersist", () => {
session,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.dispatch).toHaveBeenCalledWith({
type: "setText",
target: "hf-abc",
@@ -251,7 +263,7 @@ describe("sdkCutoverPersist", () => {
session,
deps,
);
- expect(result).toBe(false);
+ expect(result.status).toBe("declined");
expect(session!.dispatch).not.toHaveBeenCalled();
expect(deps.writeProjectFile).not.toHaveBeenCalled();
});
@@ -268,7 +280,7 @@ describe("sdkCutoverPersist", () => {
session,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.dispatch).toHaveBeenCalledWith({
type: "setAttribute",
target: "hf-abc",
@@ -289,7 +301,7 @@ describe("sdkCutoverPersist", () => {
session,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.dispatch).toHaveBeenCalledWith({
type: "setAttribute",
target: "hf-abc",
@@ -337,7 +349,7 @@ describe("sdkCutoverPersist", () => {
session,
deps,
);
- expect(result).toBe(false);
+ expect(result.status).toBe("failed");
expect(deps.reloadPreview).not.toHaveBeenCalled();
});
@@ -376,12 +388,430 @@ describe("sdkCutoverPersist", () => {
session,
deps,
);
- expect(result).toBe(false);
+ expect(result.status).toBe("failed");
expect(deps.writeProjectFile).not.toHaveBeenCalled();
expect(deps.reloadPreview).not.toHaveBeenCalled();
});
});
+describe("transactional SDK candidate publication", () => {
+ const html = `<!DOCTYPE html><html data-composition-variables='[]'><body>
+<div data-hf-id="hf-stage" data-hf-root><div data-hf-id="hf-box" data-start="0" data-duration="1"></div>
+<script>var tl = gsap.timeline({ paused: true });
+tl.to('[data-hf-id="hf-box"]', { duration: 1, x: 100 }, 0);
+window.__timelines = { main: tl };</script></div>
+</body></html>`;
+
+ it.each([
+ [
+ "style",
+ (session: Awaited<ReturnType<typeof openComposition>>) =>
+ session.setStyle("hf-box", { color: "red" }),
+ ],
+ [
+ "timing",
+ (session: Awaited<ReturnType<typeof openComposition>>) =>
+ session.setTiming("hf-box", { start: 2 }),
+ ],
+ [
+ "delete",
+ (session: Awaited<ReturnType<typeof openComposition>>) => session.removeElement("hf-box"),
+ ],
+ [
+ "variables",
+ (session: Awaited<ReturnType<typeof openComposition>>) =>
+ session.declareVariable({ id: "title", type: "string", label: "Title", default: "Hello" }),
+ ],
+ [
+ "grouping/structure",
+ (session: Awaited<ReturnType<typeof openComposition>>) =>
+ session.addElement(null, 0, '<div data-hf-group="group-1"></div>'),
+ ],
+ [
+ "GSAP",
+ (session: Awaited<ReturnType<typeof openComposition>>) => {
+ const animationId = session.getElement("hf-box")?.animationIds[0];
+ if (!animationId) throw new Error("missing fixture animation");
+ session.setGsapTween(animationId, { ease: "power2.in" });
+ },
+ ],
+ ])(
+ "restores disk and keeps the live session unchanged when %s history fails",
+ async (_name, mutate) => {
+ const live = await openComposition(html, { history: false });
+ const liveBefore = live.serialize();
+ let disk = html;
+ const publishSession = vi.fn();
+ const result = await persistSdkCandidateMutation(
+ live,
+ "/comp.html",
+ html,
+ {
+ editHistory: { recordEdit: vi.fn().mockRejectedValue(new Error("history failed")) },
+ writeProjectFile: vi.fn(async (_path: string, content: string) => {
+ disk = content;
+ }),
+ reloadPreview: vi.fn(),
+ domEditSaveTimestampRef: { current: 0 },
+ publishSession,
+ },
+ mutate,
+ { label: `Edit ${_name}` },
+ );
+
+ expect(result.status).toBe("failed");
+ expect(disk).toBe(html);
+ expect(live.serialize()).toBe(liveBefore);
+ expect(publishSession).not.toHaveBeenCalled();
+ expect(() => cutoverCommittedOrThrow(result)).toThrow("history failed");
+ live.dispose();
+ },
+ );
+
+ it("disposes a mutated real candidate and leaves the live session unpublished when the write fails", async () => {
+ const live = await openComposition(html, { history: false });
+ const liveBefore = live.serialize();
+ let candidate: Awaited<ReturnType<typeof openComposition>> | undefined;
+ let disposeCandidate: ReturnType<typeof vi.spyOn> | undefined;
+ const publishSession = vi.fn().mockReturnValue("published");
+ const writeError = new Error("write failed");
+ const writeProjectFile = vi.fn().mockRejectedValue(writeError);
+ const result = await persistSdkCandidateMutation(
+ live,
+ "/comp.html",
+ html,
+ {
+ editHistory: { recordEdit: vi.fn().mockResolvedValue(undefined) },
+ writeProjectFile,
+ reloadPreview: vi.fn(),
+ domEditSaveTimestampRef: { current: 0 },
+ createCandidateSession: async (source) => {
+ candidate = await openComposition(source, { history: false });
+ disposeCandidate = vi.spyOn(candidate, "dispose");
+ return candidate;
+ },
+ publishSession,
+ },
+ (next) => next.setStyle("hf-box", { color: "red" }),
+ );
+
+ expect(result).toMatchObject({ status: "failed", error: writeError });
+ expect(writeProjectFile).toHaveBeenCalledOnce();
+ expect(writeProjectFile.mock.calls[0]?.[0]).toBe("/comp.html");
+ expect(writeProjectFile.mock.calls[0]?.[1]).toContain("color: red");
+ expect(live.serialize()).toBe(liveBefore);
+ expect(publishSession).not.toHaveBeenCalled();
+ expect(disposeCandidate).toHaveBeenCalledOnce();
+ live.dispose();
+ });
+
+ it("publishes the candidate only after write and history commit", async () => {
+ const live = await openComposition(html, { history: false });
+ const liveBefore = live.serialize();
+ const order: string[] = [];
+ let published: Awaited<ReturnType<typeof openComposition>> | undefined;
+ const result = await persistSdkCandidateMutation(
+ live,
+ "/comp.html",
+ html,
+ {
+ editHistory: {
+ recordEdit: vi.fn(async () => {
+ order.push("history");
+ }),
+ },
+ writeProjectFile: vi.fn(async () => {
+ order.push("write");
+ }),
+ reloadPreview: vi.fn(() => order.push("refresh")),
+ domEditSaveTimestampRef: { current: 0 },
+ publishSession: ({ candidate }) => {
+ order.push("publish");
+ published = candidate;
+ return "published";
+ },
+ },
+ (candidate) => candidate.setStyle("hf-box", { color: "red" }),
+ );
+
+ expect(result.status).toBe("committed");
+ expect(order).toEqual(["write", "history", "publish", "refresh"]);
+ expect(live.serialize()).toBe(liveBefore);
+ expect(published?.serialize()).toContain("color: red");
+ live.dispose();
+ published?.dispose();
+ });
+
+ it("keeps the durable commit authoritative when a publisher throws after publication", async () => {
+ const live = await openComposition(html, { history: false });
+ let disk = html;
+ let published: Awaited<ReturnType<typeof openComposition>> | undefined;
+ const recordEdit = vi.fn().mockResolvedValue(undefined);
+ const writeProjectFile = vi.fn(async (_path: string, content: string) => {
+ disk = content;
+ });
+ const result = await persistSdkCandidateMutation(
+ live,
+ "/comp.html",
+ html,
+ {
+ editHistory: { recordEdit },
+ writeProjectFile,
+ reloadPreview: vi.fn(),
+ domEditSaveTimestampRef: { current: 0 },
+ publishSession: ({ candidate }) => {
+ published = candidate;
+ throw new Error("cleanup after publish failed");
+ },
+ },
+ (candidate) => candidate.setStyle("hf-box", { color: "red" }),
+ );
+
+ expect(result.status).toBe("committed");
+ expect(disk).toContain("color: red");
+ expect(writeProjectFile).toHaveBeenCalledTimes(1);
+ expect(recordEdit).toHaveBeenCalledTimes(1);
+ expect(published?.serialize()).toContain("color: red");
+ live.dispose();
+ published?.dispose();
+ });
+
+ it("serializes overlapping SDK edits and rebases each candidate on the latest disk bytes", async () => {
+ const live = await openComposition(html, { history: false });
+ let disk = html;
+ const published: Array<Awaited<ReturnType<typeof openComposition>>> = [];
+ const writeProjectFile = vi.fn(async (_path: string, content: string) => {
+ // Yield inside the write to make overlap deterministic.
+ await Promise.resolve();
+ disk = content;
+ });
+ const deps = {
+ editHistory: { recordEdit: vi.fn().mockResolvedValue(undefined) },
+ writeProjectFile,
+ readProjectFile: vi.fn(async () => disk),
+ reloadPreview: vi.fn(),
+ domEditSaveTimestampRef: { current: 0 },
+ publishSession: ({ candidate }) => {
+ published.push(candidate);
+ return "published";
+ },
+ };
+
+ const [first, second] = await Promise.all([
+ persistSdkCandidateMutation(live, "/comp.html", html, deps, (candidate) =>
+ candidate.setStyle("hf-box", { color: "red" }),
+ ),
+ persistSdkCandidateMutation(live, "/comp.html", html, deps, (candidate) =>
+ candidate.setStyle("hf-box", { backgroundColor: "blue" }),
+ ),
+ ]);
+
+ expect(first.status).toBe("committed");
+ expect(second.status).toBe("committed");
+ expect(disk).toContain("color: red");
+ expect(disk).toContain("background-color: blue");
+ expect(writeProjectFile).toHaveBeenCalledTimes(2);
+ live.dispose();
+ for (const candidate of published) candidate.dispose();
+ });
+
+ it("fails instead of cloning stale bytes when the authoritative queued read rejects", async () => {
+ const live = await openComposition(html, { history: false });
+ let disk = html;
+ let readCount = 0;
+ const writeProjectFile = vi.fn(async (_path: string, content: string) => {
+ disk = content;
+ });
+ const deps = {
+ editHistory: { recordEdit: vi.fn().mockResolvedValue(undefined) },
+ writeProjectFile,
+ readProjectFile: vi.fn(async () => {
+ readCount++;
+ if (readCount === 1) return disk;
+ throw new Error("transient read failure");
+ }),
+ reloadPreview: vi.fn(),
+ domEditSaveTimestampRef: { current: 0 },
+ publishSession: vi.fn().mockReturnValue("published"),
+ };
+
+ const first = await persistSdkCandidateMutation(live, "/comp.html", html, deps, (candidate) =>
+ candidate.setStyle("hf-box", { color: "red" }),
+ );
+ const second = await persistSdkCandidateMutation(live, "/comp.html", html, deps, (candidate) =>
+ candidate.setStyle("hf-box", { backgroundColor: "blue" }),
+ );
+
+ expect(first.status).toBe("committed");
+ expect(second).toMatchObject({ status: "failed", error: new Error("transient read failure") });
+ expect(disk).toContain("color: red");
+ expect(disk).not.toContain("background-color: blue");
+ expect(writeProjectFile).toHaveBeenCalledTimes(1);
+ live.dispose();
+ });
+
+ it("does not publish a delayed candidate after the active composition switches", async () => {
+ const liveA = await openComposition(html, { history: false });
+ const liveB = await openComposition(html.replace("hf-box", "hf-other"), { history: false });
+ const candidateA = await openComposition(html, { history: false });
+ const disposeCandidate = vi.spyOn(candidateA, "dispose");
+ let activePath = "/a.html";
+ let currentSession = liveA;
+ let releaseHistory: (() => void) | undefined;
+ const historyStarted = new Promise<void>((resolve) => {
+ releaseHistory = resolve;
+ });
+ let notifyHistoryStarted: (() => void) | undefined;
+ const didStartHistory = new Promise<void>((resolve) => {
+ notifyHistoryStarted = resolve;
+ });
+ const published: Array<Awaited<ReturnType<typeof openComposition>>> = [];
+ const refresh = vi.fn();
+ const pending = persistSdkCandidateMutation(
+ liveA,
+ "/a.html",
+ html,
+ {
+ editHistory: {
+ recordEdit: vi.fn(async () => {
+ notifyHistoryStarted?.();
+ await historyStarted;
+ }),
+ },
+ writeProjectFile: vi.fn().mockResolvedValue(undefined),
+ readProjectFile: vi.fn().mockResolvedValue(html),
+ reloadPreview: vi.fn(),
+ refresh,
+ domEditSaveTimestampRef: { current: 0 },
+ createCandidateSession: vi.fn().mockResolvedValue(candidateA),
+ publishSession: ({ candidate, expectedSession, targetPath }) => {
+ if (activePath !== targetPath || currentSession !== expectedSession) {
+ return "rejected-inactive-target";
+ }
+ currentSession = candidate;
+ published.push(candidate);
+ return "published";
+ },
+ },
+ (candidate) => candidate.setStyle("hf-box", { color: "red" }),
+ );
+
+ await didStartHistory;
+ activePath = "/b.html";
+ currentSession = liveB;
+ releaseHistory?.();
+
+ expect((await pending).status).toBe("committed");
+ expect(currentSession).toBe(liveB);
+ expect(published).toHaveLength(0);
+ expect(disposeCandidate).toHaveBeenCalledOnce();
+ expect(refresh).not.toHaveBeenCalled();
+ liveA.dispose();
+ liveB.dispose();
+ });
+});
+
+describe("persistSdkSerialize — shared per-file transaction boundary", () => {
+ const html = `<!DOCTYPE html><html data-composition-variables='[]'><body>
+<div data-hf-id="hf-stage" data-hf-root><div data-hf-id="hf-box" data-start="0" data-duration="1"></div></div>
+</body></html>`;
+
+ const makeDeps = (disk: { current: string }) => ({
+ editHistory: { recordEdit: vi.fn().mockResolvedValue(undefined) },
+ writeProjectFile: vi.fn(async (_path: string, content: string) => {
+ disk.current = content;
+ }),
+ readProjectFile: vi.fn(async () => disk.current),
+ reloadPreview: vi.fn(),
+ domEditSaveTimestampRef: { current: 0 },
+ });
+
+ it("rebases overlapping whole-file transforms on the latest committed bytes", async () => {
+ const disk = { current: "<html><body></body></html>" };
+ let releaseFirstWrite: (() => void) | undefined;
+ const firstWriteStarted = new Promise<void>((resolve) => {
+ releaseFirstWrite = resolve;
+ });
+ let notifyFirstWriteStarted: (() => void) | undefined;
+ const didStartFirstWrite = new Promise<void>((resolve) => {
+ notifyFirstWriteStarted = resolve;
+ });
+ const deps = makeDeps(disk);
+ deps.writeProjectFile.mockImplementationOnce(async (_path: string, content: string) => {
+ notifyFirstWriteStarted?.();
+ await firstWriteStarted;
+ disk.current = content;
+ });
+
+ const first = persistSdkSerialize(
+ (before) => before.replace("</body>", "<div>A</div></body>"),
+ "/comp.html",
+ disk.current,
+ deps,
+ );
+ await didStartFirstWrite;
+ const second = persistSdkSerialize(
+ (before) => before.replace("</body>", "<div>B</div></body>"),
+ "/comp.html",
+ disk.current,
+ deps,
+ );
+ releaseFirstWrite?.();
+ await Promise.all([first, second]);
+
+ expect(disk.current).toContain("<div>A</div>");
+ expect(disk.current).toContain("<div>B</div>");
+ });
+
+ it("shares the same queue with candidate mutations", async () => {
+ const disk = { current: html };
+ const live = await openComposition(html, { history: false });
+ const published: Array<Awaited<ReturnType<typeof openComposition>>> = [];
+ const deps = {
+ ...makeDeps(disk),
+ publishSession: ({
+ candidate,
+ }: {
+ candidate: Awaited<ReturnType<typeof openComposition>>;
+ }) => {
+ published.push(candidate);
+ return "published";
+ },
+ };
+ let releaseCandidateWrite: (() => void) | undefined;
+ const candidateWriteGate = new Promise<void>((resolve) => {
+ releaseCandidateWrite = resolve;
+ });
+ let notifyCandidateWriteStarted: (() => void) | undefined;
+ const candidateWriteStarted = new Promise<void>((resolve) => {
+ notifyCandidateWriteStarted = resolve;
+ });
+ deps.writeProjectFile.mockImplementationOnce(async (_path: string, content: string) => {
+ notifyCandidateWriteStarted?.();
+ await candidateWriteGate;
+ disk.current = content;
+ });
+
+ const candidateEdit = persistSdkCandidateMutation(live, "/comp.html", html, deps, (candidate) =>
+ candidate.setStyle("hf-box", { color: "red" }),
+ );
+ await candidateWriteStarted;
+ const islandEdit = persistSdkSerialize(
+ (before) => before.replace("</body>", "<script>island</script></body>"),
+ "/comp.html",
+ html,
+ deps,
+ );
+ releaseCandidateWrite?.();
+ await Promise.all([candidateEdit, islandEdit]);
+
+ expect(disk.current).toContain("color: red");
+ expect(disk.current).toContain("<script>island</script>");
+ live.dispose();
+ for (const candidate of published) candidate.dispose();
+ });
+});
+
describe("sdkDeletePersist", () => {
const makeRef = <T>(val: T): MutableRefObject<T> => ({ current: val });
const makeDeps = () => ({
@@ -389,6 +819,7 @@ describe("sdkDeletePersist", () => {
writeProjectFile: vi.fn().mockResolvedValue(undefined),
reloadPreview: vi.fn(),
domEditSaveTimestampRef: makeRef(0),
+ ...candidateTestDeps(),
});
const makeSession = (hasEl = true) =>
@@ -403,21 +834,23 @@ describe("sdkDeletePersist", () => {
}) as unknown as Parameters<typeof sdkDeletePersist>[3];
it("returns false when session is null", async () => {
- expect(await sdkDeletePersist("hf-abc", "before", "/comp.html", null, makeDeps())).toBe(false);
+ expect(
+ (await sdkDeletePersist("hf-abc", "before", "/comp.html", null, makeDeps())).status,
+ ).toBe("declined");
});
it("returns false when element not found in session", async () => {
const session = makeSession(false);
- expect(await sdkDeletePersist("hf-abc", "before", "/comp.html", session, makeDeps())).toBe(
- false,
- );
+ expect(
+ (await sdkDeletePersist("hf-abc", "before", "/comp.html", session, makeDeps())).status,
+ ).toBe("declined");
});
it("calls removeElement and writes serialized content", async () => {
const deps = makeDeps();
const session = makeSession(true);
const result = await sdkDeletePersist("hf-abc", "before", "/comp.html", session, deps);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.removeElement).toHaveBeenCalledWith("hf-abc");
expect(deps.writeProjectFile).toHaveBeenCalledWith("/comp.html", "<html>after</html>");
});
@@ -448,7 +881,7 @@ describe("sdkDeletePersist", () => {
throw new Error("remove failed");
});
const result = await sdkDeletePersist("hf-abc", "before", "/comp.html", session, deps);
- expect(result).toBe(false);
+ expect(result.status).toBe("failed");
expect(deps.writeProjectFile).not.toHaveBeenCalled();
expect(deps.reloadPreview).not.toHaveBeenCalled();
});
@@ -461,6 +894,7 @@ describe("sdkTimingPersist", () => {
writeProjectFile: vi.fn().mockResolvedValue(undefined),
reloadPreview: vi.fn(),
domEditSaveTimestampRef: makeRef(0),
+ ...candidateTestDeps(),
});
const makeSession = (hasEl = true) =>
@@ -475,16 +909,16 @@ describe("sdkTimingPersist", () => {
}) as unknown as Parameters<typeof sdkTimingPersist>[3];
it("returns false when session is null", async () => {
- expect(await sdkTimingPersist("hf-clip", "/comp.html", { start: 1 }, null, makeDeps())).toBe(
- false,
- );
+ expect(
+ (await sdkTimingPersist("hf-clip", "/comp.html", { start: 1 }, null, makeDeps())).status,
+ ).toBe("declined");
});
it("returns false when element not found in session", async () => {
const session = makeSession(false);
- expect(await sdkTimingPersist("hf-clip", "/comp.html", { start: 1 }, session, makeDeps())).toBe(
- false,
- );
+ expect(
+ (await sdkTimingPersist("hf-clip", "/comp.html", { start: 1 }, session, makeDeps())).status,
+ ).toBe("declined");
});
it("calls setTiming with provided update and writes serialized content", async () => {
@@ -497,7 +931,7 @@ describe("sdkTimingPersist", () => {
session,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.setTiming).toHaveBeenCalledWith("hf-clip", {
start: 2,
duration: 5,
@@ -524,7 +958,7 @@ describe("sdkTimingPersist", () => {
throw new Error("timing error");
});
const result = await sdkTimingPersist("hf-clip", "/comp.html", { start: 1 }, session, deps);
- expect(result).toBe(false);
+ expect(result.status).toBe("failed");
expect(deps.writeProjectFile).not.toHaveBeenCalled();
});
@@ -539,6 +973,7 @@ describe("sdkTimingPersist", () => {
const session = makeSession(true);
await sdkTimingPersist("hf-clip", "/comp.html", { start: 3 }, session, deps);
expect(deps.readProjectFile).toHaveBeenCalledWith("/comp.html");
+ expect(deps.readProjectFile).toHaveBeenCalledOnce();
expect(deps.editHistory.recordEdit).toHaveBeenCalledWith(
expect.objectContaining({
files: {
@@ -548,18 +983,16 @@ describe("sdkTimingPersist", () => {
);
});
- it("falls back to serialize() before when the reader throws", async () => {
+ it("fails without writing when the authoritative reader throws", async () => {
const deps = {
...makeDeps(),
readProjectFile: vi.fn().mockRejectedValue(new Error("read failed")),
};
const session = makeSession(true);
- await sdkTimingPersist("hf-clip", "/comp.html", { start: 3 }, session, deps);
- expect(deps.editHistory.recordEdit).toHaveBeenCalledWith(
- expect.objectContaining({
- files: { "/comp.html": { before: "<html>before</html>", after: "<html>after</html>" } },
- }),
- );
+ const result = await sdkTimingPersist("hf-clip", "/comp.html", { start: 3 }, session, deps);
+ expect(result).toMatchObject({ status: "failed", error: new Error("read failed") });
+ expect(deps.writeProjectFile).not.toHaveBeenCalled();
+ expect(deps.editHistory.recordEdit).not.toHaveBeenCalled();
});
});
@@ -583,6 +1016,7 @@ describe("sdkGsapTweenPersist — undo baseline (finding #12)", () => {
reloadPreview: vi.fn(),
domEditSaveTimestampRef: makeRef(0),
readProjectFile: vi.fn().mockResolvedValue("<html>on-disk gsap bytes</html>"),
+ ...candidateTestDeps(),
};
const session = makeSession();
await sdkGsapTweenPersist(
@@ -591,6 +1025,7 @@ describe("sdkGsapTweenPersist — undo baseline (finding #12)", () => {
session,
deps,
);
+ expect(deps.readProjectFile).toHaveBeenCalledOnce();
expect(deps.editHistory.recordEdit).toHaveBeenCalledWith(
expect.objectContaining({
files: {
@@ -604,16 +1039,18 @@ describe("sdkGsapTweenPersist — undo baseline (finding #12)", () => {
describe("sdkGsapTweenPersist — per-file serialization (finding #8)", () => {
const makeRef = <T>(val: T): MutableRefObject<T> => ({ current: val });
- it("routes the read-modify-write through the keyed serializer so same-file flushes can't interleave", async () => {
+ it("routes the read-modify-write through the shared file coordinator", async () => {
const order: string[] = [];
let writeResolve: (() => void) | null = null;
+ let writeCall = 0;
const deps = {
editHistory: { recordEdit: vi.fn().mockResolvedValue(undefined) },
// First write blocks until we release it, so without serialization the
// second op's serialize()/dispatch would interleave ahead of it.
writeProjectFile: vi.fn().mockImplementation((_p: string, content: string) => {
+ writeCall++;
order.push(`write-start:${content}`);
- if (content === "<html>after-1</html>") {
+ if (writeCall === 1) {
return new Promise<void>((res) => {
writeResolve = () => {
order.push(`write-done:${content}`);
@@ -626,16 +1063,7 @@ describe("sdkGsapTweenPersist — per-file serialization (finding #8)", () => {
}),
reloadPreview: vi.fn(),
domEditSaveTimestampRef: makeRef(0),
- // A real per-key serializer: tasks under the same key run strictly in order.
- serialize: (() => {
- const inFlight = new Map<string, Promise<unknown>>();
- return <T>(key: string, task: () => Promise<T>): Promise<T> => {
- const prior = inFlight.get(key) ?? Promise.resolve();
- const next = prior.then(task, task);
- inFlight.set(key, next);
- return next as Promise<T>;
- };
- })(),
+ ...candidateTestDeps(),
};
let serializeCall = 0;
@@ -662,15 +1090,17 @@ describe("sdkGsapTweenPersist — per-file serialization (finding #8)", () => {
session,
deps,
);
- // Let the first op reach its (blocked) write before releasing it.
- await Promise.resolve();
- await Promise.resolve();
+ // Let the first op finish candidate construction and reach its blocked write.
+ await vi.waitFor(() => expect(writeResolve).not.toBeNull());
writeResolve?.();
await Promise.all([p1, p2]);
// The second op's write must NOT start before the first op's write completes.
- const firstWriteDone = order.indexOf("write-done:<html>after-1</html>");
- const secondWriteStart = order.indexOf("write-start:<html>after-2</html>");
+ const firstWriteDone = order.findIndex((entry) => entry.startsWith("write-done:"));
+ const writeStarts = order
+ .map((entry, index) => (entry.startsWith("write-start:") ? index : -1))
+ .filter((index) => index >= 0);
+ const secondWriteStart = writeStarts[1] ?? -1;
expect(firstWriteDone).toBeGreaterThanOrEqual(0);
expect(secondWriteStart).toBeGreaterThan(firstWriteDone);
});
@@ -683,6 +1113,7 @@ describe("sdkGsapTweenPersist", () => {
writeProjectFile: vi.fn().mockResolvedValue(undefined),
reloadPreview: vi.fn(),
domEditSaveTimestampRef: makeRef(0),
+ ...candidateTestDeps(),
});
const makeSession = (opts?: { addGsapTween?: string; hasEl?: boolean }) =>
@@ -706,7 +1137,7 @@ describe("sdkGsapTweenPersist", () => {
null,
makeDeps(),
),
- ).toBe(false);
+ ).toMatchObject({ status: "declined" });
});
it("calls addGsapTween and writes for kind=add", async () => {
@@ -722,7 +1153,7 @@ describe("sdkGsapTweenPersist", () => {
session,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.addGsapTween).toHaveBeenCalledWith(
"hf-box",
expect.objectContaining({ method: "to" }),
@@ -739,7 +1170,7 @@ describe("sdkGsapTweenPersist", () => {
session,
deps,
);
- expect(result).toBe(false);
+ expect(result.status).toBe("declined");
expect(deps.writeProjectFile).not.toHaveBeenCalled();
});
@@ -752,7 +1183,7 @@ describe("sdkGsapTweenPersist", () => {
session,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.setGsapTween).toHaveBeenCalledWith("tw-1", { ease: "power3.in" });
expect(deps.reloadPreview).toHaveBeenCalled();
});
@@ -766,7 +1197,7 @@ describe("sdkGsapTweenPersist", () => {
session,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.removeGsapTween).toHaveBeenCalledWith("tw-1");
});
@@ -782,7 +1213,7 @@ describe("sdkGsapTweenPersist", () => {
session,
deps,
);
- expect(result).toBe(false);
+ expect(result.status).toBe("failed");
expect(deps.writeProjectFile).not.toHaveBeenCalled();
});
});
@@ -794,6 +1225,7 @@ describe("sdkGsapKeyframePersist", () => {
writeProjectFile: vi.fn().mockResolvedValue(undefined),
reloadPreview: vi.fn(),
domEditSaveTimestampRef: makeRef(0),
+ ...candidateTestDeps(),
});
const makeSession = () =>
@@ -809,7 +1241,7 @@ describe("sdkGsapKeyframePersist", () => {
it("returns false when session is null", async () => {
expect(
await sdkGsapKeyframePersist("/comp.html", "tw-1", 50, { opacity: 0.5 }, null, makeDeps()),
- ).toBe(false);
+ ).toMatchObject({ status: "declined" });
});
it("dispatches addGsapKeyframe and writes serialized content", async () => {
@@ -823,7 +1255,7 @@ describe("sdkGsapKeyframePersist", () => {
session,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
expect(session!.dispatch).toHaveBeenCalledWith({
type: "addGsapKeyframe",
animationId: "tw-1",
@@ -848,7 +1280,7 @@ describe("sdkGsapKeyframePersist", () => {
session,
deps,
);
- expect(result).toBe(false);
+ expect(result.status).toBe("failed");
expect(deps.writeProjectFile).not.toHaveBeenCalled();
});
});
@@ -860,6 +1292,7 @@ describe("sdkCutoverPersist — GSAP script preservation (integration)", () => {
writeProjectFile: vi.fn().mockResolvedValue(undefined),
reloadPreview: vi.fn(),
domEditSaveTimestampRef: makeRef(0),
+ ...candidateTestDeps(),
});
it("preserves GSAP <script> block and data-position-mode through setStyle dispatch", async () => {
@@ -880,7 +1313,7 @@ gsap.timeline().to('[data-hf-id="hf-layer"]', { duration: 1, x: 100 });
comp,
deps,
);
- expect(result).toBe(true);
+ expect(result.status).toBe("committed");
const written = (deps.writeProjectFile as ReturnType<typeof vi.fn>).mock
.calls[0]?.[1] as string;
expect(written).toContain("data-hf-gsap");
diff --git a/packages/studio/src/utils/sdkCutover.ts b/packages/studio/src/utils/sdkCutover.ts
index b17b03fe2b..cffcec0bf8 100644
--- a/packages/studio/src/utils/sdkCutover.ts
+++ b/packages/studio/src/utils/sdkCutover.ts
@@ -1,81 +1,32 @@
-import type { MutableRefObject } from "react";
import type { Composition, GsapTweenSpec } from "@hyperframes/sdk";
import type { DomEditSelection } from "../components/editor/domEditing";
-import type { EditHistoryKind } from "./editHistory";
import type { PatchOperation } from "./sourcePatcher";
import { STUDIO_SDK_CUTOVER_ENABLED } from "../components/editor/manualEditingAvailability";
import { trackStudioEvent } from "./studioTelemetry";
-import { markSelfWrite } from "../hooks/sdkSelfWriteRegistry";
import { patchOpsToSdkEditOps } from "./sdkOpMapping";
import { recordResolverParity, recordAnimationResolverParity } from "./sdkResolverShadow";
import { shouldDeclineTextCutoverForTarget, shouldUseSdkCutover } from "./sdkCutoverEligibility";
+import {
+ asCutoverError,
+ declinedCutover,
+ persistSdkCandidateMutation,
+ type CutoverDeps,
+ type CutoverOptions,
+ type CutoverResult,
+} from "./sdkEditTransaction";
export { shouldUseSdkCutover } from "./sdkCutoverEligibility";
-
-export interface CutoverDeps {
- editHistory: {
- recordEdit: (entry: {
- label: string;
- kind: EditHistoryKind;
- coalesceKey?: string;
- coalesceMs?: number;
- files: Record<string, { before: string; after: string }>;
- }) => Promise<void>;
- };
- writeProjectFile: (path: string, content: string) => Promise<void>;
- reloadPreview: () => void;
- domEditSaveTimestampRef: MutableRefObject<number>;
- /**
- * Optional post-write refresh. When provided, it REPLACES the default
- * reloadPreview() — the GSAP path passes one that soft-reloads (preserving
- * the playhead) and invalidates the keyframe/gsap panel cache. Receives the
- * serialized document just written.
- */
- refresh?: (after: string) => void;
- /**
- * Path of the composition the SDK session was opened for. The session models
- * ONLY this file (serialize() emits the whole active composition), so any edit
- * whose targetPath differs (a sub-composition file) must take the server path
- * — otherwise we'd write the full active-comp serialization into that file.
- */
- compositionPath?: string | null;
- /**
- * Optional per-key task serializer (the same `gsap-file:${file}` serializer the
- * legacy `commitMutation` uses). When provided, every GSAP-op persist routes its
- * read-serialize → dispatch → serialize → write through it so two concurrent
- * same-file flushes can't interleave their read-modify-write and lose an edit.
- * Absent (e.g. in unit tests) → ops run unserialized as before.
- */
- serialize?: <T>(key: string, task: () => Promise<T>) => Promise<T>;
- /**
- * Optional reader for the on-disk content of targetPath. Timing/GSAP persists
- * use it to capture the EXACT prior bytes as the undo-history `before`, so undo
- * restores the file verbatim instead of a normalized SDK re-emit (which would
- * reformat the whole file). The style/delete paths already thread originalContent
- * in explicitly; this gives timing/GSAP parity without touching every call site.
- * Absent → falls back to the SDK's pre-edit serialize() (the prior behavior).
- */
- readProjectFile?: (path: string) => Promise<string>;
-}
-
-/**
- * Capture the undo-history `before` baseline for timing/GSAP persists: the exact
- * on-disk bytes when a reader is available (so undo restores them verbatim),
- * falling back to the SDK's pre-edit serialization when it isn't. Never throws —
- * a failed read degrades to the serialized fallback rather than aborting the edit.
- */
-async function captureOnDiskBefore(
- deps: CutoverDeps,
- targetPath: string,
- serializedFallback: string,
-): Promise<string> {
- if (!deps.readProjectFile) return serializedFallback;
- try {
- return await deps.readProjectFile(targetPath);
- } catch {
- return serializedFallback;
- }
-}
+export {
+ cutoverCommittedOrThrow,
+ persistSdkCandidateMutation,
+ persistSdkSerialize,
+} from "./sdkEditTransaction";
+export type {
+ CutoverDeps,
+ CutoverOptions,
+ CutoverResult,
+ PublishSdkSession,
+} from "./sdkEditTransaction";
/** True when targetPath isn't the composition the SDK session models. */
function wrongCompositionFile(deps: CutoverDeps, targetPath: string): boolean {
@@ -95,45 +46,6 @@ function gsapReadSource(
const read = deps.readProjectFile;
return read ? () => read(targetPath) : undefined;
}
-
-interface CutoverOptions {
- label?: string;
- coalesceKey?: string;
- /** Coalesce window (ms); Infinity folds across a slow round-trip. */
- coalesceMs?: number;
- /** Skip the preview reload (mirrors the server path's skipRefresh). */
- skipRefresh?: boolean;
-}
-
-// ponytail: exported for setSlideshowManifest (third caller — island write bypasses
-// the SDK dispatch path since <script> nodes are not in the element tree).
-// `after` is serialized once by the caller (which also did the no-op check
-// against its pre-dispatch snapshot), so this never re-serializes.
-export async function persistSdkSerialize(
- after: string,
- targetPath: string,
- originalContent: string,
- deps: CutoverDeps,
- options?: CutoverOptions,
-): Promise<void> {
- deps.domEditSaveTimestampRef.current = Date.now();
- // Tag this write with the exact content (by hash) so the file-change
- // reload-suppression can recognize its own echo by IDENTITY, not just a 2 s
- // clock — an undo write (different bytes, not registered here) then always
- // reloads instead of being swallowed by the time window.
- markSelfWrite(targetPath, after);
- await deps.writeProjectFile(targetPath, after);
- await deps.editHistory.recordEdit({
- label: options?.label ?? "Edit layer",
- kind: "manual",
- ...(options?.coalesceKey ? { coalesceKey: options.coalesceKey } : {}),
- ...(options?.coalesceMs != null ? { coalesceMs: options.coalesceMs } : {}),
- files: { [targetPath]: { before: originalContent, after } },
- });
- if (deps.refresh) deps.refresh(after);
- else if (!options?.skipRefresh) deps.reloadPreview();
-}
-
export async function sdkCutoverPersist(
selection: DomEditSelection,
ops: PatchOperation[],
@@ -142,35 +54,33 @@ export async function sdkCutoverPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
if (!shouldUseSdkCutover(STUDIO_SDK_CUTOVER_ENABLED, !!sdkSession, selection.hfId, ops))
- return false;
- if (!sdkSession) return false;
+ return declinedCutover("ineligible_operation");
+ if (!sdkSession) return declinedCutover("session_unavailable");
const hfId = selection.hfId;
- if (!hfId) return false;
+ if (!hfId) return declinedCutover("target_unaddressable");
const target = sdkSession.getElement(hfId);
- if (!target) return false;
- if (shouldDeclineTextCutoverForTarget(target, ops)) return false;
- if (wrongCompositionFile(deps, targetPath)) return false;
- try {
- const before = sdkSession.serialize();
- sdkSession.batch(() => {
- for (const editOp of patchOpsToSdkEditOps(hfId, ops)) {
- sdkSession.dispatch(editOp);
- }
- });
- const after = sdkSession.serialize();
- if (after === before) return false;
- await persistSdkSerialize(after, targetPath, originalContent, deps, options);
+ if (!target) return declinedCutover("target_not_found");
+ if (shouldDeclineTextCutoverForTarget(target, ops))
+ return declinedCutover("unsupported_text_target");
+ if (wrongCompositionFile(deps, targetPath)) return declinedCutover("wrong_composition_file");
+ const result = await persistSdkCandidateMutation(
+ sdkSession,
+ targetPath,
+ originalContent,
+ deps,
+ (session) => {
+ for (const editOp of patchOpsToSdkEditOps(hfId, ops)) session.dispatch(editOp);
+ },
+ options,
+ );
+ if (result.status === "committed") {
trackStudioEvent("sdk_cutover_success", { hfId, opCount: ops.length });
- return true;
- } catch (err) {
- trackStudioEvent("sdk_cutover_fallback", {
- hfId: selection.hfId ?? null,
- error: String(err),
- });
- return false;
+ } else if (result.status === "failed") {
+ trackStudioEvent("sdk_cutover_failed", { hfId, error: result.error.message });
}
+ return result;
}
export async function sdkTimingPersist(
@@ -180,7 +90,7 @@ export async function sdkTimingPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
// Resolver tripwire — runs BEFORE the cutover gate (decoupled): records when
// the SDK can't resolve a target the server timing path is addressing.
const timingSrc = deps.readProjectFile;
@@ -194,24 +104,31 @@ export async function sdkTimingPersist(
// Dark-launch gate: without this, timing cutover runs whenever an SDK session
// exists (it always does, for shadow/selection) — flipping the flag OFF would
// NOT disable it. Gate here so flag-off routes back to the legacy server path.
- if (!STUDIO_SDK_CUTOVER_ENABLED) return false;
- if (!sdkSession || !sdkSession.getElement(hfId)) return false;
- if (wrongCompositionFile(deps, targetPath)) return false;
+ if (!STUDIO_SDK_CUTOVER_ENABLED) return declinedCutover("feature_disabled");
+ if (!sdkSession) return declinedCutover("session_unavailable");
+ if (!sdkSession.getElement(hfId)) return declinedCutover("target_not_found");
+ if (wrongCompositionFile(deps, targetPath)) return declinedCutover("wrong_composition_file");
try {
const serializedBefore = sdkSession.serialize();
- sdkSession.batch(() => sdkSession.setTiming(hfId, timingUpdate));
- const after = sdkSession.serialize();
- if (after === serializedBefore) return false;
- // Undo baseline = exact on-disk bytes (matching the style/delete paths), so
- // undoing a timing edit restores the file verbatim instead of a normalized
- // full-DOM re-emit. Falls back to serializedBefore when no reader is wired.
- const undoBefore = await captureOnDiskBefore(deps, targetPath, serializedBefore);
- await persistSdkSerialize(after, targetPath, undoBefore, deps, options);
- trackStudioEvent("sdk_cutover_success", { hfId, opCount: 1 });
- return true;
- } catch (err) {
- trackStudioEvent("sdk_cutover_fallback", { hfId, error: String(err) });
- return false;
+ const result = await persistSdkCandidateMutation(
+ sdkSession,
+ targetPath,
+ serializedBefore,
+ deps,
+ (session) => session.setTiming(hfId, timingUpdate),
+ options,
+ serializedBefore,
+ );
+ if (result.status === "committed") {
+ trackStudioEvent("sdk_cutover_success", { hfId, opCount: 1 });
+ } else if (result.status === "failed") {
+ trackStudioEvent("sdk_cutover_failed", { hfId, error: result.error.message });
+ }
+ return result;
+ } catch (error) {
+ const failed = { status: "failed", error: asCutoverError(error) } as const;
+ trackStudioEvent("sdk_cutover_failed", { hfId, error: failed.error.message });
+ return failed;
}
}
@@ -224,7 +141,7 @@ export async function sdkTimingBatchPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
const timingSrc = deps.readProjectFile;
for (const change of changes) {
void recordResolverParity(
@@ -235,29 +152,43 @@ export async function sdkTimingBatchPersist(
{ targetPath, compositionPath: deps.compositionPath },
);
}
- if (!STUDIO_SDK_CUTOVER_ENABLED) return false;
- if (!sdkSession || wrongCompositionFile(deps, targetPath)) return false;
- if (changes.some((change) => !sdkSession.getElement(change.hfId))) return false;
+ if (!STUDIO_SDK_CUTOVER_ENABLED) return declinedCutover("feature_disabled");
+ if (!sdkSession) return declinedCutover("session_unavailable");
+ if (wrongCompositionFile(deps, targetPath)) return declinedCutover("wrong_composition_file");
+ if (changes.some((change) => !sdkSession.getElement(change.hfId)))
+ return declinedCutover("target_not_found");
try {
const serializedBefore = sdkSession.serialize();
- sdkSession.batch(() => {
- for (const change of changes) sdkSession.setTiming(change.hfId, change.timingUpdate);
- });
- const after = sdkSession.serialize();
- if (after === serializedBefore) return false;
- const undoBefore = await captureOnDiskBefore(deps, targetPath, serializedBefore);
- await persistSdkSerialize(after, targetPath, undoBefore, deps, options);
+ const result = await persistSdkCandidateMutation(
+ sdkSession,
+ targetPath,
+ serializedBefore,
+ deps,
+ (session) => {
+ for (const change of changes) session.setTiming(change.hfId, change.timingUpdate);
+ },
+ options,
+ serializedBefore,
+ );
+ if (result.status === "failed") {
+ trackStudioEvent("sdk_cutover_failed", {
+ hfId: changes[0]?.hfId ?? null,
+ error: result.error.message,
+ });
+ return result;
+ }
trackStudioEvent("sdk_cutover_success", {
hfId: changes[0]?.hfId ?? null,
opCount: changes.length,
});
- return true;
- } catch (err) {
- trackStudioEvent("sdk_cutover_fallback", {
+ return result;
+ } catch (error) {
+ const failed = { status: "failed", error: asCutoverError(error) } as const;
+ trackStudioEvent("sdk_cutover_failed", {
hfId: changes[0]?.hfId ?? null,
- error: String(err),
+ error: failed.error.message,
});
- return false;
+ return failed;
}
}
@@ -272,7 +203,7 @@ export function sdkGsapTweenPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
// Resolver tripwire — runs BEFORE this function's own cutover gate (decoupled).
// add targets an element (element-resolution parity); set/remove target an
// animationId (animation-resolution parity). Done here, not via
@@ -298,10 +229,10 @@ export function sdkGsapTweenPersist(
}
// Leading dark-launch gate so flag-off does no SDK touch (getElement) at all —
// matches the other three chokepoints' discipline.
- if (!STUDIO_SDK_CUTOVER_ENABLED) return Promise.resolve(false);
+ if (!STUDIO_SDK_CUTOVER_ENABLED) return Promise.resolve(declinedCutover("feature_disabled"));
if (op.kind === "add" && sdkSession && !sdkSession.getElement(op.target))
- return Promise.resolve(false);
- // dispatchGsapOpAndPersist returns false on before===after — that catches stale
+ return Promise.resolve(declinedCutover("target_not_found"));
+ // dispatchGsapOpAndPersist declines on before===after — that catches stale
// animationIds and unsupported shapes (e.g. from-prop on a plain tween), falling
// back to the server path. This subsumes explicit existence guards for set/remove.
return dispatchGsapOpAndPersist(targetPath, sdkSession, deps, options, (s) => {
@@ -324,7 +255,7 @@ async function dispatchGsapOpAndPersist(
options: CutoverOptions | undefined,
dispatch: (s: Composition) => void,
resolverTarget?: { animationId: string; opLabel: string },
-): Promise<boolean> {
+): Promise<CutoverResult> {
// Resolver tripwire — runs BEFORE the cutover gate (decoupled): records when
// the SDK can't resolve the animationId the server GSAP path is addressing.
if (resolverTarget) {
@@ -337,34 +268,35 @@ async function dispatchGsapOpAndPersist(
);
}
// Dark-launch gate (shared chokepoint for every GSAP-op cutover persist):
- // flag OFF → return false → caller falls back to the legacy server path.
- if (!STUDIO_SDK_CUTOVER_ENABLED) return false;
- if (!sdkSession) return false;
- if (wrongCompositionFile(deps, targetPath)) return false;
+ // flag OFF → explicit decline → caller falls back to the legacy server path.
+ if (!STUDIO_SDK_CUTOVER_ENABLED) return declinedCutover("feature_disabled");
+ if (!sdkSession) return declinedCutover("session_unavailable");
+ if (wrongCompositionFile(deps, targetPath)) return declinedCutover("wrong_composition_file");
const session = sdkSession;
- // Route the whole read-serialize → dispatch → serialize → write through the
- // per-file serializer (when provided) so overlapping same-file flushes can't
- // interleave their read-modify-write and drop an edit, matching the legacy
- // commitMutation path's `gsap-file:${file}` serialization.
- const run = async (): Promise<boolean> => {
- try {
- const serializedBefore = session.serialize();
- dispatch(session);
- const after = session.serialize();
- if (after === serializedBefore) return false;
- // Undo baseline = exact on-disk bytes (matching the style/delete paths), so
- // undoing a GSAP edit restores the file verbatim instead of a normalized
- // full-DOM re-emit. Falls back to serializedBefore when no reader is wired.
- const undoBefore = await captureOnDiskBefore(deps, targetPath, serializedBefore);
- await persistSdkSerialize(after, targetPath, undoBefore, deps, options);
+ // persistSdkCandidateMutation owns the shared per-project/file transaction
+ // coordinator used by both SDK and legacy GSAP writes.
+ try {
+ const serializedBefore = session.serialize();
+ const result = await persistSdkCandidateMutation(
+ session,
+ targetPath,
+ serializedBefore,
+ deps,
+ dispatch,
+ options,
+ serializedBefore,
+ );
+ if (result.status === "committed") {
trackStudioEvent("sdk_cutover_success", { opCount: 1 });
- return true;
- } catch (err) {
- trackStudioEvent("sdk_cutover_fallback", { error: String(err) });
- return false;
+ } else if (result.status === "failed") {
+ trackStudioEvent("sdk_cutover_failed", { error: result.error.message });
}
- };
- return deps.serialize ? deps.serialize(`gsap-file:${targetPath}`, run) : run();
+ return result;
+ } catch (error) {
+ const failed = { status: "failed", error: asCutoverError(error) } as const;
+ trackStudioEvent("sdk_cutover_failed", { error: failed.error.message });
+ return failed;
+ }
}
export function sdkGsapKeyframePersist(
@@ -375,7 +307,7 @@ export function sdkGsapKeyframePersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
@@ -393,7 +325,7 @@ export function sdkGsapRemoveKeyframePersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
@@ -412,7 +344,7 @@ export function sdkGsapRemovePropertyPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
@@ -429,7 +361,7 @@ export function sdkGsapDeleteAllForSelectorPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
return dispatchGsapOpAndPersist(targetPath, sdkSession, deps, options, (s) =>
s.dispatch({ type: "deleteAllForSelector", selector }),
);
@@ -441,7 +373,7 @@ export function sdkGsapRemoveAllKeyframesPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
@@ -459,7 +391,7 @@ export function sdkGsapConvertToKeyframesPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
@@ -508,7 +440,7 @@ export function sdkAddWithKeyframesPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
const payload: KeyframesPayload = {
targetSelector,
position,
@@ -532,7 +464,7 @@ export function sdkReplaceWithKeyframesPersist(
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
-): Promise<boolean> {
+): Promise<CutoverResult> {
const payload: KeyframesPayload = {
targetSelector,
position,
@@ -556,7 +488,7 @@ export async function sdkDeletePersist(
targetPath: string,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
-): Promise<boolean> {
+): Promise<CutoverResult> {
// Resolver tripwire — runs BEFORE the cutover gate (decoupled).
void recordResolverParity(
sdkSession,
@@ -566,21 +498,22 @@ export async function sdkDeletePersist(
{ targetPath, compositionPath: deps.compositionPath },
);
// Dark-launch gate: flag OFF → legacy server delete path.
- if (!STUDIO_SDK_CUTOVER_ENABLED) return false;
- if (!sdkSession || !sdkSession.getElement(hfId)) return false;
- if (wrongCompositionFile(deps, targetPath)) return false;
- try {
- const before = sdkSession.serialize();
- sdkSession.batch(() => sdkSession.removeElement(hfId));
- const after = sdkSession.serialize();
- if (after === before) return false;
- await persistSdkSerialize(after, targetPath, originalContent, deps, {
- label: "Delete element",
- });
+ if (!STUDIO_SDK_CUTOVER_ENABLED) return declinedCutover("feature_disabled");
+ if (!sdkSession) return declinedCutover("session_unavailable");
+ if (!sdkSession.getElement(hfId)) return declinedCutover("target_not_found");
+ if (wrongCompositionFile(deps, targetPath)) return declinedCutover("wrong_composition_file");
+ const result = await persistSdkCandidateMutation(
+ sdkSession,
+ targetPath,
+ originalContent,
+ deps,
+ (session) => session.removeElement(hfId),
+ { label: "Delete element" },
+ );
+ if (result.status === "committed") {
trackStudioEvent("sdk_cutover_success", { hfId, opCount: 1 });
- return true;
- } catch (err) {
- trackStudioEvent("sdk_cutover_fallback", { hfId, error: String(err) });
- return false;
+ } else if (result.status === "failed") {
+ trackStudioEvent("sdk_cutover_failed", { hfId, error: result.error.message });
}
+ return result;
}
diff --git a/packages/studio/src/utils/sdkEditTransaction.ts b/packages/studio/src/utils/sdkEditTransaction.ts
new file mode 100644
index 0000000000..b4663f89ea
--- /dev/null
+++ b/packages/studio/src/utils/sdkEditTransaction.ts
@@ -0,0 +1,292 @@
+import type { MutableRefObject } from "react";
+import { openComposition, type Composition } from "@hyperframes/sdk";
+import type { EditHistoryKind } from "./editHistory";
+import { hashContent, markSelfWrite } from "../hooks/sdkSelfWriteRegistry";
+import { trackStudioEvent } from "./studioTelemetry";
+import { serializeStudioFileMutation } from "./studioFileMutationCoordinator";
+
+export type CutoverResult =
+ | { status: "declined"; reason: string }
+ | { status: "committed"; version: string }
+ | { status: "failed"; error: Error };
+
+export interface SdkSessionPublication {
+ candidate: Composition;
+ expectedSession: Composition;
+ targetPath: string;
+}
+
+export type SdkSessionPublicationResult =
+ | "published"
+ | "rejected-active-target"
+ | "rejected-inactive-target";
+
+export type PublishSdkSession = (publication: SdkSessionPublication) => SdkSessionPublicationResult;
+
+export interface CutoverDeps {
+ editHistory: {
+ recordEdit: (entry: {
+ label: string;
+ kind: EditHistoryKind;
+ coalesceKey?: string;
+ coalesceMs?: number;
+ files: Record<string, { before: string; after: string }>;
+ }) => Promise<void>;
+ };
+ /**
+ * Must be bound to one project. Its identity plus path scopes the shared
+ * mutation queue used by every whole-file writer in that project.
+ */
+ writeProjectFile: (path: string, content: string) => Promise<void>;
+ reloadPreview: () => void;
+ domEditSaveTimestampRef: MutableRefObject<number>;
+ refresh?: (after: string) => void;
+ compositionPath?: string | null;
+ readProjectFile?: (path: string) => Promise<string>;
+ /**
+ * Takes ownership only when it returns `published`. Rejection identifies
+ * whether target-sensitive preview refresh is still safe. MUST NOT throw
+ * after installation; rejection leaves ownership with the caller.
+ */
+ publishSession?: PublishSdkSession;
+ /** Test seam; production clones with openComposition. */
+ createCandidateSession?: (serialized: string, live: Composition) => Promise<Composition>;
+}
+
+export interface CutoverOptions {
+ label?: string;
+ coalesceKey?: string;
+ /** Coalesce window (ms); Infinity folds across a slow round-trip. */
+ coalesceMs?: number;
+ skipRefresh?: boolean;
+}
+
+interface CandidateEdit {
+ live: Composition;
+ candidate: Composition;
+ serializedBefore: string;
+ after: string;
+}
+
+export function declinedCutover(reason: string): CutoverResult {
+ return { status: "declined", reason };
+}
+
+export function asCutoverError(error: unknown): Error {
+ return error instanceof Error ? error : new Error(String(error));
+}
+
+/** Only an explicit decline may enter the legacy mutation backend. */
+export function cutoverCommittedOrThrow(result: CutoverResult): boolean {
+ if (result.status === "failed") throw result.error;
+ return result.status === "committed";
+}
+
+/** A supplied authoritative reader fails closed; only its absence uses the snapshot fallback. */
+async function captureOnDiskBefore(
+ deps: CutoverDeps,
+ targetPath: string,
+ serializedFallback: string,
+): Promise<string> {
+ if (!deps.readProjectFile) return serializedFallback;
+ return deps.readProjectFile(targetPath);
+}
+
+function disposeCandidate(candidate: Composition | undefined, live: Composition): void {
+ if (candidate && candidate !== live) candidate.dispose();
+}
+
+function createCandidateSession(
+ serializedBefore: string,
+ live: Composition,
+ deps: CutoverDeps,
+): Promise<Composition> {
+ return deps.createCandidateSession
+ ? deps.createCandidateSession(serializedBefore, live)
+ : openComposition(serializedBefore, { history: false });
+}
+
+function candidatePublisherAvailable(
+ candidate: Composition,
+ live: Composition,
+ deps: CutoverDeps,
+): boolean {
+ return candidate === live || deps.publishSession !== undefined;
+}
+
+async function buildCandidateEdit(
+ live: Composition,
+ deps: CutoverDeps,
+ mutate: (candidate: Composition) => void,
+ sourceSnapshot?: string,
+): Promise<CandidateEdit | CutoverResult> {
+ let candidate: Composition | undefined;
+ try {
+ const serializedBefore = sourceSnapshot ?? live.serialize();
+ candidate = await createCandidateSession(serializedBefore, live, deps);
+ candidate.batch(() => mutate(candidate!));
+ const after = candidate.serialize();
+ if (after === serializedBefore) {
+ disposeCandidate(candidate, live);
+ return declinedCutover("no_change");
+ }
+ if (!candidatePublisherAvailable(candidate, live, deps)) {
+ disposeCandidate(candidate, live);
+ return { status: "failed", error: new Error("SDK candidate publisher is unavailable") };
+ }
+ return { live, candidate, serializedBefore, after };
+ } catch (error) {
+ disposeCandidate(candidate, live);
+ return { status: "failed", error: asCutoverError(error) };
+ }
+}
+
+function isCutoverResult(value: CandidateEdit | CutoverResult): value is CutoverResult {
+ return "status" in value;
+}
+
+async function rollbackWrite(
+ targetPath: string,
+ originalContent: string,
+ deps: CutoverDeps,
+ cause: Error,
+): Promise<Error> {
+ try {
+ deps.domEditSaveTimestampRef.current = Date.now();
+ markSelfWrite(targetPath, originalContent);
+ await deps.writeProjectFile(targetPath, originalContent);
+ return cause;
+ } catch (rollbackError) {
+ return new AggregateError(
+ [cause, asCutoverError(rollbackError)],
+ `SDK edit failed and rollback could not restore ${targetPath}`,
+ );
+ }
+}
+
+async function writeAndRecord(
+ after: string,
+ targetPath: string,
+ originalContent: string,
+ deps: CutoverDeps,
+ options?: CutoverOptions,
+): Promise<Error | null> {
+ deps.domEditSaveTimestampRef.current = Date.now();
+ markSelfWrite(targetPath, after);
+ try {
+ await deps.writeProjectFile(targetPath, after);
+ } catch (error) {
+ return asCutoverError(error);
+ }
+ try {
+ await deps.editHistory.recordEdit({
+ label: options?.label ?? "Edit layer",
+ kind: "manual",
+ ...(options?.coalesceKey ? { coalesceKey: options.coalesceKey } : {}),
+ ...(options?.coalesceMs != null ? { coalesceMs: options.coalesceMs } : {}),
+ files: { [targetPath]: { before: originalContent, after } },
+ });
+ return null;
+ } catch (error) {
+ return rollbackWrite(targetPath, originalContent, deps, asCutoverError(error));
+ }
+}
+
+function refreshCommittedEdit(after: string, deps: CutoverDeps, options?: CutoverOptions): void {
+ try {
+ if (deps.refresh) deps.refresh(after);
+ else if (!options?.skipRefresh) deps.reloadPreview();
+ } catch (error) {
+ trackStudioEvent("sdk_cutover_refresh_failed", { error: asCutoverError(error).message });
+ }
+}
+
+async function commitCandidateEdit(
+ edit: CandidateEdit,
+ targetPath: string,
+ originalContent: string,
+ deps: CutoverDeps,
+ options?: CutoverOptions,
+): Promise<CutoverResult> {
+ const writeError = await writeAndRecord(edit.after, targetPath, originalContent, deps, options);
+ if (writeError) {
+ if (edit.candidate !== edit.live) edit.candidate.dispose();
+ return { status: "failed", error: writeError };
+ }
+ let refreshTarget = true;
+ try {
+ if (edit.candidate !== edit.live) {
+ const publication = deps.publishSession!({
+ candidate: edit.candidate,
+ expectedSession: edit.live,
+ targetPath,
+ });
+ if (publication !== "published") edit.candidate.dispose();
+ if (publication === "rejected-inactive-target") refreshTarget = false;
+ }
+ } catch (error) {
+ // Persistence and history are already committed. A publisher can throw
+ // after installing the candidate, so rolling back disk or disposing the
+ // candidate here can make all three authorities disagree (or dispose the
+ // now-live session). Production publishers are non-throwing; keep the
+ // durable commit authoritative and surface this post-commit fault.
+ trackStudioEvent("sdk_cutover_publish_failed", {
+ path: targetPath,
+ error: asCutoverError(error).message,
+ });
+ }
+ if (refreshTarget) refreshCommittedEdit(edit.after, deps, options);
+ return { status: "committed", version: hashContent(edit.after) };
+}
+
+export async function persistSdkCandidateMutation(
+ live: Composition,
+ targetPath: string,
+ originalContent: string,
+ deps: CutoverDeps,
+ mutate: (candidate: Composition) => void,
+ options?: CutoverOptions,
+ sourceSnapshot?: string,
+): Promise<CutoverResult> {
+ return serializeStudioFileMutation(
+ deps.writeProjectFile,
+ targetPath,
+ async (): Promise<CutoverResult> => {
+ // Re-read only after acquiring the path queue. This makes each candidate
+ // clone the latest committed bytes, even when React has not yet re-rendered
+ // and the caller still holds the preceding live-session object.
+ const serializedFallback = sourceSnapshot ?? originalContent;
+ let onDiskBefore: string;
+ try {
+ onDiskBefore = await captureOnDiskBefore(deps, targetPath, serializedFallback);
+ } catch (error) {
+ return { status: "failed", error: asCutoverError(error) };
+ }
+ // Preserve the live-session path for adapters without a reader (notably
+ // isolated consumers/tests). Production Studio supplies a reader so
+ // queued edits always clone the latest durable source.
+ const candidateSource = deps.readProjectFile ? onDiskBefore : sourceSnapshot;
+ const candidate = await buildCandidateEdit(live, deps, mutate, candidateSource);
+ if (isCutoverResult(candidate)) return candidate;
+ return commitCandidateEdit(candidate, targetPath, onDiskBefore, deps, options);
+ },
+ );
+}
+
+/** Transactional writer for non-SDK islands and throwaway composition sessions. */
+export async function persistSdkSerialize(
+ buildAfter: (onDiskBefore: string) => string | Promise<string>,
+ targetPath: string,
+ originalContent: string,
+ deps: CutoverDeps,
+ options?: CutoverOptions,
+): Promise<void> {
+ await serializeStudioFileMutation(deps.writeProjectFile, targetPath, async () => {
+ const onDiskBefore = await captureOnDiskBefore(deps, targetPath, originalContent);
+ const after = await buildAfter(onDiskBefore);
+ if (after === onDiskBefore) return;
+ const error = await writeAndRecord(after, targetPath, onDiskBefore, deps, options);
+ if (error) throw error;
+ refreshCommittedEdit(after, deps, options);
+ });
+}
diff --git a/packages/studio/src/utils/setSlideshowManifest.test.ts b/packages/studio/src/utils/setSlideshowManifest.test.ts
index a8cbe39981..4cf6dd3498 100644
--- a/packages/studio/src/utils/setSlideshowManifest.test.ts
+++ b/packages/studio/src/utils/setSlideshowManifest.test.ts
@@ -74,11 +74,8 @@ describe("persistSlideshowManifest — op construction", () => {
const deps = makeDeps(writeProjectFile);
const recordEdit = deps.editHistory.recordEdit as ReturnType<typeof vi.fn>;
- const mockSession = { serialize: vi.fn().mockReturnValue(originalHtml) };
-
await persistSlideshowManifest({
manifest: { slides: [{ sceneId: "scene-2" }] },
- sdkSession: mockSession as never,
originalContent: originalHtml,
targetPath: "/proj/comp.html",
deps,
@@ -96,11 +93,8 @@ describe("persistSlideshowManifest — op construction", () => {
const baseHtml = "<html><head></head><body></body></html>";
const writeProjectFile = vi.fn().mockResolvedValue(undefined);
const deps = makeDeps(writeProjectFile);
- const mockSession = { serialize: vi.fn().mockReturnValue(baseHtml) };
-
await persistSlideshowManifest({
manifest: { slides: [{ sceneId: "new-scene" }] },
- sdkSession: mockSession as never,
originalContent: baseHtml,
targetPath: "/proj/comp.html",
deps,
@@ -122,11 +116,8 @@ describe("persistSlideshowManifest — op construction", () => {
const writeProjectFile = vi.fn().mockResolvedValue(undefined);
const deps = makeDeps(writeProjectFile);
- const mockSession = { serialize: vi.fn().mockReturnValue(twoIslandHtml) };
-
await persistSlideshowManifest({
manifest: { slides: [{ sceneId: "fresh" }] },
- sdkSession: mockSession as never,
originalContent: twoIslandHtml,
targetPath: "/proj/comp.html",
deps,
diff --git a/packages/studio/src/utils/setSlideshowManifest.ts b/packages/studio/src/utils/setSlideshowManifest.ts
index 7a00593411..508c6beec3 100644
--- a/packages/studio/src/utils/setSlideshowManifest.ts
+++ b/packages/studio/src/utils/setSlideshowManifest.ts
@@ -5,7 +5,7 @@
* embedded in the composition HTML. Because <script> nodes are not tracked by
* the SDK element tree (they have no hf-id), we cannot use a `setText` dispatch
* op. Instead we:
- * 1. Call `sdkSession.serialize()` to get the current HTML.
+ * 1. Acquire the per-file transaction and read the current on-disk HTML.
* 2. Replace or insert the island with the new manifest JSON.
* 3. Write via `persistSdkSerialize` — the same low-level writer used by the
* other SDK-cutover paths (sdkDeletePersist, sdkTimingPersist, etc.).
@@ -23,7 +23,6 @@ import {
parseSlideshowManifest,
slideshowIslandRegex,
} from "@hyperframes/core/slideshow";
-import type { Composition } from "@hyperframes/sdk";
import type { CutoverDeps } from "./sdkCutover";
import { persistSdkSerialize } from "./sdkCutover";
@@ -46,8 +45,6 @@ export function buildSlideshowIslandHtml(manifest: SlideshowManifest): string {
export interface PersistSlideshowArgs {
manifest: SlideshowManifest;
- /** Live SDK Composition session — used only to read the current serialized HTML. */
- sdkSession: Pick<Composition, "serialize">;
/** Exact on-disk bytes for the undo-history `before` baseline. */
originalContent: string;
targetPath: string;
@@ -62,7 +59,7 @@ export interface PersistSlideshowArgs {
}
export async function persistSlideshowManifest(args: PersistSlideshowArgs): Promise<void> {
- const { manifest, sdkSession, originalContent, targetPath, deps, label, coalesceKey } = args;
+ const { manifest, originalContent, targetPath, deps, label, coalesceKey } = args;
const islandHtml = buildSlideshowIslandHtml(manifest);
@@ -77,26 +74,22 @@ export async function persistSlideshowManifest(args: PersistSlideshowArgs): Prom
throw new Error(`refusing to persist invalid slideshow manifest: ${(err as Error).message}`);
}
- const current = sdkSession.serialize();
-
- // Strip ALL existing islands (handles the case where two stale islands
- // accumulated) then insert exactly one fresh island.
- const stripped = current.replace(ISLAND_RE, "");
-
- let after: string;
- const bodyClose = stripped.lastIndexOf("</body>");
- if (bodyClose !== -1) {
- after = stripped.slice(0, bodyClose) + islandHtml + "\n" + stripped.slice(bodyClose);
- } else {
- after = stripped + "\n" + islandHtml;
- }
-
- // No-op gate: if the rewritten HTML is byte-identical to the current serialized
- // HTML, skip the write — avoids a spurious disk write and a no-op undo entry.
- if (after === current) return;
-
- await persistSdkSerialize(after, targetPath, originalContent, deps, {
- label: label ?? "Edit slideshow",
- ...(coalesceKey ? { coalesceKey } : {}),
- });
+ await persistSdkSerialize(
+ (current) => {
+ // Strip ALL existing islands (handles the case where two stale islands
+ // accumulated) then insert exactly one fresh island.
+ const stripped = current.replace(ISLAND_RE, "");
+ const bodyClose = stripped.lastIndexOf("</body>");
+ return bodyClose !== -1
+ ? stripped.slice(0, bodyClose) + islandHtml + "\n" + stripped.slice(bodyClose)
+ : stripped + "\n" + islandHtml;
+ },
+ targetPath,
+ originalContent,
+ deps,
+ {
+ label: label ?? "Edit slideshow",
+ ...(coalesceKey ? { coalesceKey } : {}),
+ },
+ );
}
diff --git a/packages/studio/src/utils/studioFileHistory.test.ts b/packages/studio/src/utils/studioFileHistory.test.ts
index 375843e800..f909bd3db4 100644
--- a/packages/studio/src/utils/studioFileHistory.test.ts
+++ b/packages/studio/src/utils/studioFileHistory.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { saveProjectFilesWithHistory } from "./studioFileHistory";
+import { serializeStudioFileMutation } from "./studioFileMutationCoordinator";
describe("saveProjectFilesWithHistory", () => {
it("reads before content, writes after content, and records a history entry", async () => {
@@ -153,4 +154,44 @@ describe("saveProjectFilesWithHistory", () => {
["index.html", "index-before"],
]);
});
+
+ it("reads and writes after an earlier same-file mutation completes", async () => {
+ let disk = "before";
+ let release!: () => void;
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const writeFile = vi.fn(async (_path: string, content: string) => {
+ disk = content;
+ });
+ const priorMutation = serializeStudioFileMutation(writeFile, "index.html", async () => {
+ await blocked;
+ disk = "sdk-after";
+ });
+ const readFile = vi.fn(async () => disk);
+ const recordEdit = vi.fn();
+
+ const save = saveProjectFilesWithHistory({
+ projectId: "project-1",
+ label: "Edit source",
+ kind: "source",
+ files: { "index.html": "editor-after" },
+ readFile,
+ writeFile,
+ recordEdit,
+ });
+
+ await Promise.resolve();
+ expect(readFile).not.toHaveBeenCalled();
+ release();
+ await priorMutation;
+ await save;
+
+ expect(disk).toBe("editor-after");
+ expect(recordEdit).toHaveBeenCalledWith(
+ expect.objectContaining({
+ files: { "index.html": { before: "sdk-after", after: "editor-after" } },
+ }),
+ );
+ });
});
diff --git a/packages/studio/src/utils/studioFileHistory.ts b/packages/studio/src/utils/studioFileHistory.ts
index de65254b56..951f5f3c5f 100644
--- a/packages/studio/src/utils/studioFileHistory.ts
+++ b/packages/studio/src/utils/studioFileHistory.ts
@@ -1,5 +1,6 @@
import type { MutableRefObject } from "react";
import type { EditHistoryKind } from "./editHistory";
+import { serializeStudioFileMutations } from "./studioFileMutationCoordinator";
import { createStudioSaveHttpError } from "./studioSaveDiagnostics";
export interface RecordEditInput {
@@ -55,37 +56,39 @@ export async function saveProjectFilesWithHistory({
writeFile,
recordEdit,
}: SaveProjectFilesWithHistoryInput): Promise<string[]> {
- const snapshots: Record<string, { before: string; after: string }> = {};
- for (const [path, after] of Object.entries(files)) {
- const before = await readFile(path);
- if (before !== after) {
- snapshots[path] = { before, after };
+ return serializeStudioFileMutations(writeFile, Object.keys(files), async () => {
+ const snapshots: Record<string, { before: string; after: string }> = {};
+ for (const [path, after] of Object.entries(files)) {
+ const before = await readFile(path);
+ if (before !== after) {
+ snapshots[path] = { before, after };
+ }
}
- }
- const changedPaths = Object.keys(snapshots);
- if (changedPaths.length === 0) return [];
-
- const writtenPaths: string[] = [];
- try {
- for (const path of changedPaths) {
- await writeFile(path, snapshots[path].after);
- writtenPaths.push(path);
- }
+ const changedPaths = Object.keys(snapshots);
+ if (changedPaths.length === 0) return [];
- await recordEdit({ label, kind, coalesceKey, coalesceMs, files: snapshots });
- } catch (error) {
+ const writtenPaths: string[] = [];
try {
- for (const path of writtenPaths.reverse()) {
- await writeFile(path, snapshots[path].before);
+ for (const path of changedPaths) {
+ await writeFile(path, snapshots[path].after);
+ writtenPaths.push(path);
}
- } catch (rollbackError) {
- throw new AggregateError(
- [error, rollbackError],
- "Failed to save project files and rollback did not complete",
- );
+
+ await recordEdit({ label, kind, coalesceKey, coalesceMs, files: snapshots });
+ } catch (error) {
+ try {
+ for (const path of writtenPaths.reverse()) {
+ await writeFile(path, snapshots[path].before);
+ }
+ } catch (rollbackError) {
+ throw new AggregateError(
+ [error, rollbackError],
+ "Failed to save project files and rollback did not complete",
+ );
+ }
+ throw error;
}
- throw error;
- }
- return changedPaths;
+ return changedPaths;
+ });
}
diff --git a/packages/studio/src/utils/studioFileMutationCoordinator.ts b/packages/studio/src/utils/studioFileMutationCoordinator.ts
new file mode 100644
index 0000000000..3f98f33a06
--- /dev/null
+++ b/packages/studio/src/utils/studioFileMutationCoordinator.ts
@@ -0,0 +1,45 @@
+export type StudioProjectFileWriter = (path: string, content: string) => Promise<void>;
+
+// A writer is bound to one project (see useFileManager), so writer identity plus
+// path is the complete durable-file identity. Sharing this queue across SDK and
+// legacy mutation paths prevents independent read-modify-write transactions from
+// cloning the same stale bytes and overwriting one another.
+const mutationQueues = new WeakMap<StudioProjectFileWriter, Map<string, Promise<unknown>>>();
+
+export function serializeStudioFileMutation<T>(
+ writer: StudioProjectFileWriter,
+ targetPath: string,
+ task: () => Promise<T>,
+): Promise<T> {
+ let queues = mutationQueues.get(writer);
+ if (!queues) {
+ queues = new Map();
+ mutationQueues.set(writer, queues);
+ }
+ const prior = queues.get(targetPath) ?? Promise.resolve();
+ const next = prior.then(task, task);
+ queues.set(targetPath, next);
+ void next.then(
+ () => {
+ if (queues?.get(targetPath) === next) queues.delete(targetPath);
+ },
+ () => {
+ if (queues?.get(targetPath) === next) queues.delete(targetPath);
+ },
+ );
+ return next;
+}
+
+export function serializeStudioFileMutations<T>(
+ writer: StudioProjectFileWriter,
+ targetPaths: readonly string[],
+ task: () => Promise<T>,
+): Promise<T> {
+ const paths = [...new Set(targetPaths)].sort();
+ const acquire = (index: number): Promise<T> => {
+ const path = paths[index];
+ if (path === undefined) return task();
+ return serializeStudioFileMutation(writer, path, () => acquire(index + 1));
+ };
+ return acquire(0);
+}
diff --git a/packages/studio/src/utils/studioSaveDiagnostics.ts b/packages/studio/src/utils/studioSaveDiagnostics.ts
index 9424aba81e..17bc274736 100644
--- a/packages/studio/src/utils/studioSaveDiagnostics.ts
+++ b/packages/studio/src/utils/studioSaveDiagnostics.ts
@@ -71,6 +71,23 @@ export function getStudioSaveErrorMessage(error: unknown): string {
return "Unknown save failure";
}
+export function markStudioSaveErrorAlreadyToasted<T>(error: T): T {
+ if (!error || typeof error !== "object") return error;
+ try {
+ Object.defineProperty(error, "alreadyToasted", { value: true, configurable: true });
+ } catch {
+ // Best effort: failure reporting must not replace the original save error.
+ }
+ return error;
+}
+
+export function isStudioSaveErrorAlreadyToasted(error: unknown): boolean {
+ if (!error || typeof error !== "object") return false;
+ if ((error as { alreadyToasted?: unknown }).alreadyToasted === true) return true;
+ const cause = (error as { cause?: unknown }).cause;
+ return cause !== error && isStudioSaveErrorAlreadyToasted(cause);
+}
+
export function getStudioSaveStatusCode(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const direct =