diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 1c2164722..666189049 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -143,9 +143,9 @@ def _scan_in_flight_message(running: Job | None, queued: list[Job]) -> str: return f"{_scan_job_label(running)} is already running" -# A scan reports progress after every rom, and each report is a synchronous -# redis write plus a publish. Coalescing them keeps a large library from -# spending longer announcing progress than making it. +# Each report is a synchronous redis write plus a publish, and a scan makes one +# per rom. Coalescing keeps a large library from spending longer announcing +# progress than making it. SCAN_STATS_PUBLISH_INTERVAL = 0.25 @@ -1096,6 +1096,11 @@ async def scan_platforms( socket_manager = _get_socket_manager() scan_stats = ScanStats() + async def finish(event: str, payload: Any) -> None: + """End the scan, reporting whatever a coalesced increment held back.""" + await scan_stats.flush(socket_manager) + await socket_manager.emit(event, payload) + # A ROM-id-scoped scan resolves its work from the database, so it neither # needs nor can afford the filesystem walk a library scan starts with. scoped_roms_by_platform: dict[int, list[Rom]] = {} @@ -1115,7 +1120,7 @@ async def scan_platforms( fs_platforms = await fs_platform_handler.get_platforms() except FolderStructureNotMatchException as e: log.error(e) - await socket_manager.emit("scan:done_ko", e.message) + await finish("scan:done_ko", e.message) return scan_stats # Clear the gamelist cache to ensure we're using fresh gamelist.xml data @@ -1221,8 +1226,7 @@ async def scan_platforms( async def stop_scan(): log.info(f"{emoji.EMOJI_STOP_SIGN} Scan stopped manually") - await scan_stats.flush(socket_manager) - await socket_manager.emit("scan:done", scan_stats.to_dict()) + await finish("scan:done", scan_stats.to_dict()) redis_client.delete(STOP_SCAN_FLAG) try: @@ -1338,20 +1342,13 @@ async def scan_platforms( ) log.info("Pegasus metadata auto-export completed.") - await scan_stats.flush(socket_manager) - await socket_manager.emit("scan:done", scan_stats.to_dict()) + await finish("scan:done", scan_stats.to_dict()) except ScanStoppedException: await stop_scan() except Exception as e: log.error(f"Error in scan_platform: {e}") - # What the scan did get through still counts, so report it before saying - # it failed; a failure to do so must not replace the error being raised. - try: - await scan_stats.flush(socket_manager) - except Exception: - log.error("Could not report the stats of a failed scan", exc_info=True) # Catch all exceptions and emit error to the client - await socket_manager.emit("scan:done_ko", str(e)) + await finish("scan:done_ko", str(e)) # Re-raise the exception to be caught by the error handler raise e diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 466930729..c839f8b6c 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -47,67 +47,76 @@ from models.rom import Rom, RomFile, RomFileCategory, RomIdentity from utils.platform_slugs import UniversalPlatformSlug as UPS +@pytest.fixture +def hold_everything_back(mocker): + """An interval no test can outrun, so coalescing is what decides.""" + mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600) + + class TestScanStatsPublishing: """Counters are exact on every increment; only the reporting is coalesced.""" @pytest.fixture - def emit(self, mocker): + def socket_manager(self, mocker): mocker.patch.object(scan_module, "update_job_meta") return AsyncMock() - async def test_reports_once_for_a_burst_of_increments(self, mocker, emit): - mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600) + async def test_reports_once_for_a_burst_of_increments( + self, hold_everything_back, socket_manager + ): stats = ScanStats() for _ in range(50): - await stats.increment(socket_manager=emit, scanned_roms=1) + await stats.increment(socket_manager=socket_manager, scanned_roms=1) # The first increment reports, the rest ride along with it. - emit.emit.assert_awaited_once() + socket_manager.emit.assert_awaited_once() assert stats.scanned_roms == 50 - async def test_flush_reports_what_a_burst_held_back(self, mocker, emit): - mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600) + async def test_flush_reports_what_a_burst_held_back( + self, hold_everything_back, socket_manager + ): stats = ScanStats() for _ in range(5): - await stats.increment(socket_manager=emit, scanned_roms=1) - emit.emit.reset_mock() + await stats.increment(socket_manager=socket_manager, scanned_roms=1) + socket_manager.emit.reset_mock() - await stats.flush(emit) + await stats.flush(socket_manager) - assert emit.emit.await_args.args[1]["scanned_roms"] == 5 + assert socket_manager.emit.await_args.args[1]["scanned_roms"] == 5 - async def test_flush_is_quiet_with_nothing_held_back(self, mocker, emit): + async def test_flush_is_quiet_with_nothing_held_back(self, mocker, socket_manager): mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 0) stats = ScanStats() - await stats.increment(socket_manager=emit, scanned_roms=1) - emit.emit.reset_mock() + await stats.increment(socket_manager=socket_manager, scanned_roms=1) + socket_manager.emit.reset_mock() - await stats.flush(emit) + await stats.flush(socket_manager) - emit.emit.assert_not_awaited() + socket_manager.emit.assert_not_awaited() - async def test_a_phase_boundary_reports_immediately(self, mocker, emit): - mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600) + async def test_a_phase_boundary_reports_immediately( + self, hold_everything_back, socket_manager + ): stats = ScanStats() - await stats.increment(socket_manager=emit, scanned_roms=1) - emit.emit.reset_mock() + await stats.increment(socket_manager=socket_manager, scanned_roms=1) + socket_manager.emit.reset_mock() - await stats.update(socket_manager=emit, total_roms=12) + await stats.update(socket_manager=socket_manager, total_roms=12) - assert emit.emit.await_args.args[1]["total_roms"] == 12 + assert socket_manager.emit.await_args.args[1]["total_roms"] == 12 async def test_the_first_report_survives_a_clock_reading_near_zero( - self, mocker, emit + self, mocker, socket_manager ): # A monotonic clock counting from boot can read below the interval, and # the first report must not be coalesced against a scan that never ran. mocker.patch.object(scan_module.time, "monotonic", return_value=0.01) stats = ScanStats() - await stats.increment(socket_manager=emit, scanned_roms=1) + await stats.increment(socket_manager=socket_manager, scanned_roms=1) - emit.emit.assert_awaited_once() + socket_manager.emit.assert_awaited_once() def test_scan_stats(): @@ -217,9 +226,8 @@ class TestScanFailureReporting: """A failed scan still reports the progress it made before saying it failed.""" async def test_a_failure_publishes_what_an_increment_held_back( - self, patched, mocker + self, patched, hold_everything_back, mocker ): - mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600) update_job_meta = mocker.patch.object(scan_module, "update_job_meta") async def scan_then_fail(**kwargs): @@ -238,25 +246,6 @@ class TestScanFailureReporting: assert update_job_meta.call_args.args[0]["scan_stats"]["scanned_roms"] == 7 assert patched.emit.await_args.args[0] == "scan:done_ko" - async def test_a_failure_to_report_does_not_replace_the_error( - self, patched, mocker - ): - mocker.patch.object( - scan_module.ScanStats, - "flush", - AsyncMock(side_effect=OSError("redis is gone")), - ) - - async def scan_then_fail(**_kwargs): - raise RuntimeError("boom") - - mocker.patch.object( - scan_module, "_identify_platform", side_effect=scan_then_fail - ) - - with pytest.raises(RuntimeError, match="boom"): - await scan_platforms(platform_ids=[], metadata_sources=[]) - class TestScanTotals: """The scan tracker totals must reflect the platforms/roms actually scanned.""" @@ -309,11 +298,8 @@ class TestScreenScraperScanReporting: when the scan actually uses ScreenScraper.""" @pytest.fixture - def patched(self, mocker): - socket_manager = AsyncMock() - mocker.patch.object( - scan_module, "_get_socket_manager", return_value=socket_manager - ) + def patched(self, patched, mocker): + """The shared harness, narrowed to a single platform with no roms.""" mocker.patch.object( scan_module.fs_platform_handler, "get_platforms", @@ -322,28 +308,10 @@ class TestScreenScraperScanReporting: mocker.patch.object( scan_module.fs_rom_handler, "count_roms", AsyncMock(return_value=0) ) - mocker.patch.object(scan_module.meta_gamelist_handler, "clear_cache") - mocker.patch.object( - scan_module.db_platform_handler, "mark_missing_platforms", return_value=[] - ) mocker.patch.object( scan_module.db_platform_handler, "get_platforms", return_value=[] ) - mocker.patch.object( - scan_module.db_rom_handler, "invalidate_filter_values_cache" - ) - config = MagicMock() - config.GAMELIST_AUTO_EXPORT_ON_SCAN = False - config.PEGASUS_AUTO_EXPORT_ON_SCAN = False - mocker.patch.object(scan_module.cm, "get_config", return_value=config) - - async def fake_identify(**kwargs): - return kwargs["scan_stats"] - - mocker.patch.object( - scan_module, "_identify_platform", side_effect=fake_identify - ) - return socket_manager + return patched async def test_begins_a_screenscraper_scan(self, patched, mocker): begin = mocker.patch.object( diff --git a/frontend/src/v2/components/Dialogs/DeleteManualDialog.vue b/frontend/src/v2/components/Dialogs/DeleteManualDialog.vue index a92e91de8..32dc2ff54 100644 --- a/frontend/src/v2/components/Dialogs/DeleteManualDialog.vue +++ b/frontend/src/v2/components/Dialogs/DeleteManualDialog.vue @@ -7,7 +7,7 @@ import type { Emitter } from "mitt"; import { inject, onBeforeUnmount, ref } from "vue"; import { useI18n } from "vue-i18n"; import romApi from "@/services/api/rom"; -import storeRoms, { type DetailedRom } from "@/stores/roms"; +import { type DetailedRom } from "@/stores/roms"; import type { Events } from "@/types/emitter"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; @@ -18,8 +18,7 @@ defineOptions({ inheritAttrs: false }); const { t } = useI18n(); const emitter = inject>("emitter"); const snackbar = useSnackbar(); -const romsStore = storeRoms(); -const { syncCachedRom } = useRomSync(); +const { refetchCurrentRom } = useRomSync(); const show = ref(false); const rom = ref(null); @@ -36,17 +35,6 @@ const handleShow = (payload: Events["showDeleteManualDialog"]) => { emitter?.on("showDeleteManualDialog", handleShow); onBeforeUnmount(() => emitter?.off("showDeleteManualDialog", handleShow)); -async function refreshRom() { - if (!rom.value) return; - try { - const { data } = await romApi.getRom({ romId: rom.value.id }); - romsStore.currentRom = data; - syncCachedRom(data); - } catch (error) { - console.error(error); - } -} - async function deleteManual() { if (!rom.value || deleting.value) return; deleting.value = true; @@ -58,7 +46,7 @@ async function deleteManual() { } else if (fileId.value !== undefined) { await romApi.deleteManualFile({ romId, fileId: fileId.value }); } - await refreshRom(); + await refetchCurrentRom(romId); snackbar.success( t(primary ? "rom.manual-removed" : "rom.manual-file-removed"), { icon: "mdi-check-bold" }, diff --git a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue index 39d18af69..13f174f56 100644 --- a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue +++ b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue @@ -7,7 +7,7 @@ import type { Emitter } from "mitt"; import { inject, onBeforeUnmount, ref } from "vue"; import { useI18n } from "vue-i18n"; import romApi from "@/services/api/rom"; -import storeRoms, { type DetailedRom } from "@/stores/roms"; +import type { DetailedRom } from "@/stores/roms"; import storeUpload from "@/stores/upload"; import type { Events } from "@/types/emitter"; import { useRomSync } from "@/v2/composables/useRomSync"; @@ -18,7 +18,6 @@ defineOptions({ inheritAttrs: false }); const { t } = useI18n(); const emitter = inject>("emitter"); const snackbar = useSnackbar(); -const romsStore = storeRoms(); const { refetchCurrentRom } = useRomSync(); const uploadStore = storeUpload(); @@ -58,10 +57,6 @@ const handleShow = (payload: Events["showManualUploadTargetDialog"]) => { emitter?.on("showManualUploadTargetDialog", handleShow); onBeforeUnmount(() => emitter?.off("showManualUploadTargetDialog", handleShow)); -async function refreshRom(target: DetailedRom) { - await refetchCurrentRom(target.id); -} - async function handleUploadResult( responses: PromiseSettledResult[], successKey: string, @@ -78,7 +73,7 @@ async function handleUploadResult( icon: "mdi-check-bold", timeout: 3000, }); - await refreshRom(target); + await refetchCurrentRom(target.id); } else { snackbar.warning(t(skippedKey), { icon: "mdi-close-circle", diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts index 8ddd16227..d4a4ad4b8 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts @@ -6,7 +6,6 @@ import FilesTab from "./FilesTab.vue"; const { uploadRoms, - getRom, refetchCurrentRom, confirmFn, snackbar, @@ -14,7 +13,6 @@ const { grants, } = vi.hoisted(() => ({ uploadRoms: vi.fn(), - getRom: vi.fn(), refetchCurrentRom: vi.fn(), confirmFn: vi.fn(), snackbar: { @@ -36,7 +34,7 @@ vi.mock("vue-router", async (importOriginal) => ({ useRouter: () => ({ replace: vi.fn(), push: vi.fn() }), })); vi.mock("@/services/api/rom", () => ({ - default: { uploadRoms, getRom, deleteRomFile: vi.fn() }, + default: { uploadRoms, deleteRomFile: vi.fn() }, })); vi.mock("@/v2/composables/useCan", async () => { const { computed } = await import("vue"); diff --git a/frontend/src/v2/components/GameDetails/ManualSubtab.vue b/frontend/src/v2/components/GameDetails/ManualSubtab.vue index b94935b4b..2a725770f 100644 --- a/frontend/src/v2/components/GameDetails/ManualSubtab.vue +++ b/frontend/src/v2/components/GameDetails/ManualSubtab.vue @@ -12,7 +12,7 @@ import type { Emitter } from "mitt"; import { computed, defineAsyncComponent, inject, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import romApi from "@/services/api/rom"; -import storeRoms, { type DetailedRom } from "@/stores/roms"; +import type { DetailedRom } from "@/stores/roms"; import type { Events } from "@/types/emitter"; import { FRONTEND_RESOURCES_PATH } from "@/utils"; import { useCan } from "@/v2/composables/useCan"; @@ -33,7 +33,6 @@ const TextViewer = defineAsyncComponent( const props = defineProps<{ rom: DetailedRom }>(); const emitter = inject>("emitter"); const snackbar = useSnackbar(); -const romsStore = storeRoms(); const { refetchCurrentRom } = useRomSync(); const { t } = useI18n(); @@ -123,10 +122,6 @@ const manualItems = computed(() => const manualDz = ref | null>(null); const redownloadingManual = ref(false); -async function refreshRom() { - await refetchCurrentRom(props.rom.id); -} - function handleManualFiles(files: File[]) { if (files.length === 0) return; emitter?.emit("showManualUploadTargetDialog", { rom: props.rom, files }); @@ -137,7 +132,7 @@ async function redownloadManual() { redownloadingManual.value = true; try { await romApi.redownloadManual({ romId: props.rom.id }); - await refreshRom(); + await refetchCurrentRom(props.rom.id); snackbar.success(t("rom.manual-redownloaded"), { icon: "mdi-check-bold", }); diff --git a/frontend/src/v2/components/GameDetails/MediaTab.vue b/frontend/src/v2/components/GameDetails/MediaTab.vue index fc6975f6d..6347adc2f 100644 --- a/frontend/src/v2/components/GameDetails/MediaTab.vue +++ b/frontend/src/v2/components/GameDetails/MediaTab.vue @@ -16,7 +16,7 @@ import { computed, defineAsyncComponent, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; import romApi from "@/services/api/rom"; -import storeRoms, { type DetailedRom } from "@/stores/roms"; +import type { DetailedRom } from "@/stores/roms"; import storeUpload from "@/stores/upload"; import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; @@ -50,7 +50,6 @@ const { loading: soundtrackLoading, fallbackArtUrl: soundtrackArtUrl, } = useRomSoundtrack(() => props.rom); -const romsStore = storeRoms(); const { refetchCurrentRom } = useRomSync(); const uploadStore = storeUpload(); const { t } = useI18n(); diff --git a/frontend/src/v2/components/GameDetails/NotesTab.vue b/frontend/src/v2/components/GameDetails/NotesTab.vue index 631649286..6c588a300 100644 --- a/frontend/src/v2/components/GameDetails/NotesTab.vue +++ b/frontend/src/v2/components/GameDetails/NotesTab.vue @@ -23,7 +23,6 @@ import type { UserNoteSchema } from "@/__generated__"; import romApi from "@/services/api/rom"; 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"; @@ -38,7 +37,6 @@ const { t } = useI18n(); const snackbar = useSnackbar(); const confirm = useConfirm(); const authStore = storeAuth(); -const romsStore = storeRoms(); const { refetchCurrentRom } = useRomSync(); const route = useRoute(); const router = useRouter(); diff --git a/frontend/src/v2/components/GameDetails/SaveDataTab.vue b/frontend/src/v2/components/GameDetails/SaveDataTab.vue index 8dc7b5a72..3080c3b15 100644 --- a/frontend/src/v2/components/GameDetails/SaveDataTab.vue +++ b/frontend/src/v2/components/GameDetails/SaveDataTab.vue @@ -27,11 +27,9 @@ import type { UserSaveSchema, UserStateSchema, } from "@/__generated__"; -import romApi from "@/services/api/rom"; import saveApi from "@/services/api/save"; import stateApi from "@/services/api/state"; import storeAuth from "@/stores/auth"; -import storeRoms from "@/stores/roms"; import AssetList from "@/v2/components/shared/AssetList.vue"; import AssetStrip from "@/v2/components/shared/AssetStrip.vue"; import { useConfirm } from "@/v2/composables/useConfirm"; @@ -138,7 +136,6 @@ const uploadingStates = ref(false); const snackbar = useSnackbar(); const confirm = useConfirm(); -const romsStore = storeRoms(); const { refetchCurrentRom } = useRomSync(); async function refreshRom() { diff --git a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue index 436d0d6b2..13fc00190 100644 --- a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue +++ b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue @@ -19,7 +19,7 @@ import { useI18n } from "vue-i18n"; import romApi from "@/services/api/rom"; import screenshotApi from "@/services/api/screenshot"; import storeAuth from "@/stores/auth"; -import storeRoms, { type DetailedRom } from "@/stores/roms"; +import type { DetailedRom } from "@/stores/roms"; import storeUpload from "@/stores/upload"; import type { ScreenshotItem } from "@/v2/components/GameDetails/ScreenshotsTab.vue"; import { useCan } from "@/v2/composables/useCan"; @@ -49,7 +49,6 @@ const props = defineProps<{ rom: DetailedRom }>(); const { t } = useI18n(); const snackbar = useSnackbar(); const confirm = useConfirm(); -const romsStore = storeRoms(); const { refetchCurrentRom } = useRomSync(); const uploadStore = storeUpload(); const authStore = storeAuth(); diff --git a/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue b/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue index a85817a27..64e975ff9 100644 --- a/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue +++ b/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue @@ -8,7 +8,7 @@ import axios from "axios"; import { computed, defineAsyncComponent, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import romApi from "@/services/api/rom"; -import storeRoms, { type DetailedRom } from "@/stores/roms"; +import type { DetailedRom } from "@/stores/roms"; import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; import { useRomSync } from "@/v2/composables/useRomSync"; @@ -45,7 +45,6 @@ type WalkthroughEntry = { const props = defineProps<{ rom: DetailedRom }>(); const snackbar = useSnackbar(); const confirm = useConfirm(); -const romsStore = storeRoms(); const { refetchCurrentRom } = useRomSync(); const { t } = useI18n(); diff --git a/frontend/src/v2/composables/useRomScanRefresh/index.test.ts b/frontend/src/v2/composables/useRomScanRefresh/index.test.ts index 8483b5471..fd7332d8e 100644 --- a/frontend/src/v2/composables/useRomScanRefresh/index.test.ts +++ b/frontend/src/v2/composables/useRomScanRefresh/index.test.ts @@ -14,7 +14,9 @@ vi.mock("@/services/socket", () => ({ on: (event: string, handler: (payload: unknown) => void) => { handlers.set(event, handler); }, - off: vi.fn(), + off: (event: string) => { + handlers.delete(event); + }, }, })); diff --git a/frontend/src/v2/composables/useRomScanRefresh/index.ts b/frontend/src/v2/composables/useRomScanRefresh/index.ts index d2a94d249..b9dce0f84 100644 --- a/frontend/src/v2/composables/useRomScanRefresh/index.ts +++ b/frontend/src/v2/composables/useRomScanRefresh/index.ts @@ -2,21 +2,18 @@ // events carry no file rows and the Files tab would keep the stale listing. import type { ScanStats } from "@/__generated__"; import storeRoms from "@/stores/roms"; -import { useIsAlive } from "@/v2/composables/useIsAlive"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSocketEvent } from "@/v2/composables/useSocketEvent"; export function useRomScanRefresh() { const romsStore = storeRoms(); const { refetchCurrentRom } = useRomSync(); - const alive = useIsAlive(); useSocketEvent( "scan:done", async () => { const romId = romsStore.currentRom?.id; - if (romId === undefined || !alive.value) return; - await refetchCurrentRom(romId); + if (romId !== undefined) await refetchCurrentRom(romId); }, { connect: false }, ); diff --git a/frontend/src/v2/composables/useRomSync/index.ts b/frontend/src/v2/composables/useRomSync/index.ts index fc396beb0..332921b2e 100644 --- a/frontend/src/v2/composables/useRomSync/index.ts +++ b/frontend/src/v2/composables/useRomSync/index.ts @@ -60,18 +60,16 @@ export function useRomSync() { } } - /** Re-read a ROM from the API and apply it everywhere it is cached. + /** Re-read a ROM from the API and apply it everywhere it is cached, for the + * surfaces that write a ROM's assets and need the detailed record back + * rather than the row the write returned. * - * 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. */ + * `syncCachedRom` owns the `currentRom` write, so a response that lands + * after the user opened another game updates the caches and leaves the + * open ROM alone. Returns null when the request failed. */ 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) {