Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): select and reveal a timeline clip after a drop (#4067)
Miguel Ángel42f947f4c336
diff --git a/packages/studio/src/hooks/useBlockHandlers.ts b/packages/studio/src/hooks/useBlockHandlers.tsindex 368de32027..c857ceacfb 100644--- a/packages/studio/src/hooks/useBlockHandlers.ts+++ b/packages/studio/src/hooks/useBlockHandlers.ts@@ -6,6 +6,7 @@ import { useCallback, useMemo, useRef, useState } from "react";import type { TimelineElement } from "../player";import { usePlayerStore } from "../player";import { addBlockToProject } from "../utils/blockInstaller";+import { selectAndRevealTimelineElement } from "../player/components/timelineDropReveal";import type { BlockParam } from "@hyperframes/core/registry";import type { EditHistoryKind } from "../utils/editHistory";import type { RightPanelTab } from "../utils/studioHelpers";@@ -148,7 +149,9 @@ export function useBlockHandlers({previewIframe: previewIframeRef.current,currentTime: usePlayerStore.getState().currentTime,}),- );+ ).then((result) => {+ if (result) selectAndRevealTimelineElement(result.hostKey);+ });},[projectId, blockCtx, previewIframeRef, runBlockInstall],);@@ -184,7 +187,9 @@ export function useBlockHandlers({previewIframe: previewIframeRef.current,currentTime: usePlayerStore.getState().currentTime,}),- );+ ).then((result) => {+ if (result) selectAndRevealTimelineElement(result.hostKey);+ });},[projectId, blockCtx, previewIframeRef, runBlockInstall],);diff --git a/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx b/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsxindex 4ecf87ac15..623a0c6abd 100644--- a/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx+++ b/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx@@ -4,12 +4,14 @@ import React, { act } from "react";import { afterEach, describe, expect, it, vi } from "vitest";import { useTimelineAssetDropOps } from "./useTimelineAssetDropOps";import { mountReactHarness } from "./domSelectionTestHarness";+import { usePlayerStore } from "../player/store/playerStore";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;afterEach(() => {document.body.innerHTML = "";vi.unstubAllGlobals();+ usePlayerStore.getState().reset();});type DropFn = ReturnType<typeof useTimelineAssetDropOps>["handleTimelineAssetDrop"];@@ -69,4 +71,17 @@ describe("useTimelineAssetDropOps handleTimelineAssetDrop", () => {const [, written] = writeProjectFile.mock.calls[0] as [string, string];expect(written).toContain('data-duration="10"');});++ it("selects and reveals the newly dropped clip", async () => {+ const source =+ '<main data-composition-id="scene" data-duration="10" data-width="1920" data-height="1080"></main>';+ const writeProjectFile = vi.fn().mockResolvedValue(undefined);+ const getDrop = renderDropHook(source, writeProjectFile);++ await act(async () => {+ await getDrop()("clip.mp4", { start: 1, track: 0 }, 2);+ });++ expect(usePlayerStore.getState().selectedElementId).toBe("index.html#clip");+ });});diff --git a/packages/studio/src/hooks/useTimelineAssetDropOps.ts b/packages/studio/src/hooks/useTimelineAssetDropOps.tsindex 6aaafec755..3b2c30fd7f 100644--- a/packages/studio/src/hooks/useTimelineAssetDropOps.ts+++ b/packages/studio/src/hooks/useTimelineAssetDropOps.ts@@ -21,7 +21,8 @@ import { formatTimelineAttributeNumber } from "./timelineEditingHelpers";import { readFileContent } from "./timelineTimingSync";import { commitTimelineCompositionInsertion } from "../utils/timelineCompositionInsert";import { extendRootDurationInSource } from "../utils/rootDuration";-import { usePlayerStore } from "../player";+import { deriveTimelineStoreKeyForDomId } from "../player/lib/timelineElementHelpers";+import { selectAndRevealTimelineElement } from "../player/components/timelineDropReveal";interface UseTimelineAssetDropOpsOptions {projectIdRef: MutableRefObject<string | null>;@@ -121,6 +122,7 @@ export function useTimelineAssetDropOps({recordEdit,});+ selectAndRevealTimelineElement(deriveTimelineStoreKeyForDomId(newId, targetPath));forceReloadSdkSession?.();reloadPreview();} catch (error) {@@ -194,7 +196,7 @@ export function useTimelineAssetDropOps({writeFile: writeProjectFile,recordEdit,observeVersion: observeProjectFileVersion,- selectHost: (key) => usePlayerStore.getState().setSelectedElementId(key),+ selectHost: selectAndRevealTimelineElement,resync: forceReloadSdkSession,refresh: reloadPreview,});diff --git a/packages/studio/src/hooks/useTimelineSelectionPreviewSync.test.tsx b/packages/studio/src/hooks/useTimelineSelectionPreviewSync.test.tsxindex aa2922fe01..93672b9eac 100644--- a/packages/studio/src/hooks/useTimelineSelectionPreviewSync.test.tsx+++ b/packages/studio/src/hooks/useTimelineSelectionPreviewSync.test.tsx@@ -175,7 +175,70 @@ describe("useTimelineSelectionPreviewSync", () => {harness.cleanup();});- it("warns once while retrying a timeline selection after preview refreshes", async () => {+ it("does not clear the selection when the selected clip is not in timelineElements yet", async () => {+ // A freshly-dropped clip is selected before the reload that adds it to+ // timelineElements has completed. Bailing quietly here (like the+ // DOM-node-not-ready case above) lets the later effect run, once the+ // element exists, apply the selection instead of wiping it.+ const { timelineElements } = makeSyncFixture();+ const applyDomSelection = vi.fn();+ const applyMarqueeSelection = vi.fn();+ const onSelectionNotFound = vi.fn();+ const buildDomSelectionForTimelineElement = vi.fn(async () => null);+ const harness = renderHarness();++ await harness.rerender({+ selectedElementId: "clip-3",+ selectedElementIds: new Set(["clip-3"]),+ timelineElements,+ domEditSelection: null,+ domEditGroupSelections: [],+ buildDomSelectionForTimelineElement,+ applyDomSelection,+ applyMarqueeSelection,+ onSelectionNotFound,+ });++ // Still within the retry grace window: quiet, not yet a warning.+ expect(onSelectionNotFound).not.toHaveBeenCalled();+ expect(applyDomSelection).not.toHaveBeenCalled();+ harness.cleanup();+ });++ it("does not shrink a pasted or duplicated group's selection when only some members have appeared yet", async () => {+ // Paste/duplicate of a group selects every new id up front; one member+ // (clip-1) is already in timelineElements, the other (a fresh paste/dup+ // target, "clip-3") is not yet. Applying only the resolved member would+ // silently drop the rest of the group from the store.+ const { firstSelection, timelineElements, selectionById } = makeSyncFixture();+ const applyDomSelection = vi.fn();+ const applyMarqueeSelection = vi.fn();+ const onSelectionNotFound = vi.fn();+ const buildDomSelectionForTimelineElement = vi.fn(async (element: TimelineElement) => {+ return selectionById.get(element.id) ?? firstSelection;+ });+ const harness = renderHarness();++ await harness.rerender({+ selectedElementId: "clip-1",+ selectedElementIds: new Set(["clip-1", "clip-3"]),+ timelineElements,+ domEditSelection: null,+ domEditGroupSelections: [],+ buildDomSelectionForTimelineElement,+ applyDomSelection,+ applyMarqueeSelection,+ onSelectionNotFound,+ });++ // Still within the retry grace window: quiet, not yet a warning.+ expect(onSelectionNotFound).not.toHaveBeenCalled();+ expect(applyDomSelection).not.toHaveBeenCalled();+ expect(applyMarqueeSelection).not.toHaveBeenCalled();+ harness.cleanup();+ });++ it("stays quiet through retries and resolves once the preview refreshes", async () => {const { secondSelection, timelineElements } = makeSyncFixture();const applyDomSelection = vi.fn();const applyMarqueeSelection = vi.fn();@@ -199,7 +262,7 @@ describe("useTimelineSelectionPreviewSync", () => {onSelectionNotFound,});- expect(onSelectionNotFound).toHaveBeenCalledOnce();+ expect(onSelectionNotFound).not.toHaveBeenCalled();expect(applyDomSelection).not.toHaveBeenCalled();await harness.rerender({@@ -214,7 +277,7 @@ describe("useTimelineSelectionPreviewSync", () => {onSelectionNotFound,});- expect(onSelectionNotFound).toHaveBeenCalledOnce();+ expect(onSelectionNotFound).not.toHaveBeenCalled();previewReady = true;await harness.rerender({@@ -230,6 +293,102 @@ describe("useTimelineSelectionPreviewSync", () => {});expect(applyDomSelection).toHaveBeenCalledWith(secondSelection);+ expect(onSelectionNotFound).not.toHaveBeenCalled();+ harness.cleanup();+ });++ it("degrades to the resolvable subset once a group member never resolves", async () => {+ // clip-2 is a permanent hold-out (deleted out of band, a stale id, or+ // anything else that will never build a selection). Retrying forever+ // would leave the whole group's selection stuck; after a few attempts,+ // apply the members that did resolve instead.+ const { firstSelection, timelineElements } = makeSyncFixture();+ const applyDomSelection = vi.fn();+ const applyMarqueeSelection = vi.fn();+ const onSelectionNotFound = vi.fn();+ const buildDomSelectionForTimelineElement = vi.fn(async (element: TimelineElement) =>+ element.id === "clip-1" ? firstSelection : null,+ );+ const selectedElementIds = new Set(["clip-1", "clip-2"]);+ const harness = renderHarness();++ for (let attempt = 0; attempt < 4; attempt++) {+ await harness.rerender({+ selectedElementId: "clip-1",+ selectedElementIds,+ timelineElements: [...timelineElements],+ domEditSelection: null,+ domEditGroupSelections: [],+ buildDomSelectionForTimelineElement,+ applyDomSelection,+ applyMarqueeSelection,+ onSelectionNotFound,+ });+ }++ expect(onSelectionNotFound).toHaveBeenCalledOnce();+ expect(applyDomSelection).toHaveBeenCalledWith(firstSelection);+ expect(applyMarqueeSelection).not.toHaveBeenCalled();+ harness.cleanup();+ });++ it("gives a fresh retry budget after deselecting a permanently-unresolvable selection", async () => {+ // Same permanent hold-out as the test above, but the user deselects and+ // reselects the exact same group afterward. Without resetting the retry+ // budget on deselect, reselecting the same key resumes an already-+ // exhausted count and degrades on the very first attempt with no warning.+ const { firstSelection, timelineElements } = makeSyncFixture();+ const applyDomSelection = vi.fn();+ const applyMarqueeSelection = vi.fn();+ const onSelectionNotFound = vi.fn();+ const buildDomSelectionForTimelineElement = vi.fn(async (element: TimelineElement) =>+ element.id === "clip-1" ? firstSelection : null,+ );+ const selectedElementIds = new Set(["clip-1", "clip-2"]);+ const harness = renderHarness();++ for (let attempt = 0; attempt < 4; attempt++) {+ await harness.rerender({+ selectedElementId: "clip-1",+ selectedElementIds,+ timelineElements: [...timelineElements],+ domEditSelection: null,+ domEditGroupSelections: [],+ buildDomSelectionForTimelineElement,+ applyDomSelection,+ applyMarqueeSelection,+ onSelectionNotFound,+ });+ }+ expect(onSelectionNotFound).toHaveBeenCalledOnce();++ await harness.rerender({+ selectedElementId: null,+ selectedElementIds: new Set(),+ timelineElements: [...timelineElements],+ domEditSelection: null,+ domEditGroupSelections: [],+ buildDomSelectionForTimelineElement,+ applyDomSelection,+ applyMarqueeSelection,+ onSelectionNotFound,+ });++ for (let attempt = 0; attempt < 4; attempt++) {+ await harness.rerender({+ selectedElementId: "clip-1",+ selectedElementIds,+ timelineElements: [...timelineElements],+ domEditSelection: null,+ domEditGroupSelections: [],+ buildDomSelectionForTimelineElement,+ applyDomSelection,+ applyMarqueeSelection,+ onSelectionNotFound,+ });+ }++ expect(onSelectionNotFound).toHaveBeenCalledTimes(2);harness.cleanup();});});diff --git a/packages/studio/src/hooks/useTimelineSelectionPreviewSync.ts b/packages/studio/src/hooks/useTimelineSelectionPreviewSync.tsindex 79752e3f64..4359f78c40 100644--- a/packages/studio/src/hooks/useTimelineSelectionPreviewSync.ts+++ b/packages/studio/src/hooks/useTimelineSelectionPreviewSync.ts@@ -3,6 +3,7 @@ import type { TimelineElement } from "../player";import type { DomEditSelection } from "../components/editor/domEditing";import { resolveTimelineIdForSelection } from "../utils/studioHelpers";import { logSelect } from "../utils/selectDebug";+import { recordRetryAttempt, type RetryBudgetState } from "../utils/retryBudget";interface UseTimelineSelectionPreviewSyncParams {selectedElementId: string | null;@@ -27,6 +28,12 @@ interface UseTimelineSelectionPreviewSyncParams {onSelectionNotFound: () => void;}+// A member still resolving (a just-dropped/pasted/duplicated clip, or a preview+// still reloading) heals within a few retries. One that never will (deleted out+// of band, a stale id) would otherwise bail forever; past this cap, apply+// whatever did resolve instead of leaving the group selection stuck.+const MAX_UNRESOLVED_SYNC_RETRIES = 3;+function orderSelectedIds(ids: Set<string>, anchor: string | null): string[] {const ordered = [...ids];if (!anchor || !ids.has(anchor)) return ordered;@@ -63,6 +70,35 @@ function anchorIsOutsideSelection(anchor: string | null, selectedIds: string[]):return anchor !== null && !selectedIds.includes(anchor);}+async function resolveSelectionsForIds(+ ids: string[],+ timelineElements: TimelineElement[],+ buildDomSelectionForTimelineElement: UseTimelineSelectionPreviewSyncParams["buildDomSelectionForTimelineElement"],+): Promise<DomEditSelection[]> {+ const selections: DomEditSelection[] = [];+ for (const id of ids) {+ const element = timelineElements.find((item) => (item.key ?? item.id) === id);+ if (!element) continue;+ const selection = await buildDomSelectionForTimelineElement(element);+ if (selection) selections.push(selection);+ }+ return selections;+}++function applyResolvedSelections(+ selections: DomEditSelection[],+ applyDomSelection: UseTimelineSelectionPreviewSyncParams["applyDomSelection"],+ applyMarqueeSelection: UseTimelineSelectionPreviewSyncParams["applyMarqueeSelection"],+): void {+ if (selections.length === 0) {+ applyDomSelection(null, { revealPanel: false });+ } else if (selections.length === 1) {+ applyDomSelection(selections[0]);+ } else {+ applyMarqueeSelection(selections, false);+ }+}+export function useTimelineSelectionPreviewSync({selectedElementId,selectedElementIds,@@ -84,6 +120,7 @@ export function useTimelineSelectionPreviewSync({const domEditGroupSelectionsRef = useRef(domEditGroupSelections);const lastSyncedSelectedKeyRef = useRef("");const missingSelectionKeyRef = useRef("");+ const unresolvedAttemptsRef = useRef<RetryBudgetState<string>>({ id: "", count: 0 });domEditSelectionRef.current = domEditSelection;domEditGroupSelectionsRef.current = domEditGroupSelections;@@ -109,6 +146,10 @@ export function useTimelineSelectionPreviewSync({if (selectedIds.length === 0) {missingSelectionKeyRef.current = "";+ // A deselect is the one unambiguous "new attempt" signal: without it, reselecting the+ // same permanently-unresolvable id later picks up an already-exhausted retry budget+ // and skips straight to the degraded fallback instead of getting a fresh grace window.+ unresolvedAttemptsRef.current = { id: "", count: 0 };// The timeline holds nothing, so the canvas is about to hold nothing either.// This is the path that silently drops a selection the user can still see.logSelect("timeline-empty", {@@ -134,46 +175,35 @@ export function useTimelineSelectionPreviewSync({onSelectionNotFound();};const syncSelection = async () => {- const selections: DomEditSelection[] = [];- let resolvableCount = 0;- for (const id of selectedIds) {- const element = timelineElements.find((item) => (item.key ?? item.id) === id);- if (!element) continue;- resolvableCount += 1;- const selection = await buildDomSelectionForTimelineElement(element);- if (selection) selections.push(selection);- }+ const selections = await resolveSelectionsForIds(+ selectedIds,+ timelineElements,+ buildDomSelectionForTimelineElement,+ );if (cancelled) return;- // The store is the source of truth: applying a partial set would write that- // shrunk set back and silently drop the members whose DOM node was not ready.- // Bail instead; a later effect run (on timelineElements/DOM change) applies the- // full set once every resolvable member has a live node.- if (selections.length < resolvableCount) {- warnSelectionMissingOnce();- // Bailing keeps whatever the canvas already held, and Delete acts on the- // canvas first — so an anchor pointing OUTSIDE this selection is an- // element the user is no longer looking at, and deleting it is the- // damage. Only that goes: a member still resolving has no anchor of its- // own here and is left for the later run. Quietly, because announcing- // the clear would deselect the clip that was just picked.- if (anchorIsOutsideSelection(currentAnchor, selectedIds)) {- applyDomSelection(null, { revealPanel: false, announce: false });+ if (selections.length < selectedIds.length) {+ if (recordRetryAttempt(unresolvedAttemptsRef, selectedKey, MAX_UNRESOLVED_SYNC_RETRIES)) {+ // Still within the retry grace window: stay quiet (warn only once+ // exhausted, below). Delete acts on the canvas first, so only an+ // anchor OUTSIDE this selection is cleared here, quietly.+ if (anchorIsOutsideSelection(currentAnchor, selectedIds)) {+ applyDomSelection(null, { revealPanel: false, announce: false });+ }+ return;}- return;+ // Budget exhausted: warn once (missingSelectionKeyRef dedupes further+ // reruns of this same still-unresolved key) and apply whatever did resolve.+ warnSelectionMissingOnce();+ } else {+ unresolvedAttemptsRef.current = { id: "", count: 0 };+ missingSelectionKeyRef.current = "";}- missingSelectionKeyRef.current = "";logSelect("timeline-sync", {wanted: selectedIds.length,had: currentIds.length,resolved: selections.length,});- if (selections.length === 0) {- applyDomSelection(null, { revealPanel: false });- } else if (selections.length === 1) {- applyDomSelection(selections[0]);- } else {- applyMarqueeSelection(selections, false);- }+ applyResolvedSelections(selections, applyDomSelection, applyMarqueeSelection);};void syncSelection();diff --git a/packages/studio/src/player/components/timelineDropReveal.test.ts b/packages/studio/src/player/components/timelineDropReveal.test.tsnew file mode 100644index 0000000000..69fdd0da82--- /dev/null+++ b/packages/studio/src/player/components/timelineDropReveal.test.ts@@ -0,0 +1,34 @@+// @vitest-environment happy-dom++import { beforeEach, describe, expect, it } from "vitest";+import { usePlayerStore } from "../store/playerStore";+import { timelineClipFocusId } from "./timelineNavigationIdentity";+import { selectAndRevealTimelineElement } from "./timelineDropReveal";++beforeEach(() => {+ usePlayerStore.getState().reset();+});++describe("selectAndRevealTimelineElement", () => {+ it("selects the element and requests a scroll-to-focus on the same key", () => {+ selectAndRevealTimelineElement("index.html#clip-1");++ expect(usePlayerStore.getState().selectedElementId).toBe("index.html#clip-1");+ expect(usePlayerStore.getState().timelineFocus?.id).toBe(+ timelineClipFocusId("index.html#clip-1"),+ );+ });++ it("moves the focus request to the new element when called again", () => {+ selectAndRevealTimelineElement("index.html#clip-1");+ const firstNonce = usePlayerStore.getState().timelineFocus?.nonce;++ selectAndRevealTimelineElement("index.html#clip-2");++ expect(usePlayerStore.getState().selectedElementId).toBe("index.html#clip-2");+ expect(usePlayerStore.getState().timelineFocus?.id).toBe(+ timelineClipFocusId("index.html#clip-2"),+ );+ expect(usePlayerStore.getState().timelineFocus?.nonce).not.toBe(firstNonce);+ });+});diff --git a/packages/studio/src/player/components/timelineDropReveal.ts b/packages/studio/src/player/components/timelineDropReveal.tsnew file mode 100644index 0000000000..fc117f0350--- /dev/null+++ b/packages/studio/src/player/components/timelineDropReveal.ts@@ -0,0 +1,12 @@+import { usePlayerStore } from "../store/playerStore";+import { timelineClipFocusId } from "./timelineNavigationIdentity";++/**+ * Select a newly-created clip and scroll the timeline to it, the same pair of+ * calls AssetCard/AudioRow use to reveal an existing clip on activation.+ */+export function selectAndRevealTimelineElement(key: string): void {+ const store = usePlayerStore.getState();+ store.setSelectedElementId(key);+ store.requestTimelineFocus(timelineClipFocusId(key));+}diff --git a/packages/studio/src/player/components/useTimelineFocusCoordinator.test.tsx b/packages/studio/src/player/components/useTimelineFocusCoordinator.test.tsxindex 32439881cb..10fa3ae243 100644--- a/packages/studio/src/player/components/useTimelineFocusCoordinator.test.tsx+++ b/packages/studio/src/player/components/useTimelineFocusCoordinator.test.tsx@@ -35,12 +35,16 @@ function Harness({mountedId,logicalRows = rows,projectId = "project-a",+ lastScrollLeftRef: sharedLastScrollLeftRef,}: {mountedId?: string;logicalRows?: readonly TimelineLogicalRow[];projectId?: string;+ lastScrollLeftRef?: React.RefObject<number>;}) {const scrollRef = useRef<HTMLDivElement>(null);+ const ownLastScrollLeftRef = useRef(0);+ const lastScrollLeftRef = sharedLastScrollLeftRef ?? ownLastScrollLeftRef;const rowGeometry = useMemo(() => {const rowKeys = [...new Set(logicalRows.map((row) => row.physicalTrackKey))];return createTimelineRowGeometry(@@ -60,6 +64,7 @@ function Harness({projectId,sessionEpoch: 1,syncScrollViewport,+ lastScrollLeftRef,});return (<div@@ -171,4 +176,65 @@ describe("useTimelineFocusCoordinator", () => {expect(usePlayerStore.getState().timelineFocus?.id).toBe(nextRowId);expect(document.activeElement?.getAttribute("data-timeline-focus-id")).toBe(nextRowId);});++ it("keeps a request alive across a few renders where its target hasn't landed yet", async () => {+ // A request issued the same tick as its own element's creation (a fresh+ // drop) can race logicalRows by a render or two; it must not be dropped+ // before the element actually appears.+ usePlayerStore.getState().requestTimelineFocus(clipId);+ for (let attempt = 0; attempt < 2; attempt++) {+ const notYetRows: readonly TimelineLogicalRow[] = [{ ...rows[0]!, items: [] }];+ await act(async () => root.render(<Harness logicalRows={notYetRows} />));+ }+ expect(usePlayerStore.getState().timelineFocus?.id).toBe(clipId);++ await act(async () => root.render(<Harness logicalRows={rows} mountedId={clipId} />));+ expect(usePlayerStore.getState().timelineFocus?.id).toBe(clipId);+ expect(document.activeElement?.getAttribute("data-timeline-focus-id")).toBe(clipId);+ });++ it("gives up once a target never lands after its retry budget", async () => {+ usePlayerStore.getState().requestTimelineFocus(clipId);+ for (let attempt = 0; attempt < 6; attempt++) {+ // A fresh array reference each render, like a real re-render caused by+ // unrelated state, or the memoized resolution never recomputes at all.+ const neverRows: readonly TimelineLogicalRow[] = [{ ...rows[0]!, items: [] }];+ await act(async () => root.render(<Harness logicalRows={neverRows} />));+ }+ expect(usePlayerStore.getState().timelineFocus).toBeNull();+ });++ it("clears an unresolved request on a timeout even if nothing else ever re-renders", async () => {+ // The render-count retry budget can't advance without a rerun; if the+ // target never lands and nothing else re-renders, only a wall-time+ // backstop clears it — otherwise it sits forever, eligible to resolve+ // against an unrelated element that later reuses its id.+ vi.useFakeTimers();+ try {+ usePlayerStore.getState().requestTimelineFocus(clipId);+ const neverRows: readonly TimelineLogicalRow[] = [{ ...rows[0]!, items: [] }];+ await act(async () => root.render(<Harness logicalRows={neverRows} />));+ expect(usePlayerStore.getState().timelineFocus?.id).toBe(clipId);++ await act(async () => {+ vi.advanceTimersByTime(4001);+ });++ expect(usePlayerStore.getState().timelineFocus).toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });++ it("keeps lastScrollLeftRef in sync with a reveal so a sibling restore effect doesn't undo it", async () => {+ // Timeline.tsx's own "restore scroll after an edit re-derives the elements"+ // effect reads this ref to decide what to scroll back to. A reveal that+ // doesn't update it looks, to that effect, like scroll drift to undo.+ const lastScrollLeftRef = { current: 999 };+ usePlayerStore.getState().requestTimelineFocus(clipId);+ await act(async () => root.render(<Harness lastScrollLeftRef={lastScrollLeftRef} />));+ const scroll = host.firstElementChild as HTMLDivElement;++ expect(lastScrollLeftRef.current).toBe(scroll.scrollLeft);+ });});diff --git a/packages/studio/src/player/components/useTimelineFocusCoordinator.ts b/packages/studio/src/player/components/useTimelineFocusCoordinator.tsindex 3f678d4909..6e20247ce0 100644--- a/packages/studio/src/player/components/useTimelineFocusCoordinator.ts+++ b/packages/studio/src/player/components/useTimelineFocusCoordinator.ts@@ -11,6 +11,7 @@ import {type TimelineLogicalTarget,} from "./timelineKeyboardNavigation";import { computeRevealScroll } from "./timelineRevealScroll";+import { recordRetryAttempt, type RetryBudgetState } from "../../utils/retryBudget";interface TimelineFocusCoordinatorInput {scrollRef: RefObject<HTMLDivElement | null>;@@ -24,6 +25,7 @@ interface TimelineFocusCoordinatorInput {projectId: string | null;sessionEpoch: number;syncScrollViewport: (element: HTMLDivElement) => void;+ lastScrollLeftRef: RefObject<number>;}export interface TimelineFocusCoordinatorState {@@ -77,6 +79,7 @@ function scrollToTarget(pixelsPerSecond: number,contentOrigin: number,allowHorizontal: boolean,+ lastScrollLeftRef: RefObject<number>,): boolean {const rowIndex = rowGeometry.getRowIndex(resolution.row.physicalTrackKey);if (rowIndex < 0) return false;@@ -103,11 +106,26 @@ function scrollToTarget(stickyTop: RULER_H,allowHorizontal: allowHorizontal && left !== null,});- if (target.left !== null) container.scrollLeft = target.left;+ if (target.left !== null) {+ container.scrollLeft = target.left;+ // Keep the geometry effect's "restore scroll after an edit re-derives the+ // elements" in sync, or it reads the pre-reveal position on the next tick+ // and scrolls the freshly-revealed clip back out of view.+ lastScrollLeftRef.current = target.left;+ }if (target.top !== null) container.scrollTop = target.top;return target.left !== null || target.top !== null;}+// A request racing a fresh element's own creation (drop/paste) resolves within+// a render or two; past this many misses on the same nonce it truly never will.+const MAX_UNRESOLVED_FOCUS_RETRIES = 5;++// Backstop for a request whose target never appears and nothing else ever+// re-renders: the retry budget above can't advance without a rerun, so this+// bounds it by wall time instead, independent of re-renders.+const UNRESOLVED_FOCUS_TIMEOUT_MS = 4000;+/** Model-first focus actor; mounting is a consequence of its returned pins. */// Resolution, fallback, reveal, and focus form one ordered state machine.// fallow-ignore-next-line complexity@@ -123,11 +141,13 @@ export function useTimelineFocusCoordinator({projectId,sessionEpoch,syncScrollViewport,+ lastScrollLeftRef,}: TimelineFocusCoordinatorInput): TimelineFocusCoordinatorState {const request = usePlayerStore((state) => state.timelineFocus);const previousRowsRef = useRef(logicalRows);const resolvedRef = useRef<{ nonce: number; id: string } | null>(null);const appliedRef = useRef<{ nonce: number; id: string } | null>(null);+ const unresolvedFocusAttemptsRef = useRef<RetryBudgetState<number>>({ id: -1, count: 0 });const resolution = useMemo<ResolvedFocus | null>(() => {if (isCurrentRequest(request, projectId, sessionEpoch)) {if (resolvedRef.current?.nonce !== request.nonce) {@@ -163,8 +183,26 @@ export function useTimelineFocusCoordinator({useEffect(() => {if (!isCurrentRequest(request, projectId, sessionEpoch)) return;if (!resolution) {- usePlayerStore.getState().clearTimelineFocus(request.nonce);- return;+ // A request issued the same tick as its element (a fresh drop/paste) can+ // outrun logicalRows by a render or two; only give up once it clearly+ // never resolves, so the reveal isn't lost to that ordinary race.+ const withinBudget = recordRetryAttempt(+ unresolvedFocusAttemptsRef,+ request.nonce,+ MAX_UNRESOLVED_FOCUS_RETRIES,+ );+ if (!withinBudget) {+ usePlayerStore.getState().clearTimelineFocus(request.nonce);+ return;+ }+ const nonce = request.nonce;+ const timeout = setTimeout(() => {+ usePlayerStore.getState().clearTimelineFocus(nonce);+ }, UNRESOLVED_FOCUS_TIMEOUT_MS);+ return () => clearTimeout(timeout);+ }+ if (unresolvedFocusAttemptsRef.current.count !== 0) {+ unresolvedFocusAttemptsRef.current = { id: -1, count: 0 };}if (resolution.target.id !== request.id) {usePlayerStore.getState().requestTimelineFocus(resolution.target.id);@@ -187,6 +225,7 @@ export function useTimelineFocusCoordinator({pixelsPerSecond,contentOrigin,allowHorizontal,+ lastScrollLeftRef,)) {syncScrollViewport(container);@@ -197,6 +236,7 @@ export function useTimelineFocusCoordinator({allowHorizontal,contentOrigin,elements,+ lastScrollLeftRef,pixelsPerSecond,projectId,request,diff --git a/packages/studio/src/player/components/useTimelineGeometry.test.tsx b/packages/studio/src/player/components/useTimelineGeometry.test.tsxnew file mode 100644index 0000000000..8d486f50ca--- /dev/null+++ b/packages/studio/src/player/components/useTimelineGeometry.test.tsx@@ -0,0 +1,117 @@+// @vitest-environment happy-dom++import React, { act, useRef } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { usePlayerStore, type TimelineElement } from "../store/playerStore";+import { useTimelineGeometry } from "./useTimelineGeometry";++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });++const element: TimelineElement = { id: "hero", tag: "div", start: 20, duration: 2, track: 1 };++const nextFrame = () => new Promise<number>((resolve) => requestAnimationFrame(resolve));++function Harness({+ expandedElements,+ lastScrollLeftRef,+ scrollWidth = 20_000,+}: {+ expandedElements: TimelineElement[];+ lastScrollLeftRef: React.RefObject<number>;+ scrollWidth?: number;+}) {+ const scrollRef = useRef<HTMLDivElement>(null);+ const isDragging = useRef(false);+ const ppsRef = useRef(0);+ const fitPpsRef = useRef(0);+ useTimelineGeometry({+ viewportWidth: 1600,+ effectiveDuration: 60,+ zoomMode: "manual",+ manualZoomPercent: 100,+ ppsRef,+ fitPpsRef,+ draggedClip: null,+ resizingClip: null,+ expandedElements,+ isDragging,+ scrollRef,+ lastScrollLeftRef,+ contentOrigin: 32,+ });+ return (+ <div+ ref={(node) => {+ scrollRef.current = node;+ if (node) {+ Object.defineProperty(node, "clientWidth", { configurable: true, value: 1600 });+ Object.defineProperty(node, "scrollWidth", { configurable: true, value: scrollWidth });+ }+ }}+ />+ );+}++let host: HTMLDivElement;+let root: Root;+beforeEach(() => {+ usePlayerStore.setState({ timelineProjectId: "project-a" });+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ usePlayerStore.getState().reset();+ document.body.replaceChildren();+});++describe("useTimelineGeometry restore-scroll effect", () => {+ it("reads lastScrollLeftRef at frame time, not effect time, so a same-commit reveal isn't undone", async () => {+ // A sibling effect in the same commit (a fresh timeline-focus reveal) can+ // update lastScrollLeftRef and the DOM scrollLeft together after this+ // effect has already scheduled its frame. The frame must see that update,+ // not the value that was current when it was scheduled.+ const lastScrollLeftRef = { current: 132 };+ act(() => {+ root.render(<Harness expandedElements={[]} lastScrollLeftRef={lastScrollLeftRef} />);+ });+ const scroll = host.firstElementChild as HTMLDivElement;+ scroll.scrollLeft = 132;++ // Flush this effect (it schedules a frame, capturing whatever it reads+ // right now) BEFORE the sibling mutates the ref, exactly as in a real+ // commit where this effect registers and runs ahead of the reveal's.+ act(() => {+ root.render(<Harness expandedElements={[element]} lastScrollLeftRef={lastScrollLeftRef} />);+ });+ // Simulate the sibling reveal effect: it runs after this one in the same+ // commit and updates both the DOM and the ref before the frame fires.+ lastScrollLeftRef.current = 450;+ scroll.scrollLeft = 450;+ await act(async () => {+ await nextFrame();+ });++ expect(scroll.scrollLeft).toBe(450);+ });++ it("still restores the pre-edit position when nothing else changed the ref mid-frame", async () => {+ const lastScrollLeftRef = { current: 300 };+ act(() => {+ root.render(<Harness expandedElements={[]} lastScrollLeftRef={lastScrollLeftRef} />);+ });+ const scroll = host.firstElementChild as HTMLDivElement;+ scroll.scrollLeft = 0;++ act(() => {+ root.render(<Harness expandedElements={[element]} lastScrollLeftRef={lastScrollLeftRef} />);+ });+ await act(async () => {+ await nextFrame();+ });++ expect(scroll.scrollLeft).toBe(300);+ });+});diff --git a/packages/studio/src/player/components/useTimelineGeometry.ts b/packages/studio/src/player/components/useTimelineGeometry.tsindex 3c147718c3..52d0a28647 100644--- a/packages/studio/src/player/components/useTimelineGeometry.ts+++ b/packages/studio/src/player/components/useTimelineGeometry.ts@@ -93,9 +93,14 @@ export function useTimelineGeometry({useEffect(() => {if (zoomMode !== "manual" || isDragging.current) return;const el = scrollRef.current;- const target = lastScrollLeftRef.current;- if (!el || target <= 0) return;+ if (!el) return;+ // Read the ref inside the frame, not here: a sibling effect in the same+ // commit (a fresh reveal) can still update lastScrollLeftRef before this+ // frame runs, and a value captured now would fight that reveal with a+ // stale target.const raf = requestAnimationFrame(() => {+ const target = lastScrollLeftRef.current;+ if (target <= 0) return;const max = Math.max(0, el.scrollWidth - el.clientWidth);const next = Math.min(target, max);if (Math.abs(el.scrollLeft - next) > 0.5) el.scrollLeft = next;diff --git a/packages/studio/src/player/components/useTimelineGeometryFocusOrder.test.tsx b/packages/studio/src/player/components/useTimelineGeometryFocusOrder.test.tsxnew file mode 100644index 0000000000..38512cdc68--- /dev/null+++ b/packages/studio/src/player/components/useTimelineGeometryFocusOrder.test.tsx@@ -0,0 +1,184 @@+// @vitest-environment happy-dom++import React, { act, useMemo, useRef } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { usePlayerStore } from "../store/playerStore";+import { createTimelineRowGeometry } from "./timelineLayout";+import type { TimelineLogicalRow } from "./timelineKeyboardNavigation";+import { timelineClipFocusId, timelineTrackRowId } from "./timelineNavigationIdentity";+import { useTimelineFocusCoordinator } from "./useTimelineFocusCoordinator";+import { useTimelineGeometry } from "./useTimelineGeometry";++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });++const nextFrame = () => new Promise<number>((resolve) => requestAnimationFrame(resolve));++const oldElement = { id: "old", tag: "div", start: 0, duration: 1, track: 1 };+const heroElement = { id: "hero", tag: "div", start: 20, duration: 2, track: 1 };+const clipId = timelineClipFocusId("hero");+const rowId = timelineTrackRowId(1);+const beforeRows: readonly TimelineLogicalRow[] = [+ {+ id: rowId,+ kind: "row",+ physicalTrackKey: 1,+ logicalIndex: 0,+ level: 1,+ parentId: null,+ elementId: null,+ expandable: false,+ expanded: false,+ items: [],+ },+];+const afterRows: readonly TimelineLogicalRow[] = [+ {+ id: rowId,+ kind: "row",+ physicalTrackKey: 1,+ logicalIndex: 0,+ level: 1,+ parentId: null,+ elementId: null,+ expandable: false,+ expanded: false,+ items: [{ id: clipId, kind: "clip", rowId, elementId: "hero", time: 21 }],+ },+];++// Renders the two real production hooks side by side, in a caller-chosen call+// order, to test whether their interaction actually depends on that order —+// as opposed to simulating one hook's effect by hand.+function OrderHarness({+ order,+ expandedElements,+ logicalRows,+ lastScrollLeftRef,+}: {+ order: "geometry-first" | "coordinator-first";+ expandedElements: (typeof oldElement)[];+ logicalRows: readonly TimelineLogicalRow[];+ lastScrollLeftRef: React.RefObject<number>;+}) {+ const scrollRef = useRef<HTMLDivElement>(null);+ const isDragging = useRef(false);+ const ppsRef = useRef(0);+ const fitPpsRef = useRef(0);+ const rowGeometry = useMemo(() => createTimelineRowGeometry([1], [48]), []);++ const runGeometry = () =>+ useTimelineGeometry({+ viewportWidth: 300,+ effectiveDuration: 60,+ zoomMode: "manual",+ manualZoomPercent: 100,+ ppsRef,+ fitPpsRef,+ draggedClip: null,+ resizingClip: null,+ expandedElements,+ isDragging,+ scrollRef,+ lastScrollLeftRef,+ contentOrigin: 32,+ });+ const runFocus = () =>+ useTimelineFocusCoordinator({+ scrollRef,+ logicalRows,+ elements: expandedElements,+ rowGeometry,+ pixelsPerSecond: 100,+ contentOrigin: 32,+ allowHorizontal: true,+ viewportVersion: logicalRows.length,+ projectId: "project-a",+ sessionEpoch: 1,+ syncScrollViewport: () => {},+ lastScrollLeftRef,+ });++ // `order` is fixed for the lifetime of one mounted harness, so this call+ // order is stable across that instance's renders.+ if (order === "geometry-first") {+ runGeometry();+ runFocus();+ } else {+ runFocus();+ runGeometry();+ }++ return (+ <div+ ref={(node) => {+ scrollRef.current = node;+ if (node) {+ Object.defineProperty(node, "clientWidth", { configurable: true, value: 300 });+ Object.defineProperty(node, "clientHeight", { configurable: true, value: 100 });+ Object.defineProperty(node, "scrollWidth", { configurable: true, value: 20_000 });+ }+ }}+ />+ );+}++let host: HTMLDivElement;+let root: Root;+beforeEach(() => {+ usePlayerStore.setState({ timelineProjectId: "project-a", timelineSessionEpoch: 1 });+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ usePlayerStore.getState().reset();+ document.body.replaceChildren();+});++describe.each(["geometry-first", "coordinator-first"] as const)(+ "useTimelineGeometry + useTimelineFocusCoordinator, %s",+ (order) => {+ it("a same-commit reveal survives the geometry restore effect regardless of hook registration order", async () => {+ const lastScrollLeftRef = { current: 132 };+ await act(async () => {+ root.render(+ <OrderHarness+ order={order}+ expandedElements={[oldElement]}+ logicalRows={beforeRows}+ lastScrollLeftRef={lastScrollLeftRef}+ />,+ );+ });+ const scroll = host.firstElementChild as HTMLDivElement;+ scroll.scrollLeft = 132;+ await act(async () => {+ await nextFrame();+ });+ expect(scroll.scrollLeft).toBe(132);++ // One commit: the drop both adds the element (expandedElements changes,+ // arming the geometry restore effect) and resolves the focus request+ // (arming the coordinator's reveal), exactly as Timeline.tsx renders them.+ usePlayerStore.getState().requestTimelineFocus(clipId);+ await act(async () => {+ root.render(+ <OrderHarness+ order={order}+ expandedElements={[oldElement, heroElement]}+ logicalRows={afterRows}+ lastScrollLeftRef={lastScrollLeftRef}+ />,+ );+ });+ await act(async () => {+ await nextFrame();+ });++ expect(scroll.scrollLeft).toBe(1_944);+ expect(lastScrollLeftRef.current).toBe(1_944);+ });+ },+);diff --git a/packages/studio/src/player/components/useTimelineLogicalFocus.ts b/packages/studio/src/player/components/useTimelineLogicalFocus.tsindex 8f6fe0e097..03c8374ed6 100644--- a/packages/studio/src/player/components/useTimelineLogicalFocus.ts+++ b/packages/studio/src/player/components/useTimelineLogicalFocus.ts@@ -63,6 +63,7 @@ export function useTimelineLogicalFocus(input: TimelineLogicalFocusInput) {projectId,sessionEpoch: input.sessionEpoch,syncScrollViewport: input.syncScrollViewport,+ lastScrollLeftRef: input.lastScrollLeftRef,});const rows = useTimelineRowVirtualization({scrollRef: input.scrollRef,diff --git a/packages/studio/src/player/lib/timelineElementHelpers.ts b/packages/studio/src/player/lib/timelineElementHelpers.tsindex f1a5d6f96b..f4983c7aa7 100644--- a/packages/studio/src/player/lib/timelineElementHelpers.ts+++ b/packages/studio/src/player/lib/timelineElementHelpers.ts@@ -392,6 +392,14 @@ export function deriveTimelineStoreKey(params: {return buildTimelineElementKey({ id: "", fallbackIndex: 0, ...params });}+/**+ * {@link deriveTimelineStoreKey} for a caller that already has a DOM id in+ * hand (e.g. one it just minted), so the undefined branch never applies.+ */+export function deriveTimelineStoreKeyForDomId(domId: string, sourceFile?: string): string {+ return deriveTimelineStoreKey({ domId, sourceFile })!;+}+// ---------------------------------------------------------------------------// DOM node querying// ---------------------------------------------------------------------------diff --git a/packages/studio/src/utils/blockInstaller.test.ts b/packages/studio/src/utils/blockInstaller.test.tsindex 8f75ee35ea..bf0a3dbdf9 100644--- a/packages/studio/src/utils/blockInstaller.test.ts+++ b/packages/studio/src/utils/blockInstaller.test.ts@@ -63,5 +63,9 @@ describe("addBlockToProject", () => {expect(source).toContain('data-start="2.5"');expect(source).toContain('data-duration="4.25"');expect(source).toContain('data-track-index="3"');+ // hostKey addresses the new element the same way the timeline selects+ // clips (sourceFile#domId), so the caller can select and reveal it.+ expect(result?.hostKey).toBe("compositions/scene.html#camcorder-hud");+ expect(source).toContain('id="camcorder-hud"');});});diff --git a/packages/studio/src/utils/blockInstaller.ts b/packages/studio/src/utils/blockInstaller.tsindex 7255b4c50c..94eacf9db1 100644--- a/packages/studio/src/utils/blockInstaller.ts+++ b/packages/studio/src/utils/blockInstaller.ts@@ -11,6 +11,7 @@ import { formatTimelineAttributeNumber } from "../player/components/timelineEditimport { saveProjectFilesWithHistory } from "./studioFileHistory";import type { EditHistoryKind } from "./editHistory";import { extendRootDurationInSource } from "./rootDuration";+import { deriveTimelineStoreKeyForDomId } from "../player/lib/timelineElementHelpers";function getMaxZIndexFromIframe(iframe: HTMLIFrameElement | null): number {try {@@ -174,7 +175,7 @@ function buildSubCompositionHtml({export async function addBlockToProject(opts: AddBlockOptions,-): Promise<{ block: RegistryItem; compositionPath: string } | null> {+): Promise<{ block: RegistryItem; compositionPath: string; hostKey: string } | null> {const {projectId,blockName,@@ -213,8 +214,9 @@ export async function addBlockToProject(currentTime: opts.currentTime ?? 0,});const { width, height } = resolveTimelineAssetCompositionSize(originalContent);+ const hostId = buildUniqueCompositionId(block.name, collectHtmlIds(originalContent));const subComposition = buildSubCompositionHtml({- id: buildUniqueCompositionId(block.name, collectHtmlIds(originalContent)),+ id: hostId,compositionFile,start,duration,@@ -242,7 +244,11 @@ export async function addBlockToProject(await refreshFileTree();reloadPreview();- return { block, compositionPath: compositionFile };+ return {+ block,+ compositionPath: compositionFile,+ hostKey: deriveTimelineStoreKeyForDomId(hostId, targetPath),+ };} catch (error) {const message = error instanceof Error ? error.message : "Failed to add block";showToast(message);diff --git a/packages/studio/src/utils/retryBudget.ts b/packages/studio/src/utils/retryBudget.tsnew file mode 100644index 0000000000..4156817a2a--- /dev/null+++ b/packages/studio/src/utils/retryBudget.ts@@ -0,0 +1,20 @@+import type { MutableRefObject } from "react";++export interface RetryBudgetState<K> {+ id: K;+ count: number;+}++// A target still resolving (a just-dropped/pasted/duplicated element, or a+// preview still reloading) heals within a few retries; one that never will+// would otherwise retry forever. A new id resets the count.+export function recordRetryAttempt<K>(+ ref: MutableRefObject<RetryBudgetState<K>>,+ id: K,+ maxRetries: number,+): boolean {+ const previous = ref.current;+ const count = previous.id === id ? previous.count + 1 : 1;+ ref.current = { id, count };+ return count <= maxRetries;+}diff --git a/packages/studio/src/utils/timelineCompositionInsert.ts b/packages/studio/src/utils/timelineCompositionInsert.tsindex 275905a6d9..0b92c67ebd 100644--- a/packages/studio/src/utils/timelineCompositionInsert.ts+++ b/packages/studio/src/utils/timelineCompositionInsert.ts@@ -3,6 +3,7 @@ import { serializeStudioFileMutation } from "./studioFileMutationCoordinator";import type { RecordEditInput } from "./studioFileHistory";import { buildProjectApiPath } from "./projectRouting";import { studioWriteHeaders } from "./studioFileVersion";+import { deriveTimelineStoreKeyForDomId } from "../player/lib/timelineElementHelpers";interface TimelineCompositionInsertionResult {path: string;@@ -76,7 +77,7 @@ export async function commitTimelineCompositionInsertion(input: {await input.writeFile(input.targetPath, result.before, result.after);throw error;}- input.selectHost(`${input.targetPath}#${result.hostId}`);+ input.selectHost(deriveTimelineStoreKeyForDomId(result.hostId, input.targetPath));try {input.resync?.();} catch (error) {