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 composition drop placeholders visible

罗高434dffb0ed98
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index eef67348..53ef4c00 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 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.
+- Each accepted project-asset, composition-list 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; composition insertions and catalog installs queue their writes while each accepted drop keeps its own visible placeholder instead of relying on a transient progress toast. Composition placeholders settle to the native insertion's actual track and duration; switching composition or project invalidates queued insertions and old selection changes. 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/useTimelineAssetDropOps.ts b/studio/src/hooks/useTimelineAssetDropOps.ts
index 0dfbbcf5..25ea54b7 100644
--- a/studio/src/hooks/useTimelineAssetDropOps.ts
+++ b/studio/src/hooks/useTimelineAssetDropOps.ts
@@ -319,8 +319,10 @@ export function useTimelineAssetDropOps({
}
const pid = projectIdRef.current;
if (!pid) throw new Error("No active project");
+ const pendingId = beginPendingAssetDrop(sourcePath, placement);
+ const isActive = () => usePlayerStore.getState().pendingAssetDrops.some((drop) => drop.id === pendingId);
try {
- await commitTimelineCompositionInsertion({
+ const element = await commitTimelineCompositionInsertion({
projectId: pid,
targetPath,
sourcePath,
@@ -332,9 +334,15 @@ export function useTimelineAssetDropOps({
selectHost: selectAndRevealTimelineElement,
resync: forceReloadSdkSession,
refresh: reloadPreview,
+ isActive,
+ });
+ if (element && isActive()) updatePendingAssetDrop(pendingId, {
+ element, duration: element.duration,
+ placement: { start: element.start, track: element.track },
});
- showToast("Composition added to the timeline.", "info");
} catch (error) {
+ if (!isActive()) return;
+ updatePendingAssetDrop(pendingId, { failed: "add" });
showToast(compositionInsertionFailureMessage(error), "error");
}
},
diff --git a/studio/src/hooks/useTimelineCompositionDropFeedback.test.tsx b/studio/src/hooks/useTimelineCompositionDropFeedback.test.tsx
new file mode 100644
index 00000000..21d2c1b6
--- /dev/null
+++ b/studio/src/hooks/useTimelineCompositionDropFeedback.test.tsx
@@ -0,0 +1,133 @@
+// @vitest-environment happy-dom
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, expect, it, vi } from "vitest";
+import { useTimelineAssetDropOps } from "./useTimelineAssetDropOps";
+import { usePlayerStore } from "../player/store/playerStore";
+import { Timeline } from "../player/components/Timeline";
+import { installTimelineMountEnv } from "../player/components/timelineMountTestEnv";
+import { TIMELINE_COMPOSITION_MIME } from "../utils/timelineCompositionDrop";
+import { getTimelineRowTop, TRACK_H } from "../player/components/timelineLayout";
+
+(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 mountEditor() {
+ const requests: Array<{ resolve: (response: Response) => void }> = [];
+ vi.stubGlobal("fetch", vi.fn(async (url: string) => {
+ if (url.includes("/file-mutations/insert-composition/")) {
+ return new Promise<Response>(resolve => requests.push({ resolve }));
+ }
+ return Response.json({ content: "before", version: "v1" });
+ }));
+ const showToast = vi.fn();
+ const reloadPreview = vi.fn();
+ const recordEdit = vi.fn(async () => {});
+ const writeProjectFile = vi.fn(async () => {});
+ const projectIdRef = { current: "project" };
+ let drop!: ReturnType<typeof useTimelineAssetDropOps>["handleTimelineCompositionDrop"];
+ 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 handlers = useTimelineAssetDropOps({
+ projectIdRef, activeCompPath: path, timelineElements,
+ writeProjectFile, recordEdit, reloadPreview, showToast,
+ uploadProjectFiles: async () => [],
+ });
+ drop = handlers.handleTimelineCompositionDrop;
+ return <Timeline onCompositionDrop={drop} />;
+ }
+ act(() => root.render(<Editor path={null} />));
+ const finish = (index: number, status = 200) => requests[index].resolve(Response.json(status === 200 ? {
+ path: "index.html", hostId: `first_${index + 2}`, track: index + 2, duration: 3,
+ before: "before", after: "after", version: `v${index + 2}`,
+ } : { error: "Cannot insert composition" }, { status }));
+ return {
+ host, requests, finish, showToast, reloadPreview, recordEdit,
+ drop: (start = 0) => drop("compositions/first.html", { start, track: 0 }),
+ switchComposition: () => act(() => root.render(<Editor path="other.html" />)),
+ placeholders: () => host.querySelectorAll('[data-testid="timeline-pending-asset"]'),
+ };
+}
+
+it("keeps a composition-list drop visible after dragend until its actual native clip is ready", async () => {
+ const view = mountEditor();
+ const target = view.host.querySelector(".h-full.border-t")!;
+ const transfer = { types: [TIMELINE_COMPOSITION_MIME], files: [], getData: () => '{"sourcePath":"compositions/first.html"}' };
+ 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.requests).toHaveLength(1);
+ expect(view.showToast).not.toHaveBeenCalled();
+ await act(async () => view.finish(0));
+ expect(view.placeholders()).toHaveLength(1);
+ const clip = usePlayerStore.getState().pendingAssetDrops[0].element!;
+ expect(clip).toMatchObject({ key: "index.html#first_2", duration: 3, track: 2 });
+ act(() => usePlayerStore.setState({ elements: [clip], timelineReady: false }));
+ expect(view.placeholders()).toHaveLength(1);
+ act(() => usePlayerStore.getState().setTimelineReady(true));
+ expect(view.placeholders()).toHaveLength(0);
+ expect(view.showToast).not.toHaveBeenCalled();
+});
+
+it("shows each repeated drop immediately while native writes queue independently", async () => {
+ const view = mountEditor();
+ act(() => usePlayerStore.setState({ elements: [
+ { id: "control", tag: "div", start: 0, duration: 30, track: 0 },
+ ] }));
+ let first!: Promise<void>, second!: Promise<void>;
+ await act(async () => { first = view.drop(); second = view.drop(8); });
+ expect(view.placeholders()).toHaveLength(2);
+ expect(usePlayerStore.getState().pendingAssetDrops.map(drop => drop.placement.start)).toEqual([0, 8]);
+ expect(view.requests).toHaveLength(1);
+ await act(async () => { view.finish(0); await first; });
+ expect(view.requests).toHaveLength(2);
+ expect(view.placeholders()).toHaveLength(2);
+ await act(async () => { view.finish(1); await second; });
+ expect(view.recordEdit).toHaveBeenCalledTimes(2);
+ expect(usePlayerStore.getState().pendingAssetDrops.map(drop => drop.element?.key))
+ .toEqual(["index.html#first_2", "index.html#first_3"]);
+});
+
+it("leaves a dismissible error at a failed composition's placement", async () => {
+ const view = mountEditor();
+ let task!: Promise<void>;
+ await act(async () => { task = view.drop(); });
+ await act(async () => { view.finish(0, 400); await task; });
+ expect(view.placeholders()[0].getAttribute("role")).toBe("alert");
+ expect(view.placeholders()[0].getAttribute("aria-busy")).toBe("false");
+ expect(view.reloadPreview).not.toHaveBeenCalled();
+ act(() => (view.placeholders()[0].querySelector("button") as HTMLButtonElement).click());
+ expect(view.placeholders()).toHaveLength(0);
+});
+
+it("finishes an in-flight save but cancels queued inserts and old selection on composition switch", 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.finish(0); await Promise.all([first, second]); });
+ expect(view.requests).toHaveLength(1);
+ expect(view.recordEdit).toHaveBeenCalledOnce();
+ expect(view.reloadPreview).not.toHaveBeenCalled();
+ expect(view.placeholders()).toHaveLength(0);
+ expect(usePlayerStore.getState().selectedElementId).toBeNull();
+});
diff --git a/studio/src/player/store/pendingAssetDrops.ts b/studio/src/player/store/pendingAssetDrops.ts
index 76efd84b..1741dfa7 100644
--- a/studio/src/player/store/pendingAssetDrops.ts
+++ b/studio/src/player/store/pendingAssetDrops.ts
@@ -28,7 +28,8 @@ export function beginPendingAssetDrop(
id: drop.id, tag: getTimelineAssetKind(drop.assetPath) ?? "div",
...drop.placement, duration: drop.duration ?? 5,
});
- const busy = [...(placement.insertRow == null ? state.elements : []), ...pending]
+ // Native composition insertion chooses a free track at the requested time.
+ const busy = [...(kind && placement.insertRow == null ? state.elements : []), ...pending]
.filter((element) => (element.tag === "audio") === (kind === "audio"));
const start = resolveNearestFreeStart(busy, placement.track, placement.start, duration ?? 5, null);
return { pendingAssetDrops: [...state.pendingAssetDrops, {
diff --git a/studio/src/utils/timelineCompositionInsert.test.ts b/studio/src/utils/timelineCompositionInsert.test.ts
index 9a853fad..f3a8a34f 100644
--- a/studio/src/utils/timelineCompositionInsert.test.ts
+++ b/studio/src/utils/timelineCompositionInsert.test.ts
@@ -19,6 +19,8 @@ describe("commitTimelineCompositionInsertion", () => {
response({
path: "index.html",
hostId: "headline",
+ track: 3,
+ duration: 8,
before: "before",
after: "after",
version: "v2",
@@ -32,7 +34,7 @@ describe("commitTimelineCompositionInsertion", () => {
const resync = vi.fn();
const refresh = vi.fn();
- await commitTimelineCompositionInsertion({
+ const element = await commitTimelineCompositionInsertion({
projectId: "launch#demo",
targetPath: "index.html",
sourcePath: "headline.html",
@@ -57,6 +59,7 @@ describe("commitTimelineCompositionInsertion", () => {
expect(selectHost).toHaveBeenCalledWith("index.html#headline");
expect(resync).toHaveBeenCalledOnce();
expect(refresh).toHaveBeenCalledOnce();
+ expect(element).toMatchObject({ key: "index.html#headline", start: 4, track: 3, duration: 8 });
});
it("CAS-restores the server write when history registration fails", async () => {
@@ -69,6 +72,8 @@ describe("commitTimelineCompositionInsertion", () => {
response({
path: "index.html",
hostId: "headline",
+ track: 2,
+ duration: 8,
before: "before",
after: "after",
version: "v2",
@@ -106,6 +111,8 @@ describe("commitTimelineCompositionInsertion", () => {
response({
path: "index.html",
hostId: "headline",
+ track: 2,
+ duration: 8,
before: "before",
after: "after",
version: "v2",
@@ -130,7 +137,7 @@ describe("commitTimelineCompositionInsertion", () => {
},
refresh,
}),
- ).resolves.toBeUndefined();
+ ).resolves.toMatchObject({ key: "index.html#headline", duration: 8 });
expect(refresh).toHaveBeenCalledOnce();
expect(consoleError).toHaveBeenCalledWith(
diff --git a/studio/src/utils/timelineCompositionInsert.ts b/studio/src/utils/timelineCompositionInsert.ts
index b29e26c8..c5c58130 100644
--- a/studio/src/utils/timelineCompositionInsert.ts
+++ b/studio/src/utils/timelineCompositionInsert.ts
@@ -5,10 +5,13 @@ import { buildProjectApiPath } from "./projectRouting";
import { studioWriteHeaders } from "./studioFileVersion";
import { deriveTimelineStoreKeyForDomId } from "../player/lib/timelineElementHelpers";
import { studioApiFetch } from "./studioApiFetch";
+import type { TimelineElement } from "../player";
interface TimelineCompositionInsertionResult {
path: string;
hostId: string;
+ track: number;
+ duration: number;
before: string;
after: string;
version: string;
@@ -64,8 +67,10 @@ export async function commitTimelineCompositionInsertion(input: {
selectHost: (key: string) => void;
resync?: () => void;
refresh: () => void;
-}): Promise<void> {
- await serializeStudioFileMutation(input.writeFile, input.targetPath, async () => {
+ isActive?: () => boolean;
+}): Promise<TimelineElement | undefined> {
+ return serializeStudioFileMutation(input.writeFile, input.targetPath, async () => {
+ if (input.isActive?.() === false) return;
const result = await insertTimelineComposition(input);
input.observeVersion?.(input.targetPath, result.version);
try {
@@ -77,7 +82,14 @@ export async function commitTimelineCompositionInsertion(input: {
await input.writeFile(input.targetPath, result.before, result.after);
throw error;
}
- input.selectHost(deriveTimelineStoreKeyForDomId(result.hostId, input.targetPath));
+ const key = deriveTimelineStoreKeyForDomId(result.hostId, input.targetPath);
+ const element: TimelineElement = {
+ id: result.hostId, key, domId: result.hostId, sourceFile: input.targetPath,
+ tag: "div", start: Math.round(input.start * 100) / 100, duration: result.duration,
+ track: result.track, authoredTrack: result.track, compositionSrc: input.sourcePath,
+ };
+ if (input.isActive?.() === false) return element;
+ input.selectHost(key);
try {
input.resync?.();
} catch (error) {
@@ -88,5 +100,6 @@ export async function commitTimelineCompositionInsertion(input: {
} catch (error) {
console.error("[Studio] Composition insertion committed but refresh failed", error);
}
+ return element;
});
}
diff --git a/studio/tests/e2e/composition-drop-loading.mjs b/studio/tests/e2e/composition-drop-loading.mjs
new file mode 100644
index 00000000..72e8e99e
--- /dev/null
+++ b/studio/tests/e2e/composition-drop-loading.mjs
@@ -0,0 +1,137 @@
+// Run with browser-lock.sh. Delay real insertion requests; never mock their responses.
+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-composition-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);
+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="30" data-width="640" data-height="360" style="position:relative;width:640px;height:360px;background:#eee"><div id="control" data-start="0" data-duration="30" data-track-index="0">Control</div></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 requests = [];
+const server = createServer((req, res) => {
+ const forward = () => handler(req, res, store, { studio, runtimeRoot: root, nativeRoot: root, ffmpeg: true, ensureStudio: async () => studio });
+ if (req.method === 'POST' && req.url.includes('/file-mutations/insert-composition/')) {
+ requests.push({ forward });
+ } else void forward();
+});
+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}`;
+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'));
+ 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.waitForSelector('[data-timeline-scroll-viewport] [data-clip="true"]', { timeout: 60000 });
+ await page.waitForFunction(() => !document.querySelector('[data-testid="timeline-loading-disabled-overlay"]'));
+ await page.evaluate(() => {
+ const button = Array.from(document.querySelectorAll('.hf-dock-side-rail button')).find(button => /compositions/i.test(`${button.title} ${button.getAttribute('aria-label')}`));
+ if (!button) throw new Error('Composition rail button missing');
+ button.click();
+ });
+ await page.waitForSelector('[data-composition-list] [draggable]');
+ const drag = (name, offset) => page.evaluate(({ name, offset }) => {
+ const card = [...document.querySelectorAll('[data-composition-list] [draggable]')].find(node => node.textContent.includes(`compositions/${name}.html`));
+ if (!card) throw new Error(`No composition card for ${name}`);
+ const target = document.querySelector('[data-timeline-scroll-viewport]');
+ 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 + offset, clientY: rect.top + 64 };
+ target.dispatchEvent(new DragEvent('dragover', options));
+ target.dispatchEvent(new DragEvent('drop', options));
+ card.dispatchEvent(new DragEvent('dragend', options));
+ }, { name, offset });
+ await page.evaluate(() => {
+ window.__dropSamples = [];
+ const visible = node => {
+ const box = node.getBoundingClientRect();
+ const view = node.closest('[data-timeline-scroll-viewport]').getBoundingClientRect();
+ return box.right > view.left && box.left < view.right && box.bottom > view.top && box.top < view.bottom;
+ };
+ const sample = () => {
+ window.__dropSamples.push({
+ pending: [...document.querySelectorAll('[data-testid="timeline-pending-asset"]')].filter(visible).map(node => node.dataset.dropId),
+ clips: [...document.querySelectorAll('[data-clip="true"]')].filter(visible).map(node => node.dataset.elId),
+ });
+ window.__dropSampleFrame = requestAnimationFrame(sample);
+ };
+ sample();
+ });
+ await drag('first', 340);
+ await page.waitForSelector('[data-testid="timeline-pending-asset"][aria-busy="true"]');
+ const firstId = await page.$eval('[data-testid="timeline-pending-asset"]', node => node.dataset.dropId);
+ assert.ok(await page.$eval('[data-testid="timeline-pending-asset"]', node => {
+ const box = node.getBoundingClientRect(), view = node.closest('[data-timeline-scroll-viewport]').getBoundingClientRect();
+ return box.left >= view.left && box.right <= view.right;
+ }), 'The pending clip must remain inside the visible timeline after release');
+ 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);
+ assert.equal(await page.$$eval('.hf-toast-enter[role="status"]', nodes => nodes.length), 0);
+ await drag('first', 540);
+ await page.waitForFunction(() => document.querySelectorAll('[data-testid="timeline-pending-asset"]').length === 2);
+ const secondId = await page.$$eval('[data-testid="timeline-pending-asset"]', nodes => nodes[1].dataset.dropId);
+ assert.equal(requests.length, 1, 'Second insertion must wait in the existing file mutation queue');
+ await page.screenshot({ path: path.join(output, 'composition-pending.png') });
+ await requests[0].forward();
+ for (let attempt = 0; attempt < 100 && requests.length < 2; attempt++) await new Promise(resolve => setTimeout(resolve, 50));
+ assert.equal(requests.length, 2);
+ assert.ok(await page.$(`[data-drop-id="${secondId}"]`));
+ await requests[1].forward();
+ await page.waitForFunction(() => !document.querySelector('[data-testid="timeline-pending-asset"]') && !!document.querySelector('[data-el-id="index.html#first_2"]'), { timeout: 30000 });
+ assert.equal(await page.$$eval('.hf-toast-enter[role="status"]', nodes => nodes.length), 0);
+ const samples = await page.evaluate(() => { cancelAnimationFrame(window.__dropSampleFrame); return window.__dropSamples; });
+ for (const [id, key] of [[firstId, 'index.html#first'], [secondId, 'index.html#first_2']]) {
+ const accepted = samples.findIndex(sample => sample.pending.includes(id));
+ assert.ok(accepted >= 0);
+ assert.ok(samples.slice(accepted).every(sample => sample.pending.includes(id) || sample.clips.includes(key)), `No empty frame for ${key}`);
+ }
+ assert.equal((await readFile(entry, 'utf8')).match(/data-composition-src=/g).length, 2);
+ await page.screenshot({ path: path.join(output, 'composition-ready.png') });
+ // Insert the root into itself to exercise the real native cycle refusal.
+ await page.evaluate(() => {
+ const card = [...document.querySelectorAll('[data-composition-list] [draggable]')].find(node => node.textContent.includes('index.html'));
+ const target = document.querySelector('[data-timeline-scroll-viewport]');
+ 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 + 340, clientY: rect.top + 64 };
+ target.dispatchEvent(new DragEvent('dragover', options));
+ target.dispatchEvent(new DragEvent('drop', options));
+ card.dispatchEvent(new DragEvent('dragend', options));
+ });
+ for (let attempt = 0; attempt < 100 && requests.length < 3; attempt++) await new Promise(resolve => setTimeout(resolve, 50));
+ assert.equal(requests.length, 3);
+ await requests[2].forward();
+ await page.waitForSelector('[data-testid="timeline-pending-asset"][role="alert"][aria-busy="false"]');
+ assert.equal((await readFile(entry, 'utf8')).match(/data-composition-src=/g).length, 2);
+ await page.screenshot({ path: path.join(output, 'composition-failed.png') });
+ const result = { status: 'PASS', scope: 'Real composition-list drag payload, native insertions/history and preview; requests delayed, responses never mocked', sampledFrames: samples.length, eachDropHasNoEmptyFrame: true, repeatedClips: 2, nativeCycleErrorVisible: 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();
+}