refactor: dedupe js-dos emulation checks and player plumbing

usePlatformPlayable is the platform-level twin of useCanPlay, but only the
latter learned about js-dos, so win3x/win9x games offered Play while their
platform tile showed no playable badge and sorted into the unplayable bucket.
Teach resolveEmulator about js-dos and derive `playable`/`isPlayable` from it
instead of hand-maintained OR chains.

Collapse the duplication the new backend introduced: a shared
resolvePlatformSlug in utils, a supportedBy factory for useCanPlay's three
identical computeds, one COOP/COEP nginx pattern per map, and a single
hard-navigation branch in useGameActions that reuses the canPlay useCanPlay
already returns.

In JsDos.vue, share the teardown tail between leavePlayer and onBeforeUnmount,
collapse four derivations of the route rom id into one, start the js-dos
runtime alongside the rom request rather than behind it, and hold the rom in a
shallowRef since the view only reads scalars off it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-08-29 10:20:47 -04:00
parent c38282f989
commit 4142fbc018
11 changed files with 131 additions and 168 deletions

View File

@@ -104,7 +104,7 @@ RUN git clone --recursive --branch "${RALIBRETRO_VERSION}" --depth 1 https://git
make HAVE_CHD=1 -f ./Makefile.RAHasher
# FETCH EMULATORJS AND RUFFLE
# FETCH EMULATORJS, RUFFLE AND JS-DOS
FROM alpine:${ALPINE_VERSION}@sha256:${ALPINE_SHA256} AS emulator-stage
RUN apk add --no-cache \

View File

