Skip to content

Commit f35c9bc

Browse files
vanceingallsclaude
andcommitted
fix(studio): a reopened project checks its videos again, and the disk index counts a frame once
The stored version a session validated was kept per video for the whole page, so reopening a project after one of its videos was replaced at the same path painted the old file's frames until a full reload. It is now kept per video and project open (its contentVersion): each open re-validates once. The index now counts a frame stored again under its name once, and merges with what other tabs saved before writing, keeping caches this tab dropped out, so the 256 MiB budget holds across tabs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 34a9762 commit f35c9bc

4 files changed

Lines changed: 123 additions & 28 deletions

File tree

‎packages/studio/src/player/lib/thumbnailDiskCache.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,4 +121,38 @@ describe("stored thumbnails", () => {
121121
expect(await readStoredInfo(v1)).toBeUndefined();
122122
expect(await storeInfo(v1, { aspect: 1, metadataDuration: 1 })).toBeUndefined();
123123
});
124+
125+
it("count a frame stored again under its name once, so the budget holds", async () => {
126+
await storeFrame(v1, "cover 1x1 0", 0, jpeg(100));
127+
await storeFrame(v1, "cover 1x1 0", 0, jpeg(100));
128+
129+
await vi.waitFor(() => expect(localStorage.getItem("hf-thumbnails-index")).toContain("bytes"), {
130+
timeout: 3000,
131+
});
132+
const saved = JSON.parse(localStorage.getItem("hf-thumbnails-index")!);
133+
expect(Object.values(saved.caches)).toMatchObject([{ bytes: 100 }]);
134+
});
135+
136+
it("keep what another tab stored when saving, but not what this tab dropped", async () => {
137+
await rememberVersion(v1);
138+
await storeFrame(v1, "cover 1x1 0", 0, jpeg());
139+
await vi.waitFor(() => expect(localStorage.getItem("hf-thumbnails-index")).toContain("bytes"), {
140+
timeout: 3000,
141+
});
142+
// another tab saves its snapshot: a source of its own, and v1 as it was before this tab moved on
143+
const other = JSON.parse(localStorage.getItem("hf-thumbnails-index")!);
144+
other.caches["hf-thumbnails:other:tab"] = { usedAt: Date.now(), bytes: 7 };
145+
localStorage.setItem("hf-thumbnails-index", JSON.stringify(other));
146+
const v1Cache = Object.keys(other.caches).find((name) => name !== "hf-thumbnails:other:tab")!;
147+
await rememberVersion(v2);
148+
await storeFrame(v2, "cover 1x1 0", 0, jpeg());
149+
150+
await vi.waitFor(
151+
() => expect(localStorage.getItem("hf-thumbnails-index")).not.toContain(v1Cache),
152+
{ timeout: 3000 },
153+
);
154+
const saved = JSON.parse(localStorage.getItem("hf-thumbnails-index")!);
155+
expect(Object.keys(saved.caches)).toContain("hf-thumbnails:other:tab");
156+
expect(Object.keys(saved.caches)).toHaveLength(2);
157+
});
124158
});

‎packages/studio/src/player/lib/thumbnailDiskCache.ts‎

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ interface Index {
2222
}
2323

2424
let index: Index | undefined;
25+
// caches this tab dropped since its last save, which another tab's older snapshot must not bring back
26+
const dropped = new Set<string>();
2527
let saveTimer: ReturnType<typeof setTimeout> | undefined;
2628
let warned = false;
2729

