From a80858bb2b5cf13e148e77fb4086189b42c6bbf8 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 3 Sep 2026 21:21:33 -0400 Subject: [PATCH] refactor(v2): give the post-write rom refetch one home Nine surfaces each spelled out "fetch the rom, write it to currentRom, sync the caches", and they had drifted: the notes tab never synced the gallery cache, the walkthrough subtab updated the v1 store instead of it, and only the scan refresh guarded against the user opening another game while the request was in flight. `useRomSync.refetchCurrentRom` does it once, with the guard, so every asset write reconciles the same way. Co-Authored-By: Claude Opus 5 (1M context) --- .../Dialogs/ManualUploadTargetDialog.vue | 10 +--- .../GameDetails/FilesTab/FilesTab.test.ts | 44 ++++++++++------- .../GameDetails/FilesTab/FilesTab.vue | 10 +--- .../components/GameDetails/ManualSubtab.vue | 10 +--- .../v2/components/GameDetails/MediaTab.vue | 10 +--- .../v2/components/GameDetails/NotesTab.vue | 5 +- .../v2/components/GameDetails/SaveDataTab.vue | 10 +--- .../GameDetails/ScreenshotsSubtab.vue | 10 +--- .../GameDetails/WalkthroughSubtab.vue | 10 ++-- .../useRomScanRefresh/index.test.ts | 48 +++++++----------- .../v2/composables/useRomScanRefresh/index.ts | 14 ++---- .../v2/composables/useRomSync/index.test.ts | 49 ++++++++++++++++++- .../src/v2/composables/useRomSync/index.ts | 24 ++++++++- 13 files changed, 135 insertions(+), 119 deletions(-) diff --git a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue index da10bfbf2..39d18af69 100644 --- a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue +++ b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue @@ -19,7 +19,7 @@ const { t } = useI18n(); const emitter = inject>("emitter"); const snackbar = useSnackbar(); const romsStore = storeRoms(); -const { syncCachedRom } = useRomSync(); +const { refetchCurrentRom } = useRomSync(); const uploadStore = storeUpload(); const TARGETS = { @@ -59,13 +59,7 @@ emitter?.on("showManualUploadTargetDialog", handleShow); onBeforeUnmount(() => emitter?.off("showManualUploadTargetDialog", handleShow)); async function refreshRom(target: DetailedRom) { - try { - const { data } = await romApi.getRom({ romId: target.id }); - romsStore.currentRom = data; - syncCachedRom(data); - } catch (error) { - console.error(error); - } + await refetchCurrentRom(target.id); } async function handleUploadResult( diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts index 5573ad828..8ddd16227 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts @@ -4,20 +4,28 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { DetailedRomSchema, RomFileSchema } from "@/__generated__"; import FilesTab from "./FilesTab.vue"; -const { uploadRoms, getRom, confirmFn, snackbar, routeQuery, grants } = - vi.hoisted(() => ({ - uploadRoms: vi.fn(), - getRom: vi.fn(), - confirmFn: vi.fn(), - snackbar: { - success: vi.fn(), - error: vi.fn(), - warning: vi.fn(), - info: vi.fn(), - }, - routeQuery: { subtab: undefined as string | undefined }, - grants: { upload: true, delete: false }, - })); +const { + uploadRoms, + getRom, + refetchCurrentRom, + confirmFn, + snackbar, + routeQuery, + grants, +} = vi.hoisted(() => ({ + uploadRoms: vi.fn(), + getRom: vi.fn(), + refetchCurrentRom: vi.fn(), + confirmFn: vi.fn(), + snackbar: { + success: vi.fn(), + error: vi.fn(), + warning: vi.fn(), + info: vi.fn(), + }, + routeQuery: { subtab: undefined as string | undefined }, + grants: { upload: true, delete: false }, +})); vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }), @@ -41,7 +49,7 @@ vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirmFn, })); vi.mock("@/v2/composables/useRomSync", () => ({ - useRomSync: () => ({ syncCachedRom: vi.fn() }), + useRomSync: () => ({ refetchCurrentRom }), })); vi.mock("@/v2/composables/useSnackbar", () => ({ useSnackbar: () => snackbar, @@ -130,7 +138,7 @@ describe("FilesTab uploads", () => { routeQuery.subtab = undefined; grants.upload = true; uploadRoms.mockResolvedValue([{ status: "fulfilled", value: null }]); - getRom.mockResolvedValue({ data: rom() }); + confirmFn.mockResolvedValue(true); }); @@ -156,7 +164,7 @@ describe("FilesTab uploads", () => { folder: "hack", filesToUpload: [expect.objectContaining({ name: "fix.ips" })], }); - expect(getRom).toHaveBeenCalledWith({ romId: 1 }); + expect(refetchCurrentRom).toHaveBeenCalledWith(1); expect(snackbar.success).toHaveBeenCalledWith( "rom.files-uploaded-n", expect.anything(), @@ -226,6 +234,6 @@ describe("FilesTab uploads", () => { "rom.no-files-uploaded", expect.anything(), ); - expect(getRom).not.toHaveBeenCalled(); + expect(refetchCurrentRom).not.toHaveBeenCalled(); }); }); diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue index 0d0aa4935..761d03e5b 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue @@ -71,7 +71,7 @@ const confirm = useConfirm(); const route = useRoute(); const router = useRouter(); const romsStore = storeRoms(); -const { syncCachedRom } = useRomSync(); +const { refetchCurrentRom } = useRomSync(); const canUpload = useCan("rom.upload"); const hasDeleteGrant = useCan("rom.delete"); @@ -650,13 +650,7 @@ async function uploadFiles(folder: string, picked: File[]) { } async function refreshRom() { - try { - const { data } = await romApi.getRom({ romId: props.rom.id }); - romsStore.currentRom = data; - syncCachedRom(data); - } catch (error) { - console.error(error); - } + await refetchCurrentRom(props.rom.id); } diff --git a/frontend/src/v2/components/GameDetails/ManualSubtab.vue b/frontend/src/v2/components/GameDetails/ManualSubtab.vue index dc0f1edfa..b94935b4b 100644 --- a/frontend/src/v2/components/GameDetails/ManualSubtab.vue +++ b/frontend/src/v2/components/GameDetails/ManualSubtab.vue @@ -34,7 +34,7 @@ const props = defineProps<{ rom: DetailedRom }>(); const emitter = inject>("emitter"); const snackbar = useSnackbar(); const romsStore = storeRoms(); -const { syncCachedRom } = useRomSync(); +const { refetchCurrentRom } = useRomSync(); const { t } = useI18n(); // Every manual endpoint (upload / redownload / delete) gates on the ROM write @@ -124,13 +124,7 @@ const manualDz = ref | null>(null); const redownloadingManual = ref(false); async function refreshRom() { - try { - const { data } = await romApi.getRom({ romId: props.rom.id }); - romsStore.currentRom = data; - syncCachedRom(data); - } catch (error) { - console.error(error); - } + await refetchCurrentRom(props.rom.id); } function handleManualFiles(files: File[]) { diff --git a/frontend/src/v2/components/GameDetails/MediaTab.vue b/frontend/src/v2/components/GameDetails/MediaTab.vue index d8817f1c5..fc6975f6d 100644 --- a/frontend/src/v2/components/GameDetails/MediaTab.vue +++ b/frontend/src/v2/components/GameDetails/MediaTab.vue @@ -51,7 +51,7 @@ const { fallbackArtUrl: soundtrackArtUrl, } = useRomSoundtrack(() => props.rom); const romsStore = storeRoms(); -const { syncCachedRom } = useRomSync(); +const { refetchCurrentRom } = useRomSync(); const uploadStore = storeUpload(); const { t } = useI18n(); @@ -165,13 +165,7 @@ const subtabDefs = computed(() => [ const soundtrackDz = ref | null>(null); async function refreshRom() { - try { - const { data } = await romApi.getRom({ romId: props.rom.id }); - romsStore.currentRom = data; - syncCachedRom(data); - } catch (error) { - console.error(error); - } + await refetchCurrentRom(props.rom.id); } // ---------- File handlers (shared by file input + drag-and-drop) ---------- diff --git a/frontend/src/v2/components/GameDetails/NotesTab.vue b/frontend/src/v2/components/GameDetails/NotesTab.vue index 56e8ddfcd..631649286 100644 --- a/frontend/src/v2/components/GameDetails/NotesTab.vue +++ b/frontend/src/v2/components/GameDetails/NotesTab.vue @@ -25,6 +25,7 @@ import storeAuth from "@/stores/auth"; import type { DetailedRom } from "@/stores/roms"; import storeRoms from "@/stores/roms"; import { useConfirm } from "@/v2/composables/useConfirm"; +import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useThemeMode } from "@/v2/composables/useThemeMode"; import { userAvatarUrl } from "@/v2/utils/userAvatar"; @@ -38,6 +39,7 @@ const snackbar = useSnackbar(); const confirm = useConfirm(); const authStore = storeAuth(); const romsStore = storeRoms(); +const { refetchCurrentRom } = useRomSync(); const route = useRoute(); const router = useRouter(); const { isLight: isLightTheme } = useThemeMode(); @@ -183,8 +185,7 @@ const canSave = computed(() => { }); async function refreshRom() { - const { data } = await romApi.getRom({ romId: props.rom.id }); - romsStore.setCurrentRom(data); + await refetchCurrentRom(props.rom.id); } function startAdd() { diff --git a/frontend/src/v2/components/GameDetails/SaveDataTab.vue b/frontend/src/v2/components/GameDetails/SaveDataTab.vue index 2ef9fb16a..8dc7b5a72 100644 --- a/frontend/src/v2/components/GameDetails/SaveDataTab.vue +++ b/frontend/src/v2/components/GameDetails/SaveDataTab.vue @@ -139,16 +139,10 @@ const uploadingStates = ref(false); const snackbar = useSnackbar(); const confirm = useConfirm(); const romsStore = storeRoms(); -const { syncCachedRom } = useRomSync(); +const { refetchCurrentRom } = useRomSync(); async function refreshRom() { - try { - const { data } = await romApi.getRom({ romId: props.rom.id }); - romsStore.currentRom = data; - syncCachedRom(data); - } catch (error) { - console.error(error); - } + await refetchCurrentRom(props.rom.id); } async function onSaveUpload(files: File[]) { diff --git a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue index b02442fe2..436d0d6b2 100644 --- a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue +++ b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue @@ -50,7 +50,7 @@ const { t } = useI18n(); const snackbar = useSnackbar(); const confirm = useConfirm(); const romsStore = storeRoms(); -const { syncCachedRom } = useRomSync(); +const { refetchCurrentRom } = useRomSync(); const uploadStore = storeUpload(); const authStore = storeAuth(); const { user } = storeToRefs(authStore); @@ -124,13 +124,7 @@ const communityScreenshots = computed(() => ); async function refreshRom() { - try { - const { data } = await romApi.getRom({ romId: props.rom.id }); - romsStore.currentRom = data; - syncCachedRom(data); - } catch (error) { - console.error(error); - } + await refetchCurrentRom(props.rom.id); } // ---------- Upload result toast (shared by both upload paths) ---------- diff --git a/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue b/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue index eb4c9fa4e..a85817a27 100644 --- a/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue +++ b/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue @@ -11,6 +11,7 @@ import romApi from "@/services/api/rom"; import storeRoms, { type DetailedRom } from "@/stores/roms"; import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; +import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; const PdfViewer = defineAsyncComponent( @@ -45,6 +46,7 @@ const props = defineProps<{ rom: DetailedRom }>(); const snackbar = useSnackbar(); const confirm = useConfirm(); const romsStore = storeRoms(); +const { refetchCurrentRom } = useRomSync(); const { t } = useI18n(); // Adding and removing walkthroughs both ride the ROMS write grant, matching @@ -106,13 +108,7 @@ const selectItems = computed(() => ); async function refreshRom() { - try { - const { data } = await romApi.getRom({ romId: props.rom.id }); - romsStore.currentRom = data; - romsStore.update(data); - } catch (error) { - console.error(error); - } + await refetchCurrentRom(props.rom.id); } // ---------- Single-file -> folder conversion ---------- diff --git a/frontend/src/v2/composables/useRomScanRefresh/index.test.ts b/frontend/src/v2/composables/useRomScanRefresh/index.test.ts index 967406d40..8483b5471 100644 --- a/frontend/src/v2/composables/useRomScanRefresh/index.test.ts +++ b/frontend/src/v2/composables/useRomScanRefresh/index.test.ts @@ -2,7 +2,6 @@ import { flushPromises, mount } from "@vue/test-utils"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { defineComponent } from "vue"; -import type { RomFileSchema } from "@/__generated__"; import type { DetailedRom } from "@/stores/roms"; import storeRoms from "@/stores/roms"; import { useRomScanRefresh } from "./index"; @@ -19,13 +18,11 @@ vi.mock("@/services/socket", () => ({ }, })); -const { getRom, syncCachedRom } = vi.hoisted(() => ({ - getRom: vi.fn(), - syncCachedRom: vi.fn(), +const { refetchCurrentRom } = vi.hoisted(() => ({ + refetchCurrentRom: vi.fn(), })); -vi.mock("@/services/api/rom", () => ({ default: { getRom } })); vi.mock("@/v2/composables/useRomSync", () => ({ - useRomSync: () => ({ syncCachedRom }), + useRomSync: () => ({ refetchCurrentRom }), })); function rom(overrides: Partial = {}): DetailedRom { @@ -47,39 +44,18 @@ describe("useRomScanRefresh", () => { beforeEach(() => { setActivePinia(createPinia()); handlers.clear(); - getRom.mockReset(); - syncCachedRom.mockClear(); + refetchCurrentRom.mockClear(); }); it("refetches the open rom when a scan finishes", async () => { const romsStore = storeRoms(); romsStore.setCurrentRom(rom()); - const fresh = rom({ files: [{ id: 9 } as RomFileSchema] }); - getRom.mockResolvedValue({ data: fresh }); install(); handlers.get("scan:done")?.({}); await flushPromises(); - expect(getRom).toHaveBeenCalledWith({ romId: 3 }); - expect(romsStore.currentRom).toStrictEqual(fresh); - expect(syncCachedRom).toHaveBeenCalledWith(fresh); - }); - - it("drops a response for a rom the user already left", async () => { - const romsStore = storeRoms(); - romsStore.setCurrentRom(rom()); - let resolve: (value: unknown) => void = () => {}; - getRom.mockReturnValue(new Promise((r) => (resolve = r))); - install(); - - handlers.get("scan:done")?.({}); - romsStore.setCurrentRom(rom({ id: 4 })); - resolve({ data: { id: 3 } }); - await flushPromises(); - - expect(romsStore.currentRom?.id).toBe(4); - expect(syncCachedRom).not.toHaveBeenCalled(); + expect(refetchCurrentRom).toHaveBeenCalledWith(3); }); it("does nothing without an open rom", () => { @@ -87,6 +63,18 @@ describe("useRomScanRefresh", () => { handlers.get("scan:done")?.({}); - expect(getRom).not.toHaveBeenCalled(); + expect(refetchCurrentRom).not.toHaveBeenCalled(); + }); + + it("does nothing once the view is gone", async () => { + const romsStore = storeRoms(); + romsStore.setCurrentRom(rom()); + const wrapper = install(); + wrapper.unmount(); + + handlers.get("scan:done")?.({}); + await flushPromises(); + + expect(refetchCurrentRom).not.toHaveBeenCalled(); }); }); diff --git a/frontend/src/v2/composables/useRomScanRefresh/index.ts b/frontend/src/v2/composables/useRomScanRefresh/index.ts index 8e347c5c7..d2a94d249 100644 --- a/frontend/src/v2/composables/useRomScanRefresh/index.ts +++ b/frontend/src/v2/composables/useRomScanRefresh/index.ts @@ -1,7 +1,6 @@ // useRomScanRefresh: refetch the open ROM when a scan finishes, since scan // events carry no file rows and the Files tab would keep the stale listing. import type { ScanStats } from "@/__generated__"; -import romApi from "@/services/api/rom"; import storeRoms from "@/stores/roms"; import { useIsAlive } from "@/v2/composables/useIsAlive"; import { useRomSync } from "@/v2/composables/useRomSync"; @@ -9,22 +8,15 @@ import { useSocketEvent } from "@/v2/composables/useSocketEvent"; export function useRomScanRefresh() { const romsStore = storeRoms(); - const { syncCachedRom } = useRomSync(); + const { refetchCurrentRom } = useRomSync(); const alive = useIsAlive(); useSocketEvent( "scan:done", async () => { const romId = romsStore.currentRom?.id; - if (romId === undefined) return; - try { - const { data } = await romApi.getRom({ romId }); - if (!alive.value || romsStore.currentRom?.id !== romId) return; - romsStore.setCurrentRom(data); - syncCachedRom(data); - } catch (error) { - console.error(error); - } + if (romId === undefined || !alive.value) return; + await refetchCurrentRom(romId); }, { connect: false }, ); diff --git a/frontend/src/v2/composables/useRomSync/index.test.ts b/frontend/src/v2/composables/useRomSync/index.test.ts index df73316d3..eca76ce9b 100644 --- a/frontend/src/v2/composables/useRomSync/index.test.ts +++ b/frontend/src/v2/composables/useRomSync/index.test.ts @@ -8,10 +8,13 @@ import storeGalleryRoms from "@/v2/stores/galleryRoms"; import storeGallerySelection from "@/v2/stores/gallerySelection"; import { useRomSync } from "./index"; -const { getRoms } = vi.hoisted(() => ({ getRoms: vi.fn() })); +const { getRoms, getRom } = vi.hoisted(() => ({ + getRoms: vi.fn(), + getRom: vi.fn(), +})); vi.mock("@/services/api/rom", () => ({ - default: { getRoms }, + default: { getRoms, getRom }, })); function makeRom(overrides: Partial = {}): SimpleRom { @@ -38,6 +41,7 @@ describe("useRomSync", () => { beforeEach(() => { setActivePinia(createPinia()); getRoms.mockReset(); + getRom.mockReset(); getRoms.mockResolvedValue({ data: { total: 0, items: [], char_index: {}, rom_id_index: [] }, }); @@ -250,4 +254,45 @@ describe("useRomSync", () => { expect(gallery.byPosition.size).toBe(1); expect(getRoms).not.toHaveBeenCalled(); }); + + describe("refetchCurrentRom", () => { + const detailed = (id: number) => + ({ id, name: "Chrono Trigger" }) as unknown as DetailedRom; + + it("applies the fresh rom to the open view and the caches", async () => { + const romsStore = storeRoms(); + romsStore.setCurrentRom(detailed(1)); + const gallery = seedGallery(makeRom()); + const fresh = detailed(1); + getRom.mockResolvedValue({ data: fresh }); + + const result = await useRomSync().refetchCurrentRom(1); + + expect(getRom).toHaveBeenCalledWith({ romId: 1 }); + expect(result).toBe(fresh); + expect(romsStore.currentRom).toStrictEqual(fresh); + expect(gallery.getRomById(1)).toStrictEqual(fresh); + }); + + it("leaves a rom the user opened meanwhile alone", async () => { + const romsStore = storeRoms(); + romsStore.setCurrentRom(detailed(1)); + let resolve: (value: unknown) => void = () => {}; + getRom.mockReturnValue(new Promise((r) => (resolve = r))); + + const pending = useRomSync().refetchCurrentRom(1); + romsStore.setCurrentRom(detailed(2)); + resolve({ data: detailed(1) }); + await pending; + + expect(romsStore.currentRom?.id).toBe(2); + }); + + it("reports a failed request rather than throwing at the caller", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + getRom.mockRejectedValue(new Error("offline")); + + await expect(useRomSync().refetchCurrentRom(1)).resolves.toBeNull(); + }); + }); }); diff --git a/frontend/src/v2/composables/useRomSync/index.ts b/frontend/src/v2/composables/useRomSync/index.ts index 887cbd2e4..fc396beb0 100644 --- a/frontend/src/v2/composables/useRomSync/index.ts +++ b/frontend/src/v2/composables/useRomSync/index.ts @@ -8,9 +8,10 @@ // mutate the ROM object in place and the gallery holds that same object // reference. Anything that replaces the object with a fresh one from the // API response (edit, match, asset upload) needs an explicit sync. +import romApi from "@/services/api/rom"; import storeCollections from "@/stores/collections"; import storeGalleryFilter from "@/stores/galleryFilter"; -import storeRoms, { type SimpleRom } from "@/stores/roms"; +import storeRoms, { type DetailedRom, type SimpleRom } from "@/stores/roms"; import storeGalleryRoms, { type GalleryOrderKey, } from "@/v2/stores/galleryRoms"; @@ -59,6 +60,26 @@ export function useRomSync() { } } + /** Re-read a ROM from the API and apply it everywhere it is cached. + * + * For the surfaces that write a ROM's assets (saves, screenshots, manuals, + * notes, files) and need the detailed record back rather than the row the + * write returned. `currentRom` is only replaced when it is still this ROM: + * the user can open another game while the request is in flight. + * + * Returns the fresh ROM, or null when the request failed or landed late. */ + async function refetchCurrentRom(romId: number): Promise { + try { + const { data } = await romApi.getRom({ romId }); + if (romsStore.currentRom?.id === romId) romsStore.setCurrentRom(data); + syncCachedRom(data); + return data; + } catch (error) { + console.error(error); + return null; + } + } + /** Drop ROMs that have left the current view from every cache holding * them: the gallery's windowed cache, the v1 store, and the selection. * Missing any one of the three leaves the cards on screen. @@ -156,6 +177,7 @@ export function useRomSync() { return { syncCachedRom, + refetchCurrentRom, removeCachedRoms, applyRomWrite, refreshAfterUserStateChange,