Merge pull request #4558 from rommapp/claude/ejs-auto-save-sync

feat(player): sync in-game saves seconds after the game writes them
This commit is contained in:
Zurdi
2026-09-16 22:14:04 +02:00
committed by GitHub
12 changed files with 562 additions and 99 deletions

View File

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

View File

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

View File

@@ -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 == {}

View File

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

View File

@@ -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<string, unknown>;
}) => {
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<typeof fetch>().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();
});
});

View File

@@ -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<AddSaveInput, "saveFile" | "screenshotFile"> & {
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<SaveUploadInput>([
["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<SaveUploadInput>([
["saveFile", saveFile],
["screenshotFile", screenshotFile],
]);
}
async function uploadSaves({
savesToUpload,
...version
}: SaveVersionParams & { savesToUpload: SaveUploadInput[] }) {
const promises = savesToUpload.map(({ saveFile, screenshotFile }) => {
return new Promise<SaveSchema>((resolve, reject) => {
api
.post<SaveSchema>("/saves", formData, {
.post<SaveSchema>("/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<number[]>("/saves/delete", { saves: saves.map((s) => s.id) });
}
@@ -117,6 +165,7 @@ async function setSaveVisibility({
export default {
uploadSaves,
updateSave,
sendSaveOnUnload,
deleteSaves,
setSaveVisibility,
};

View File

@@ -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: {},

View File

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

View File

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

View File

@@ -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,
@@ -36,6 +36,9 @@ import {
createSaveQuitButton,
createExitEmulationButton,
createSaveSyncTracker,
bytesEqual,
pollSaveFiles,
saveSaveOnUnload,
toArrayBuffer,
} from "./utils";
@@ -78,6 +81,8 @@ function baselineSaveTrackerFromEmulator() {
let saveWrite: Promise<unknown> = 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,
@@ -85,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;
@@ -259,6 +270,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,7 +309,10 @@ onMounted(() => {
});
onBeforeUnmount(async () => {
autoSaveSyncEmulator = null;
disposed = true;
window.removeEventListener("beforeunload", onBeforeUnload);
window.removeEventListener("pagehide", onPageHide);
uninstallAutoSaveSync();
emitter?.off("saveSelected", loadSave);
emitter?.off("stateSelected", loadState);
window.EJS_emulator?.callEvent("exit");
@@ -344,13 +362,17 @@ async function waitForGameManager(timeoutMs = 5000): Promise<boolean> {
// 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
// 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 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) => {
@@ -364,6 +386,7 @@ function installAutoSaveSync() {
romsStore.update(romRef.value);
displayMessage("Save synced with server", {
duration: 3000,
className: "msg-success",
icon: "mdi-cloud-sync",
});
}
@@ -373,6 +396,65 @@ function installAutoSaveSync() {
uploading = false;
}
});
stopSavePolling = pollSaveFiles(emulator);
}
function uninstallAutoSaveSync() {
autoSaveSyncEmulator = 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.
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);
// 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) {
// 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;
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();
// 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,
saveFile: toArrayBuffer(unloadSave),
deviceId: deviceIDRef.value,
slot: loadedSave?.slot || props.saveSlot || undefined,
});
}
// Saves management
@@ -422,6 +504,7 @@ window.EJS_onSaveSave = async function ({
if (synced) {
displayMessage("Save synced with server", {
duration: 4000,
className: "msg-success",
icon: "mdi-cloud-sync",
});
} else {
@@ -477,6 +560,7 @@ window.EJS_onSaveState = async function ({
if (state) {
displayMessage("State synced with server", {
duration: 4000,
className: "msg-success",
icon: "mdi-cloud-sync",
});
} else {
@@ -585,15 +669,15 @@ window.EJS_onGameStart = async () => {
const exitEmulation = createExitEmulationButton();
exitEmulation.addEventListener("click", async () => {
autoSaveSyncEmulator = null;
if (!romRef.value || !window.EJS_emulator) return immediateExit();
await flushPendingSave();
romsStore.update(romRef.value);
immediateExit();
});
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
@@ -670,35 +754,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)));
}
</style>

View File

@@ -7,14 +7,17 @@ import {
captureStateScreenshot,
createSaveSyncTracker,
installEJSDefaultOptionsTrap,
pollSaveFiles,
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(),
@@ -186,6 +189,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);
@@ -243,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(() => {
@@ -337,6 +393,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;

View File

@@ -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,12 +197,42 @@ 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() {
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 +251,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;
@@ -228,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 {