@@ -49,22 +51,45 @@ async function digest(text: string): Promise<string> {
4951
const cacheNameOf = async ({ source, etag }: StoredSource) =>
5052
`${CACHE_PREFIX}${await digest(source)}:${await digest(etag)}`;
5153

52-
function loadIndex(): Index {
53-
if (index) return index;
54+
function savedIndex(): Index | undefined {
5455
try {
5556
const saved = JSON.parse(localStorage.getItem(INDEX_KEY) ?? "null") as Index | null;
56-
if (saved?.etags && saved.caches) index = saved;
57+
return saved?.etags && saved.caches ? saved : undefined;
5758
} catch {
58-
// expected: no storage (a private window) or a value this version can't read starts an empty index
59+
return undefined; // expected: no storage (a private window) or a value this version can't read
60+
}
61+
}
62+
63+
function loadIndex(): Index {
64+
return (index ??= savedIndex() ?? { etags: {}, caches: {} });
65+
}
66+
67+
type CacheEntry = Index["caches"][string];
68+
69+
/** Another tab's entry when it was used later than this tab's, with the larger count of bytes. */
70+
function laterOf(own: CacheEntry | undefined, theirs: CacheEntry): CacheEntry | undefined {
71+
if (own && own.usedAt >= theirs.usedAt) return undefined;
72+
return { usedAt: theirs.usedAt, bytes: Math.max(theirs.bytes, own?.bytes ?? 0) };
73+
}
74+
75+
/** This tab's index with what other tabs saved since: each cache at its latest use, none this tab dropped. */
76+
function mergedIndex(): Index {
77+
const mine = loadIndex();
78+
const theirs = savedIndex() ?? { etags: {}, caches: {} };
79+
for (const [name, entry] of Object.entries(theirs.caches)) {
80+
const later = dropped.has(name) ? undefined : laterOf(mine.caches[name], entry);
81+
if (later) mine.caches[name] = later;
5982
}
60-
return (index ??= { etags: {}, caches: {} });
83+
mine.etags = { ...theirs.etags, ...mine.etags };
84+
dropped.clear();
85+
return mine;
6186
}
6287

6388
function saveIndexSoon(): void {
6489
saveTimer ??= setTimeout(() => {
6590
saveTimer = undefined;
6691
try {
67-
localStorage.setItem(INDEX_KEY, JSON.stringify(loadIndex()));
92+
localStorage.setItem(INDEX_KEY, JSON.stringify(mergedIndex()));
6893
} catch {
6994
// expected: storage refused; the caches still hold the frames, only their order of use is lost
7095
}
@@ -103,6 +128,7 @@ export const rememberVersion = (stored: StoredSource) =>
103128
if (!name.startsWith(`${CACHE_PREFIX}${key}:`) || name === keep) continue;
104129
await caches.delete(name);
105130
delete saved.caches[name];
131+
dropped.add(name);
106132
}
107133
});
108134

@@ -151,9 +177,14 @@ export const readStoredFrame = (stored: StoredSource, frame: string) =>
151177
export const storeFrame = (stored: StoredSource, frame: string, decodedAt: number, blob: Blob) =>
152178
quietly(async () => {
153179
const { name, cache, url } = await entry(stored, `frame?${encodeURIComponent(frame)}`);
154-
const headers = { "content-type": blob.type, "x-decoded-at": String(decodedAt) };
180+
const replaced = Number((await cache.match(url))?.headers.get("x-bytes")) || 0;
181+
const headers = {
182+
"content-type": blob.type,
183+
"x-decoded-at": String(decodedAt),
184+
"x-bytes": String(blob.size),
185+
};
155186
await cache.put(url, new Response(blob, { headers }));
156-
used(name, blob.size);
187+
used(name, blob.size - replaced);
157188
await dropLeastUsed(STORED_THUMBNAIL_BYTES);
158189
});
159190

@@ -166,6 +197,7 @@ async function dropLeastUsed(budgetBytes: number): Promise<void> {
166197
if (total <= budgetBytes) break;
167198
await caches.delete(name);
168199
delete saved.caches[name];
200+
dropped.add(name);
169201
total -= bytes;
170202
}
171203
saveIndexSoon();

‎packages/studio/src/player/lib/thumbnailVideoDecoder.test.ts‎

Lines changed: 41 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,26 @@ describe("videoThumbnailTimestamps", () => {
114114
});
115115
});
116116

