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) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-03 21:21:33 -04:00
parent 73e0e0390f
commit a80858bb2b
13 changed files with 135 additions and 119 deletions

View File

@@ -19,7 +19,7 @@ const { t } = useI18n();
const emitter = inject<Emitter<Events>>("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(

View File

@@ -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();
});
});

View File

@@ -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);
}
</script>

View File

@@ -34,7 +34,7 @@ const props = defineProps<{ rom: DetailedRom }>();
const emitter = inject<Emitter<Events>>("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<InstanceType<typeof RDropzone> | 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[]) {

View File

@@ -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<SubtabDef[]>(() => [
const soundtrackDz = ref<InstanceType<typeof RDropzone> | 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) ----------

View File

@@ -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() {

View File

@@ -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[]) {

View File

@@ -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<ScreenshotItem[]>(() =>
);
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) ----------

View File

@@ -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 ----------

View File

@@ -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> = {}): 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();
});
});

View File

@@ -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<ScanStats>(
"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 },
);

View File

@@ -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> = {}): 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();
});
});
});

View File

@@ -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<DetailedRom | null> {
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,