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.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
fix(studio): show loading feedback for timeline asset drops
罗高e11b061755ea
diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex fba9eef4..d3c89602 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -22,6 +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. 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, centers the editable project name, and places undo/redo and export on the right. Transient save/error status remains available. Workspace and export failures show concise causes and available next steps, with raw diagnostics behind expandable, copyable details. Reconnecting retries status reads only; dismissing a notice does not bypass write guards. Toasts stack at the top center of the editor. 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. 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; 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.- 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 and 320px for each expanded side. Side availability is derived from these minimums plus rail/gap space: 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 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. 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/components/EditorShell.tsx b/studio/src/components/EditorShell.tsxindex 02e92811..f6822697 100644--- a/studio/src/components/EditorShell.tsx+++ b/studio/src/components/EditorShell.tsx@@ -1,4 +1,5 @@import { MVP_PANEL_IDS } from "./dock/panelRegistry";+import { failPendingAssetPreviews } from "../player/store/pendingAssetDrops";import { useI18n } from "../i18n/I18n";import { memo, useCallback, type ReactNode } from "react";import { matchesKey } from "../player/components/studioShortcuts";@@ -189,7 +190,7 @@ export const EditorShell = memo(function EditorShell({activeCompositionPath={activeCompPath}onIframeRef={handlePreviewIframeRef}onCompIdToSrcChange={setCompIdToSrc}- onPreviewReloadFailed={(message) => showToast(message, "error")}+ onPreviewReloadFailed={(message) => { failPendingAssetPreviews(); showToast(message, "error"); }}onCompositionLoadingChange={setCompositionLoading}onCompositionChange={(compPath) => {// Sync activeCompPath when the user drills down via the timeline ordiff --git a/studio/src/components/sidebar/AssetCard.test.tsx b/studio/src/components/sidebar/AssetCard.test.tsxindex 919b14d3..78386aae 100644--- a/studio/src/components/sidebar/AssetCard.test.tsx+++ b/studio/src/components/sidebar/AssetCard.test.tsx@@ -8,6 +8,7 @@ import { useAssetPreviewStore } from "../../utils/assetPreviewStore";import { AssetCard } from "./AssetCard";import { AudioRow } from "./AudioRow";import { InlineAssetRename } from "./InlineAssetRename";+import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -131,6 +132,15 @@ describe("AudioRow click behavior", () => {copyFeedback: null,};+ it("carries the known audio duration with its drag payload", () => {+ const host = mount(<AudioRow {...rowProps} asset="assets/bgm.mp3" used={false} meta={{ duration: 42 }} />);+ const setData = vi.fn();+ const event = new Event("dragstart", { bubbles: true });+ Object.defineProperty(event, "dataTransfer", { value: { setData, effectAllowed: "none" } });+ act(() => host.querySelector("[draggable]")!.dispatchEvent(event));+ expect(setData).toHaveBeenCalledWith(TIMELINE_ASSET_MIME, JSON.stringify({ path: "assets/bgm.mp3", duration: 42 }));+ });+it("clears an open preview overlay when clicking an already-added audio asset (reveal branch)", () => {usePlayerStore.getState()diff --git a/studio/src/components/sidebar/AssetCard.tsx b/studio/src/components/sidebar/AssetCard.tsxindex 15772bd8..38e2f8c3 100644--- a/studio/src/components/sidebar/AssetCard.tsx+++ b/studio/src/components/sidebar/AssetCard.tsx@@ -22,9 +22,9 @@ import { resolveMediaPreviewUrl } from "../../player/components/thumbnailUtils";/** Drag payload writer shared by the asset tile and the font row: copy effect* plus the timeline-asset MIME and a plain-text path fallback. */-function writeAssetDragData(e: React.DragEvent, asset: string): void {+function writeAssetDragData(e: React.DragEvent, asset: string, duration?: number): void {e.dataTransfer.effectAllowed = "copy";- e.dataTransfer.setData(TIMELINE_ASSET_MIME, JSON.stringify({ path: asset }));+ e.dataTransfer.setData(TIMELINE_ASSET_MIME, JSON.stringify({ path: asset, duration }));e.dataTransfer.setData("text/plain", asset);}@@ -229,7 +229,7 @@ export function AssetCard({activateCard();}}}- onDragStart={(e) => writeAssetDragData(e, asset)}+ onDragStart={(e) => writeAssetDragData(e, asset, resolvedDuration)}onContextMenu={(e) => openAssetContextMenu(e, setContextMenu)}onPointerEnter={() => setHovered(true)}onPointerLeave={() => setHovered(false)}diff --git a/studio/src/components/sidebar/AudioRow.tsx b/studio/src/components/sidebar/AudioRow.tsxindex 335f0a38..815275e6 100644--- a/studio/src/components/sidebar/AudioRow.tsx+++ b/studio/src/components/sidebar/AudioRow.tsx@@ -228,7 +228,7 @@ export function AudioRow({}}onDragStart={(e) => {e.dataTransfer.effectAllowed = "copy";- e.dataTransfer.setData(TIMELINE_ASSET_MIME, JSON.stringify({ path: asset }));+ e.dataTransfer.setData(TIMELINE_ASSET_MIME, JSON.stringify({ path: asset, duration: meta?.duration }));e.dataTransfer.setData("text/plain", asset);}}onContextMenu={(e) => {diff --git a/studio/src/hooks/useTimelineAssetDropFeedback.test.tsx b/studio/src/hooks/useTimelineAssetDropFeedback.test.tsxnew file mode 100644index 00000000..11ddb1a0--- /dev/null+++ b/studio/src/hooks/useTimelineAssetDropFeedback.test.tsx@@ -0,0 +1,161 @@+// @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 { useTimelineAssetDropOps } from "./useTimelineAssetDropOps";+import { usePlayerStore } from "../player/store/playerStore";+import { Timeline } from "../player/components/Timeline";+import { installTimelineMountEnv } from "../player/components/timelineMountTestEnv";+import { I18nProvider } from "../i18n/I18n";+import type { TimelineElement } from "../player";+import { failPendingAssetPreviews } from "../player/store/pendingAssetDrops";++(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.restoreAllMocks();+ vi.unstubAllGlobals();+ document.body.replaceChildren();+});++function mountDropEditor(elements: TimelineElement[] = []) {+ let source = '<main data-composition-id="scene" data-duration="30"></main>';+ const write = vi.fn(async (_path: string, content: string) => { source = content; });+ const recordEdit = vi.fn(async () => {});+ const showToast = vi.fn();+ const projectIdRef = { current: "project" };+ usePlayerStore.setState({ elements, timelineReady: true, duration: 30 });+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ content: source })));+ let handlers!: ReturnType<typeof useTimelineAssetDropOps>;+ function Editor({ path }: { path: string }) {+ const timelineElements = usePlayerStore((state) => state.elements);+ handlers = useTimelineAssetDropOps({+ projectIdRef, activeCompPath: path, timelineElements, showToast,+ writeProjectFile: write, recordEdit, reloadPreview: vi.fn(), uploadProjectFiles: vi.fn(),+ });+ return <I18nProvider initialLocale="zh-CN"><Timeline onAssetDrop={handlers.handleTimelineAssetDrop} /></I18nProvider>;+ }+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host);+ roots.push(root);+ act(() => root.render(<Editor path="index.html" />));+ return {+ host, write, recordEdit, showToast,+ drop: (...args: Parameters<typeof handlers.handleTimelineAssetDrop>) => handlers.handleTimelineAssetDrop(...args),+ switchComposition: () => act(() => root.render(<Editor path="other.html" />)),+ source: () => source,+ placeholders: () => Array.from(host.querySelectorAll<HTMLElement>('[data-testid="timeline-pending-asset"]')),+ };+}++describe("timeline asset drop feedback", () => {+ it("shows each repeated audio drop immediately, shares probing, and replaces each only when its clip appears", async () => {+ const view = mountDropEditor();+ const createElement = document.createElement.bind(document);+ const probes: HTMLAudioElement[] = [];+ vi.spyOn(document, "createElement").mockImplementation((tag, options) => {+ const element = createElement(tag, options);+ if (tag === "audio") probes.push(element as HTMLAudioElement);+ return element;+ });+ let first!: Promise<void>;+ let second!: Promise<void>;+ act(() => {+ first = view.drop("assets/music.mp3", { start: 0, track: 0 });+ second = view.drop("assets/music.mp3", { start: 0, track: 0 });+ });+ expect(view.placeholders()).toHaveLength(2);+ expect(new Set(view.placeholders().map((node) => node.style.left)).size).toBe(2);+ expect(view.placeholders().every((node) => node.getAttribute("aria-busy") === "true")).toBe(true);+ expect(probes).toHaveLength(1);+ expect(view.write).not.toHaveBeenCalled();+ Object.defineProperty(probes[0], "duration", { value: 6 });+ await act(async () => {+ probes[0].dispatchEvent(new Event("loadedmetadata"));+ await Promise.all([first, second]);+ });+ expect(view.write).toHaveBeenCalledTimes(2);+ expect(view.recordEdit).toHaveBeenCalledTimes(2);+ expect(view.source().match(/<audio /g)).toHaveLength(2);+ expect(view.placeholders()).toHaveLength(2);+ const inserted = usePlayerStore.getState().pendingAssetDrops.map((drop) => drop.element!);+ expect(inserted.map((element) => element.start)).toEqual([0, 6]);+ expect(new Set(inserted.map((element) => element.key)).size).toBe(2);+ act(() => usePlayerStore.getState().setElements(inserted.slice(0, 1)));+ expect(view.placeholders()).toHaveLength(1);+ act(() => usePlayerStore.setState({ timelineReady: false, elements: inserted }));+ expect(view.placeholders()).toHaveLength(1);+ act(() => usePlayerStore.getState().setTimelineReady(true));+ expect(view.placeholders()).toHaveLength(0);+ expect(usePlayerStore.getState().pendingAssetDrops).toEqual([]);+ expect(view.source()).not.toContain("pending");+ });++ it("keeps feedback through saving on a populated row, then leaves a dismissible failure", async () => {+ const view = mountDropEditor([{ id: "title", tag: "div", start: 0, duration: 10, track: 0 }]);+ let rejectWrite!: (reason: Error) => void;+ view.write.mockImplementation(() => new Promise<void>((_resolve, reject) => { rejectWrite = reject; }));+ let drop!: Promise<void>;+ await act(async () => { drop = view.drop("assets/music.mp3", { start: 12, track: 0 }, 6); });+ expect(view.placeholders()).toHaveLength(1);+ const before = view.placeholders()[0].style.left;+ await act(async () => {+ rejectWrite(new Error("Save unavailable"));+ await drop;+ });+ const failed = view.placeholders()[0];+ expect(failed.style.left).toBe(before);+ expect(failed.getAttribute("role")).toBe("alert");+ expect(failed.getAttribute("aria-busy")).toBe("false");+ expect(failed.textContent).toContain("添加素材失败");+ expect(view.source()).not.toContain("<audio");+ act(() => failed.querySelector<HTMLButtonElement>("button")!.click());+ expect(view.placeholders()).toHaveLength(0);+ });++ it("clears the old composition's loading operation before it can write to the new one", async () => {+ const view = mountDropEditor();+ let drop!: Promise<void>;+ act(() => { drop = view.drop("assets/music.mp3", { start: 0, track: 0 }, 6); });+ expect(view.placeholders()).toHaveLength(1);+ view.switchComposition();+ await act(async () => { await drop; });+ expect(view.placeholders()).toHaveLength(0);+ expect(view.write).not.toHaveBeenCalled();+ expect(view.showToast).not.toHaveBeenCalled();+ });++ it("ends loading on a media read failure without inserting a made-up duration", async () => {+ const view = mountDropEditor();+ const createElement = document.createElement.bind(document);+ let probe!: HTMLAudioElement;+ vi.spyOn(document, "createElement").mockImplementation((tag, options) => {+ const element = createElement(tag, options);+ if (tag === "audio") probe = element as HTMLAudioElement;+ return element;+ });+ let drop!: Promise<void>;+ act(() => { drop = view.drop("assets/broken.mp3", { start: 0, track: 0 }); });+ await act(async () => {+ probe.dispatchEvent(new Event("error"));+ await drop;+ });+ expect(view.placeholders()[0].getAttribute("aria-busy")).toBe("false");+ expect(view.placeholders()[0].textContent).toContain("添加素材失败");+ expect(view.write).not.toHaveBeenCalled();+ expect(probe.getAttribute("src")).toBe("");+ });++ it("ends loading on a preview failure while preserving the already saved clip", async () => {+ const view = mountDropEditor();+ await act(async () => { await view.drop("assets/music.mp3", { start: 0, track: 0 }, 6); });+ act(() => failPendingAssetPreviews());+ expect(view.placeholders()[0].getAttribute("aria-busy")).toBe("false");+ expect(view.placeholders()[0].textContent).toContain("预览加载失败");+ expect(view.source().match(/<audio /g)).toHaveLength(1);+ });+});diff --git a/studio/src/hooks/useTimelineAssetDropOps.test.tsx b/studio/src/hooks/useTimelineAssetDropOps.test.tsxindex a0d6ecd2..feaf554c 100644--- a/studio/src/hooks/useTimelineAssetDropOps.test.tsx+++ b/studio/src/hooks/useTimelineAssetDropOps.test.tsx@@ -15,6 +15,7 @@ import { translate } from "../i18n/messages";afterEach(() => {document.body.innerHTML = "";vi.unstubAllGlobals();+ vi.restoreAllMocks();usePlayerStore.getState().reset();});@@ -272,12 +273,21 @@ describe("useTimelineAssetDropOps handleTimelineAssetDrop", () => {});it("keeps two audio files dropped on a visual row together, as a single one would go", async () => {+ const createElement = document.createElement.bind(document);+ vi.spyOn(document, "createElement").mockImplementation((tag, options) => {+ const element = createElement(tag, options);+ if (tag === "audio") {+ Object.defineProperty(element, "duration", { value: 5 });+ queueMicrotask(() => element.dispatchEvent(new Event("loadedmetadata")));+ }+ return element;+ });const clips = [rowClip("title", 0, 10, { track: 1 }),rowClip("music", 2, 3, { tag: "audio", row: 1, track: 0 }),];const landed = await twoFileDrop(clips, { start: 12, track: 0 }, [["a.mp3", "b.mp3"], "audio"]);- // Audio length probing times out in this harness, so each file gets the 5 s default.+ // Each readable audio file reports a 5 s duration.expect(landed).toEqual([["12", "0"],["17", "0"],diff --git a/studio/src/hooks/useTimelineAssetDropOps.ts b/studio/src/hooks/useTimelineAssetDropOps.tsindex 3f44077a..70263517 100644--- a/studio/src/hooks/useTimelineAssetDropOps.ts+++ b/studio/src/hooks/useTimelineAssetDropOps.ts@@ -2,7 +2,7 @@// placement, or upload dragged-in OS files and place them sequentially.// Extracted verbatim from useTimelineEditing.ts to keep it under the studio// 600-line cap.-import { useCallback, type MutableRefObject, type RefObject } from "react";+import { useCallback, useEffect, useRef, type MutableRefObject, type RefObject } from "react";import { compositionInsertionFailureMessage } from "../i18n/editorErrors";import type { TimelineElement } from "../player";import type { TimelineDropPlacement } from "../player/components/timelineCallbacks";@@ -10,7 +10,6 @@ import { resolveDropTrack } from "../utils/timelineDropTrackInsert";import {buildTimelineAssetId,buildTimelineAssetInsertHtml,- buildTimelineFileDropPlacements,fitTimelineAssetGeometry,getTimelineAssetKind,insertTimelineAssetIntoSource,@@ -30,6 +29,8 @@ import { commitTimelineCompositionInsertion } from "../utils/timelineCompositionimport { extendRootDurationInSource } from "../utils/rootDuration";import { deriveTimelineStoreKeyForDomId } from "../player/lib/timelineElementHelpers";import { selectAndRevealTimelineElement } from "../player/components/timelineDropReveal";+import { usePlayerStore } from "../player/store/playerStore";+import { beginPendingAssetDrop, updatePendingAssetDrop } from "../player/store/pendingAssetDrops";/** The first uploaded file opens the new track (if asked); each next one aims right after the previous. */function fileDropPlacement(@@ -90,6 +91,25 @@ export function useTimelineAssetDropOps({observeProjectFileVersion,checkEditable,}: UseTimelineAssetDropOpsOptions) {+ const projectId = projectIdRef.current;+ const timelineReady = usePlayerStore((state) => state.timelineReady);+ const elementsRef = useRef(timelineElements);+ const dropScopeRef = useRef(0);+ elementsRef.current = timelineElements;+ useEffect(() => () => {+ dropScopeRef.current++;+ usePlayerStore.setState({ pendingAssetDrops: [] });+ }, [projectId, activeCompPath]);+ useEffect(() => {+ if (!timelineReady) return;+ usePlayerStore.setState((state) => {+ const pendingAssetDrops = state.pendingAssetDrops.filter((drop) =>+ !drop.element || !timelineElements.some((element) =>+ (element.key ?? element.id) === drop.element!.key),+ );+ return pendingAssetDrops.length === state.pendingAssetDrops.length ? state : { pendingAssetDrops };+ });+ }, [timelineElements, timelineReady]);// fallow-ignore-next-line complexityconst dropAssetAt = useCallback(// fallow-ignore-next-line complexity@@ -116,6 +136,8 @@ export function useTimelineAssetDropOps({return undefined;}+ const pendingId = beginPendingAssetDrop(assetPath, placement, durationOverride);+ const stillActive = () => usePlayerStore.getState().pendingAssetDrops.some((drop) => drop.id === pendingId);try {const normalizedStart = Number(formatTimelineAttributeNumber(placement.start));const duration =@@ -123,28 +145,36 @@ export function useTimelineAssetDropOps({? durationOverride: await resolveDroppedAssetDuration(pid, assetPath, kind);const normalizedDuration = Number(formatTimelineAttributeNumber(duration));+ updatePendingAssetDrop(pendingId, { duration: normalizedDuration });// A video with an audio stream lands audible; the mixer only hears a// <video> marked data-has-audio, and a muted drop was losing the sound.const hasAudio = await resolveDroppedAssetHasAudio(pid, assetPath, kind);+ if (!stillActive()) return undefined;const resolvedAssetSrc = resolveTimelineAssetSrc(targetPath, assetPath);- const resolvedTargetPath = targetPath || "index.html";- const fileElements = timelineElements- .filter((te) => (te.sourceFile || activeCompPath || "index.html") === resolvedTargetPath)- .map((te) => ({ ...te, sourceFile: resolvedTargetPath }));- const newElementZIndex = Math.max(1, fileElements.length + gesture.placed.length + 1);const tag = kind === "image" ? "img" : kind;let newId = "";let track = 0;let start = normalizedStart;const insertAsset = (originalContent: string) => {- newId = buildTimelineAssetId(assetPath, collectHtmlIds(originalContent));+ if (!stillActive()) throw new Error("The timeline drop is no longer active.");+ const fileElements = elementsRef.current+ .filter((te) => (te.sourceFile || activeCompPath || "index.html") === targetPath)+ .map((te) => ({ ...te, sourceFile: targetPath }));+ const newElementZIndex = Math.max(1, fileElements.length + gesture.placed.length + 1);+ const ids = collectHtmlIds(originalContent);+ newId = buildTimelineAssetId(assetPath, ids);+ // Include drops saved while this preview was still reloading.+ const awaitingPreview = usePlayerStore.getState().pendingAssetDrops.flatMap((drop) =>+ drop.element && ids.includes(drop.element.domId ?? "")+ ? [drop.element] : [],+ );const resolved = resolveDropTrack({source: originalContent,// Rows and insertRow count the rows the timeline shows; a track this drop opened has no others.elements: gesture.onNewTrack ? [] : fileElements,- placed: gesture.placed,+ placed: [...gesture.placed, ...awaitingPreview],placement,dropped: {id: newId,@@ -155,6 +185,9 @@ export function useTimelineAssetDropOps({});track = resolved.track;start = resolved.start;+ updatePendingAssetDrop(pendingId, {+ placement: { ...placement, start },+ });return extendRootDurationInSource(insertTimelineAssetIntoSource(resolved.source,@@ -187,19 +220,21 @@ export function useTimelineAssetDropOps({recordEdit,});- selectAndRevealTimelineElement(deriveTimelineStoreKeyForDomId(newId, targetPath));- forceReloadSdkSession?.();- reloadPreview();+ const key = deriveTimelineStoreKeyForDomId(newId, targetPath);const lane = placement.insertRow == null ? placement.track : track;- return {- id: newId,- tag,- start,- duration: normalizedDuration,- track: lane,- authoredTrack: track,+ const element = {+ id: newId, key, domId: newId, sourceFile: targetPath,+ tag, start, duration: normalizedDuration, track: lane, authoredTrack: track,};+ updatePendingAssetDrop(pendingId, { element });+ if (!stillActive()) return element;+ selectAndRevealTimelineElement(key);+ forceReloadSdkSession?.();+ reloadPreview();+ return element;} catch (error) {+ if (!stillActive()) return undefined;+ updatePendingAssetDrop(pendingId, { failed: "add" });const message =error instanceof Error ? error.message : "Failed to drop asset onto timeline";showToast(message);@@ -243,25 +278,16 @@ export function useTimelineAssetDropOps({}const pid = projectIdRef.current;if (!pid) return;+ const scope = dropScopeRef.current;const uploaded = await uploadProjectFiles(files);+ if (scope !== dropScopeRef.current) return;if (uploaded.length === 0) return;- const durations: number[] = [];- for (const assetPath of uploaded) {- const kind = getTimelineAssetKind(assetPath);- const duration = kind ? await resolveDroppedAssetDuration(pid, assetPath, kind) : 0;- durations.push(Number(formatTimelineAttributeNumber(duration)));- }- const placements = buildTimelineFileDropPlacements(- placement ?? { start: 0, track: 0 },- durations,- );const gesture: DropGesture = { placed: [], onNewTrack: false };for (const [index, assetPath] of uploaded.entries()) {- const next = placements[index] ?? placements[0];const clip = await dropAssetAt(assetPath,- fileDropPlacement(index, next, placement, gesture.placed.at(-1)),- durations[index],+ fileDropPlacement(index, initialPlacement, placement, gesture.placed.at(-1)),+ undefined,gesture,);if (!clip) continue;diff --git a/studio/src/i18n/de.json b/studio/src/i18n/de.jsonindex 0b293d84..8ce9940e 100644--- a/studio/src/i18n/de.json+++ b/studio/src/i18n/de.json@@ -1805,5 +1805,7 @@"purple": "Violett","multicolor": "Mehrfarbig","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Verlaufsdateien fehlen, sind nicht lesbar oder beschädigt: {files}. Diese Version wurde nicht wiederhergestellt. Das aktuelle Projekt bleibt unverändert.",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Verlaufsdateien konnten nicht für die Wiederherstellung vorbereitet werden: {files}. Das aktuelle Projekt bleibt unverändert."+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Verlaufsdateien konnten nicht für die Wiederherstellung vorbereitet werden: {files}. Das aktuelle Projekt bleibt unverändert.",+ "Failed to add media": "Medien konnten nicht hinzugefügt werden",+ "Could not read media duration. Try adding the file again.": "Die Mediendauer konnte nicht gelesen werden. Fügen Sie die Datei erneut hinzu."}diff --git a/studio/src/i18n/es.json b/studio/src/i18n/es.jsonindex 08c2cc6f..42085d72 100644--- a/studio/src/i18n/es.json+++ b/studio/src/i18n/es.json@@ -1805,5 +1805,7 @@"purple": "Morado","multicolor": "Multicolor","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Faltan archivos del historial, no se pueden leer o están dañados: {files}. Esta versión no se ha restaurado. El proyecto actual no ha cambiado.",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "No se pudieron preparar los archivos del historial para la restauración: {files}. El proyecto actual no ha cambiado."+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "No se pudieron preparar los archivos del historial para la restauración: {files}. El proyecto actual no ha cambiado.",+ "Failed to add media": "No se pudo añadir el archivo multimedia",+ "Could not read media duration. Try adding the file again.": "No se pudo leer la duración del archivo multimedia. Intenta añadirlo de nuevo."}diff --git a/studio/src/i18n/fr.json b/studio/src/i18n/fr.jsonindex 98720af5..62c7666b 100644--- a/studio/src/i18n/fr.json+++ b/studio/src/i18n/fr.json@@ -1805,5 +1805,7 @@"purple": "Violet","multicolor": "Multicolore","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Des fichiers de l’historique sont manquants, illisibles ou endommagés : {files}. Cette version n’a pas été restaurée. Le projet actuel reste inchangé.",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Impossible de préparer les fichiers de l’historique pour la restauration : {files}. Le projet actuel reste inchangé."+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Impossible de préparer les fichiers de l’historique pour la restauration : {files}. Le projet actuel reste inchangé.",+ "Failed to add media": "Échec de l’ajout du média",+ "Could not read media duration. Try adding the file again.": "Impossible de lire la durée du média. Essayez d’ajouter à nouveau le fichier."}diff --git a/studio/src/i18n/it.json b/studio/src/i18n/it.jsonindex 68233cbf..d65219ea 100644--- a/studio/src/i18n/it.json+++ b/studio/src/i18n/it.json@@ -1805,5 +1805,7 @@"purple": "Viola","multicolor": "Multicolore","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Alcuni file della cronologia sono mancanti, illeggibili o danneggiati: {files}. Questa versione non è stata ripristinata. Il progetto attuale rimane invariato.",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Impossibile preparare i file della cronologia per il ripristino: {files}. Il progetto attuale rimane invariato."+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Impossibile preparare i file della cronologia per il ripristino: {files}. Il progetto attuale rimane invariato.",+ "Failed to add media": "Impossibile aggiungere il file multimediale",+ "Could not read media duration. Try adding the file again.": "Impossibile leggere la durata del file multimediale. Prova ad aggiungere nuovamente il file."}diff --git a/studio/src/i18n/ja.json b/studio/src/i18n/ja.jsonindex 03f41ba3..e9bbd5d5 100644--- a/studio/src/i18n/ja.json+++ b/studio/src/i18n/ja.json@@ -1769,5 +1769,7 @@"blue": "青","monochrome": "モノクロ","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "履歴ファイルが見つからないか、読み取れないか、破損しています:{files}。このバージョンは復元されませんでした。現在のプロジェクトは変更されていません。",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "復元に必要な履歴ファイルを準備できませんでした:{files}。現在のプロジェクトは変更されていません。"+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "復元に必要な履歴ファイルを準備できませんでした:{files}。現在のプロジェクトは変更されていません。",+ "Failed to add media": "メディアを追加できませんでした",+ "Could not read media duration. Try adding the file again.": "メディアの長さを読み取れませんでした。ファイルをもう一度追加してください。"}diff --git a/studio/src/i18n/ko.json b/studio/src/i18n/ko.jsonindex 94c55046..ccb94086 100644--- a/studio/src/i18n/ko.json+++ b/studio/src/i18n/ko.json@@ -1769,5 +1769,7 @@"blue": "파랑","monochrome": "흑백","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "이전 버전의 파일이 없거나 읽을 수 없거나 손상되었습니다: {files}. 이 버전은 복원되지 않았습니다. 현재 프로젝트는 변경되지 않았습니다.",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "복원에 필요한 이전 버전의 파일을 준비하지 못했습니다: {files}. 현재 프로젝트는 변경되지 않았습니다."+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "복원에 필요한 이전 버전의 파일을 준비하지 못했습니다: {files}. 현재 프로젝트는 변경되지 않았습니다.",+ "Failed to add media": "미디어를 추가하지 못했습니다",+ "Could not read media duration. Try adding the file again.": "미디어 길이를 읽을 수 없습니다. 파일을 다시 추가해 주세요."}diff --git a/studio/src/i18n/pt-BR.json b/studio/src/i18n/pt-BR.jsonindex 6a0a6ca9..47339fc1 100644--- a/studio/src/i18n/pt-BR.json+++ b/studio/src/i18n/pt-BR.json@@ -1805,5 +1805,7 @@"blue": "Azul","monochrome": "Monocromático","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Arquivos do histórico estão ausentes, ilegíveis ou danificados: {files}. Esta versão não foi restaurada. O projeto atual permanece inalterado.",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Não foi possível preparar os arquivos do histórico para restauração: {files}. O projeto atual permanece inalterado."+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Não foi possível preparar os arquivos do histórico para restauração: {files}. O projeto atual permanece inalterado.",+ "Failed to add media": "Não foi possível adicionar a mídia",+ "Could not read media duration. Try adding the file again.": "Não foi possível ler a duração da mídia. Tente adicionar o arquivo novamente."}diff --git a/studio/src/i18n/ru.json b/studio/src/i18n/ru.jsonindex 0934ecf6..b7c41572 100644--- a/studio/src/i18n/ru.json+++ b/studio/src/i18n/ru.json@@ -1829,5 +1829,7 @@"blue": "Синий","monochrome": "Монохромный","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Файлы истории отсутствуют, недоступны для чтения или повреждены: {files}. Эта версия не восстановлена. Текущий проект не изменён.",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Не удалось подготовить файлы истории для восстановления: {files}. Текущий проект не изменён."+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Не удалось подготовить файлы истории для восстановления: {files}. Текущий проект не изменён.",+ "Failed to add media": "Не удалось добавить медиафайл",+ "Could not read media duration. Try adding the file again.": "Не удалось определить длительность медиафайла. Попробуйте добавить файл ещё раз."}diff --git a/studio/src/i18n/tr.json b/studio/src/i18n/tr.jsonindex 5ef5de22..45eae53a 100644--- a/studio/src/i18n/tr.json+++ b/studio/src/i18n/tr.json@@ -1769,5 +1769,7 @@"blue": "Mavi","monochrome": "Tek renkli","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Geçmiş dosyaları eksik, okunamıyor veya hasarlı: {files}. Bu sürüm geri yüklenmedi. Mevcut proje değişmedi.",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Geçmiş dosyaları geri yükleme için hazırlanamadı: {files}. Mevcut proje değişmedi."+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Geçmiş dosyaları geri yükleme için hazırlanamadı: {files}. Mevcut proje değişmedi.",+ "Failed to add media": "Medya eklenemedi",+ "Could not read media duration. Try adding the file again.": "Medya süresi okunamadı. Dosyayı tekrar eklemeyi deneyin."}diff --git a/studio/src/i18n/zh-CN.json b/studio/src/i18n/zh-CN.jsonindex ed9035be..1f195fa3 100644--- a/studio/src/i18n/zh-CN.json+++ b/studio/src/i18n/zh-CN.json@@ -1769,5 +1769,7 @@"yellow": "黄色","{count} templates": "{count} 个模板","Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "历史文件缺失、无法读取或已损坏:{files}。未恢复此版本,当前工程保持不变。",- "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "无法准备恢复所需的历史文件:{files}。当前工程保持不变。"+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "无法准备恢复所需的历史文件:{files}。当前工程保持不变。",+ "Failed to add media": "添加素材失败",+ "Could not read media duration. Try adding the file again.": "无法读取素材时长,请重新添加文件。"}diff --git a/studio/src/player/components/TimelineCanvas.tsx b/studio/src/player/components/TimelineCanvas.tsxindex f6daf37f..b321f7ec 100644--- a/studio/src/player/components/TimelineCanvas.tsx+++ b/studio/src/player/components/TimelineCanvas.tsx@@ -8,6 +8,7 @@ import { getTimelinePlayheadTransform } from "./timelinePlayheadTransform";import { TimelineLanes } from "./TimelineLanes";import { TimelineGestureOverlay } from "./TimelineGestureOverlay";import { useTimelineContext } from "./TimelineProvider";+import { TimelinePendingAssetDrops } from "./TimelinePendingAssetDrops";// A dropped clip's length is unknown until it lands; the preview shows a default.const DROP_PREVIEW_SECONDS = 3;@@ -49,6 +50,12 @@ export const TimelineCanvas = memo(function TimelineCanvas() {style={{ height: props.totalH, width: props.contentOrigin + props.trackContentWidth }}><TimelineRulerPart />+ <TimelinePendingAssetDrops+ contentOrigin={props.contentOrigin}+ pixelsPerSecond={props.pps}+ trackOrder={displayTrackOrder}+ rowTop={props.rowGeometry.getRowTop}+ />{/* Breathing room between the sticky ruler and the first track lane — thetop half of the CapCut-style padding (see TimelineRowGeometry.padding). */}diff --git a/studio/src/player/components/TimelineEmptyState.tsx b/studio/src/player/components/TimelineEmptyState.tsxindex 00ce74ca..97791874 100644--- a/studio/src/player/components/TimelineEmptyState.tsx+++ b/studio/src/player/components/TimelineEmptyState.tsx@@ -5,6 +5,7 @@ import { CLIP_Y, GUTTER, LABEL_COL_W, RULER_H, TRACK_H, TRACKS_TOP_PAD } from ".import { useMediaGateway } from "../../motion/MediaGatewayContext";import { usePlayerStore } from "../store/playerStore";import { mediaPopoverAnchor } from "../../motion/mediaPopoverPosition";+import { TimelinePendingAssetDrops } from "./TimelinePendingAssetDrops";function EmptyGenerationRange() {const range = usePlayerStore(s => s.rangeSelection);@@ -38,13 +39,19 @@ export function TimelineEmptyState({const hideGuide = !!gateway?.generationOpen && !isDragOver;return (<div- className={`h-full border-t bg-[var(--timeline-shell-bg)] flex flex-col select-none transition-colors duration-150 ${+ className={`relative h-full border-t bg-[var(--timeline-shell-bg)] flex flex-col select-none transition-colors duration-150 ${isDragOver ? "border-studio-accent/50 bg-studio-accent/3" : "border-neutral-800/50"}`}onDragOver={onDragOver}onDragLeave={onDragLeave}onDrop={onDrop}>+ <TimelinePendingAssetDrops+ contentOrigin={emptyOrigin}+ pixelsPerSecond={14}+ trackOrder={[]}+ rowTop={() => RULER_H + trackTopPadding}+ />{/* Ruler */}<divclassName="shrink-0 border-b border-neutral-800/40 flex items-end relative"diff --git a/studio/src/player/components/TimelinePendingAssetDrops.tsx b/studio/src/player/components/TimelinePendingAssetDrops.tsxnew file mode 100644index 00000000..dfb5c861--- /dev/null+++ b/studio/src/player/components/TimelinePendingAssetDrops.tsx@@ -0,0 +1,60 @@+import { useI18n } from "../../i18n/I18n";+import { RemixIcon, X } from "../../icons/RemixIcons";+import { usePlayerStore } from "../store/playerStore";+import { dismissPendingAssetDrop } from "../store/pendingAssetDrops";+import { CLIP_Y, TRACK_H } from "./timelineLayout";++export function TimelinePendingAssetDrops({+ contentOrigin, pixelsPerSecond, trackOrder, rowTop,+}: {+ contentOrigin: number;+ pixelsPerSecond: number;+ trackOrder: readonly number[];+ rowTop: (index: number) => number;+}) {+ const { t } = useI18n();+ const drops = usePlayerStore((state) => state.pendingAssetDrops);+ const elements = usePlayerStore((state) => state.elements);+ const timelineReady = usePlayerStore((state) => state.timelineReady);+ return drops.map((drop) => {+ if (timelineReady && drop.element && elements.some((element) => (element.key ?? element.id) === drop.element!.key)) return null;+ const placement = drop.placement;+ const index = trackOrder.indexOf(drop.element?.track ?? placement.track);+ const row = placement.insertRow ?? (index < 0 ? trackOrder.length : index);+ const start = drop.element?.start ?? placement.start;+ const name = drop.assetPath.split("/").pop() ?? drop.assetPath;+ const message = t(drop.failed === "preview" ? "Preview failed to load" : drop.failed ? "Failed to add media" : "Adding…");+ return (+ <div+ key={drop.id}+ data-testid="timeline-pending-asset"+ data-drop-id={drop.id}+ role={drop.failed ? "alert" : "status"}+ aria-busy={!drop.failed}+ aria-label={`${name}: ${message}`}+ title={`${name}: ${message}`}+ className="absolute flex items-center gap-1.5 overflow-hidden rounded border border-dashed px-2 text-[11px] text-neutral-200"+ style={{+ top: rowTop(row) + CLIP_Y,+ left: contentOrigin + start * pixelsPerSecond,+ width: Math.max(drop.failed ? 140 : 48, (drop.duration ?? 5) * pixelsPerSecond),+ height: TRACK_H - CLIP_Y * 2,+ background: "var(--timeline-shell-bg)",+ borderColor: drop.failed ? "var(--color-red-400)" : "var(--timeline-accent)",+ zIndex: 40,+ pointerEvents: drop.failed ? "auto" : "none",+ }}+ >+ {!drop.failed && <RemixIcon name="loader-4-line" size={14} className="shrink-0 motion-safe:animate-spin" aria-hidden="true" />}+ <span className="min-w-0 truncate">{message} · {name}</span>+ {drop.failed && <button+ type="button"+ className="ml-auto shrink-0 rounded p-1 focus-visible:outline focus-visible:outline-2"+ aria-label={t("Dismiss error")}+ onPointerDown={(event) => event.stopPropagation()}+ onClick={(event) => { event.stopPropagation(); dismissPendingAssetDrop(drop.id); }}+ ><X size={12} /></button>}+ </div>+ );+ });+}diff --git a/studio/src/player/components/timelineCallbacks.ts b/studio/src/player/components/timelineCallbacks.tsindex dcc50740..dab0964e 100644--- a/studio/src/player/components/timelineCallbacks.ts+++ b/studio/src/player/components/timelineCallbacks.ts@@ -30,7 +30,7 @@ export type TimelineDropPlacement = { start: number; track: number } & (*/export interface TimelineDropCallbacks {onFileDrop?: (files: File[], placement?: TimelineDropPlacement) => Promise<void> | void;- onAssetDrop?: (assetPath: string, placement: TimelineDropPlacement) => Promise<void> | void;+ onAssetDrop?: (assetPath: string, placement: TimelineDropPlacement, duration?: number) => Promise<void> | void;onBlockDrop?: (blockName: string,placement: { start: number; track: number },diff --git a/studio/src/player/components/timelineDragDrop.test.tsx b/studio/src/player/components/timelineDragDrop.test.tsxindex 7f9ffdbc..10baf17b 100644--- a/studio/src/player/components/timelineDragDrop.test.tsx+++ b/studio/src/player/components/timelineDragDrop.test.tsx@@ -110,6 +110,17 @@ afterEach(() => {});describe("useTimelineAssetDrop", () => {+ it("forwards a known duration so dropping does not need another probe", () => {+ const onAssetDrop = vi.fn();+ const view = renderHarness(onAssetDrop);+ const event = dragEvent(assetTransfer('{"path":"music.mp3","duration":12.5}'), 80, ROW0_MID_Y);+ act(() => {+ view.api.handleAssetDragOver(event);+ view.api.handleAssetDrop(event);+ });+ expect(onAssetDrop).toHaveBeenCalledWith("music.mp3", { start: 2, track: 0 }, 12.5);+ act(() => view.root.unmount());+ });it("edge-autoscrolls the sole timeline viewport while a supported asset is held", () => {let frame: FrameRequestCallback | null = null;vi.spyOn(globalThis, "requestAnimationFrame").mockImplementation((callback) => {diff --git a/studio/src/player/components/timelineDragDrop.ts b/studio/src/player/components/timelineDragDrop.tsindex 8c9680fb..a2ff78d2 100644--- a/studio/src/player/components/timelineDragDrop.ts+++ b/studio/src/player/components/timelineDragDrop.ts@@ -1,5 +1,5 @@import { useCallback, useEffect, useRef, useState, type RefObject } from "react";-import { TIMELINE_ASSET_MIME, TIMELINE_BLOCK_MIME } from "../../utils/timelineAssetDrop";+import { parseTimelineAssetPayload, TIMELINE_ASSET_MIME, TIMELINE_BLOCK_MIME } from "../../utils/timelineAssetDrop";import {parseTimelineCompositionPayload,TIMELINE_COMPOSITION_MIME,@@ -290,7 +290,12 @@ export function useTimelineAssetDrop({}if (applyFileDrop(e.dataTransfer, onFileDrop, placement)) return;- if (applyTypedJsonDrop(e.dataTransfer, TIMELINE_ASSET_MIME, "path", onAssetDrop, placement)) {+ const asset = types.includes(TIMELINE_ASSET_MIME)+ ? parseTimelineAssetPayload(e.dataTransfer.getData(TIMELINE_ASSET_MIME)) : null;+ if (asset && onAssetDrop) {+ invokeDropCallback(() => asset.duration == null+ ? onAssetDrop(asset.path, placement)+ : onAssetDrop(asset.path, placement, asset.duration));return;}applyTypedJsonDrop(e.dataTransfer, TIMELINE_BLOCK_MIME, "name", onBlockDrop, placement);diff --git a/studio/src/player/store/pendingAssetDrops.ts b/studio/src/player/store/pendingAssetDrops.tsnew file mode 100644index 00000000..76efd84b--- /dev/null+++ b/studio/src/player/store/pendingAssetDrops.ts@@ -0,0 +1,58 @@+import type { TimelineElement } from "./timelineElement";+import type { TimelineDropPlacement } from "../components/timelineCallbacks";+import { usePlayerStore } from "./playerStore";+import { generateId } from "../../utils/generateId";+import { getTimelineAssetKind } from "../../utils/timelineAssetDrop";+import { resolveNearestFreeStart } from "../components/timelineCollision";++export interface PendingAssetDrop {+ id: string;+ assetPath: string;+ placement: TimelineDropPlacement;+ duration?: number;+ element?: TimelineElement;+ failed?: "add" | "preview";+}++export function beginPendingAssetDrop(+ assetPath: string,+ placement: TimelineDropPlacement,+ duration?: number,+): string {+ const id = generateId();+ usePlayerStore.setState((state) => {+ const kind = getTimelineAssetKind(assetPath);+ const pending = state.pendingAssetDrops.filter((drop) =>+ (!drop.failed || drop.element) && drop.placement.insertRow === placement.insertRow,+ ).map((drop) => drop.element ?? {+ id: drop.id, tag: getTimelineAssetKind(drop.assetPath) ?? "div",+ ...drop.placement, duration: drop.duration ?? 5,+ });+ const busy = [...(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, {+ id, assetPath, placement: { ...placement, start }, duration,+ }] };+ });+ return id;+}++export function updatePendingAssetDrop(id: string, patch: Partial<PendingAssetDrop>): void {+ usePlayerStore.setState((state) => ({+ pendingAssetDrops: state.pendingAssetDrops.map((drop) => drop.id === id ? { ...drop, ...patch } : drop),+ }));+}++export function dismissPendingAssetDrop(id: string): void {+ usePlayerStore.setState((state) => ({+ pendingAssetDrops: state.pendingAssetDrops.filter((drop) => drop.id !== id),+ }));+}++export function failPendingAssetPreviews(): void {+ usePlayerStore.setState((state) => ({+ pendingAssetDrops: state.pendingAssetDrops.map((drop) =>+ drop.element && !drop.failed ? { ...drop, failed: "preview" } : drop),+ }));+}diff --git a/studio/src/player/store/playerStore.ts b/studio/src/player/store/playerStore.tsindex 0588cb6c..891d4161 100644--- a/studio/src/player/store/playerStore.ts+++ b/studio/src/player/store/playerStore.ts@@ -26,18 +26,16 @@ import { patchElements, queueElementPatch } from "./elementPatchQueue";export type { KeyframeCacheEntry } from "./keyframeSlice";export { liveTime } from "./liveTime";import { liveTime } from "./liveTime";+import type { PendingAssetDrop } from "./pendingAssetDrops";export { createTimelineResetState };-import type {TimelineElement,TimelineElementPatch,SubCompositionHostState,} from "./timelineElement";-export type { TimelineElement, SubCompositionHostState };export type ZoomMode = "fit" | "manual";type TimelineTool = "select" | "razor";-export interface SelectElementOptions {preserveSet?: boolean;}@@ -77,6 +75,7 @@ interface PlayerState extends PlayerStoreSlices {/** True while a beat dot is being dragged — hides the playhead guideline. */beatDragging: boolean;elements: TimelineElement[];+ pendingAssetDrops: PendingAssetDrop[];selectedElementId: string | null;playbackRate: number;audioMuted: boolean;@@ -274,6 +273,7 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({timelineProjectId: null,beatDragging: false,elements: [],+ pendingAssetDrops: [],selectedElementId: null,playbackRate: readStudioUiPreferences().playbackRate ?? 1,audioMuted: readStudioUiPreferences().audioMuted ?? false,diff --git a/studio/src/player/store/timelineResetState.ts b/studio/src/player/store/timelineResetState.tsindex 8661277f..28301426 100644--- a/studio/src/player/store/timelineResetState.ts+++ b/studio/src/player/store/timelineResetState.ts@@ -2,6 +2,7 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import type { KeyframeCacheEntry } from "./keyframeSlice";import { resetPlaybackReadinessState } from "./readinessSlice";import type { SubCompositionHostState } from "./timelineElement";+import type { PendingAssetDrop } from "./pendingAssetDrops";export function createTimelineResetState() {return {@@ -11,6 +12,7 @@ export function createTimelineResetState() {...resetPlaybackReadinessState(),beatDragging: false,elements: [],+ pendingAssetDrops: [] as PendingAssetDrop[],selectedElementId: null,zEditVersion: 0,inPoint: null,diff --git a/studio/src/utils/studioHelpers.test.ts b/studio/src/utils/studioHelpers.test.tsindex 17984db3..346124de 100644--- a/studio/src/utils/studioHelpers.test.ts+++ b/studio/src/utils/studioHelpers.test.ts@@ -215,6 +215,30 @@ describe("dropped asset probes", () => {const NAME = "assets/50% off #1?'s take.mp4";const URL = "/api/projects/demo/preview/assets/50%25%20off%20%231%3F%27s%20take.mp4";+ it("shares an in-flight audio probe, reports timeout, and permits a fresh retry", async () => {+ vi.useFakeTimers();+ const createElement = document.createElement.bind(document);+ const probes: HTMLAudioElement[] = [];+ vi.spyOn(document, "createElement").mockImplementation((tag, options) => {+ const element = createElement(tag, options);+ if (tag === "audio") probes.push(element as HTMLAudioElement);+ return element;+ });+ const first = resolveDroppedAssetDuration("demo", "music.mp3", "audio");+ const second = resolveDroppedAssetDuration("demo", "music.mp3", "audio");+ expect(second).toBe(first);+ const failure = expect(first).rejects.toThrow("Could not read media duration");+ await vi.advanceTimersByTimeAsync(3000);+ await failure;+ expect(probes).toHaveLength(1);+ expect(probes[0].getAttribute("src")).toBe("");+ const retried = resolveDroppedAssetDuration("demo", "music.mp3", "audio");+ expect(probes).toHaveLength(2);+ Object.defineProperty(probes[1], "duration", { value: 22.42 });+ probes[1].dispatchEvent(new Event("loadedmetadata"));+ await expect(retried).resolves.toBe(22.42);+ });+it("probe a dropped file's length and size at its own URL", async () => {vi.useFakeTimers();const probes: HTMLVideoElement[] = [];@@ -226,10 +250,11 @@ describe("dropped asset probes", () => {});const duration = resolveDroppedAssetDuration("demo", NAME, "video");+ const durationFailed = expect(duration).rejects.toThrow("Could not read media duration");const size = resolveDroppedAssetDimensions("demo", NAME, "video");expect(probes.map((probe) => probe.getAttribute("src"))).toEqual([URL, URL]);await vi.advanceTimersByTimeAsync(3000);- await Promise.all([duration, size]);+ await Promise.all([durationFailed, size]);});});diff --git a/studio/src/utils/studioHelpers.ts b/studio/src/utils/studioHelpers.tsindex a0d72ef5..2b803126 100644--- a/studio/src/utils/studioHelpers.ts+++ b/studio/src/utils/studioHelpers.ts@@ -341,50 +341,61 @@ export function collectHtmlIds(source: string): string[] {return Array.from(source.matchAll(/\bid="([^"]+)"/g), (match) => match[1] ?? "");}-const DEFAULT_TIMELINE_ASSET_DURATION: Record<TimelineAssetKind, number> = {- image: 3,- video: 5,- audio: 5,-};+const pendingDurationProbes = new Map<string, Promise<number>>();-export async function resolveDroppedAssetDuration(+export function resolveDroppedAssetDuration(projectId: string,assetPath: string,kind: TimelineAssetKind,): Promise<number> {- if (kind === "image") return DEFAULT_TIMELINE_ASSET_DURATION.image;+ const key = JSON.stringify([projectId, assetPath, kind]);+ const pending = pendingDurationProbes.get(key);+ if (pending) return pending;+ const probe = probeDroppedAssetDuration(projectId, assetPath, kind).finally(() => {+ pendingDurationProbes.delete(key);+ });+ pendingDurationProbes.set(key, probe);+ return probe;+}++async function probeDroppedAssetDuration(+ projectId: string,+ assetPath: string,+ kind: TimelineAssetKind,+): Promise<number> {+ if (kind === "image") return 3;const media = document.createElement(kind === "video" ? "video" : "audio");media.preload = "metadata";- media.src = buildProjectApiPath(projectId, `/preview/${encodeUrlPath(assetPath)}`);- const duration = await new Promise<number>((resolve) => {- const timeout = window.setTimeout(() => resolve(DEFAULT_TIMELINE_ASSET_DURATION[kind]), 3000);- const finalize = (value: number) => {- window.clearTimeout(timeout);- resolve(value);- };+ try {+ return await new Promise<number>((resolve, reject) => {+ const fail = () => {+ window.clearTimeout(timeout);+ reject(new Error("Could not read media duration. Try adding the file again."));+ };+ const timeout = window.setTimeout(fail, 3000);+ const finalize = (value: number) => {+ window.clearTimeout(timeout);+ resolve(value);+ };- media.addEventListener(- "loadedmetadata",- () => {- const raw = Number(media.duration);- finalize(- Number.isFinite(raw) && raw > 0- ? roundToCenti(raw)- : DEFAULT_TIMELINE_ASSET_DURATION[kind],- );- },- { once: true },- );- media.addEventListener("error", () => finalize(DEFAULT_TIMELINE_ASSET_DURATION[kind]), {- once: true,+ media.addEventListener(+ "loadedmetadata",+ () => {+ const raw = Number(media.duration);+ if (Number.isFinite(raw) && raw > 0) finalize(roundToCenti(raw));+ else fail();+ },+ { once: true },+ );+ media.addEventListener("error", fail, { once: true });+ media.src = buildProjectApiPath(projectId, `/preview/${encodeUrlPath(assetPath)}`);});- });-- media.src = "";- media.load();- return duration;+ } finally {+ media.src = "";+ media.load();+ }}export function mediaMetadataUrl(projectId: string, assetPath: string): string {diff --git a/studio/src/utils/timelineAssetDrop.test.ts b/studio/src/utils/timelineAssetDrop.test.tsindex 246a5b51..ae6f5fdc 100644--- a/studio/src/utils/timelineAssetDrop.test.ts+++ b/studio/src/utils/timelineAssetDrop.test.ts@@ -7,11 +7,27 @@ import {fitTimelineAssetGeometry,getTimelineAssetKind,insertTimelineAssetIntoSource,+ parseTimelineAssetPayload,resolveTimelineAssetCompositionSize,resolveTimelineAssetSrc,setCompositionDurationToContent,} from "./timelineAssetDrop";+describe("parseTimelineAssetPayload", () => {+ it("keeps valid known durations and ignores invalid duration hints", () => {+ expect(parseTimelineAssetPayload('{"path":"music.mp3","duration":12.5}')).toEqual({ path: "music.mp3", duration: 12.5 });+ for (const duration of [0, -1, "12", null]) {+ expect(parseTimelineAssetPayload(JSON.stringify({ path: "music.mp3", duration })))+ .toEqual({ path: "music.mp3", duration: undefined });+ }+ });+ it("rejects malformed payloads before accepting a drop", () => {+ for (const raw of ["no json", "null", "{}", '{"path":12}', '{"path":""}']) {+ expect(parseTimelineAssetPayload(raw)).toBeNull();+ }+ });+});+describe("setCompositionDurationToContent", () => {const src = (dur: number) =>`<div id="root" data-composition-id="c" data-duration="${dur}">x</div>`;diff --git a/studio/src/utils/timelineAssetDrop.ts b/studio/src/utils/timelineAssetDrop.tsindex 14186263..eb55e174 100644--- a/studio/src/utils/timelineAssetDrop.ts+++ b/studio/src/utils/timelineAssetDrop.ts@@ -11,6 +11,18 @@ const FALLBACK_TIMELINE_FILE_DROP_DURATION = 5;export type TimelineAssetKind = "image" | "video" | "audio";+export function parseTimelineAssetPayload(raw: string): { path: string; duration?: number } | null {+ try {+ const value = JSON.parse(raw) as { path?: unknown; duration?: unknown } | null;+ if (!value || typeof value.path !== "string" || !value.path) return null;+ const duration = typeof value.duration === "number" && Number.isFinite(value.duration) && value.duration > 0+ ? value.duration : undefined;+ return { path: value.path, duration };+ } catch {+ return null;+ }+}+export function getTimelineAssetKind(assetPath: string): TimelineAssetKind | null {if (IMAGE_EXT.test(assetPath)) return "image";if (VIDEO_EXT.test(assetPath)) return "video";