Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

šŸ› fix(portal): keep a saved local-file preview when an older read fails terminally (#21124)

Arvin Xu94f32d6bda89
diff --git a/src/store/localFilePreview/index.test.ts b/src/store/localFilePreview/index.test.ts
index f8422fa6ddd..39eb6463d01 100644
--- a/src/store/localFilePreview/index.test.ts
+++ b/src/store/localFilePreview/index.test.ts
@@ -402,6 +402,64 @@ describe('local file preview replica', () => {
await waitFor(async () => expect(await storedRow(NOTES)).toBeUndefined());
});
+ it.each([404, 403])(
+ 'keeps the saved content when a read started before the save answers %i',
+ async (status) => {
+ // The persisted preview belongs to a file that was deleted meanwhile.
+ await seedRow(NOTES, textPreview('# cached'));
+ let fail: (error: unknown) => void = () => {};
+ vi.mocked(projectFileService.getLocalFilePreview).mockImplementation(
+ () => new Promise((_, reject) => (fail = reject)) as never,
+ );
+ const { result } = renderPreview(NOTES);
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('# cached')));
+
+ // The user saves (recreating the file) while the mount-time read is pending…
+ act(() => useLocalFilePreviewStore.getState().beginSave(NOTES)('saved'));
+ // …and the older read then settles with the pre-save 404 / 403.
+ await act(async () => {
+ fail(new LocalFileResponseError(status));
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ expect(result.current.preview).toEqual(textPreview('saved'));
+ expect(result.current.sync.error).toBeUndefined();
+ expect((await storedRow(NOTES))?.data).toEqual(textPreview('saved'));
+ },
+ );
+
+ it('still evicts the row when a save under another identity races a terminal read', async () => {
+ const first = scope;
+ await seedRow(NOTES, textPreview('# forbidden'));
+ const fails: ((error: unknown) => void)[] = [];
+ vi.mocked(projectFileService.getLocalFilePreview).mockImplementation(
+ () => new Promise((_, reject) => fails.push(reject)) as never,
+ );
+ const { result } = renderPreview(NOTES);
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('# forbidden')));
+
+ // The read started under the first identity; the same file is saved under another…
+ useScope(`local-file-user-${randomUUID()}:personal`);
+ // (where the same file is open with a cached preview too)
+ await seedRow(NOTES, textPreview('# other identity'));
+ const { result: other } = renderPreview(NOTES);
+ await waitFor(() => expect(other.current.preview).toEqual(textPreview('# other identity')));
+ act(() => useLocalFilePreviewStore.getState().beginSave(NOTES)('saved elsewhere'));
+ expect(other.current.preview).toEqual(textPreview('saved elsewhere'));
+ // …so the first identity's 403 must still purge its own stored row.
+ await act(async () => {
+ fails[0](new LocalFileResponseError(403));
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ useScope(first);
+ await waitFor(async () => expect(await storedRow(NOTES)).toBeUndefined());
+ });
+
it('keeps the cached text when the file read fails transiently', async () => {
await seedRow(NOTES, textPreview('# cached'));
let fail: (error: unknown) => void = () => {};
diff --git a/src/store/localFilePreview/index.ts b/src/store/localFilePreview/index.ts
index 5415552c9cd..60a07047994 100644
--- a/src/store/localFilePreview/index.ts
+++ b/src/store/localFilePreview/index.ts
@@ -119,19 +119,38 @@ export const useLocalFilePreviewStore: UseBoundStoreWithEqualityFn<
StoreApi<LocalFilePreviewStore>
> = createWithEqualityFn<LocalFilePreviewStore>()((set, get) => {
/**
- * Saves folded into each preview (by key). A read started before a save may
- * still hold the pre-save file; once the save lands it must not replace the
- * confirmed content — the same guard as the document detail's adoptions.
+ * Saves folded into each preview, by identity (cache scope) and key. A read
+ * started before a save may still hold the pre-save file; once the save lands
+ * it must not replace the confirmed content — the same guard as the document
+ * detail's adoptions. A save under another identity never vouches for a read
+ * of this one.
*/
const saveGenerations = new Map<string, number>();
+ const generationKey = (scope: string, key: string) => JSON.stringify([scope, key]);
const previews = createReplicaSlice(localFilePreviewResource, {
actionPrefix: 'localFilePreview/previews',
fetcher: async (key) => {
- const savedBefore = saveGenerations.get(key) ?? 0;
- const preview = await fetchLocalFilePreview(key);
+ const scope = cacheScope.get();
+ const generation = generationKey(scope, key);
+ const savedBefore = saveGenerations.get(generation) ?? 0;
+ // `previewMap` shows the active identity, so the saved body is only
+ // readable while the read's identity is still the active one.
+ const savedSince = () =>
+ cacheScope.get() === scope && (saveGenerations.get(generation) ?? 0) !== savedBefore;
+ let preview: LocalFilePreview;
+ try {
+ preview = await fetchLocalFilePreview(key);
+ } catch (error) {
+ // A save landed while this read was in flight: its failure (e.g. the
+ // 404 of a file the save then recreated) describes the pre-save file,
+ // so it must neither surface nor evict the confirmed saved body.
+ const saved = get().previewMap[key];
+ if (savedSince() && saved) return saved;
+ throw error;
+ }
const current = get().previewMap[key];
- if ((saveGenerations.get(key) ?? 0) === savedBefore || !current) return preview;
+ if (!savedSince() || !current) return preview;
// A save landed while this read was in flight: keep the saved body, but
// take the rest of the fresh read — notably the `resourceBaseUrl` an HTML
// preview needs for its relative assets (never persisted, so the cached
@@ -166,7 +185,8 @@ export const useLocalFilePreviewStore: UseBoundStoreWithEqualityFn<
// The write settled after an account / workspace switch: `update` writes
// the active scope, which would plant this file body in another identity.
if (cacheScope.get() !== scope) return;
- saveGenerations.set(key, (saveGenerations.get(key) ?? 0) + 1);
+ const generation = generationKey(scope, key);
+ saveGenerations.set(generation, (saveGenerations.get(generation) ?? 0) + 1);
previews.update(key, (preview) =>
preview?.type === 'text' ? { ...preview, content } : preview,
);