Skip to content

The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.

fix(studio): keep catalog drop placeholders until clips are ready

罗高04929978a387
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index 277d7cfe..eef67348 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -22,7 +22,7 @@ Model Gateway remains a shared media-generation backend for MCP, using local Cod
- The composition list places the full video first, preserves the remaining clip order, and marks the live preview target. Queued, loading, missing and failed covers share a muted gray OD placeholder without failure text; decoded covers replace it automatically. A confirmed empty root is omitted from this list using the same loaded-preview content check; when no clips remain, the panel shows a brief empty state. The MVP omits the duplicate preview breadcrumb; composition switching and existing return shortcuts remain available.
- The editor header keeps the OpenDesign logo, drawer toggle and template library on the left (the English entry is Template; Chinese remains 模板库), centers the editable project name, and places undo/redo and export on the right. Clearing the title and committing with blur or Enter saves the localized Untitled default; Escape cancels. A logo-only community link sits immediately before Export and opens the public Discord community in every interface language, with a localized accessible tooltip; external links open separately from the editor. Undo, redo and version history form one visual group with 4px internal gaps; the history group and community retain a 16px button gap. The community-to-Export button gap is 12px (18px from the 16px community icon to the Export edge), shifting only community and the three history icons right by 4px while Export and the other header content stay fixed. A decorative 1px by 16px divider in the shared border color sits between history and community without moving the buttons; it hides with the history group on narrow screens. Transient save/error status remains available. Workspace and export failures show concise causes and available next steps, with raw diagnostics behind expandable, copyable details. Workspace connection failures use a persistent single-line feedback toast at the top center with a Reconnecting status and no buttons or diagnostic details. The Reconnecting ellipsis animates without changing the toast width; reduced-motion preferences keep it static. Automatic polling waits 1.8 seconds after each completed attempt and removes the toast on recovery; it has no overall retry limit or explicit per-request timeout and does not start a stopped service. Other notice dismissal does not bypass write guards. Editor toasts stack at the top center; editor, connection and template-copy feedback share a top-layer host above native dialogs and ordinary overlays, without taking focus. Template-copy feedback retains its existing placement and three-second lifetime; identical notices replace their previous instance. Error toasts use the compact neutral feedback surface and concise recognized causes, with a dismiss button and no details icon or expandable diagnostics. Detailed error panels retain their diagnostic controls. Informational toasts disappear after three seconds without a close control; actionable error notices remain dismissible and do not auto-expire. Save-queue pauses use a brief, localized feedback toast without paths, diagnostics or a retry action; it expires after three seconds without clearing the write guard or claiming that failed edits were saved. The template library reuses the website catalog layout: brand/use-case/video-type facets, configured featured templates, search and sorting, without site navigation, promotional hero or footer. Prism metadata and local cache updates drive the list. The catalog selects the editor locale from a shared multilingual publication, falling back to English and then the Resource default; template-copy prompts support the same eleven UI languages. Previews, author/source links and editable-project opening remain available. The detail view keeps the motion.md download action (`motionDocumentUrl`) above its guide content (`styleDescription`, `reviewFocus`, `motionGuideUrl`). Recreate opens a separate prompt dialog; copied instructions never occupy the guide area.
- The asset panel shows only the current project, with compact search/import controls, type filters, and a dedicated scrollable list. User-uploaded audio rows in My assets show full filenames with their original extensions and wrap long names within the panel; the generic Audio label is omitted, while duration and specific BGM/SFX/Voice labels remain when available. Official library sources and presentation are unchanged. Assets referenced by the current composition carry an In use badge (已使用 in Chinese); unused assets have no badge. MVP My assets deletion invokes the existing file-deletion handler directly from the menu, without a second confirmation; the full editor retains its confirmation. This does not introduce a new undo mechanism or alter official catalog assets. Usage filtering is omitted; used assets still sort first within each type. In both My assets and the official animation library, hover plays only the card thumbnail, while clicking opens a centered modal preview over a gray full-editor backdrop. The modal reuses Studio-styled playback, volume and speed controls; its play button stays centered, and speed/loop controls hide below 420px to avoid overlap. Volume and loop icons are 16px inside 28px buttons, and playback speed text is 12px; closing it restores access to the paused composition; previewing media does not add it to the project. The global cache view remains in source but has no editor entry in the MVP.
-- Each accepted project-asset drop immediately shows a transient loading clip at its timeline placement, including an empty timeline. It remains until the saved clip appears; failures remain at the placement with a dismiss action. Repeated drops create independent clips. Known drag metadata bypasses duration probing, and concurrent requests for the same project asset share one in-flight probe without coalescing insertions. Unreadable durations fail visibly instead of inserting a five-second clip. Placeholders never enter project source or undo history.
+- Each accepted project-asset or catalog-block drop immediately shows a transient loading clip at its timeline placement, including an empty timeline. It remains until the saved clip appears; failures remain at the placement with a dismiss action. Repeated drops create independent clips; catalog installs queue their writes while each accepted drop keeps its own visible placeholder instead of relying on a transient progress toast. Known drag metadata bypasses duration probing, and concurrent requests for the same project asset share one in-flight probe without coalescing insertions. Unreadable durations fail visibly instead of inserting a five-second clip. Placeholders never enter project source or undo history.
- Panel positions are fixed. Export settings and render history live in a compact popover below the header Export button, outside the right panel. Both side groups can temporarily collapse into 48px vertical icon rails, giving their width to preview; the rail toggle restores the previous width and tab, while a module icon opens that module. Collapse does not remove panels or remount the player. Opening the MVP starts both sides collapsed and the timeline at 30% of the available dock height (subject to minimum sizes); users can then drag the divider to enlarge or reduce it. The fixed layout reserves at least 360px for preview, 260px for each expanded side panel. Side availability retains the existing conservative breakpoints, independently of the resizable minimums: below 740px both side groups and rails hide; from 740px to 1011px only one side can expand; wider hosts allow both only when their requested widths leave the preview floor intact. Opening a side through a toggle, module shortcut or programmatic activation uses the same fit check and closes the opposite side when necessary. Shrinking the host collapses expanded sides when they no longer fit; widening restores collapsed rails without automatically reopening panels. At widths smaller than the preview floor, preview uses the available workspace. Remembered expanded side widths remain available when reopening a side. Divider hover and drag change only the thin line to green. Divider resizing and per-project expanded-size persistence remain; panel movement, closing and layout presets are absent. Preview alone can temporarily expand within the editor workspace, keeping the host chat visible and the player mounted. Its header button or Escape restores the previous layout and playback position; expansion is not persisted across reloads.
- MVP controls share a locally bundled Remix Icon 4.9.1 set with the reference design system. Menu selections consistently use check icons, and the language menu is 180px wide. Expanded side-panel tabs remain text-only; collapsed rails use the corresponding panel icons. Brand artwork and timeline geometry are separate from control icons.
- The editor startup shell and project/editor loading boundaries share a centered, theme-aware OD symbol without adding a minimum loading delay. Below 700px of workspace content width, the editor header stays on one row: undo/redo and version history hide, the template library becomes icon-only, the project title truncates, and Export stays at the right edge.
diff --git a/studio/src/hooks/useBlockHandlers.ts b/studio/src/hooks/useBlockHandlers.ts
index a1b991c9..86b7f551 100644
--- a/studio/src/hooks/useBlockHandlers.ts
+++ b/studio/src/hooks/useBlockHandlers.ts
@@ -2,7 +2,7 @@
* Block drop/add handlers for the Studio.
* Extracted from App.tsx to keep file sizes under the 600-line limit.
*/
-import { useCallback, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { TimelineElement } from "../player";
import { usePlayerStore } from "../player";
import { addBlockToProject } from "../utils/blockInstaller";
@@ -10,6 +10,7 @@ import { selectAndRevealTimelineElement } from "../player/components/timelineDro
import type { BlockParam } from "@hyperframes/core/registry";
import type { RightPanelTab } from "../utils/studioHelpers";
import type { MediaOverlayPlacement } from "../components/editor/propertyPanelTypes";
+import { beginPendingAssetDrop, updatePendingAssetDrop } from "../player/store/pendingAssetDrops";
interface BlockCtxDeps {
activeCompPath: string | null;
@@ -46,7 +47,7 @@ export interface UseBlockHandlersResult {
React.SetStateAction<UseBlockHandlersResult["activeBlockParams"]>
>;
handleAddBlock: (blockName: string) => void;
- handleTimelineBlockDrop: (blockName: string, placement: { start: number; track: number }) => void;
+ handleTimelineBlockDrop: (blockName: string, placement: { start: number; track: number }) => Promise<void>;
handleAddMediaOverlay: (blockName: string, placement: MediaOverlayPlacement) => Promise<void>;
handlePreviewBlockDrop: (blockName: string, position: { left: number; top: number }) => void;
}
@@ -85,26 +86,43 @@ export function useBlockHandlers({
],
);
- // Block installs hit the server and end in a full preview reload; without a
- // guard, repeat drops while one is in flight stack duplicate installs.
- const installingBlockRef = useRef(false);
+ // Serialize registry writes while keeping every accepted drop as its own operation.
+ const installQueueRef = useRef(Promise.resolve());
+ const scope = useMemo(() => ({}), [projectId, blockCtx.activeCompPath]);
+ const scopeRef = useRef<object | null>(scope);
+ scopeRef.current = scope;
+ useEffect(() => {
+ scopeRef.current = scope;
+ return () => { scopeRef.current = null; };
+ }, [scope]);
const { showToast, dismissToast } = blockCtxDeps;
const runBlockInstall = useCallback(
- async <T>(blockName: string, install: () => Promise<T>): Promise<T | null> => {
- if (installingBlockRef.current) {
- showToast("A block is already installing. One moment…", "info");
- return null;
- }
- installingBlockRef.current = true;
- const progress = showToast(`Adding ${blockName}…`, "info");
- try {
- return await install();
- } finally {
- installingBlockRef.current = false;
- dismissToast(progress);
- }
+ (blockName: string, install: () => ReturnType<typeof addBlockToProject>, pendingId?: string) => {
+ const work = installQueueRef.current.then(async () => {
+ if (scopeRef.current !== scope) return null;
+ const progress = pendingId ? null : showToast(`Adding ${blockName}…`, "info");
+ try {
+ const result = await install();
+ if (scopeRef.current !== scope) return null;
+ if (pendingId) updatePendingAssetDrop(pendingId, result
+ ? { element: result.element, duration: result.element.duration,
+ placement: { start: result.element.start, track: result.element.track } }
+ : { failed: "add" });
+ return result;
+ } catch (error) {
+ if (scopeRef.current === scope) {
+ if (pendingId) updatePendingAssetDrop(pendingId, { failed: "add" });
+ showToast(error instanceof Error ? error.message : "Failed to add block", "error");
+ }
+ return null;
+ } finally {
+ if (progress !== null) dismissToast(progress);
+ }
+ });
+ installQueueRef.current = work.then(() => undefined, () => undefined);
+ return work;
},
- [showToast, dismissToast],
+ [showToast, dismissToast, scope],
);
const handleAddBlock = useCallback(
@@ -139,9 +157,10 @@ export function useBlockHandlers({
);
const handleTimelineBlockDrop = useCallback(
- (blockName: string, placement: { start: number; track: number }) => {
+ async (blockName: string, placement: { start: number; track: number }) => {
if (!projectId) return;
- void runBlockInstall(blockName, () =>
+ const pendingId = beginPendingAssetDrop(blockName, placement);
+ const result = await runBlockInstall(blockName, () =>
addBlockToProject({
projectId,
blockName,
@@ -149,10 +168,9 @@ export function useBlockHandlers({
...blockCtx,
previewIframe: previewIframeRef.current,
currentTime: usePlayerStore.getState().currentTime,
- }),
- ).then((result) => {
- if (result) selectAndRevealTimelineElement(result.hostKey);
- });
+ }), pendingId,
+ );
+ if (result) selectAndRevealTimelineElement(result.hostKey);
},
[projectId, blockCtx, previewIframeRef, runBlockInstall],
);
diff --git a/studio/src/hooks/useTimelineAssetDropOps.ts b/studio/src/hooks/useTimelineAssetDropOps.ts
index 70263517..0dfbbcf5 100644
--- a/studio/src/hooks/useTimelineAssetDropOps.ts
+++ b/studio/src/hooks/useTimelineAssetDropOps.ts
@@ -93,6 +93,7 @@ export function useTimelineAssetDropOps({
}: UseTimelineAssetDropOpsOptions) {
const projectId = projectIdRef.current;
const timelineReady = usePlayerStore((state) => state.timelineReady);
+ const pendingDrops = usePlayerStore((state) => state.pendingAssetDrops);
const elementsRef = useRef(timelineElements);
const dropScopeRef = useRef(0);
elementsRef.current = timelineElements;
@@ -109,7 +110,7 @@ export function useTimelineAssetDropOps({
);
return pendingAssetDrops.length === state.pendingAssetDrops.length ? state : { pendingAssetDrops };
});
- }, [timelineElements, timelineReady]);
+ }, [timelineElements, timelineReady, pendingDrops]);
// fallow-ignore-next-line complexity
const dropAssetAt = useCallback(
// fallow-ignore-next-line complexity
diff --git a/studio/src/hooks/useTimelineBlockDropFeedback.test.tsx b/studio/src/hooks/useTimelineBlockDropFeedback.test.tsx
new file mode 100644
index 00000000..976bf576
--- /dev/null
+++ b/studio/src/hooks/useTimelineBlockDropFeedback.test.tsx
@@ -0,0 +1,153 @@
+// @vitest-environment happy-dom
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useBlockHandlers, type UseBlockHandlersResult } from "./useBlockHandlers";
+import { useTimelineAssetDropOps } from "./useTimelineAssetDropOps";
+import { Timeline } from "../player/components/Timeline";
+import { usePlayerStore } from "../player/store/playerStore";
+import { installTimelineMountEnv } from "../player/components/timelineMountTestEnv";
+import { getTimelineRowTop, TRACK_H } from "../player/components/timelineLayout";
+import { TIMELINE_BLOCK_MIME } from "../utils/timelineAssetDrop";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+installTimelineMountEnv();
+const roots: Root[] = [];
+afterEach(() => {
+ act(() => roots.splice(0).forEach((root) => root.unmount()));
+ usePlayerStore.getState().reset();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+function mountEditor() {
+ const source = '<main data-composition-id="main" data-duration="30"></main>';
+ const files = new Map([["index.html", source], ["other.html", source]]);
+ const installs: Array<ReturnType<typeof deferred<Response>>> = [];
+ const showToast = vi.fn(() => 1);
+ const reloadPreview = vi.fn();
+ const recordEdit = vi.fn(async () => {});
+ const projectIdRef = { current: "project" };
+ const block = { name: "sparkle", title: "Sparkle", type: "hyperframes:block", duration: 8, files: [] };
+ const installed = () => Response.json({ written: ["compositions/sparkle.html"], block });
+ vi.stubGlobal("fetch", vi.fn(async (url: string) => {
+ if (!url.endsWith("/registry/install")) throw new Error(`Unexpected request: ${url}`);
+ const request = deferred<Response>();
+ installs.push(request);
+ return request.promise;
+ }));
+ let handlers!: UseBlockHandlersResult;
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ roots.push(root);
+ usePlayerStore.setState({ timelineReady: true, duration: 30 });
+ function Editor({ path }: { path: string | null }) {
+ const timelineElements = usePlayerStore((state) => state.elements);
+ const ctx = {
+ activeCompPath: path, timelineElements, showToast, dismissToast: vi.fn(),
+ readProjectFile: async (path: string) => files.get(path) ?? "",
+ writeProjectFile: async (path: string, content: string) => { files.set(path, content); },
+ recordEdit, reloadPreview, refreshFileTree: async () => {},
+ };
+ useTimelineAssetDropOps({ ...ctx, projectIdRef, uploadProjectFiles: async () => [] });
+ handlers = useBlockHandlers({ projectId: "project", blockCtxDeps: ctx,
+ previewIframeRef: { current: null }, setRightCollapsed: vi.fn(), setRightPanelTab: vi.fn() });
+ return <Timeline onBlockDrop={handlers.handleTimelineBlockDrop} />;
+ }
+ act(() => root.render(<Editor path={null} />));
+ return {
+ host, files, installs, installed, showToast, reloadPreview, recordEdit,
+ drop: (start = 0) => handlers.handleTimelineBlockDrop("sparkle", { start, track: 0 }),
+ switchComposition: () => act(() => root.render(<Editor path="other.html" />)),
+ unmount: () => act(() => root.unmount()),
+ placeholders: () => host.querySelectorAll('[data-testid="timeline-pending-asset"]'),
+ };
+}
+
+describe("catalog block drop feedback", () => {
+ it("keeps the actual block drag's placeholder after mouse release until the inserted clip is usable", async () => {
+ const view = mountEditor();
+ const target = view.host.querySelector(".h-full.border-t")!;
+ const transfer = { types: [TIMELINE_BLOCK_MIME], files: [], getData: () => '{"name":"sparkle"}' };
+ for (const type of ["dragover", "drop", "dragend"]) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ Object.defineProperties(event, {
+ clientX: { value: 400 }, clientY: { value: getTimelineRowTop(0) + TRACK_H / 2 },
+ dataTransfer: { value: transfer },
+ });
+ act(() => target.dispatchEvent(event));
+ }
+ expect(view.placeholders()).toHaveLength(1);
+ await act(async () => {});
+ expect(view.installs).toHaveLength(1);
+ expect(view.showToast).not.toHaveBeenCalled();
+ await act(async () => { view.installs[0].resolve(view.installed()); });
+ expect(view.reloadPreview).toHaveBeenCalledOnce();
+ expect(view.placeholders()).toHaveLength(1);
+ const clip = usePlayerStore.getState().pendingAssetDrops[0].element!;
+ expect(clip.duration).toBe(8);
+ expect(view.files.get("index.html")).toContain('id="sparkle"');
+ act(() => usePlayerStore.setState({ elements: [clip], timelineReady: false }));
+ expect(view.placeholders()).toHaveLength(1);
+ act(() => usePlayerStore.getState().setTimelineReady(true));
+ expect(view.placeholders()).toHaveLength(0);
+ expect(usePlayerStore.getState().pendingAssetDrops).toEqual([]);
+ });
+
+ it("accepts repeated drops immediately and serializes their installs instead of rejecting them", async () => {
+ const view = mountEditor();
+ let first!: Promise<void>, second!: Promise<void>;
+ act(() => { first = view.drop(); second = view.drop(8); });
+ expect(view.placeholders()).toHaveLength(2);
+ await act(async () => {});
+ expect(view.installs).toHaveLength(1);
+ await act(async () => { view.installs[0].resolve(view.installed()); await first; });
+ expect(view.installs).toHaveLength(2);
+ expect(view.placeholders()).toHaveLength(2);
+ await act(async () => { view.installs[1].resolve(view.installed()); await second; });
+ expect(view.files.get("index.html")).toContain('id="sparkle_2"');
+ expect(view.recordEdit).toHaveBeenCalledTimes(2);
+ expect(view.showToast).not.toHaveBeenCalled();
+ });
+
+ it("ends loading at the drop placement when registry installation fails", async () => {
+ const view = mountEditor();
+ let task!: Promise<void>;
+ await act(async () => { task = view.drop(); });
+ await act(async () => { view.installs[0].resolve(Response.json({ error: "Catalog unavailable" }, { status: 503 })); await task; });
+ const failed = view.placeholders()[0];
+ expect(failed.getAttribute("role")).toBe("alert");
+ expect(failed.getAttribute("aria-busy")).toBe("false");
+ expect(view.files.get("index.html")).not.toContain("sparkle");
+ expect(view.reloadPreview).not.toHaveBeenCalled();
+ });
+
+ it("does not start an old queued install after the composition changes", async () => {
+ const view = mountEditor();
+ let first!: Promise<void>, second!: Promise<void>;
+ await act(async () => { first = view.drop(); second = view.drop(8); });
+ view.switchComposition();
+ await act(async () => { view.installs[0].resolve(view.installed()); await Promise.all([first, second]); });
+ expect(view.installs).toHaveLength(1);
+ expect(view.placeholders()).toHaveLength(0);
+ expect(view.files.get("other.html")).not.toContain("sparkle");
+ expect(usePlayerStore.getState().selectedElementId).toBeNull();
+ });
+
+ it("does not start queued installs or reveal an old selection after the editor unmounts", async () => {
+ const view = mountEditor();
+ let first!: Promise<void>, second!: Promise<void>;
+ await act(async () => { first = view.drop(); second = view.drop(8); });
+ view.unmount();
+ await act(async () => { view.installs[0].resolve(view.installed()); await Promise.all([first, second]); });
+ expect(view.installs).toHaveLength(1);
+ expect(usePlayerStore.getState().selectedElementId).toBeNull();
+ });
+});
diff --git a/studio/src/utils/blockInstaller.ts b/studio/src/utils/blockInstaller.ts
index 256a8c80..c0421ab0 100644
--- a/studio/src/utils/blockInstaller.ts
+++ b/studio/src/utils/blockInstaller.ts
@@ -177,7 +177,7 @@ function buildSubCompositionHtml({
export async function addBlockToProject(
opts: AddBlockOptions,
-): Promise<{ block: RegistryItem; compositionPath: string; hostKey: string } | null> {
+): Promise<{ block: RegistryItem; compositionPath: string; hostKey: string; element: TimelineElement } | null> {
const {
projectId,
blockName,
@@ -247,10 +247,13 @@ export async function addBlockToProject(
await refreshFileTree();
reloadPreview();
+ const hostKey = deriveTimelineStoreKeyForDomId(hostId, targetPath);
return {
block,
compositionPath: compositionFile,
- hostKey: deriveTimelineStoreKeyForDomId(hostId, targetPath),
+ hostKey,
+ element: { id: hostKey, key: hostKey, domId: hostId, sourceFile: targetPath,
+ tag: "div", start, duration, track, authoredTrack: track, compositionSrc: compositionFile },
};
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to add block";
diff --git a/studio/tests/e2e/catalog-drop-loading.mjs b/studio/tests/e2e/catalog-drop-loading.mjs
new file mode 100644
index 00000000..f2530c7a
--- /dev/null
+++ b/studio/tests/e2e/catalog-drop-loading.mjs
@@ -0,0 +1,123 @@
+// Run with browser-lock.sh. Only catalog download is controlled; editor, saves,
+// native history and preview reload use an isolated real workspace backend.
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { tmpdir } from 'node:os';
+import { fileURLToPath } from 'node:url';
+import puppeteer from 'puppeteer-core';
+import { WorkspaceStore } from '../../../workspace.ts';
+import { handler } from '../../../server.ts';
+import { startWorkspaceStudio } from '../../../shared/workspace-studio.ts';
+import { resolveChromeExecutable } from './chrome-executable.mjs';
+
+assert.ok(process.env.D4_LANE, 'Acquire a shared browser lane first');
+const root = fileURLToPath(new URL('../../../', import.meta.url));
+const output = process.env.EVIDENCE_DIR || await mkdtemp(path.join(tmpdir(), 'motion-catalog-drop-'));
+await mkdir(output, { recursive: true });
+process.env.HYPERFRAMES_HISTORY_ROOT = path.join(output, 'history');
+const store = new WorkspaceStore(await mkdtemp(path.join(output, 'workspace-')));
+await store.initialize(root);
+await mkdir(path.join(store.projectDirectory, 'assets'), { recursive: true });
+await writeFile(path.join(store.projectDirectory, 'assets/gsap.min.js'), await readFile(path.join(root, 'node_modules/gsap/dist/gsap.min.js')));
+const entry = path.join(store.projectDirectory, 'index.html');
+await writeFile(entry, `<!doctype html><html><head><script src="assets/gsap.min.js"></script></head><body style="margin:0"><div id="main" data-composition-id="main" data-start="0" data-duration="20" data-width="640" data-height="360" style="position:relative;width:640px;height:360px;background:#eee"></div><script>window.__timelines={main:gsap.timeline({paused:true})};</script></body></html>`);
+const native = await startWorkspaceStudio(root, store.directory, store.projectDirectory, Number(process.env.D4_LANE_API_PORT));
+const studio = { url: native.origin, alive: () => true, projectDirectory: store.projectDirectory };
+const server = createServer((req, res) => void handler(req, res, store, { studio, runtimeRoot: root, nativeRoot: root, ffmpeg: true, ensureStudio: async () => studio }));
+await new Promise(resolve => server.listen(Number(process.env.PLAYWRIGHT_WEB_PORT), '127.0.0.1', resolve));
+const origin = `http://127.0.0.1:${server.address().port}`;
+const block = { name: 'loading-test', title: 'Loading Test', type: 'hyperframes:block', duration: 8,
+ description: 'Catalog loading regression', tags: ['social'], files: [], dimensions: { width: 640, height: 360 } };
+const requests = [];
+let browser;
+try {
+ browser = await puppeteer.launch({ executablePath: resolveChromeExecutable(), headless: true });
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1440, height: 1000 });
+ await page.evaluateOnNewDocument(() => localStorage.setItem('motion.studio.locale', 'en'));
+ await page.setRequestInterception(true);
+ page.on('request', request => {
+ const url = request.url();
+ if (url.includes('/api/registry/blocks')) return void request.respond({ status: 200, contentType: 'application/json', body: JSON.stringify([block]) });
+ if (url.endsWith('/registry/install')) { requests.push(request); return; }
+ void request.continue();
+ });
+ page.on('pageerror', error => console.log('Page error:', error.message));
+ await page.goto(`${origin}/?project=${store.projectId}#project/${store.projectId}`);
+ await page.waitForSelector('[data-studio-timeline]', { timeout: 60000 });
+ await page.waitForFunction(() => !document.querySelector('[data-testid="timeline-loading-disabled-overlay"]'));
+ const openCatalog = await page.evaluate(() => {
+ const button = Array.from(document.querySelectorAll('.hf-dock-side-rail button')).find(button => /catalog/i.test(`${button.getAttribute('title')} ${button.getAttribute('aria-label')} ${button.textContent}`));
+ if (!button) return Array.from(document.querySelectorAll('.hf-dock-side-rail button')).map(button => ({ title: button.title, label: button.getAttribute('aria-label') }));
+ button.click(); return true;
+ });
+ assert.equal(openCatalog, true, JSON.stringify(openCatalog));
+ await page.waitForSelector('[data-motion-catalog] [draggable]');
+ const drag = () => page.evaluate(() => {
+ const card = document.querySelector('[data-motion-catalog] [draggable]');
+ const target = document.querySelector('[data-timeline-scroll-viewport]') || document.querySelector('[data-studio-timeline] .h-full.border-t');
+ if (!target) throw new Error('No visible timeline drop target');
+ const transfer = new DataTransfer();
+ card.dispatchEvent(new DragEvent('dragstart', { bubbles: true, dataTransfer: transfer }));
+ const rect = target.getBoundingClientRect();
+ const options = { bubbles: true, cancelable: true, dataTransfer: transfer, clientX: rect.left + 300, clientY: rect.top + 64 };
+ target.dispatchEvent(new DragEvent('dragover', options));
+ target.dispatchEvent(new DragEvent('drop', options));
+ card.dispatchEvent(new DragEvent('dragend', options));
+ });
+ await page.evaluate(() => {
+ window.__dropSamples = [];
+ const sample = () => {
+ window.__dropSamples.push({ at: performance.now(), pending: document.querySelectorAll('[data-testid="timeline-pending-asset"]').length, clips: document.querySelectorAll('[data-clip="true"]').length });
+ window.__dropSampleFrame = requestAnimationFrame(sample);
+ };
+ window.__dropSampleFrame = requestAnimationFrame(sample);
+ });
+ await drag();
+ await page.waitForSelector('[data-testid="timeline-pending-asset"][aria-busy="true"]');
+ await page.waitForFunction(() => !Array.from(document.querySelectorAll('[role="status"]')).some(node => node.textContent.includes('Adding loading-test')));
+ await page.screenshot({ path: path.join(output, 'after-release.png') });
+ await new Promise(resolve => setTimeout(resolve, 1200));
+ assert.equal(requests.length, 1);
+ assert.equal(await page.$$eval('[data-testid="timeline-pending-asset"]', nodes => nodes.length), 1);
+ await drag();
+ await page.waitForFunction(() => document.querySelectorAll('[data-testid="timeline-pending-asset"]').length === 2);
+ assert.equal(requests.length, 1, 'Second registry install waits in the queue');
+ const fulfill = async (request, index) => {
+ const file = `compositions/loading-test-${index}.html`;
+ await mkdir(path.join(store.projectDirectory, 'compositions'), { recursive: true });
+ await writeFile(path.join(store.projectDirectory, file), `<!doctype html><html><head><script src="../assets/gsap.min.js"></script></head><body style="margin:0"><div data-composition-id="loading-test" data-start="0" data-duration="8" data-width="640" data-height="360" style="width:640px;height:360px;background:#7c5ca5;color:white">Catalog test</div><script>window.__timelines={'loading-test':gsap.timeline({paused:true})};</script></body></html>`);
+ await request.respond({ status: 200, contentType: 'application/json', body: JSON.stringify({ written: [file], block }) });
+ };
+ await fulfill(requests[0], 1);
+ for (let attempt = 0; attempt < 100 && requests.length < 2; attempt++) await new Promise(resolve => setTimeout(resolve, 50));
+ assert.equal(requests.length, 2);
+ await fulfill(requests[1], 2);
+ await page.waitForFunction(() => document.querySelectorAll('[data-testid="timeline-pending-asset"]').length === 0 && document.querySelectorAll('[data-clip="true"]').length >= 2, { timeout: 30000 });
+ const samples = await page.evaluate(() => { cancelAnimationFrame(window.__dropSampleFrame); return window.__dropSamples; });
+ const firstAccepted = samples.findIndex(sample => sample.pending > 0);
+ assert.ok(firstAccepted >= 0);
+ assert.ok(samples.slice(firstAccepted).every(sample => sample.pending + sample.clips > 0), 'No frame may lose both the pending and committed clips');
+ const source = await readFile(entry, 'utf8');
+ assert.equal((source.match(/data-composition-src=/g) || []).length, 2);
+ assert.ok(source.includes('id="loading-test_2"'));
+ await page.screenshot({ path: path.join(output, 'ready.png') });
+ await drag();
+ await page.waitForSelector('[data-testid="timeline-pending-asset"][aria-busy="true"]');
+ for (let attempt = 0; attempt < 100 && requests.length < 3; attempt++) await new Promise(resolve => setTimeout(resolve, 50));
+ await requests[2].respond({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'Catalog temporarily unavailable' }) });
+ await page.waitForSelector('[data-testid="timeline-pending-asset"][role="alert"][aria-busy="false"]');
+ await page.screenshot({ path: path.join(output, 'failed.png') });
+ assert.equal((await readFile(entry, 'utf8')).match(/data-composition-src=/g).length, 2);
+ const result = { status: 'PASS', scope: 'Production editor, native saves/history and preview; controlled catalog list and download response only', sampledFrames: samples.length, noEmptyFrames: true, repeatedClips: 2, failureVisible: true };
+ await writeFile(path.join(output, 'browser-result.json'), JSON.stringify(result, null, 2));
+ console.log(JSON.stringify(result));
+} catch (error) {
+ const page = (await browser?.pages())?.at(-1);
+ if (page) { await page.screenshot({ path: path.join(output, 'failure.png') }); await writeFile(path.join(output, 'failure-text.txt'), await page.evaluate(() => document.body.innerText)); }
+ throw error;
+} finally {
+ await browser?.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await native.close();
+}