From 24cd55abe57338fe75e4e4cd3550bca47c99ed28 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 19:34:39 +0200 Subject: [PATCH 1/6] feat(player): sync in-game saves seconds after the game writes them The periodic save upload only ran on EmulatorJS' "System Save interval" tick (5 minutes by default, never when the player disabled it), and was off unless emulatorjs.auto_save_sync was set. The player now flushes the SRAM itself every 5 seconds while the game runs, so the existing tracker sees a new in-game save on the next two agreeing ticks and uploads it, and the config flag defaults to on. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01MozJiij1oQbu12GvtAPBFR --- backend/config/config_manager.py | 2 +- .../tests/config/fixtures/config/config.yml | 2 +- backend/tests/config/test_config_loader.py | 4 +-- examples/config.example.yml | 2 +- frontend/src/stores/config.ts | 2 +- .../src/views/Player/EmulatorJS/Player.vue | 25 ++++++++++++++----- 6 files changed, 25 insertions(+), 12 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index ce6714425..c29fecfb4 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -756,7 +756,7 @@ class ConfigManager: self._raw_config, "emulatorjs.disable_batch_bootup", False ), EJS_ENABLE_AUTO_SAVE_SYNC=pydash.get( - self._raw_config, "emulatorjs.auto_save_sync", False + self._raw_config, "emulatorjs.auto_save_sync", True ), EJS_NETPLAY_ENABLED=pydash.get( self._raw_config, "emulatorjs.netplay.enabled", False diff --git a/backend/tests/config/fixtures/config/config.yml b/backend/tests/config/fixtures/config/config.yml index daee39102..5bde2c5d6 100644 --- a/backend/tests/config/fixtures/config/config.yml +++ b/backend/tests/config/fixtures/config/config.yml @@ -73,7 +73,7 @@ emulatorjs: cache_limit: 1000 disable_auto_unload: true disable_batch_bootup: true - auto_save_sync: true + auto_save_sync: false netplay: enabled: true ice_servers: diff --git a/backend/tests/config/test_config_loader.py b/backend/tests/config/test_config_loader.py index b5030c55a..325741c33 100644 --- a/backend/tests/config/test_config_loader.py +++ b/backend/tests/config/test_config_loader.py @@ -58,7 +58,7 @@ def test_config_loader(): assert loader.config.EJS_DEBUG assert loader.config.EJS_DISABLE_AUTO_UNLOAD assert loader.config.EJS_DISABLE_BATCH_BOOTUP - assert loader.config.EJS_ENABLE_AUTO_SAVE_SYNC + assert not loader.config.EJS_ENABLE_AUTO_SAVE_SYNC assert loader.config.EJS_CACHE_LIMIT == 1000 assert loader.config.EJS_NETPLAY_ENABLED assert loader.config.EJS_NETPLAY_ICE_SERVERS == [ @@ -161,7 +161,7 @@ def test_empty_config_loader(): assert loader.config.EJS_CACHE_LIMIT is None assert not loader.config.EJS_DISABLE_AUTO_UNLOAD assert not loader.config.EJS_DISABLE_BATCH_BOOTUP - assert not loader.config.EJS_ENABLE_AUTO_SAVE_SYNC + assert loader.config.EJS_ENABLE_AUTO_SAVE_SYNC assert not loader.config.EJS_NETPLAY_ENABLED assert loader.config.EJS_NETPLAY_ICE_SERVERS == [] assert loader.config.EJS_DEFAULT_CORES == {} diff --git a/examples/config.example.yml b/examples/config.example.yml index 5bac71808..e4a87cde1 100644 --- a/examples/config.example.yml +++ b/examples/config.example.yml @@ -182,7 +182,7 @@ # cache_limit: null # Cache limit per ROM (in bytes) # disable_batch_bootup: false # disable_auto_unload: false -# auto_save_sync: false # Upload the save to the server whenever it changes, without Save & Quit +# auto_save_sync: true # Upload the save to the server seconds after the game writes it, without Save & Quit # default_cores: # Core preselected per platform, unless overridden on the device # # Use the exact core name, as listed for the platform in the docs # nds: desmume diff --git a/frontend/src/stores/config.ts b/frontend/src/stores/config.ts index ecb9dd307..aa395e6a9 100644 --- a/frontend/src/stores/config.ts +++ b/frontend/src/stores/config.ts @@ -30,7 +30,7 @@ const defaultConfig = { EJS_CACHE_LIMIT: null, EJS_DISABLE_AUTO_UNLOAD: false, EJS_DISABLE_BATCH_BOOTUP: false, - EJS_ENABLE_AUTO_SAVE_SYNC: false, + EJS_ENABLE_AUTO_SAVE_SYNC: true, EJS_NETPLAY_ICE_SERVERS: [], EJS_DEFAULT_CORES: {}, EJS_SETTINGS: {}, diff --git a/frontend/src/views/Player/EmulatorJS/Player.vue b/frontend/src/views/Player/EmulatorJS/Player.vue index fec1dd753..957676973 100644 --- a/frontend/src/views/Player/EmulatorJS/Player.vue +++ b/frontend/src/views/Player/EmulatorJS/Player.vue @@ -294,7 +294,7 @@ onMounted(() => { }); onBeforeUnmount(async () => { - autoSaveSyncEmulator = null; + uninstallAutoSaveSync(); emitter?.off("saveSelected", loadSave); emitter?.off("stateSelected", loadState); window.EJS_emulator?.callEvent("exit"); @@ -344,10 +344,15 @@ async function waitForGameManager(timeoutMs = 5000): Promise { // frames rendered before loadState takes cleanly. const STATE_APPLY_SETTLE_MS = 500; -// Periodic save upload on EmulatorJS' "System Save interval" tick (see -// createSaveSyncTracker). EmulatorJS has no `off`, so the handler stays -// subscribed and this slot is what tells it the component still owns it. +// Periodic save upload on the "saveSaveFiles" tick (see createSaveSyncTracker). +// EmulatorJS flushes the SRAM only on its "System Save interval" (5 minutes by +// default), so a faster flush here gets an in-game save to the server seconds +// after the game writes it. +const SAVE_SYNC_POLL_MS = 5000; +// EmulatorJS has no `off`: the handler stays subscribed and this slot is what +// tells it the component still owns it. let autoSaveSyncEmulator: object | null = null; +let autoSaveSyncTimer: ReturnType | null = null; function installAutoSaveSync() { const emulator = window.EJS_emulator; if (!emulator?.gameManager || autoSaveSyncEmulator === emulator) return; @@ -373,6 +378,14 @@ function installAutoSaveSync() { uploading = false; } }); + autoSaveSyncTimer = setInterval(() => { + if (emulator.started) emulator.gameManager.saveSaveFiles(); + }, SAVE_SYNC_POLL_MS); +} +function uninstallAutoSaveSync() { + autoSaveSyncEmulator = null; + if (autoSaveSyncTimer) clearInterval(autoSaveSyncTimer); + autoSaveSyncTimer = null; } // Saves management @@ -585,7 +598,7 @@ window.EJS_onGameStart = async () => { const exitEmulation = createExitEmulationButton(); exitEmulation.addEventListener("click", async () => { - autoSaveSyncEmulator = null; + uninstallAutoSaveSync(); if (!romRef.value || !window.EJS_emulator) return immediateExit(); romsStore.update(romRef.value); immediateExit(); @@ -593,7 +606,7 @@ window.EJS_onGameStart = async () => { const saveAndQuit = createSaveQuitButton(); saveAndQuit.addEventListener("click", async () => { - autoSaveSyncEmulator = null; + uninstallAutoSaveSync(); if (!romRef.value || !window.EJS_emulator) return immediateExit(); // Grab the screenshot while the game is still running (EmulatorJS reads From 0019750559ed534972f1b661622330a3aaa250e6 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 20:15:56 +0200 Subject: [PATCH 2/6] feat(player): poll the SRAM every second and flush a pending save on exit The core has no write hook for its SRAM, so the sync polls it every second (scaled up past 1 MB to bound the copy-and-compare cost) instead of every five. Leaving the player through Quit or a back navigation uploads a save the tick has not caught up with yet, through a route guard that waits for the upload. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01MozJiij1oQbu12GvtAPBFR --- .../src/views/Player/EmulatorJS/Player.vue | 42 +++++++++++++++---- .../src/views/Player/EmulatorJS/utils.test.ts | 12 ++++++ frontend/src/views/Player/EmulatorJS/utils.ts | 11 +++-- 3 files changed, 54 insertions(+), 11 deletions(-) diff --git a/frontend/src/views/Player/EmulatorJS/Player.vue b/frontend/src/views/Player/EmulatorJS/Player.vue index 957676973..d79dde645 100644 --- a/frontend/src/views/Player/EmulatorJS/Player.vue +++ b/frontend/src/views/Player/EmulatorJS/Player.vue @@ -2,7 +2,7 @@ import type { Emitter } from "mitt"; import { storeToRefs } from "pinia"; import { inject, onBeforeUnmount, onMounted, onUnmounted, ref } from "vue"; -import { useRouter } from "vue-router"; +import { onBeforeRouteLeave, useRouter } from "vue-router"; import { useTheme } from "vuetify"; import type { FirmwareSchema, @@ -345,10 +345,13 @@ async function waitForGameManager(timeoutMs = 5000): Promise { const STATE_APPLY_SETTLE_MS = 500; // Periodic save upload on the "saveSaveFiles" tick (see createSaveSyncTracker). -// EmulatorJS flushes the SRAM only on its "System Save interval" (5 minutes by -// default), so a faster flush here gets an in-game save to the server seconds -// after the game writes it. -const SAVE_SYNC_POLL_MS = 5000; +// The core exposes no write hook for its SRAM and EmulatorJS flushes it only on +// its "System Save interval" (5 minutes by default), so polling it every second +// is what gets an in-game save to the server right after the game writes it. +const SAVE_SYNC_POLL_MS = 1000; +// Each tick copies and compares the whole SRAM, so the interval grows with it +// past 1 MB (1 ms of work per second either way) rather than hitching big saves. +const SAVE_SYNC_BYTES_PER_MS = 1024; // EmulatorJS has no `off`: the handler stays subscribed and this slot is what // tells it the component still owns it. let autoSaveSyncEmulator: object | null = null; @@ -378,15 +381,38 @@ function installAutoSaveSync() { uploading = false; } }); - autoSaveSyncTimer = setInterval(() => { - if (emulator.started) emulator.gameManager.saveSaveFiles(); - }, SAVE_SYNC_POLL_MS); + const sramBytes = emulator.gameManager.getSaveFile(false)?.byteLength ?? 0; + autoSaveSyncTimer = setInterval( + () => { + if (emulator.started) emulator.gameManager.saveSaveFiles(); + }, + Math.max(SAVE_SYNC_POLL_MS, sramBytes / SAVE_SYNC_BYTES_PER_MS), + ); } function uninstallAutoSaveSync() { autoSaveSyncEmulator = null; if (autoSaveSyncTimer) clearInterval(autoSaveSyncTimer); autoSaveSyncTimer = null; } +// A save written right before Quit or a back navigation has not had its two +// ticks yet, so leaving the player uploads whatever the server lacks. +async function flushPendingSave() { + const emulator = window.EJS_emulator; + if (!autoSaveSyncEmulator || autoSaveSyncEmulator !== emulator) return; + uninstallAutoSaveSync(); + emulator.pause(); + await new Promise((resolve) => setTimeout(resolve, 50)); + const saveFile: Uint8Array | null = emulator.gameManager.getSaveFile(); + if (!saveFile?.byteLength || !saveTracker.hasChanges(saveFile)) return; + try { + if (await writeSave({ saveFile: toArrayBuffer(saveFile) })) { + romsStore.update(romRef.value); + } + } catch (error) { + console.error("Save sync on exit failed", error); + } +} +onBeforeRouteLeave(flushPendingSave); // Saves management async function loadSave(save: SaveSchema) { diff --git a/frontend/src/views/Player/EmulatorJS/utils.test.ts b/frontend/src/views/Player/EmulatorJS/utils.test.ts index 95304acb0..637a8ae0f 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.test.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.test.ts @@ -186,6 +186,18 @@ describe("createSaveSyncTracker", () => { expect(tracker.shouldUpload(bytes(1, 2, 3))).toBe(false); }); + it("reports pending changes without waiting for a second tick", () => { + const tracker = createSaveSyncTracker(); + tracker.seed(server); + expect(tracker.hasChanges(bytes(9, 9))).toBe(false); + expect(tracker.hasChanges(a)).toBe(true); + tracker.markUploaded(a); + expect(tracker.hasChanges(bytes(1, 2, 3))).toBe(false); + tracker.baseline(b); + expect(tracker.hasChanges(bytes(4, 5, 6))).toBe(false); + expect(tracker.hasChanges(a)).toBe(true); + }); + it("never uploads a value that keeps changing between ticks", () => { const tracker = createSaveSyncTracker(); tracker.seed(null); diff --git a/frontend/src/views/Player/EmulatorJS/utils.ts b/frontend/src/views/Player/EmulatorJS/utils.ts index 619f8ca77..9ad4495e7 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.ts @@ -193,6 +193,10 @@ export function createSaveSyncTracker() { let lastUploaded: Uint8Array | null = null; let baseline: Uint8Array | null = null; let previousTick: Uint8Array | null = null; + // Bytes the server does not hold: neither the last upload nor the SRAM the + // session started from. + const hasChanges = (save: Uint8Array): boolean => + !bytesEqual(save, lastUploaded) && !bytesEqual(save, baseline); return { // Bytes downloaded from the server: neither the tick nor a forced write // needs to send them back. @@ -211,10 +215,11 @@ export function createSaveSyncTracker() { shouldUpload(save: Uint8Array): boolean { const stable = bytesEqual(save, previousTick); previousTick = save; - return ( - stable && !bytesEqual(save, lastUploaded) && !bytesEqual(save, baseline) - ); + return stable && hasChanges(save); }, + // Leaving the player cannot wait for a second tick, so it uploads on + // this alone. + hasChanges, markUploaded(save: Uint8Array) { lastUploaded = save; baseline = null; From efccb6743be126e6ebadb70b08a9c79b29dfe2d8 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 20:33:53 +0200 Subject: [PATCH 3/6] feat(player): keep a pending save when the tab closes The browser cancels requests in flight on unload, so a save the tick has not uploaded goes out on pagehide through fetch with keepalive, which outlives the document but is capped at 64 KB. While a save is pending, beforeunload shows the leave prompt, the only way to keep a save above that cap, and runs ahead of EmulatorJS' own unload handler so a cancelled close keeps the game running. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01MozJiij1oQbu12GvtAPBFR --- frontend/src/services/api/save.test.ts | 90 +++++++++++++++++ frontend/src/services/api/save.ts | 99 ++++++++++++++----- .../src/views/Player/EmulatorJS/Player.vue | 34 +++++++ .../src/views/Player/EmulatorJS/utils.test.ts | 41 ++++++++ frontend/src/views/Player/EmulatorJS/utils.ts | 48 +++++++-- 5 files changed, 281 insertions(+), 31 deletions(-) create mode 100644 frontend/src/services/api/save.test.ts diff --git a/frontend/src/services/api/save.test.ts b/frontend/src/services/api/save.test.ts new file mode 100644 index 000000000..9ad792fcb --- /dev/null +++ b/frontend/src/services/api/save.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { DetailedRomSchema, SaveSchema } from "@/__generated__"; +import saveApi, { UNLOAD_SAVE_MAX_BYTES } from "@/services/api/save"; + +vi.mock("@/services/api", () => ({ + default: { + getUri: ({ + url, + params, + }: { + url: string; + params?: Record; + }) => { + const query = new URLSearchParams(); + for (const [key, value] of Object.entries(params ?? {})) { + if (value !== undefined && value !== null) { + query.append(key, String(value)); + } + } + const search = query.toString(); + return `/api${url}${search ? `?${search}` : ""}`; + }, + }, +})); + +const rom = { id: 1 } as DetailedRomSchema; +const saveOf = (size: number) => new File([new Uint8Array(size)], "game.srm"); + +describe("sendSaveOnUnload", () => { + const fetchMock = vi.fn().mockResolvedValue(new Response()); + + beforeEach(() => { + vi.stubGlobal("fetch", fetchMock); + document.cookie = "romm_csrftoken=token"; + }); + + afterEach(() => { + vi.unstubAllGlobals(); + fetchMock.mockClear(); + }); + + it("opens a version with a keepalive request the page does not wait for", () => { + const sent = saveApi.sendSaveOnUnload({ + rom, + save: null, + saveFile: saveOf(16), + emulator: "snes9x", + deviceId: "dev", + slot: "autosave", + autocleanup: true, + }); + + expect(sent).toBe(true); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe( + "/api/saves?rom_id=1&emulator=snes9x&device_id=dev&slot=autosave&autocleanup=true&overwrite=true", + ); + expect(init).toMatchObject({ + method: "POST", + keepalive: true, + credentials: "same-origin", + headers: { "x-csrftoken": "token" }, + }); + expect((init?.body as FormData).get("saveFile")).toBeInstanceOf(File); + }); + + it("updates the session's version in place", () => { + saveApi.sendSaveOnUnload({ + rom, + save: { id: 3 } as SaveSchema, + saveFile: saveOf(16), + deviceId: "dev", + }); + + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe("/api/saves/3?device_id=dev"); + expect(init).toMatchObject({ method: "PUT", keepalive: true }); + }); + + it("refuses a save a keepalive body cannot carry", () => { + const sent = saveApi.sendSaveOnUnload({ + rom, + save: null, + saveFile: saveOf(UNLOAD_SAVE_MAX_BYTES + 1), + }); + + expect(sent).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/services/api/save.ts b/frontend/src/services/api/save.ts index 243d0585c..671facfd8 100644 --- a/frontend/src/services/api/save.ts +++ b/frontend/src/services/api/save.ts @@ -1,3 +1,4 @@ +import { default as Cookies } from "js-cookie"; import type { Body_add_save_api_saves_post as AddSaveInput, Body_update_save_api_saves__id__put as UpdateSaveInput, @@ -14,6 +15,9 @@ export const saveApi = api; export const AUTOSAVE_SLOT = "autosave"; // Mirrors the backend's SAVE_SLOT_MAX_LENGTH so the field stops at the limit. export const SAVE_SLOT_MAX_LENGTH = 255; +// A keepalive request outlives its document, which is why the browser caps +// its body at 64 KB; the rest is left for the multipart framing. +export const UNLOAD_SAVE_MAX_BYTES = 60 * 1024; type SaveUploadInput = Omit & { saveFile: File; @@ -28,44 +32,53 @@ type UpdateSaveUploadInput = Omit< screenshotFile?: File; }; -async function uploadSaves({ - rom, - savesToUpload, - emulator, - deviceId, - slot, - autocleanup, - overwrite, -}: { +interface SaveVersionParams { rom: DetailedRomSchema; - savesToUpload: SaveUploadInput[]; emulator?: string; deviceId?: string; slot?: string; autocleanup?: boolean; /** Skip the stale-device conflict check and the content-hash dedupe. */ overwrite?: boolean; -}) { - const promises = savesToUpload.map(({ saveFile, screenshotFile }) => { - const formData = buildFormInput([ - ["saveFile", saveFile], - ["screenshotFile", screenshotFile], - ]); +} +function saveVersionQuery({ + rom, + emulator, + deviceId, + slot, + autocleanup, + overwrite, +}: SaveVersionParams) { + return { + rom_id: rom.id, + emulator, + device_id: deviceId, + slot, + autocleanup, + overwrite, + }; +} + +function saveFormData(saveFile: File, screenshotFile?: File): FormData { + return buildFormInput([ + ["saveFile", saveFile], + ["screenshotFile", screenshotFile], + ]); +} + +async function uploadSaves({ + savesToUpload, + ...version +}: SaveVersionParams & { savesToUpload: SaveUploadInput[] }) { + const promises = savesToUpload.map(({ saveFile, screenshotFile }) => { return new Promise((resolve, reject) => { api - .post("/saves", formData, { + .post("/saves", saveFormData(saveFile, screenshotFile), { headers: { "Content-Type": "multipart/form-data", }, - params: { - rom_id: rom.id, - emulator, - device_id: deviceId, - slot, - autocleanup, - overwrite, - }, + params: saveVersionQuery(version), }) .then(({ data }) => { resolve(data); @@ -98,6 +111,41 @@ async function updateSave({ }); } +/** + * Sends a save while the page unloads, updating `save` in place or opening a + * version in `slot`. Nothing outlives the document to await it. + * + * Returns: + * False when the save is too big for a keepalive body. + */ +function sendSaveOnUnload({ + save, + saveFile, + ...version +}: SaveVersionParams & { save: SaveSchema | null; saveFile: File }): boolean { + if (saveFile.size > UNLOAD_SAVE_MAX_BYTES) return false; + const request = save + ? { + url: `/saves/${save.id}`, + method: "PUT", + params: { device_id: version.deviceId }, + } + : { + url: "/saves", + method: "POST", + params: saveVersionQuery({ ...version, overwrite: true }), + }; + const csrfToken = Cookies.get("romm_csrftoken"); + void fetch(api.getUri(request), { + method: request.method, + body: saveFormData(saveFile), + keepalive: true, + credentials: "same-origin", + headers: csrfToken ? { "x-csrftoken": csrfToken } : undefined, + }).catch(() => undefined); + return true; +} + async function deleteSaves({ saves }: { saves: SaveSchema[] }) { return api.post("/saves/delete", { saves: saves.map((s) => s.id) }); } @@ -117,6 +165,7 @@ async function setSaveVisibility({ export default { uploadSaves, updateSave, + sendSaveOnUnload, deleteSaves, setSaveVisibility, }; diff --git a/frontend/src/views/Player/EmulatorJS/Player.vue b/frontend/src/views/Player/EmulatorJS/Player.vue index d79dde645..15f3c43a5 100644 --- a/frontend/src/views/Player/EmulatorJS/Player.vue +++ b/frontend/src/views/Player/EmulatorJS/Player.vue @@ -36,6 +36,7 @@ import { createSaveQuitButton, createExitEmulationButton, createSaveSyncTracker, + saveSaveOnUnload, toArrayBuffer, } from "./utils"; @@ -259,6 +260,10 @@ installEJSDefaultOptionsTrap(); onMounted(() => { window.scrollTo(0, 0); + // Registered before EmulatorJS binds its own unload handler, so the + // pending-save check runs first. + window.addEventListener("beforeunload", onBeforeUnload); + window.addEventListener("pagehide", onPageHide); if (props.bios) { localStorage.setItem( `player:${romRef.value.platform_slug}:bios_id`, @@ -294,6 +299,8 @@ onMounted(() => { }); onBeforeUnmount(async () => { + window.removeEventListener("beforeunload", onBeforeUnload); + window.removeEventListener("pagehide", onPageHide); uninstallAutoSaveSync(); emitter?.off("saveSelected", loadSave); emitter?.off("stateSelected", loadState); @@ -413,6 +420,33 @@ async function flushPendingSave() { } } onBeforeRouteLeave(flushPendingSave); +// Closing the tab cancels requests in flight, so a save the tick has not +// uploaded goes out on `pagehide` with fetch keepalive, which the browser caps +// at 64 KB. `beforeunload` asks first while one is pending: for a bigger save +// that prompt is the only way to keep it. +let unloadSave: Uint8Array | null = null; +function onBeforeUnload(event: BeforeUnloadEvent) { + const emulator = window.EJS_emulator; + if (!autoSaveSyncEmulator || autoSaveSyncEmulator !== emulator) return; + if (saveLoading) return; + const saveFile: Uint8Array | null = emulator.gameManager.getSaveFile(); + if (!saveFile?.byteLength || !saveTracker.hasChanges(saveFile)) return; + unloadSave = saveFile; + // EmulatorJS tears the core down on this event, and a cancelled close has + // to keep the game running. + event.stopImmediatePropagation(); + event.preventDefault(); +} +function onPageHide() { + if (!unloadSave || !saveTracker.hasChanges(unloadSave)) return; + saveSaveOnUnload({ + rom: romRef.value, + save: sessionSaveRef.value, + saveFile: toArrayBuffer(unloadSave), + deviceId: deviceIDRef.value, + slot: loadedSave?.slot || props.saveSlot || undefined, + }); +} // Saves management async function loadSave(save: SaveSchema) { diff --git a/frontend/src/views/Player/EmulatorJS/utils.test.ts b/frontend/src/views/Player/EmulatorJS/utils.test.ts index 637a8ae0f..90a17e0a6 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.test.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.test.ts @@ -9,12 +9,14 @@ import { installEJSDefaultOptionsTrap, resolveStateScreenshot, saveSave, + saveSaveOnUnload, saveState, } from "./utils"; const saveApiMocks = vi.hoisted(() => ({ uploadSaves: vi.fn(), updateSave: vi.fn(), + sendSaveOnUnload: vi.fn(), })); const stateApiMocks = vi.hoisted(() => ({ uploadStates: vi.fn(), @@ -349,6 +351,45 @@ describe("saveState", () => { }); }); +describe("saveSaveOnUnload", () => { + const rom = { id: 1, fs_name_no_ext: "game " } as unknown as DetailedRom; + const bytes = new Uint8Array([1, 2, 3]).buffer; + + beforeEach(() => { + saveApiMocks.sendSaveOnUnload.mockReset().mockReturnValue(true); + }); + + it("opens a capped autosave version named after the rom", () => { + expect(saveSaveOnUnload({ rom, save: null, saveFile: bytes })).toBe(true); + + const request = saveApiMocks.sendSaveOnUnload.mock.calls[0][0]; + expect(request).toMatchObject({ + save: null, + slot: "autosave", + autocleanup: true, + }); + expect(request.saveFile.name).toBe("game.srm"); + }); + + it("updates the session's version under its own name", () => { + const save = { + id: 3, + file_name: "a.srm", + slot: "main_quest", + } as SaveSchema; + + saveSaveOnUnload({ rom, save, saveFile: bytes, slot: "main_quest" }); + + const request = saveApiMocks.sendSaveOnUnload.mock.calls[0][0]; + expect(request).toMatchObject({ + save, + slot: "main_quest", + autocleanup: false, + }); + expect(request.saveFile.name).toBe("a.srm"); + }); +}); + describe("buildStateFormData", () => { const bytes = new Uint8Array([1, 2, 3]).buffer; diff --git a/frontend/src/views/Player/EmulatorJS/utils.ts b/frontend/src/views/Player/EmulatorJS/utils.ts index 9ad4495e7..e3c35acc2 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.ts @@ -100,6 +100,20 @@ export async function saveState({ return null; } +// Session saves are named after the ROM; a version updated in place keeps +// its name. +function sessionSaveFile( + rom: DetailedRom, + save: SaveSchema | null, + bytes: ArrayBuffer, +): File { + return new File( + [bytes], + save ? save.file_name : `${rom.fs_name_no_ext.trim()}.srm`, + { type: "application/octet-stream" }, + ); +} + // `save` is the version this session already created: it is updated in place, // while a null `save` opens a new version in `slot`. export async function saveSave({ @@ -121,9 +135,7 @@ export async function saveSave({ try { const { data: updatedSave } = await saveApi.updateSave({ save: save, - saveFile: new File([saveFile], save.file_name, { - type: "application/octet-stream", - }), + saveFile: sessionSaveFile(rom, save, saveFile), // A version opened by the periodic sync has no screenshot yet; name a // new one after the save so the backend links it by stem. screenshotFile: screenshotFile @@ -163,9 +175,7 @@ export async function saveSave({ overwrite: true, savesToUpload: [ { - saveFile: new File([saveFile], `${filename}.srm`, { - type: "application/octet-stream", - }), + saveFile: sessionSaveFile(rom, null, saveFile), screenshotFile: screenshotFile ? new File([screenshotFile], `${filename}.png`, { type: "application/octet-stream", @@ -187,6 +197,32 @@ export async function saveSave({ return null; } +// The unload counterpart of saveSave: nothing awaits it, so the rom's list is +// left alone. False when the save is too big for a keepalive body. +export function saveSaveOnUnload({ + rom, + save, + saveFile, + deviceId, + slot = AUTOSAVE_SLOT, +}: { + rom: DetailedRom; + save: SaveSchema | null; + saveFile: ArrayBuffer; + deviceId?: string; + slot?: string; +}): boolean { + return saveApi.sendSaveOnUnload({ + rom, + save, + saveFile: sessionSaveFile(rom, save, saveFile), + emulator: window.EJS_core, + deviceId, + slot, + autocleanup: slot === AUTOSAVE_SLOT, + }); +} + // Per EmulatorJS "saveSaveFiles" tick, whether the SRAM is worth uploading // (#4201). Two agreeing ticks keep a mid-write save from being uploaded (#2349). export function createSaveSyncTracker() { From 21185aab22070006980f5f2c5ca4686829820f84 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 20:40:41 +0200 Subject: [PATCH 4/6] style(player): dress the in-game sync toasts like the v2 toast EmulatorJS' message element takes the v2 toast's glass panel (tokens with v1 theme fallbacks), a tone-tinted icon instead of a solid colored bar, sentence case, and a short fade in and out. The "synced with server" messages read as successes. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01MozJiij1oQbu12GvtAPBFR --- .../src/views/Player/EmulatorJS/Player.vue | 58 ++++++++++++++----- 1 file changed, 42 insertions(+), 16 deletions(-) diff --git a/frontend/src/views/Player/EmulatorJS/Player.vue b/frontend/src/views/Player/EmulatorJS/Player.vue index 15f3c43a5..1cf09c71e 100644 --- a/frontend/src/views/Player/EmulatorJS/Player.vue +++ b/frontend/src/views/Player/EmulatorJS/Player.vue @@ -379,6 +379,7 @@ function installAutoSaveSync() { romsStore.update(romRef.value); displayMessage("Save synced with server", { duration: 3000, + className: "msg-success", icon: "mdi-cloud-sync", }); } @@ -495,6 +496,7 @@ window.EJS_onSaveSave = async function ({ if (synced) { displayMessage("Save synced with server", { duration: 4000, + className: "msg-success", icon: "mdi-cloud-sync", }); } else { @@ -550,6 +552,7 @@ window.EJS_onSaveState = async function ({ if (state) { displayMessage("State synced with server", { duration: 4000, + className: "msg-success", icon: "mdi-cloud-sync", }); } else { @@ -743,35 +746,58 @@ onUnmounted(() => { } /* EmulatorJS raises its own messages through this element and adds none of - RomM's classes, so the unclassed state has to be legible. */ + RomM's classes, so the unclassed state has to be legible. It wears the v2 + toast's glass panel; the fallbacks keep it readable under the v1 theme. */ #game .ejs_message { - margin: 1rem; - padding: 0.25rem 0.75rem; - border-radius: 4px; - background-color: rgba(var(--v-theme-romm-blue)); - color: white; - text-transform: uppercase; + top: 16px; + left: 16px; + margin: 0; + padding: 10px 12px; + max-width: min(420px, calc(100% - 32px)); display: flex; align-items: center; - filter: opacity(0.85) drop-shadow(0 0 0.5rem rgba(0, 0, 0, 0.5)); + gap: 10px; + border: 1px solid + var(--r-color-border-strong, rgba(var(--v-theme-on-surface), 0.15)); + border-radius: var(--r-radius-md, 8px); + background: var(--r-color-toast-bg, rgba(var(--v-theme-surface), 0.92)); + backdrop-filter: blur(18px); + box-shadow: + 0 10px 28px color-mix(in srgb, black 45%, transparent), + 0 2px 6px color-mix(in srgb, black 30%, transparent); + color: var(--r-color-fg, rgb(var(--v-theme-on-surface))); + font: 13px / 1.45 var(--r-font-family-sans, inherit); + text-shadow: none; + transition: + opacity var(--r-motion-fast, 160ms) var(--r-motion-ease-out, ease-out), + transform var(--r-motion-fast, 160ms) var(--r-motion-ease-out, ease-out); } -/* A message expires by having its text cleared, not the element removed. */ +/* A message expires by having its text cleared, not the element removed, so + the empty state is where it fades out. */ #game .ejs_message:empty { + opacity: 0; + transform: translateY(-6px); visibility: hidden; + transition: + opacity var(--r-motion-fast, 160ms) var(--r-motion-ease-out, ease-out), + transform var(--r-motion-fast, 160ms) var(--r-motion-ease-out, ease-out), + visibility 0s var(--r-motion-fast, 160ms); } +/* The icon class lands on the message itself, so the glyph is its ::before, + tinted by tone like the v2 toast icon. */ #game .ejs_message::before { - margin-right: 8px; - font-size: 20px !important; - font: normal normal normal 24px / 1 "Material Design Icons"; + flex-shrink: 0; + font: normal normal normal 18px / 1 "Material Design Icons"; + color: var(--r-color-brand-primary, rgb(var(--v-theme-romm-blue))); } -#game .ejs_message.msg-error { - background-color: rgba(var(--v-theme-romm-red)); +#game .ejs_message.msg-success::before { + color: var(--r-color-success, rgb(var(--v-theme-romm-green))); } -#game .ejs_message.msg-success { - background-color: rgba(var(--v-theme-romm-green)); +#game .ejs_message.msg-error::before { + color: var(--r-color-danger-fg, rgb(var(--v-theme-romm-red))); } From 2d374990f46652b2eb09de39a683a0aa2ac61437 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 20:52:50 +0200 Subject: [PATCH 5/6] feat(player): boot from the latest progress of either kind The launch screen armed the newest compatible state whenever one existed, even when a save was newer. It now picks whichever of the newest save and the newest compatible state is later, with a state winning a tie since it restores the SRAM too. The newer-progress warning shares that choice. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01MozJiij1oQbu12GvtAPBFR --- .../v2/views/Player/resumeSelection.test.ts | 55 +++++++++++++++---- .../src/v2/views/Player/resumeSelection.ts | 37 ++++++++----- 2 files changed, 68 insertions(+), 24 deletions(-) diff --git a/frontend/src/v2/views/Player/resumeSelection.test.ts b/frontend/src/v2/views/Player/resumeSelection.test.ts index b9681243d..4a7abed72 100644 --- a/frontend/src/v2/views/Player/resumeSelection.test.ts +++ b/frontend/src/v2/views/Player/resumeSelection.test.ts @@ -7,9 +7,10 @@ import { pickState, } from "./resumeSelection"; -const save = (id: number, slot: string | null = null) => - ({ id, file_name: `${id}.srm`, slot }) as SaveSchema; -const state = (id: number) => ({ id, file_name: `${id}.state` }) as StateSchema; +const save = (id: number, updated_at = "", slot: string | null = null) => + ({ id, file_name: `${id}.srm`, updated_at, slot }) as SaveSchema; +const state = (id: number, updated_at = "") => + ({ id, file_name: `${id}.state`, updated_at }) as StateSchema; describe("defaultResumeSelection", () => { it("starts fresh when there is nothing to resume from", () => { @@ -17,19 +18,51 @@ describe("defaultResumeSelection", () => { }); it("boots from the newest save when no state is compatible", () => { - expect(defaultResumeSelection([save(1), save(2)], [])).toEqual({ - save: save(1), + const saves = [ + save(1, "2026-09-01T10:00:00Z"), + save(2, "2026-09-02T10:00:00Z"), + ]; + + expect(defaultResumeSelection(saves, [])).toEqual({ + save: saves[1], state: null, }); }); - it("arms the newest state and binds no save", () => { - const selection = defaultResumeSelection( - [save(1, "main"), save(2)], - [state(9), state(8)], - ); + it("arms the newest state when it is the latest progress", () => { + const saves = [ + save(1, "2026-09-03T10:00:00Z", "main"), + save(2, "2026-09-01T10:00:00Z"), + ]; + const states = [ + state(9, "2026-09-02T10:00:00Z"), + state(8, "2026-09-04T10:00:00Z"), + ]; - expect(selection).toEqual({ save: null, state: state(9) }); + expect(defaultResumeSelection(saves, states)).toEqual({ + save: null, + state: states[1], + }); + }); + + it("boots from the save when it postdates every compatible state", () => { + const saves = [save(1, "2026-09-05T10:00:00Z", "main")]; + const states = [state(9, "2026-09-04T10:00:00Z")]; + + expect(defaultResumeSelection(saves, states)).toEqual({ + save: saves[0], + state: null, + }); + }); + + it("lets the state win a tie, since it restores the SRAM too", () => { + const saves = [save(1, "2026-09-05T10:00:00Z")]; + const states = [state(9, "2026-09-05T10:00:00Z")]; + + expect(defaultResumeSelection(saves, states)).toEqual({ + save: null, + state: states[0], + }); }); }); diff --git a/frontend/src/v2/views/Player/resumeSelection.ts b/frontend/src/v2/views/Player/resumeSelection.ts index 23425abb3..8a3f5c14c 100644 --- a/frontend/src/v2/views/Player/resumeSelection.ts +++ b/frontend/src/v2/views/Player/resumeSelection.ts @@ -2,19 +2,38 @@ import type { SaveSchema, StateSchema } from "@/__generated__"; import { newest } from "@/v2/utils/assets"; // What the player boots from and where progress is written back. A state -// restores the whole machine, SRAM included, so it wins at boot. +// restores the whole machine, SRAM included, so it wins a tie at boot. export interface ResumeSelection { save: SaveSchema | null; state: StateSchema | null; } -/** The newest compatible state, else the newest save; never both. */ +export type NewerAsset = + { kind: "save"; asset: SaveSchema } | { kind: "state"; asset: StateSchema }; + +/** The latest progress of either kind; a state wins a tie. */ +function newestOfEither( + saves: readonly SaveSchema[], + compatibleStates: readonly StateSchema[], +): NewerAsset | null { + const save = newest(saves); + const state = newest(compatibleStates); + if (state && (!save || state.updated_at >= save.updated_at)) { + return { kind: "state", asset: state }; + } + return save && { kind: "save", asset: save }; +} + +/** The newest save or compatible state, whichever is later; never both. */ export function defaultResumeSelection( saves: readonly SaveSchema[], compatibleStates: readonly StateSchema[], ): ResumeSelection { - const state = compatibleStates[0] ?? null; - return { save: state ? null : (saves[0] ?? null), state }; + const latest = newestOfEither(saves, compatibleStates); + if (!latest) return { save: null, state: null }; + return latest.kind === "state" + ? pickState(latest.asset) + : pickSave(latest.asset); } /** A picked save is the boot source, so any armed state is disarmed. */ @@ -27,9 +46,6 @@ export function pickState(state: StateSchema): ResumeSelection { return { save: null, state }; } -export type NewerAsset = - { kind: "save"; asset: SaveSchema } | { kind: "state"; asset: StateSchema }; - /** * The newest save or compatible state when it postdates what boots, so the * user can be warned before older progress rolls the newer back. @@ -41,12 +57,7 @@ export function newerThanPick( ): NewerAsset | null { const picked = selection.state ?? selection.save; if (!picked) return null; - const save = newest(saves); - const state = newest(compatibleStates); - const candidate: NewerAsset | null = - state && (!save || state.updated_at > save.updated_at) - ? { kind: "state", asset: state } - : save && { kind: "save", asset: save }; + const candidate = newestOfEither(saves, compatibleStates); return candidate && candidate.asset.updated_at > picked.updated_at ? candidate : null; From e5e5f00b77f1d81a3f8f2f04196a8ff5af785666 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 21:09:21 +0200 Subject: [PATCH 6/6] fix(player): flush on Quit, drop stale unload bytes, test the SRAM poll Quit cleared the sync sentinel before routing away, so the route guard that flushes a pending save found nothing to own and skipped it; Quit now flushes first. A close cancelled at the prompt kept the bytes it captured, which a later close could upload over newer progress; each beforeunload starts clean. The unload upload also stands down while the same bytes are already on the wire, beforeunload sets returnValue for older browsers, and a boot that lands after unmount installs nothing. The poll moves to pollSaveFiles in utils, covered with fake timers. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01MozJiij1oQbu12GvtAPBFR --- .../src/views/Player/EmulatorJS/Player.vue | 74 ++++++++++--------- .../src/views/Player/EmulatorJS/utils.test.ts | 42 +++++++++++ frontend/src/views/Player/EmulatorJS/utils.ts | 39 +++++++++- 3 files changed, 121 insertions(+), 34 deletions(-) diff --git a/frontend/src/views/Player/EmulatorJS/Player.vue b/frontend/src/views/Player/EmulatorJS/Player.vue index 1cf09c71e..9f2e4f478 100644 --- a/frontend/src/views/Player/EmulatorJS/Player.vue +++ b/frontend/src/views/Player/EmulatorJS/Player.vue @@ -36,6 +36,8 @@ import { createSaveQuitButton, createExitEmulationButton, createSaveSyncTracker, + bytesEqual, + pollSaveFiles, saveSaveOnUnload, toArrayBuffer, } from "./utils"; @@ -79,6 +81,8 @@ function baselineSaveTrackerFromEmulator() { let saveWrite: Promise = Promise.resolve(); let saveGeneration = 0; let saveLoading = false; +// The bytes of the write on the wire, for the unload path to leave alone. +let inFlightSave: Uint8Array | null = null; function writeSave( file: { saveFile: ArrayBuffer; screenshotFile?: ArrayBuffer }, generation = saveGeneration, @@ -86,18 +90,24 @@ function writeSave( if (saveLoading) return Promise.resolve(null); const write = saveWrite.then(async () => { if (generation !== saveGeneration) return null; - const save = await saveSave({ - rom: romRef.value, - save: sessionSaveRef.value, - deviceId: deviceIDRef.value, - slot: loadedSave?.slot || props.saveSlot || undefined, - ...file, - }); - if (save && generation === saveGeneration) { - sessionSaveRef.value = save; - saveTracker.markUploaded(new Uint8Array(file.saveFile)); + const bytes = new Uint8Array(file.saveFile); + inFlightSave = bytes; + try { + const save = await saveSave({ + rom: romRef.value, + save: sessionSaveRef.value, + deviceId: deviceIDRef.value, + slot: loadedSave?.slot || props.saveSlot || undefined, + ...file, + }); + if (save && generation === saveGeneration) { + sessionSaveRef.value = save; + saveTracker.markUploaded(bytes); + } + return save; + } finally { + inFlightSave = null; } - return save; }); saveWrite = write.catch(() => null); return write; @@ -299,6 +309,7 @@ onMounted(() => { }); onBeforeUnmount(async () => { + disposed = true; window.removeEventListener("beforeunload", onBeforeUnload); window.removeEventListener("pagehide", onPageHide); uninstallAutoSaveSync(); @@ -351,21 +362,17 @@ async function waitForGameManager(timeoutMs = 5000): Promise { // frames rendered before loadState takes cleanly. const STATE_APPLY_SETTLE_MS = 500; -// Periodic save upload on the "saveSaveFiles" tick (see createSaveSyncTracker). -// The core exposes no write hook for its SRAM and EmulatorJS flushes it only on -// its "System Save interval" (5 minutes by default), so polling it every second -// is what gets an in-game save to the server right after the game writes it. -const SAVE_SYNC_POLL_MS = 1000; -// Each tick copies and compares the whole SRAM, so the interval grows with it -// past 1 MB (1 ms of work per second either way) rather than hitching big saves. -const SAVE_SYNC_BYTES_PER_MS = 1024; -// EmulatorJS has no `off`: the handler stays subscribed and this slot is what -// tells it the component still owns it. +// Periodic save upload on the "saveSaveFiles" tick that pollSaveFiles fires +// (see createSaveSyncTracker). EmulatorJS has no `off`: the handler stays +// subscribed and this slot is what tells it the component still owns it. let autoSaveSyncEmulator: object | null = null; -let autoSaveSyncTimer: ReturnType | null = null; +let stopSavePolling: (() => void) | null = null; +// The boot path awaits before installing, so it may land after unmount. +let disposed = false; function installAutoSaveSync() { const emulator = window.EJS_emulator; - if (!emulator?.gameManager || autoSaveSyncEmulator === emulator) return; + if (disposed || !emulator?.gameManager) return; + if (autoSaveSyncEmulator === emulator) return; autoSaveSyncEmulator = emulator; let uploading = false; emulator.on("saveSaveFiles", async (saveFile: Uint8Array | null) => { @@ -389,18 +396,12 @@ function installAutoSaveSync() { uploading = false; } }); - const sramBytes = emulator.gameManager.getSaveFile(false)?.byteLength ?? 0; - autoSaveSyncTimer = setInterval( - () => { - if (emulator.started) emulator.gameManager.saveSaveFiles(); - }, - Math.max(SAVE_SYNC_POLL_MS, sramBytes / SAVE_SYNC_BYTES_PER_MS), - ); + stopSavePolling = pollSaveFiles(emulator); } function uninstallAutoSaveSync() { autoSaveSyncEmulator = null; - if (autoSaveSyncTimer) clearInterval(autoSaveSyncTimer); - autoSaveSyncTimer = null; + stopSavePolling?.(); + stopSavePolling = null; } // A save written right before Quit or a back navigation has not had its two // ticks yet, so leaving the player uploads whatever the server lacks. @@ -427,6 +428,8 @@ onBeforeRouteLeave(flushPendingSave); // that prompt is the only way to keep it. let unloadSave: Uint8Array | null = null; function onBeforeUnload(event: BeforeUnloadEvent) { + // A close cancelled earlier leaves the bytes it captured behind. + unloadSave = null; const emulator = window.EJS_emulator; if (!autoSaveSyncEmulator || autoSaveSyncEmulator !== emulator) return; if (saveLoading) return; @@ -436,10 +439,15 @@ function onBeforeUnload(event: BeforeUnloadEvent) { // EmulatorJS tears the core down on this event, and a cancelled close has // to keep the game running. event.stopImmediatePropagation(); + // preventDefault covers the current spec, returnValue the older browsers. event.preventDefault(); + event.returnValue = ""; } function onPageHide() { if (!unloadSave || !saveTracker.hasChanges(unloadSave)) return; + // These bytes are already on the wire: a second POST would only open a + // duplicate version. + if (inFlightSave && bytesEqual(inFlightSave, unloadSave)) return; saveSaveOnUnload({ rom: romRef.value, save: sessionSaveRef.value, @@ -661,8 +669,8 @@ window.EJS_onGameStart = async () => { const exitEmulation = createExitEmulationButton(); exitEmulation.addEventListener("click", async () => { - uninstallAutoSaveSync(); if (!romRef.value || !window.EJS_emulator) return immediateExit(); + await flushPendingSave(); romsStore.update(romRef.value); immediateExit(); }); diff --git a/frontend/src/views/Player/EmulatorJS/utils.test.ts b/frontend/src/views/Player/EmulatorJS/utils.test.ts index 90a17e0a6..218037b47 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.test.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.test.ts @@ -7,6 +7,7 @@ import { captureStateScreenshot, createSaveSyncTracker, installEJSDefaultOptionsTrap, + pollSaveFiles, resolveStateScreenshot, saveSave, saveSaveOnUnload, @@ -257,6 +258,47 @@ describe("createSaveSyncTracker", () => { }); }); +describe("pollSaveFiles", () => { + const emulatorWith = (sramBytes: number) => ({ + started: true, + gameManager: { + saveSaveFiles: vi.fn(), + getSaveFile: () => new Uint8Array(sramBytes), + }, + }); + + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it("flushes every second while the game runs and stops on demand", () => { + const emulator = emulatorWith(128 * 1024); + const stop = pollSaveFiles(emulator); + + vi.advanceTimersByTime(2000); + expect(emulator.gameManager.saveSaveFiles).toHaveBeenCalledTimes(2); + + emulator.started = false; + vi.advanceTimersByTime(1000); + expect(emulator.gameManager.saveSaveFiles).toHaveBeenCalledTimes(2); + + emulator.started = true; + stop(); + vi.advanceTimersByTime(5000); + expect(emulator.gameManager.saveSaveFiles).toHaveBeenCalledTimes(2); + }); + + it("slows down for a save too big to copy every second", () => { + const emulator = emulatorWith(4 * 1024 * 1024); + const stop = pollSaveFiles(emulator); + + vi.advanceTimersByTime(4095); + expect(emulator.gameManager.saveSaveFiles).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(emulator.gameManager.saveSaveFiles).toHaveBeenCalledOnce(); + stop(); + }); +}); + describe("captureStateScreenshot", () => { /* eslint-disable @typescript-eslint/no-explicit-any */ afterEach(() => { diff --git a/frontend/src/views/Player/EmulatorJS/utils.ts b/frontend/src/views/Player/EmulatorJS/utils.ts index e3c35acc2..9dece1309 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.ts @@ -269,13 +269,50 @@ export function createSaveSyncTracker() { // EmulatorJS reads each tick off the FS into a fresh buffer, so the tracker can // hold on to one rather than fingerprint it. -function bytesEqual(a: Uint8Array | null, b: Uint8Array | null): boolean { +export function bytesEqual( + a: Uint8Array | null, + b: Uint8Array | null, +): boolean { if (!a || !b) return a === b; if (a.byteLength !== b.byteLength) return false; for (let i = 0; i < a.byteLength; i++) if (a[i] !== b[i]) return false; return true; } +// The core exposes no write hook for its SRAM and EmulatorJS flushes it only on +// its "System Save interval" (5 minutes by default), so polling it every second +// is what gets an in-game save to the server right after the game writes it. +export const SAVE_SYNC_POLL_MS = 1000; +// Each tick copies and compares the whole SRAM, so the interval grows with it +// past 1 MB (1 ms of work per second either way) rather than hitching big saves. +const SAVE_SYNC_BYTES_PER_MS = 1024; + +interface PollableEmulator { + started: boolean; + gameManager: { + saveSaveFiles(): void; + getSaveFile(save: boolean): Uint8Array | null; + }; +} + +/** + * Flushes the SRAM on a timer while the game runs, firing EmulatorJS' + * "saveSaveFiles" tick. + * + * Returns: + * A function that stops the timer. + */ +export function pollSaveFiles(emulator: PollableEmulator): () => void { + const sramBytes = emulator.gameManager.getSaveFile(false)?.byteLength ?? 0; + const timer = setInterval( + () => { + if (emulator.started) emulator.gameManager.saveSaveFiles(); + }, + Math.max(SAVE_SYNC_POLL_MS, sramBytes / SAVE_SYNC_BYTES_PER_MS), + ); + return () => clearInterval(timer); +} + // saveSave needs an ArrayBuffer, and a Uint8Array's own buffer may be shared or // wider than the view, so hand it a standalone copy. export function toArrayBuffer(view: Uint8Array): ArrayBuffer {