117+
/** Cache Storage as a Map of Maps, empty, with an empty index: what a browser keeps across sessions. */
118+
function stubCacheStorage(): Map<string, Map<string, Response>> {
119+
const stores = new Map<string, Map<string, Response>>();
120+
vi.stubGlobal("caches", {
121+
open: async (name: string) => {
122+
const store = stores.get(name) ?? new Map<string, Response>();
123+
stores.set(name, store);
124+
return {
125+
match: async (url: string) => store.get(url)?.clone(),
126+
put: async (url: string, response: Response) => void store.set(url, response),
127+
};
128+
},
129+
has: async (name: string) => stores.has(name),
130+
keys: async () => [...stores.keys()],
131+
delete: async (name: string) => stores.delete(name),
132+
});
133+
localStorage.clear();
134+
return stores;
135+
}
136+
117137
describe("decodeVideoThumbnail", () => {
118138
it("extracts sparse frames, returns object URLs, and disposes once", async () => {
119139
const decoded: number[][] = [];
@@ -934,21 +954,7 @@ describe("decodeVideoThumbnail's shared source", () => {
934954
});
935955

936956
it("paints a strip from a past session's frames on disk, without opening the file", async () => {
937-
const stores = new Map<string, Map<string, Response>>();
938-
vi.stubGlobal("caches", {
939-
open: async (name: string) => {
940-
const store = stores.get(name) ?? new Map<string, Response>();
941-
stores.set(name, store);
942-
return {
943-
match: async (url: string) => store.get(url)?.clone(),
944-
put: async (url: string, response: Response) => void store.set(url, response),
945-
};
946-
},
947-
has: async (name: string) => stores.has(name),
948-
keys: async () => [...stores.keys()],
949-
delete: async (name: string) => stores.delete(name),
950-
});
951-
localStorage.clear();
957+
const stores = stubCacheStorage();
952958
const signal = new AbortController().signal;
953959
servedEtag = '"take-v1"';
954960
recordDecodes([]);
@@ -980,4 +986,24 @@ describe("decodeVideoThumbnail's shared source", () => {
980986
expect(result.value).toMatchObject({ kind: "filmstrip" });
981987
expect((result.value as { urls: string[] }).urls).toHaveLength(3);
982988
});
989+
990+
it("checks the file again when a project opens anew, so a replaced video never paints its old frames", async () => {
991+
const stores = stubCacheStorage();
992+
const signal = new AbortController().signal;
993+
servedEtag = '"v1"';
994+
recordDecodes([]);
995+
const request = { source, sourceStart: 0, sourceRangeDuration: 4, frameCount: 2 };
996+
await decodeVideoThumbnail({ ...request, contentVersion: "open-1" }, signal);
997+
await vi.waitFor(() => expect([...stores.values()][0]?.size).toBe(4));
998+
999+
// the video is replaced at the same path, then its project opened again in this page
1000+
servedEtag = '"v2"';
1001+
vi.stubGlobal(
1002+
"fetch",
1003+
vi.fn(async () => new Response("x", { status: 206, headers: { ETag: '"v2"' } })),
1004+
);
1005+
await decodeVideoThumbnail({ ...request, contentVersion: "open-2" }, signal);
1006+
1007+
expect(input.getPrimaryVideoTrack).toHaveBeenCalledTimes(2);
1008+
});
9831009
});

‎packages/studio/src/player/lib/thumbnailVideoDecoder.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,12 @@ const sourceInfos = new Map<string, { version: string | undefined; info: SourceI
6464
const storedVersions = new Map<string, Promise<StoredSource | undefined>>();
6565
const storedInfos = new Set<string>();
6666

67-
function storedVersionOf(source: string): Promise<StoredSource | undefined> {
68-
let pending = storedVersions.get(source);
69-
if (!pending) storedVersions.set(source, (pending = storedVersion(source)));
67+
const openOf = (request: VideoThumbnailDecodeRequest) =>
68+
`${request.source}\u0000${request.contentVersion ?? ""}`;
69+
70+
function storedVersionOf(request: VideoThumbnailDecodeRequest): Promise<StoredSource | undefined> {
71+
let pending = storedVersions.get(openOf(request));
72+
if (!pending) storedVersions.set(openOf(request), (pending = storedVersion(request.source)));
7073
return pending;
7174
}
7275

@@ -272,7 +275,7 @@ function versionRead(
272275
): StoredSource | undefined {
273276
if (!source.etag) return undefined;
274277
const version = { source: request.source, etag: source.etag };
275-
storedVersions.set(request.source, Promise.resolve(version));
278+
storedVersions.set(openOf(request), Promise.resolve(version));
276279
return version;
277280
}
278281

@@ -312,7 +315,7 @@ export async function decodeVideoThumbnail(
312315
};
313316
const entry = sourceInfos.get(request.source);
314317
try {
315-
const stored = await storedVersionOf(request.source);
318+
const stored = await storedVersionOf(request);
316319
const known =
317320
entry && entry.version === request.contentVersion
318321
? entry.info

0 commit comments

Comments
 (0)