Skip to content

Commit f6c09ce

Browse files
committed
fix(studio): preserve identity for stale metadata completions
1 parent 6df754f commit f6c09ce

2 files changed

Lines changed: 157 additions & 1 deletion

File tree

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
// @vitest-environment happy-dom
2+
import React, { act } from "react";
3+
import { createRoot } from "react-dom/client";
4+
import { expect, it, vi } from "vitest";
5+
import { useTimelinePlayer } from "./useTimelinePlayer";
6+
import { usePlayerStore } from "../store/playerStore";
7+
import { getMediaProbeDiagnostics, resetMediaProbeRegistry } from "../lib/mediaProbe";
8+
9+
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
10+
11+
it("publishes resolved metadata only for clips that still need it", async () => {
12+
vi.useFakeTimers({
13+
toFake: ["setInterval", "clearInterval", "requestAnimationFrame", "cancelAnimationFrame"],
14+
});
15+
const { promise: ready, resolve: release } = Promise.withResolvers<void>();
16+
const requested = new Set<string>();
17+
const bytes = new Uint8Array(44 + 192000);
18+
const view = new DataView(bytes.buffer);
19+
const word = (at: number, text: string) =>
20+
[...text].forEach((c, i) => view.setUint8(at + i, c.charCodeAt(0)));
21+
word(0, "RIFF");
22+
view.setUint32(4, bytes.length - 8, true);
23+
word(8, "WAVE");
24+
word(12, "fmt ");
25+
view.setUint32(16, 16, true);
26+
view.setUint16(20, 1, true);
27+
view.setUint16(22, 1, true);
28+
view.setUint32(24, 8000, true);
29+
view.setUint32(28, 16000, true);
30+
view.setUint16(32, 2, true);
31+
view.setUint16(34, 16, true);
32+
word(36, "data");
33+
view.setUint32(40, 192000, true);
34+
vi.stubGlobal(
35+
"fetch",
36+
vi.fn(async (input: RequestInfo | URL) => {
37+
requested.add(String(input));
38+
await ready;
39+
return new Response(bytes, {
40+
headers: { "content-type": "audio/wav", "content-length": String(bytes.length) },
41+
});
42+
}),
43+
);
44+
resetMediaProbeRegistry();
45+
usePlayerStore.getState().reset();
46+
const host = document.createElement("div");
47+
document.body.append(host);
48+
const root = createRoot(host);
49+
const current: { value?: ReturnType<typeof useTimelinePlayer> } = {};
50+
function Harness() {
51+
current.value = useTimelinePlayer();
52+
return null;
53+
}
54+
act(() => root.render(React.createElement(Harness)));
55+
const api = current.value;
56+
if (!api) throw new Error("player hook did not mount");
57+
const iframe = document.createElement("iframe");
58+
document.body.append(iframe);
59+
const frame = iframe.contentWindow;
60+
if (!frame) throw new Error("preview frame did not attach");
61+
Object.assign(frame, {
62+
__player: {
63+
play() {},
64+
pause() {},
65+
seek() {},
66+
getTime: () => 0,
67+
getDuration: () => 600,
68+
isPlaying: () => false,
69+
},
70+
postMessage() {},
71+
scrollTo() {},
72+
});
73+
act(() => {
74+
api.iframeRef.current = iframe;
75+
api.onIframeLoad();
76+
});
77+
const clips = Array.from({ length: 600 }, (_, index) => ({
78+
id: `clip-${index}`,
79+
label: `Clip ${index}`,
80+
start: index,
81+
duration: 1,
82+
track: 0,
83+
kind: "audio",
84+
tagName: "audio",
85+
compositionId: null,
86+
parentCompositionId: null,
87+
compositionSrc: null,
88+
assetUrl: `https://example.test/source-${index % 30}.wav`,
89+
}));
90+
const dispatch = () =>
91+
window.dispatchEvent(
92+
new MessageEvent("message", {
93+
source: frame,
94+
data: { source: "hf-preview", type: "timeline", clips, durationInFrames: 18000, fps: 30 },
95+
}),
96+
);
97+
let stop = () => {};
98+
try {
99+
act(() => {
100+
dispatch();
101+
dispatch();
102+
});
103+
expect(usePlayerStore.getState().elements).toHaveLength(600);
104+
act(() => usePlayerStore.getState().setTimelineReady(true));
105+
act(() =>
106+
usePlayerStore.setState((state) => ({
107+
elements: state.elements
108+
.slice(20)
109+
.map((element, index) => (index < 20 ? { ...element, sourceDuration: 99 } : element)),
110+
})),
111+
);
112+
await act(async () => {
113+
await new Promise((resolve) => setTimeout(resolve, 0));
114+
});
115+
let changed = 0;
116+
let unchanged = 0;
117+
let other = 0;
118+
stop = usePlayerStore.subscribe((state, before) => {
119+
if (state.elements !== before.elements) changed++;
120+
else if (Object.entries(state).every(([key, value]) => value === Reflect.get(before, key)))
121+
unchanged++;
122+
else other++;
123+
});
124+
await act(async () => {
125+
release();
126+
const started = Date.now();
127+
while (getMediaProbeDiagnostics().cached < 30 && Date.now() - started < 4000)
128+
await new Promise((resolve) => setTimeout(resolve, 10));
129+
await new Promise((resolve) => setTimeout(resolve, 0));
130+
});
131+
const elements = usePlayerStore.getState().elements;
132+
expect(elements).toHaveLength(580);
133+
expect(requested.size).toBe(30);
134+
expect(getMediaProbeDiagnostics()).toEqual({ cached: 30, failed: 0, inflight: 0 });
135+
expect(elements.slice(0, 20).every((element) => element.sourceDuration === 99)).toBe(true);
136+
expect(elements.slice(20).every((element) => element.sourceDuration === 12)).toBe(true);
137+
console.log({
138+
changed,
139+
unchanged,
140+
other,
141+
metadataSources: requested.size,
142+
clips: elements.length,
143+
});
144+
expect(changed).toBe(560);
145+
expect(unchanged).toBe(0);
146+
expect(other).toBe(0);
147+
} finally {
148+
stop();
149+
act(() => root.unmount());
150+
usePlayerStore.getState().reset();
151+
resetMediaProbeRegistry();
152+
vi.unstubAllGlobals();
153+
vi.useRealTimers();
154+
document.body.innerHTML = "";
155+
}
156+
});

‎packages/studio/src/player/hooks/useTimelinePlayer.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ export function useTimelinePlayer({
134134
(key, durationSeconds) => {
135135
usePlayerStore.setState((state) => {
136136
const idx = state.elements.findIndex((e) => (e.key ?? e.id) === key);
137-
if (idx === -1 || state.elements[idx].sourceDuration != null) return {};
137+
if (idx === -1 || state.elements[idx].sourceDuration != null) return state;
138138
const patched = state.elements.slice();
139139
patched[idx] = { ...state.elements[idx], sourceDuration: durationSeconds };
140140
return { elements: patched };

0 commit comments

Comments
 (0)