From efccb6743be126e6ebadb70b08a9c79b29dfe2d8 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 20:33:53 +0200 Subject: [PATCH] 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() {