@@ -19,14 +19,12 @@ map $http_x_forwarded_proto $forwardscheme {
# is needed for multi-threaded cores.
map $request_uri $coep_header {
default "";
~^/rom/.*/ejs$ "require-corp";
~^/rom/.*/jsdos$ "require-corp";
~^/rom/.*/(ejs|jsdos)$ "require-corp";
~^/console/rom/[0-9]+/play "require-corp";
}
map $request_uri $coop_header {
default "";
~^/rom/.*/ejs$ "same-origin";
~^/rom/.*/jsdos$ "same-origin";
~^/rom/.*/(ejs|jsdos)$ "same-origin";
~^/console/rom/[0-9]+/play "same-origin";
}

View File

@@ -1601,6 +1601,7 @@ Falls back to `FakeRedis` in test mode.
| `HLTB_API_ENABLED` | `false` | HowLongToBeat |
| `DISABLE_EMULATOR_JS` | `false` | Hide EmulatorJS player |
| `DISABLE_RUFFLE_RS` | `false` | Hide Ruffle Flash player |
| `DISABLE_JSDOS` | `false` | Hide js-dos player |
#### Task Scheduling

View File

@@ -508,7 +508,7 @@ Server capability flags used throughout the UI:
```typescript
METADATA_SOURCES: { IGDB, SS, MOBY, RA, STEAMGRIDDB, LAUNCHBOX, ... }
EMULATION: { DISABLE_EMULATOR_JS, DISABLE_RUFFLE_RS }
EMULATION: { DISABLE_EMULATOR_JS, DISABLE_RUFFLE_RS, DISABLE_JSDOS }
FRONTEND: { DISABLE_USERPASS_LOGIN, DISABLE_LOGS_VIEWER, YOUTUBE_BASE_URL }
OIDC: { ENABLED, AUTOLOGIN, PROVIDER, RP_INITIATED_LOGOUT }
TASKS: { scheduled task configurations }

View File

@@ -9,14 +9,10 @@ export interface JsDosOptions {
fsChanges: {
local: boolean;
urlToKey?: (url: string) => Promise<string>;
pull?: (key: string) => Promise<Uint8Array | null>;
push?: (key: string, data: Uint8Array) => Promise<void>;
delete?: (key: string) => Promise<void>;
};
}
export interface JsDosProps {
getLocalChanges(key: string): Promise<Uint8Array | null>;
setNoCloud(noCloud: boolean): void;
save(): Promise<boolean>;
stop(): Promise<void>;

View File

@@ -615,6 +615,17 @@ const canvas = document.createElement("canvas");
const gl =
canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
/**
* Resolve a platform slug through the configured version remap.
*
* @param platformSlug The platform slug.
* @param config Optional configuration object.
* @returns The remapped slug, or the original when no remap applies.
*/
export function resolvePlatformSlug(platformSlug: string, config?: Config) {
return config?.PLATFORMS_VERSIONS[platformSlug] || platformSlug;
}
/**
* Check if EJS emulation is supported for a given platform.
*
@@ -630,7 +641,7 @@ export function isEJSEmulationSupported(
) {
if (heartbeat.EMULATION.DISABLE_EMULATOR_JS) return false;
const slug = config?.PLATFORMS_VERSIONS[platformSlug] || platformSlug;
const slug = resolvePlatformSlug(platformSlug, config);
return (
getSupportedEJSCores(slug, config?.EJS_NETPLAY_ENABLED).length > 0 &&
gl instanceof WebGLRenderingContext
@@ -687,7 +698,7 @@ export function isRuffleEmulationSupported(
) {
if (heartbeat.EMULATION.DISABLE_RUFFLE_RS) return false;
const slug = config?.PLATFORMS_VERSIONS[platformSlug] || platformSlug;
const slug = resolvePlatformSlug(platformSlug, config);
return ["flash", "browser"].includes(slug.toLowerCase());
}
@@ -706,7 +717,7 @@ export function isJsDosEmulationSupported(
) {
if (heartbeat.EMULATION.DISABLE_JSDOS) return false;
const slug = config?.PLATFORMS_VERSIONS[platformSlug] || platformSlug;
const slug = resolvePlatformSlug(platformSlug, config);
return ["win3x", "win9x"].includes(slug.toLowerCase());
}

View File

@@ -1,6 +1,5 @@
// useCanPlay — reactive "is this ROM playable in-browser?" check, shared
// by every surface that renders the Play action (GameCard overlay,
// GameActions ribbon, GameActionsList more-menu). v1 had the same gate
// useCanPlay — reactive "can this ROM be played in the browser?" check.
// v1 duplicated this logic across GameCard, GameDetails and the play menu
// inside PlayBtn.vue; v2 lifts it to a composable so the card overlay
// and the menu item agree with the details-header CTA.
//
@@ -30,35 +29,16 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): {
const configStore = storeConfig();
const { value: heartbeat } = storeToRefs(heartbeatStore);
const canPlayEJS = computed(() => {
const rom = getRom();
if (!rom?.has_file_on_disk) return false;
return isEJSEmulationSupported(
rom.platform_slug,
heartbeat.value,
configStore.config,
);
});
const supportedBy = (check: typeof isEJSEmulationSupported) =>
computed(() => {
const rom = getRom();
if (!rom?.has_file_on_disk) return false;
return check(rom.platform_slug, heartbeat.value, configStore.config);
});
const canPlayRuffle = computed(() => {
const rom = getRom();
if (!rom?.has_file_on_disk) return false;
return isRuffleEmulationSupported(
rom.platform_slug,
heartbeat.value,
configStore.config,
);
});
const canPlayJsDos = computed(() => {
const rom = getRom();
if (!rom?.has_file_on_disk) return false;
return isJsDosEmulationSupported(
rom.platform_slug,
heartbeat.value,
configStore.config,
);
});
const canPlayEJS = supportedBy(isEJSEmulationSupported);
const canPlayJsDos = supportedBy(isJsDosEmulationSupported);
const canPlayRuffle = supportedBy(isRuffleEmulationSupported);
const canPlay = computed(
() => canPlayEJS.value || canPlayJsDos.value || canPlayRuffle.value,

View File

@@ -77,7 +77,12 @@ export function useGameActions(
// delete that 403s.
const canDelete = computed(() => hasDeleteGrant.value && canEdit.value);
const { isFavorite, toggleFavorite } = useFavoriteToggle(emitter);
const { canPlayEJS, canPlayJsDos, canPlayRuffle } = useCanPlay(getRom);
const {
canPlay: canPlayLocal,
canPlayEJS,
canPlayJsDos,
canPlayRuffle,
} = useCanPlay(getRom);
const streamingStore = useStreamingStore();
// Streaming is the preferred way to play where a container is
@@ -91,13 +96,7 @@ export function useGameActions(
streamingStore.containerForPlatform(rom.platform_slug),
);
});
const canPlay = computed(
() =>
canPlayStream.value ||
canPlayJsDos.value ||
canPlayEJS.value ||
canPlayRuffle.value,
);
const canPlay = computed(() => canPlayStream.value || canPlayLocal.value);
// Download, the copied link and the QR code all resolve to the download
// endpoint, which has nothing to serve without a file behind the rom.
@@ -263,13 +262,13 @@ export function useGameActions(
// EmulatorJS and js-dos need SharedArrayBuffer. Nginx only attaches the
// necessary COOP/COEP headers to the player document, so an SPA navigation
// cannot enable cross-origin isolation. Load the document directly instead.
// js-dos owns win3x/win9x, so it is checked ahead of EJS.
if (!canPlayStream.value && canPlayJsDos.value) {
window.location.assign(`/rom/${rom.id}/jsdos`);
return;
}
if (!canPlayStream.value && canPlayEJS.value) {
window.location.assign(`/rom/${rom.id}/ejs`);
const isolated = canPlayJsDos.value
? "jsdos"
: canPlayEJS.value
? "ejs"
: null;
if (!canPlayStream.value && isolated) {
window.location.assign(`/rom/${rom.id}/${isolated}`);
return;
}

View File

@@ -1,7 +1,7 @@
// usePlatformPlayable — reactive "can any ROM on this platform run
// in-browser?" check. Companion to useCanPlay (which takes a rom);
// platform-level surfaces (PlatformTile, PlatformListRow) only know the
// slug, so they read this instead. Reuses the same EJS + Ruffle utils
// slug, so they read this instead. Reuses the same engine-support utils
// so the marker on the tile and the Play button on the ROM agree.
//
// `usePlatformPlayableChecker` is the batch sibling — returns a plain
@@ -9,10 +9,11 @@
// slugs at once (sort comparators, group-by buckets in PlatformsIndex).
//
// `emulator` resolves to the in-browser engine that actually drives the
// platform: "ruffle" for Flash, "dosbox" when the EJS catalogue picks
// the dosbox_pure core (DOS is wrapped by EJS but distinctive enough to
// surface by name in the UI), "emulatorjs" for everything else playable,
// and `null` when nothing on the server can run it.
// platform: "ruffle" for Flash, "jsdos" for Windows 3.x/9x, "dosbox"
// when the EJS catalogue picks the dosbox_pure core (DOS is wrapped by
// EJS but distinctive enough to surface by name in the UI),
// "emulatorjs" for everything else playable, and `null` when nothing on
// the server can run it.
import { storeToRefs } from "pinia";
import { computed, type ComputedRef } from "vue";
import storeConfig, { type Config } from "@/stores/config";
@@ -20,10 +21,13 @@ import storeHeartbeat, { type Heartbeat } from "@/stores/heartbeat";
import {
getSupportedEJSCores,
isEJSEmulationSupported,
isJsDosEmulationSupported,
isRuffleEmulationSupported,
resolvePlatformSlug,
} from "@/utils";
export type PlatformEmulator = "emulatorjs" | "ruffle" | "dosbox" | null;
export type PlatformEmulator =
"emulatorjs" | "ruffle" | "jsdos" | "dosbox" | null;
/** Pure helper — picks the engine that would actually run a platform.
* Shared between the reactive and the batch composables so both surface
@@ -35,46 +39,28 @@ function resolveEmulator(
): PlatformEmulator {
if (!slug) return null;
if (isRuffleEmulationSupported(slug, heartbeat, config)) return "ruffle";
if (isJsDosEmulationSupported(slug, heartbeat, config)) return "jsdos";
if (!isEJSEmulationSupported(slug, heartbeat, config)) return null;
const resolved = config?.PLATFORMS_VERSIONS[slug] || slug;
const cores = getSupportedEJSCores(resolved);
const cores = getSupportedEJSCores(resolvePlatformSlug(slug, config));
if (cores.includes("dosbox_pure")) return "dosbox";
return "emulatorjs";
}
export function usePlatformPlayable(getSlug: () => string | null | undefined): {
playable: ComputedRef<boolean>;
playableEJS: ComputedRef<boolean>;
playableRuffle: ComputedRef<boolean>;
emulator: ComputedRef<PlatformEmulator>;
} {
const heartbeatStore = storeHeartbeat();
const configStore = storeConfig();
const { value: heartbeat } = storeToRefs(heartbeatStore);
const playableEJS = computed(() => {
const slug = getSlug();
if (!slug) return false;
return isEJSEmulationSupported(slug, heartbeat.value, configStore.config);
});
const playableRuffle = computed(() => {
const slug = getSlug();
if (!slug) return false;
return isRuffleEmulationSupported(
slug,
heartbeat.value,
configStore.config,
);
});
const playable = computed(() => playableEJS.value || playableRuffle.value);
const emulator = computed<PlatformEmulator>(() =>
resolveEmulator(getSlug(), heartbeat.value, configStore.config),
);
return { playable, playableEJS, playableRuffle, emulator };
const playable = computed(() => emulator.value !== null);
return { playable, emulator };
}
export function usePlatformPlayableChecker(): {
@@ -90,18 +76,6 @@ export function usePlatformPlayableChecker(): {
// Expose computed functions so callers that consume them inside another
// computed (sort comparator, bucket discriminator) re-run when the
// heartbeat or admin-toggle state changes.
const isPlayable = computed(() => {
const hb = heartbeat.value;
const cfg = configStore.config;
return (slug: string | null | undefined) => {
if (!slug) return false;
return (
isEJSEmulationSupported(slug, hb, cfg) ||
isRuffleEmulationSupported(slug, hb, cfg)
);
};
});
const getEmulator = computed(() => {
const hb = heartbeat.value;
const cfg = configStore.config;
@@ -109,6 +83,11 @@ export function usePlatformPlayableChecker(): {
resolveEmulator(slug, hb, cfg);
});
const isPlayable = computed(() => {
const resolve = getEmulator.value;
return (slug: string | null | undefined) => resolve(slug) !== null;
});
return { isPlayable, getEmulator };
}
@@ -118,11 +97,13 @@ export function playableTooltip(emulator: PlatformEmulator): string {
switch (emulator) {
case "ruffle":
return "Playable in browser through Ruffle";
case "jsdos":
return "Playable in browser through js-dos";
case "dosbox":
return "Playable in browser through DOSBox";
case "emulatorjs":
return "Playable in browser through EmulatorJS";
case null:
return "Not supported by EmulatorJS";
return "Not playable in browser";
}
}

View File

@@ -23,7 +23,7 @@ const mocks = vi.hoisted(() => ({
routeLeaveGuard: null as ((to: { fullPath: string }) => unknown) | null,
setPlaying: vi.fn(),
snackbarError: vi.fn(),
userId: 7 as number,
userId: 7,
}));
vi.mock("vue-i18n", () => ({
@@ -165,9 +165,8 @@ async function mountPlayer(handle: JsDosProps): Promise<VueWrapper> {
return wrapper;
}
function makeHandle(saveResult: boolean) {
function makeHandle(saveResult = true) {
return {
getLocalChanges: vi.fn().mockResolvedValue(null),
save: vi.fn().mockResolvedValue(saveResult),
setNoCloud: vi.fn(),
stop: vi.fn(() => new Promise<void>(() => undefined)),
@@ -210,7 +209,7 @@ describe("JsDos player exit", () => {
});
it("hard-navigates after saving without awaiting stop", async () => {
const handle = makeHandle(true);
const handle = makeHandle();
const wrapper = await mountPlayer(handle);
await wrapper.get(".r-v2-jsdos__quit").trigger("click");
@@ -261,7 +260,7 @@ describe("JsDos player exit", () => {
});
it("keeps the player open when the final save fails", async () => {
const handle = makeHandle(true);
const handle = makeHandle();
handle.save.mockRejectedValue(new Error("save failed"));
const wrapper = await mountPlayer(handle);
@@ -278,7 +277,7 @@ describe("JsDos player exit", () => {
it("ignores a second quit while the final save is pending", async () => {
let finishSave: ((saved: boolean) => void) | undefined;
const handle = makeHandle(true);
const handle = makeHandle();
handle.save.mockReturnValue(
new Promise<boolean>((resolve) => {
finishSave = resolve;
@@ -298,7 +297,7 @@ describe("JsDos player exit", () => {
it("ignores route departure while another final save is pending", async () => {
let finishSave: ((saved: boolean) => void) | undefined;
const handle = makeHandle(true);
const handle = makeHandle();
handle.save.mockReturnValue(
new Promise<boolean>((resolve) => {
finishSave = resolve;
@@ -318,7 +317,7 @@ describe("JsDos player exit", () => {
});
it("converts route departure into a saved hard navigation", async () => {
const handle = makeHandle(true);
const handle = makeHandle();
const wrapper = await mountPlayer(handle);
expect(mocks.routeLeaveGuard?.({ fullPath: "/platform/2" })).toBe(false);
@@ -330,7 +329,7 @@ describe("JsDos player exit", () => {
});
it("only performs best-effort stop during unmount", async () => {
const handle = makeHandle(true);
const handle = makeHandle();
const wrapper = await mountPlayer(handle);
wrapper.unmount();
@@ -341,7 +340,7 @@ describe("JsDos player exit", () => {
});
it("warns before reloading while the game is running", async () => {
const handle = makeHandle(true);
const handle = makeHandle();
const wrapper = await mountPlayer(handle);
const event = new Event("beforeunload", {
cancelable: true,
@@ -354,7 +353,7 @@ describe("JsDos player exit", () => {
});
it("uses a stable browser-local save key scoped to the RomM user", async () => {
const firstHandle = makeHandle(true);
const firstHandle = makeHandle();
const firstWrapper = await mountPlayer(firstHandle);
const firstOptions = vi.mocked(window.Dos!).mock.calls[0]![1];
const firstKey = await firstOptions.fsChanges?.urlToKey?.(
@@ -363,7 +362,7 @@ describe("JsDos player exit", () => {
firstWrapper.unmount();
mocks.userId = 8;
const secondHandle = makeHandle(true);
const secondHandle = makeHandle();
const secondWrapper = await mountPlayer(secondHandle);
const secondOptions = vi.mocked(window.Dos!).mock.calls[0]![1];
const secondKey = await secondOptions.fsChanges?.urlToKey?.(
@@ -372,7 +371,6 @@ describe("JsDos player exit", () => {
expect(firstKey).toBe("romm-user-7-rom-1.changes");
expect(secondKey).toBe("romm-user-8-rom-1.changes");
expect(firstKey).not.toBe(secondKey);
secondWrapper.unmount();
});
});

View File

@@ -1,6 +1,13 @@
<script setup lang="ts">
import { RBtn, RCard, RSpinner, RSwitch } from "@v2/lib";
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
ref,
shallowRef,
} from "vue";
import { useI18n } from "vue-i18n";
import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
import { ROUTES } from "@/plugins/router";
@@ -32,37 +39,30 @@ const playSession = usePlaySession();
const snackbar = useSnackbar();
const confirm = useConfirm();
const rom = ref<DetailedRom | null>(null);
const rom = shallowRef<DetailedRom | null>(null);
const gameRunning = ref(false);
const quitting = ref(false);
const stage = ref<HTMLDivElement | null>(null);
let dos: JsDosProps | null = null;
// Seed the cover before the full ROM request resolves for the view transition.
const morphRomId = computed(() => {
const r = route.params.rom;
return typeof r === "string" ? r : null;
});
const romId = Number(route.params.rom);
// Seed the cover before the full ROM request resolves so the view transition
// has an element to morph onto.
const seededRom = storeRoms().currentRom;
if (seededRom && String(seededRom.id) === morphRomId.value) {
if (seededRom?.id === romId) {
rom.value = seededRom;
}
const heroSeed = ref<SimpleRom | null>(null);
if (!rom.value && morphRomId.value != null) {
heroSeed.value = storeGalleryRoms().getRomById(Number(morphRomId.value));
const heroSeed = shallowRef<SimpleRom | null>(null);
if (!rom.value) {
heroSeed.value = storeGalleryRoms().getRomById(romId);
}
const heroRom = computed<DetailedRom | SimpleRom | null>(
() => rom.value ?? heroSeed.value,
);
const setBgArt = useBackgroundArt();
const bgCoverUrl = computed(() => {
const r = rom.value;
if (!r) return null;
return r.path_cover_large ?? r.path_cover_small ?? r.url_cover ?? null;
});
const title = computed(
() => heroRom.value?.name || heroRom.value?.fs_name_no_ext || "",
@@ -146,45 +146,48 @@ function stopDos() {
});
}
async function saveQuietly(handle: JsDosProps) {
try {
return await handle.save();
} catch (error) {
console.error("[js-dos] Final save failed", error);
return false;
}
}
function teardown() {
playSession.flush();
playingStore.setPlaying(false);
stopDos();
}
async function leavePlayer(destination: string) {
if (quitting.value) return;
quitting.value = true;
const handle = dos;
if (handle) {
let saved = false;
try {
saved = await handle.save();
} catch (error) {
console.error("[js-dos] Final save failed", error);
}
if (!saved) {
snackbar.error(t("play.stream-save-unconfirmed"));
const discard = await confirm({
title: t("play.jsdos-quit-without-saving"),
confirmText: t("common.discard"),
cancelText: t("common.cancel"),
tone: "danger",
});
if (!discard) {
quitting.value = false;
return;
}
if (handle && !(await saveQuietly(handle))) {
snackbar.error(t("play.stream-save-unconfirmed"));
const discard = await confirm({
title: t("play.jsdos-quit-without-saving"),
confirmText: t("common.discard"),
cancelText: t("common.cancel"),
tone: "danger",
});
if (!discard) {
quitting.value = false;
return;
}
}
playSession.flush();
playingStore.setPlaying(false);
stopDos();
teardown();
window.location.replace(destination);
}
function onlyQuit() {
const romId = rom.value?.id ?? route.params.rom;
void leavePlayer(`/rom/${romId}`);
}
function backToRom() {
const romId = heroRom.value?.id ?? route.params.rom;
router.push({ name: ROUTES.ROM, params: { rom: romId } });
}
function backToPlatform() {
@@ -205,18 +208,16 @@ function onBeforeUnload(event: BeforeUnloadEvent) {
onMounted(async () => {
window.addEventListener("beforeunload", onBeforeUnload);
const romResponse = await romApi.getRom({
romId: parseInt(route.params.rom as string),
});
// The runtime reads nothing from the ROM payload, so let both loads overlap
// instead of holding the 300 KB bundle behind the API roundtrip.
void loadRuntime().catch((e) => console.error(e));
const romResponse = await romApi.getRom({ romId });
rom.value = romResponse.data;
if (bgCoverUrl.value) setBgArt(bgCoverUrl.value);
try {
await loadRuntime();
} catch (e) {
console.error(e);
}
const { path_cover_large, path_cover_small, url_cover } = romResponse.data;
const cover = path_cover_large ?? path_cover_small ?? url_cover;
if (cover) setBgArt(cover);
});
onBeforeRouteLeave((to) => {
@@ -226,9 +227,7 @@ onBeforeRouteLeave((to) => {
onBeforeUnmount(() => {
window.removeEventListener("beforeunload", onBeforeUnload);
playSession.flush();
playingStore.setPlaying(false);
stopDos();
teardown();
});
</script>
@@ -241,7 +240,7 @@ onBeforeUnmount(() => {
:rom="heroRom"
:title="title"
:identified="heroRom?.is_identified ?? true"
:morph-id="morphRomId"
:morph-id="romId"
style-context="player"
morph-static
hover-motion