From f4ac8a4e065f22b5e388dfc97cfa7d123a1e6c16 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Fri, 21 Aug 2026 13:00:35 -0500 Subject: [PATCH] fix(frontend): keep collection ROM counts in step with the gallery A collection's ROM count was rendered from the collections store, whose lists are fetched once per session and never refreshed. Virtual collection membership is derived from ROM metadata, so every scan and every metadata match moves it with no collection write to update that copy from, leaving a stale count in the head band next to a gallery that fetches live. The collection page now re-reads the collection it is opening from the server, falling back to the cached copy only when that request fails, and the store re-reads its loaded virtual collections when a scan settles or a metadata write lands, so the tiles and the open page follow along. Co-Authored-By: Claude Opus 5 --- frontend/src/stores/collections.ts | 53 +++++++++++ .../v2/composables/useRomSync/index.test.ts | 14 +++ .../src/v2/composables/useRomSync/index.ts | 3 + .../useScanLifecycle/index.test.ts | 15 +++ .../v2/composables/useScanLifecycle/index.ts | 6 +- .../src/v2/views/Gallery/Collection.test.ts | 93 ++++++++++++++++++- frontend/src/v2/views/Gallery/Collection.vue | 31 ++++++- 7 files changed, 209 insertions(+), 6 deletions(-) diff --git a/frontend/src/stores/collections.ts b/frontend/src/stores/collections.ts index 5077c2925..af7ee241c 100644 --- a/frontend/src/stores/collections.ts +++ b/frontend/src/stores/collections.ts @@ -18,6 +18,9 @@ export default defineStore("collections", { state: () => ({ allCollections: [] as Collection[], virtualCollections: [] as VirtualCollection[], + // The type `virtualCollections` was fetched for, so a refresh knows which + // slice it is re-reading. + virtualCollectionType: null as string | null, smartCollections: [] as SmartCollection[], favoriteCollection: undefined as Collection | undefined, filterText: "" as string, @@ -111,6 +114,7 @@ export default defineStore("collections", { fetchVirtualCollections(type: string): Promise { if (this.fetchingVirtualCollections) return Promise.resolve([]); this.fetchingVirtualCollections = true; + this.virtualCollectionType = type; return new Promise((resolve, reject) => { collectionApi @@ -128,6 +132,47 @@ export default defineStore("collections", { }); }); }, + /** Re-read the loaded virtual collections, whose membership (and so ROM + * count) is derived from ROM metadata that scans and matches rewrite. */ + refreshVirtualCollections(): Promise { + if (this.virtualCollectionType === null) return Promise.resolve([]); + return this.fetchVirtualCollections(this.virtualCollectionType); + }, + /** Re-read one collection, refreshing the cached copy on the way through. + * Resolves to null when the server refuses it, so the caller can choose + * between its cached copy and a not-found state. */ + async refreshCollection(id: number): Promise { + try { + const { data } = await collectionApi.getCollection(id); + this.updateCollection(data); + return data; + } catch (error) { + console.error(error); + return null; + } + }, + async refreshVirtualCollection( + id: string, + ): Promise { + try { + const { data } = await collectionApi.getVirtualCollection(id); + this.updateVirtualCollection(data); + return data; + } catch (error) { + console.error(error); + return null; + } + }, + async refreshSmartCollection(id: number): Promise { + try { + const { data } = await collectionApi.getSmartCollection(id); + this.updateSmartCollection(data); + return data; + } catch (error) { + console.error(error); + return null; + } + }, setFavoriteCollection(favoriteCollection: Collection | undefined) { this.favoriteCollection = favoriteCollection; }, @@ -158,6 +203,13 @@ export default defineStore("collections", { ); this._reorderCollections(); }, + // Replaces in place only: the list holds one virtual collection type, and + // an id carries its own type, so inserting could mix them. + updateVirtualCollection(collection: VirtualCollection) { + this.virtualCollections = this.virtualCollections.map((value) => + value.id === collection.id ? collection : value, + ); + }, updateSmartCollection(collection: SmartCollection) { this.smartCollections = this.smartCollections.map((value) => value.id === collection.id ? collection : value, @@ -211,6 +263,7 @@ export default defineStore("collections", { reset() { this.allCollections = []; this.virtualCollections = []; + this.virtualCollectionType = null; this.smartCollections = []; this.favoriteCollection = undefined; this.filterText = ""; diff --git a/frontend/src/v2/composables/useRomSync/index.test.ts b/frontend/src/v2/composables/useRomSync/index.test.ts index 13d497964..73a763ba2 100644 --- a/frontend/src/v2/composables/useRomSync/index.test.ts +++ b/frontend/src/v2/composables/useRomSync/index.test.ts @@ -133,6 +133,20 @@ describe("useRomSync", () => { expect(getRoms).not.toHaveBeenCalled(); }); + // Collection heads and tiles read their ROM count off the store, including + // when the write comes from GameDetails rather than a gallery. + it("applyRomWrite re-reads the virtual collections off the gallery", () => { + const collections = storeCollections(); + const refresh = vi + .spyOn(collections, "refreshVirtualCollections") + .mockResolvedValue([]); + + useRomSync().applyRomWrite(makeRom({ igdb_id: 1234 })); + + expect(refresh).toHaveBeenCalledTimes(1); + expect(getRoms).not.toHaveBeenCalled(); + }); + it("refreshAfterUserStateChange refetches the Favourites collection", () => { const gallery = seedGallery(makeRom()); const collections = storeCollections(); diff --git a/frontend/src/v2/composables/useRomSync/index.ts b/frontend/src/v2/composables/useRomSync/index.ts index f3e020846..2a4305019 100644 --- a/frontend/src/v2/composables/useRomSync/index.ts +++ b/frontend/src/v2/composables/useRomSync/index.ts @@ -103,6 +103,9 @@ export function useRomSync() { // Read the pre-write copy before `syncCachedRom` overwrites it. const previous = galleryRomsStore.getRomById(rom.id); syncCachedRom(rom); + // Virtual collection membership is derived from the metadata this write + // rewrites, so only the server knows the ROM's new collections and counts. + void collectionsStore.refreshVirtualCollections(); if (!galleryRomsStore.onGalleryView) return; if (!galleryFilter.isFiltered() && !sortValueChanged(previous, rom)) return; galleryRomsStore.invalidateWindows(); diff --git a/frontend/src/v2/composables/useScanLifecycle/index.test.ts b/frontend/src/v2/composables/useScanLifecycle/index.test.ts index 66b2fabdd..3c689d4eb 100644 --- a/frontend/src/v2/composables/useScanLifecycle/index.test.ts +++ b/frontend/src/v2/composables/useScanLifecycle/index.test.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { defineComponent, reactive } from "vue"; import type { ScanStats } from "@/__generated__"; import taskApi from "@/services/api/task"; +import storeCollections from "@/stores/collections"; import storeScanning from "@/stores/scanning"; import { installScanLifecycle } from "./index"; @@ -128,6 +129,20 @@ describe("installScanLifecycle", () => { expect(scanning.scanStats.scanned_roms).toBe(12); }); + // A scan rewrites the metadata virtual collections derive from, so their + // counts drift like the platform ones. + it("re-reads the virtual collections when the scan settles", () => { + const collections = storeCollections(); + const refresh = vi + .spyOn(collections, "refreshVirtualCollections") + .mockResolvedValue([]); + install(); + + fire("scan:done", makeStats({ scanned_roms: 100 })); + + expect(refresh).toHaveBeenCalledTimes(1); + }); + it("reconciles with a running scan job on install", async () => { getTaskStatus.mockResolvedValue({ data: [runningScanTask(makeStats({ scanned_roms: 40, total_roms: 100 }))], diff --git a/frontend/src/v2/composables/useScanLifecycle/index.ts b/frontend/src/v2/composables/useScanLifecycle/index.ts index 94261ce03..b290d87d3 100644 --- a/frontend/src/v2/composables/useScanLifecycle/index.ts +++ b/frontend/src/v2/composables/useScanLifecycle/index.ts @@ -32,6 +32,7 @@ import type { ScanStats, ScanTaskStatusResponse } from "@/__generated__"; import platformApi from "@/services/api/platform"; import taskApi from "@/services/api/task"; import storeAuth from "@/stores/auth"; +import storeCollections from "@/stores/collections"; import storePlatforms from "@/stores/platforms"; import storeRoms, { type SimpleRom } from "@/stores/roms"; import storeScanning, { type ScanningPlatform } from "@/stores/scanning"; @@ -42,6 +43,7 @@ import storeGalleryRoms from "@/v2/stores/galleryRoms"; export function installScanLifecycle() { const scanningStore = storeScanning(); const romsStore = storeRoms(); + const collectionsStore = storeCollections(); const platformsStore = storePlatforms(); const galleryRomsStore = storeGalleryRoms(); const authStore = storeAuth(); @@ -184,8 +186,10 @@ export function installScanLifecycle() { scanningStore.setScanStats(stats); scanningStore.setScanning(false); // Reconcile against the backend once the scan settles: pick up anything - // the live updates missed and correct rom_counts that drifted. + // the live updates missed and correct rom_counts that drifted, virtual + // collections included (a scan rewrites the metadata they derive from). void platformsStore.fetchPlatforms(); + void collectionsStore.refreshVirtualCollections(); emitter?.emit("snackbarShow", { msg: "Scan completed successfully.", color: "success", diff --git a/frontend/src/v2/views/Gallery/Collection.test.ts b/frontend/src/v2/views/Gallery/Collection.test.ts index c225e7f1e..b26fa6a5b 100644 --- a/frontend/src/v2/views/Gallery/Collection.test.ts +++ b/frontend/src/v2/views/Gallery/Collection.test.ts @@ -2,7 +2,7 @@ import { flushPromises, mount } from "@vue/test-utils"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { defineComponent, ref } from "vue"; +import { defineComponent, nextTick, ref } from "vue"; import storeCollections, { type Collection, type SmartCollection, @@ -13,15 +13,19 @@ import storeGalleryRoms from "@/v2/stores/galleryRoms"; import CollectionView from "./Collection.vue"; const { + getCollection, getRandomRom, getRoms, + getVirtualCollection, push, routeGuards, snackbarError, snackbarInfo, } = vi.hoisted(() => ({ + getCollection: vi.fn(), getRandomRom: vi.fn(), getRoms: vi.fn(), + getVirtualCollection: vi.fn(), push: vi.fn(), routeGuards: [] as ((to: { name: string; @@ -62,7 +66,12 @@ vi.mock("@/services/api/rom", () => ({ })); vi.mock("@/services/api/collection", () => ({ - default: { deleteCollection: vi.fn() }, + default: { + deleteCollection: vi.fn(), + getCollection, + getVirtualCollection, + getSmartCollection: vi.fn(), + }, })); vi.mock("@v2/lib", () => ({ @@ -80,8 +89,9 @@ vi.mock("@/v2/components/Gallery/GalleryShell.vue", () => ({ vi.mock("@/v2/components/Gallery/CollectionHead.vue", () => ({ default: defineComponent({ + props: { collection: { type: Object, default: null } }, emits: ["random"], - template: `
`, + template: `
{{ collection?.rom_count }}
`, }), })); @@ -116,6 +126,14 @@ function collection(id: number): Collection { return { id, name: `Collection ${id}`, rom_count: 9000 } as Collection; } +function virtualCollection(romCount: number): VirtualCollection { + return { + id: "collection-zelda", + name: "The Legend of Zelda", + rom_count: romCount, + } as VirtualCollection; +} + function rom(id: number): SimpleRom { return { id, name: "Chrono Trigger" } as SimpleRom; } @@ -139,6 +157,9 @@ describe("Collection view random rom", () => { routeState.name = "collection"; routeState.params = { collection: "1" }; getRoms.mockResolvedValue({ data: { items: [], total: 0 } }); + getCollection.mockImplementation((id: number) => + Promise.resolve({ data: collection(id) }), + ); storeCollections().setCollections([collection(1), collection(2)]); }); @@ -329,3 +350,69 @@ describe("Collection view random rom", () => { expect(push).toHaveBeenCalledTimes(1); }); }); + +// The store's lists load once per session, and a virtual collection's ROM count +// moves with every scan and match, so a cached count disagrees with the gallery +// below it. +describe("Collection view freshness", () => { + beforeEach(() => { + setActivePinia(createPinia()); + vi.clearAllMocks(); + routeGuards.length = 0; + routeState.name = "collection"; + routeState.params = { collection: "1" }; + getRoms.mockResolvedValue({ data: { items: [], total: 0 } }); + getCollection.mockImplementation((id: number) => + Promise.resolve({ data: collection(id) }), + ); + // `collection()` caches 9000 ROMs, so any other count came from the server. + storeCollections().setCollections([collection(1)]); + }); + + it("renders the count the server returns, not the cached one", async () => { + getCollection.mockResolvedValue({ + data: { ...collection(1), rom_count: 12 }, + }); + + const wrapper = await mountView(); + + expect(getCollection).toHaveBeenCalledWith(1); + expect(wrapper.get(".rom-count").text()).toBe("12"); + }); + + it("re-reads the virtual collection being opened", async () => { + routeState.name = "virtual-collection"; + routeState.params = { collection: "collection-zelda" }; + storeCollections().setVirtualCollections([virtualCollection(4)]); + getVirtualCollection.mockResolvedValue({ data: virtualCollection(5) }); + + const wrapper = await mountView(); + + expect(getVirtualCollection).toHaveBeenCalledWith("collection-zelda"); + expect(wrapper.get(".rom-count").text()).toBe("5"); + }); + + // What a finished scan does: the store refetches, and the open page has to + // follow or it drifts again until the next visit. + it("adopts the store's copy when a refresh replaces it", async () => { + routeState.name = "virtual-collection"; + routeState.params = { collection: "collection-zelda" }; + const collections = storeCollections(); + collections.setVirtualCollections([virtualCollection(4)]); + getVirtualCollection.mockResolvedValue({ data: virtualCollection(4) }); + + const wrapper = await mountView(); + collections.setVirtualCollections([virtualCollection(5)]); + await nextTick(); + + expect(wrapper.get(".rom-count").text()).toBe("5"); + }); + + it("falls back to the cached copy when the re-read fails", async () => { + getCollection.mockRejectedValue(new Error("offline")); + + const wrapper = await mountView(); + + expect(wrapper.get(".rom-count").text()).toBe("9000"); + }); +}); diff --git a/frontend/src/v2/views/Gallery/Collection.vue b/frontend/src/v2/views/Gallery/Collection.vue index f84268de7..e02a2cd41 100644 --- a/frontend/src/v2/views/Gallery/Collection.vue +++ b/frontend/src/v2/views/Gallery/Collection.vue @@ -204,10 +204,27 @@ function findById(kind: CollectionKind, id: string): AnyCollection | undefined { return collectionsStore.smartCollections.find((c) => String(c.id) === id); } +// The head band renders a ROM count, and the store's lists are loaded once per +// session, so a cached virtual collection counts whatever it held back then +// against a gallery that fetches live. +function refreshFromServer( + kind: CollectionKind, + id: string, +): Promise { + if (kind === "regular") return collectionsStore.refreshCollection(Number(id)); + if (kind === "virtual") return collectionsStore.refreshVirtualCollection(id); + return collectionsStore.refreshSmartCollection(Number(id)); +} + async function loadForRoute(kind: CollectionKind, id: string) { currentKind.value = kind; - await ensureLoaded(kind); - const collection = findById(kind, id); + // The list is still loaded, unused here, for the surfaces reachable from + // this page that read it (the add-to-collection dialog). + const [fresh] = await Promise.all([ + refreshFromServer(kind, id), + ensureLoaded(kind), + ]); + const collection = fresh ?? findById(kind, id); if (!collection) { notFound.value = true; currentCollection.value = null; @@ -246,6 +263,16 @@ watch( }, ); +// Adopt the store's copy when a refresh replaces it, so a scan or a metadata +// write landing while this page is open corrects the head band as well as the +// gallery below. +watch( + () => findById(currentKind.value, String(route.params.collection)), + (fresh) => { + if (fresh) currentCollection.value = fresh; + }, +); + // ── Download ─────────────────────────────────────────────────── // Triggered from the InfoPanel's download button. Delegates to the // API's bulk-download endpoint, which streams a ZIP of all ROMs in the