From 2469839b6611edc060b04cb2209bcde67dc478a6 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi <3247106+gantoine@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:28:36 -0500 Subject: [PATCH] fix(jsdos): play a .jsdos bundle that sits inside a game folder (#5672) * fix(jsdos): play a .jsdos bundle that sits inside a game folder The play check read the ROM's own extension, which is empty for a folder, so a bundle moved into a folder (for example beside its manual) lost its Play button. The backend now exposes has_jsdos_bundle, true when the ROM is a bundle or has one at its folder's top level, and the js-dos player asks the content endpoint for that file instead of a zip of the folder. Fixes #5615 Co-Authored-By: Claude Opus 5.5 * test(jsdos): assert the player downloads only the bundle file Addresses Greptile's review on #5672: covers the bundle file id in the player URL and drops a comment that restated the constant. Co-Authored-By: Claude Opus 5.5 * pr-ready: code-review Pin has_jsdos_bundle's value for a plain single file and for a bundle missing from disk, on both the SQL and the with_files path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011waFLKWoBw9KCu31UJJ7Te * pr-ready: code-review Expose missing_from_fs on RomFileSchema so the js-dos player skips a bundle gone from disk, the same rule has_jsdos_bundle applies. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011waFLKWoBw9KCu31UJJ7Te * pr-ready: simplify Share the top-level file predicate and the present-file exists subquery between is_easyrpg_game and has_jsdos_bundle, compute the top-level files once in apply_file_stats, and fold the two marker flag tests into one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011waFLKWoBw9KCu31UJJ7Te * pr-ready: review-polish Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011waFLKWoBw9KCu31UJJ7Te * pr-ready: prose Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011waFLKWoBw9KCu31UJJ7Te * refactor(jsdos): rename isJsDosBundle to hasJsDosBundle It also matches a folder that holds a bundle, so the name now says what the backend flag it reads says. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011waFLKWoBw9KCu31UJJ7Te * fix(scan): derive a scanned rom's file flags from the files it read A scan emits scan:scanning_rom before it writes the rom's file rows, so a new rom reached clients with every file flag false (has_simple_single_file, has_multiple_files, has_jsdos_bundle and the rest) until a reload. The emits now derive those flags from the files the scan just read whenever it rebuilt them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011waFLKWoBw9KCu31UJJ7Te --------- Co-authored-by: Claude Opus 5.5 --- backend/endpoints/responses/rom.py | 4 + backend/endpoints/sockets/scan.py | 12 ++- backend/handler/database/roms_handler.py | 1 + backend/handler/scan_handler.py | 29 +++++-- backend/models/rom.py | 79 +++++++++++-------- .../endpoints/roms/test_rom_list_loads.py | 60 +++++++++++++- backend/tests/endpoints/sockets/test_scan.py | 45 +++++++++++ .../__generated__/models/DetailedRomSchema.ts | 4 + .../src/__generated__/models/RomFileSchema.ts | 4 + .../__generated__/models/SimpleRomSchema.ts | 4 + .../Dialogs/ManualUploadTargetDialog.test.ts | 1 + .../src/components/Gallery/listRowFixture.ts | 1 + .../GameDetails/RelatedGameCard.vue | 1 + .../src/composables/useCanPlay/index.test.ts | 2 +- frontend/src/composables/useCanPlay/index.ts | 4 +- frontend/src/utils/index.test.ts | 62 +++++++++++---- frontend/src/utils/index.ts | 25 +++++- frontend/src/utils/rom.fixtures.ts | 2 + frontend/src/utils/romFiles.test.ts | 1 + frontend/src/views/Player/JsDos.test.ts | 26 ++++-- frontend/src/views/Player/JsDos.vue | 8 +- 21 files changed, 300 insertions(+), 75 deletions(-) diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index 9e0a19880..90e1494e9 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -318,6 +318,8 @@ class RomFileSchema(BaseModel): file_size_bytes: int full_path: str is_top_level: bool + missing_from_fs: bool + """True when the file is gone from disk.""" created_at: UTCDatetime updated_at: UTCDatetime last_modified: UTCDatetime | None @@ -543,6 +545,8 @@ class RomSchema(BaseModel): """True when more than one file or folder sits at the top level.""" is_easyrpg_game: bool """True for an RPG Maker 2000 or 2003 game: a folder containing an `rpg_rt.ldb` database.""" + has_jsdos_bundle: bool + """True when the ROM is a `.jsdos` bundle, or a folder with one at its top level.""" full_path: str """The path of the file or folder relative to the library root: `fs_path` joined with `fs_name`.""" created_at: UTCDatetime diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 89ce90166..c27f0afba 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -771,6 +771,9 @@ async def _identify_rom( if rom.fs_name != fs_rom["fs_name"]: rom.fs_name = fs_rom["fs_name"] + # The stored file rows only catch up after `sync_rom_files` below. + scanned_files = fs_rom["files"] if should_update_files else None + log.debug(f"Scanning {rom.fs_name}...") scanned_rom = await scan_rom( scan_type=scan_type, @@ -781,6 +784,7 @@ async def _identify_rom( newly_added=newly_added, launchbox_remote_enabled=launchbox_remote_enabled, socket_manager=socket_manager, + scanned_files=scanned_files, ) await scan_stats.increment( @@ -794,7 +798,9 @@ async def _identify_rom( scanned_rom_ids.add(_added_rom.id) if _added_rom.is_identified: - await emit_scanning_rom(socket_manager, _added_rom, is_new=newly_added) + await emit_scanning_rom( + socket_manager, _added_rom, is_new=newly_added, files=scanned_files + ) if should_update_files: # Reconcile against the existing rows instead of replacing them, so file @@ -823,7 +829,9 @@ async def _identify_rom( }, ) - await emit_scanning_rom(socket_manager, _added_rom, is_new=newly_added) + await emit_scanning_rom( + socket_manager, _added_rom, is_new=newly_added, files=scanned_files + ) async def _scan_selected_roms( diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index d11f1b965..b02edd8f6 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -725,6 +725,7 @@ def _rom_card_loaders( undefer(Rom.top_level_file_count), undefer(Rom.has_soundtrack), undefer(Rom.is_easyrpg_game), + undefer(Rom.has_jsdos_bundle), ] if siblings: options.append( diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 290a1af8b..cf843e8ef 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -1,5 +1,5 @@ import asyncio -from collections.abc import Callable, Mapping +from collections.abc import Callable, Mapping, Sequence from typing import Any, Final, NotRequired, TypedDict import socketio @@ -75,7 +75,13 @@ from logger.logger import log from models.assets import MemoryCardVersion, Save, Screenshot, State from models.firmware import Firmware from models.platform import Platform -from models.rom import METADATA_SOURCE_COLUMNS, Rom, RomFile, RomFileCategory +from models.rom import ( + METADATA_SOURCE_COLUMNS, + Rom, + RomFile, + RomFileCategory, + apply_file_stats, +) from models.user import User from utils import emoji from utils.audio_tags import persist_embedded_cover, remove_persisted_cover @@ -288,9 +294,19 @@ _SCANNING_ROM_EXCLUDE: Final = { async def emit_scanning_rom( - socket_manager: socketio.AsyncRedisManager, rom: Rom, *, is_new: bool + socket_manager: socketio.AsyncRedisManager, + rom: Rom, + *, + is_new: bool, + files: Sequence[RomFile] | None = None, ) -> None: - """Report a scanned rom; `is_new` lets clients count only roms the scan added.""" + """Report a scanned rom; `is_new` lets clients count only roms the scan added. + + Args: + files: The rom's scanned files, when its stored file rows are not written yet. + """ + if files is not None: + apply_file_stats(rom, files) payload = SimpleRomSchema.from_orm_with_factory(rom).model_dump( exclude=_SCANNING_ROM_EXCLUDE ) @@ -341,6 +357,7 @@ async def scan_rom( newly_added: bool, launchbox_remote_enabled: bool = True, socket_manager: socketio.AsyncRedisManager | None = None, + scanned_files: Sequence[RomFile] | None = None, ) -> Rom: rom_attrs = seed_rom_attrs(scan_type, platform, rom, fs_rom, newly_added) is_complete_rescan = not newly_added and scan_type == ScanType.COMPLETE @@ -362,7 +379,9 @@ async def scan_rom( scanning_rom.is_identifying = True if socket_manager: - await emit_scanning_rom(socket_manager, scanning_rom, is_new=newly_added) + await emit_scanning_rom( + socket_manager, scanning_rom, is_new=newly_added, files=scanned_files + ) # Run hash fetches concurrently ( diff --git a/backend/models/rom.py b/backend/models/rom.py index 7aac64f41..b6308c3bf 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -43,6 +43,7 @@ from sqlalchemy.orm import ( ) from sqlalchemy.orm.attributes import InstrumentedAttribute, set_committed_value from sqlalchemy.sql.elements import ColumnElement +from sqlalchemy.sql.selectable import ScalarSelect from config import FRONTEND_RESOURCES_PATH from models.base import ( @@ -335,6 +336,8 @@ IDENTITY_PROVIDER_ID_LENGTH: Final = 100 # The database file at the root of every RPG Maker 2000/2003 game folder. EASYRPG_GAME_DATABASE: Final = "rpg_rt.ldb" +JSDOS_BUNDLE_EXTENSION: Final = ".jsdos" + class RomIdentityKey(BaseModel): """One row per (ROM, provider it has a match id for), scoped to a platform. @@ -1263,6 +1266,7 @@ class Rom(BaseModel): multi_file: Mapped[bool] top_level_file_count: Mapped[int] is_easyrpg_game: Mapped[bool] + has_jsdos_bundle: Mapped[bool] @property def has_simple_single_file(self) -> bool: @@ -1405,6 +1409,25 @@ class Rom(BaseModel): # Revisit (real columns, JOIN/aggregate, or added indexes) if gallery latency regresses _rom_full_path = func.concat(Rom.fs_path, "/", Rom.fs_name) +# `RomFile.is_top_level` in SQL. +_is_top_level_file = or_( + func.concat(RomFile.file_path, "/", RomFile.file_name) == _rom_full_path, + RomFile.file_path == _rom_full_path, +) + + +def _rom_has_present_file(*criteria: ColumnElement[bool]) -> ScalarSelect[bool]: + """Whether the rom has a file on disk matching every one of `criteria`.""" + return ( + select(RomFile.id) + .where(RomFile.rom_id == Rom.id, RomFile.missing_from_fs.is_(False), *criteria) + .correlate_except(RomFile) + .exists() + .select() + .scalar_subquery() + ) + + Rom.multi_file = column_property( select(RomFile.id) .where( @@ -1422,53 +1445,36 @@ Rom.multi_file = column_property( Rom.top_level_file_count = column_property( select(func.count(RomFile.id)) - .where( - and_( - RomFile.rom_id == Rom.id, - or_( - func.concat(RomFile.file_path, "/", RomFile.file_name) - == _rom_full_path, - RomFile.file_path == _rom_full_path, - ), - ) - ) + .where(and_(RomFile.rom_id == Rom.id, _is_top_level_file)) .correlate_except(RomFile) .scalar_subquery(), deferred=True, ) Rom.is_easyrpg_game = column_property( - select(RomFile.id) - .where( - and_( - RomFile.rom_id == Rom.id, - RomFile.file_path == _rom_full_path, - func.lower(RomFile.file_name) == EASYRPG_GAME_DATABASE, - RomFile.missing_from_fs.is_(False), - ) - ) - .correlate_except(RomFile) - .exists() - .select() - .scalar_subquery(), + _rom_has_present_file( + RomFile.file_path == _rom_full_path, + func.lower(RomFile.file_name) == EASYRPG_GAME_DATABASE, + ), + deferred=True, +) + +Rom.has_jsdos_bundle = column_property( + _rom_has_present_file( + _is_top_level_file, + func.lower(RomFile.file_name).like(f"%{JSDOS_BUNDLE_EXTENSION}"), + ), deferred=True, ) def apply_file_stats(rom: Rom, files: Sequence[RomFile]) -> None: """Fill the deferred file-stat columns from an already-loaded file list.""" + top_level = [f for f in files if rom.full_path in (f.full_path, f.file_path)] set_committed_value( rom, "multi_file", any(f.file_path != rom.fs_path for f in files) ) - set_committed_value( - rom, - "top_level_file_count", - sum( - 1 - for f in files - if f.full_path == rom.full_path or f.file_path == rom.full_path - ), - ) + set_committed_value(rom, "top_level_file_count", len(top_level)) set_committed_value( rom, "has_soundtrack", @@ -1484,6 +1490,15 @@ def apply_file_stats(rom: Rom, files: Sequence[RomFile]) -> None: for f in files ), ) + set_committed_value( + rom, + "has_jsdos_bundle", + any( + f.file_name.lower().endswith(JSDOS_BUNDLE_EXTENSION) + and not f.missing_from_fs + for f in top_level + ), + ) SEARCH_TITLE_COLUMNS = ("name", *(column for column, _ in ALTERNATIVE_NAME_SOURCES)) diff --git a/backend/tests/endpoints/roms/test_rom_list_loads.py b/backend/tests/endpoints/roms/test_rom_list_loads.py index a25018373..ac243a5a3 100644 --- a/backend/tests/endpoints/roms/test_rom_list_loads.py +++ b/backend/tests/endpoints/roms/test_rom_list_loads.py @@ -18,6 +18,7 @@ FILE_STAT_FIELDS = ( "has_multiple_files", "has_soundtrack", "is_easyrpg_game", + "has_jsdos_bundle", ) @@ -35,6 +36,7 @@ def _add_file( *, file_path: str, category: RomFileCategory = RomFileCategory.GAME, + missing_from_fs: bool = False, ) -> None: db_rom_handler.add_rom_file( RomFile( @@ -44,6 +46,7 @@ def _add_file( file_size_bytes=10, last_modified=LAST_MODIFIED, category=category, + missing_from_fs=missing_from_fs, ) ) @@ -101,6 +104,42 @@ def easyrpg_rom(admin_user: User, platform: Platform) -> Rom: return rom +@pytest.fixture +def jsdos_rom(admin_user: User, platform: Platform) -> Rom: + """A single js-dos bundle, its extension in upper case.""" + rom = _add_rom(admin_user, platform, "dos_game", fs_extension="JSDOS") + _add_file(rom, "dos_game.JSDOS", file_path=rom.fs_path) + return rom + + +@pytest.fixture +def jsdos_folder_rom(admin_user: User, platform: Platform) -> Rom: + """A folder holding a js-dos bundle beside its manual.""" + rom = _add_rom(admin_user, platform, "Dos Game (1996)", fs_extension="") + file_path = f"{rom.fs_path}/Dos Game (1996)" + _add_file(rom, "Dos Game (1996).jsdos", file_path=file_path) + _add_file(rom, "manual.pdf", file_path=file_path) + return rom + + +@pytest.fixture +def nested_jsdos_rom(admin_user: User, platform: Platform) -> Rom: + """A folder whose only bundle sits in a subdirectory.""" + rom = _add_rom(admin_user, platform, "nested_dos", fs_extension="") + _add_file(rom, "game.jsdos", file_path=f"{rom.fs_path}/nested_dos/extras") + return rom + + +@pytest.fixture +def missing_jsdos_rom(admin_user: User, platform: Platform) -> Rom: + """A folder whose only bundle is gone from disk.""" + rom = _add_rom(admin_user, platform, "gone_dos", fs_extension="") + file_path = f"{rom.fs_path}/gone_dos" + _add_file(rom, "game.jsdos", file_path=file_path, missing_from_fs=True) + _add_file(rom, "manual.pdf", file_path=file_path) + return rom + + def _fetch_one( client: TestClient, access_token: str, platform: Platform, *, with_files: bool ) -> dict[str, Any]: @@ -124,6 +163,10 @@ def _fetch_one( "soundtrack_rom", "fileless_rom", "easyrpg_rom", + "jsdos_rom", + "jsdos_folder_rom", + "nested_jsdos_rom", + "missing_jsdos_rom", ], ) def test_file_stats_match_between_derived_and_sql_paths( @@ -149,12 +192,23 @@ def test_file_stats_match_between_derived_and_sql_paths( @pytest.mark.parametrize("with_files", [True, False]) @pytest.mark.parametrize( - ("rom_fixture", "expected"), [("easyrpg_rom", True), ("folder_rom", False)] + ("field", "rom_fixture", "expected"), + [ + ("is_easyrpg_game", "easyrpg_rom", True), + ("is_easyrpg_game", "folder_rom", False), + ("has_jsdos_bundle", "jsdos_rom", True), + ("has_jsdos_bundle", "jsdos_folder_rom", True), + ("has_jsdos_bundle", "nested_jsdos_rom", False), + ("has_jsdos_bundle", "missing_jsdos_rom", False), + ("has_jsdos_bundle", "folder_rom", False), + ("has_jsdos_bundle", "flat_rom", False), + ], ) -def test_is_easyrpg_game_needs_a_top_level_game_database( +def test_marker_file_flags_need_a_top_level_file( client: TestClient, access_token: str, platform: Platform, + field: str, rom_fixture: str, expected: bool, with_files: bool, @@ -164,7 +218,7 @@ def test_is_easyrpg_game_needs_a_top_level_game_database( rom = _fetch_one(client, access_token, platform, with_files=with_files) - assert rom["is_easyrpg_game"] is expected + assert rom[field] is expected def test_with_files_query_count_does_not_scale_with_file_count( diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 1758ea256..e3c55a151 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -3334,6 +3334,51 @@ class TestIdentifyRomEmitsNewFlag: assert [payload["is_new"] for payload in payloads] == [is_new, is_new] +class TestScanningRomFileFlags: + """Every scan emit of a rom precedes the write of its file rows, so the file + flags in its payload come from the files the scan read.""" + + async def test_rebuilt_files_reach_every_emit(self, mocker, identify_harness): + scanned = [ + RomFile( + file_name="game.jsdos", file_path="test/roms/Game", file_size_bytes=1 + ) + ] + identify_harness.get_rom_files.return_value = ParsedRomFiles( + rom_files=scanned, crc_hash="", md5_hash="", sha1_hash="", ra_hash="" + ) + identify_harness.db.add_rom.return_value.is_identified = True + emit = mocker.patch.object(scan_module, "emit_scanning_rom", AsyncMock()) + + await identify_harness.run(None, ScanType.COMPLETE, []) + + assert identify_harness.scan_rom.await_args.kwargs["scanned_files"] is scanned + assert [call.kwargs["files"] for call in emit.await_args_list] == [ + scanned, + scanned, + ] + + async def test_payload_flags_follow_the_scanned_files(self, rom: Rom): + loaded = db_rom_handler.get_rom(rom.id) + assert loaded is not None + files = [ + RomFile( + file_name="game.jsdos", + file_path=loaded.full_path, + category=RomFileCategory.GAME, + ) + ] + socket_manager = AsyncMock() + + await scan_handler_module.emit_scanning_rom( + socket_manager, loaded, is_new=True, files=files + ) + + payload = socket_manager.emit.await_args.args[1] + assert payload["has_jsdos_bundle"] is True + assert payload["has_nested_single_file"] is True + + class TestIdentifyRomIncrementalHashing: """Selected-rom metadata scans hand the stored rows to the file rebuild so unchanged files keep their hashes; full rescans read every file.""" diff --git a/frontend/src/__generated__/models/DetailedRomSchema.ts b/frontend/src/__generated__/models/DetailedRomSchema.ts index cf72a1c0a..d26e7392a 100644 --- a/frontend/src/__generated__/models/DetailedRomSchema.ts +++ b/frontend/src/__generated__/models/DetailedRomSchema.ts @@ -262,6 +262,10 @@ export type DetailedRomSchema = { * True for an RPG Maker 2000 or 2003 game: a folder containing an `rpg_rt.ldb` database. */ is_easyrpg_game: boolean; + /** + * True when the ROM is a `.jsdos` bundle, or a folder with one at its top level. + */ + has_jsdos_bundle: boolean; /** * The path of the file or folder relative to the library root: `fs_path` joined with `fs_name`. */ diff --git a/frontend/src/__generated__/models/RomFileSchema.ts b/frontend/src/__generated__/models/RomFileSchema.ts index c206e052c..a642c46fc 100644 --- a/frontend/src/__generated__/models/RomFileSchema.ts +++ b/frontend/src/__generated__/models/RomFileSchema.ts @@ -20,6 +20,10 @@ export type RomFileSchema = { file_size_bytes: number; full_path: string; is_top_level: boolean; + /** + * True when the file is gone from disk. + */ + missing_from_fs: boolean; created_at: string; updated_at: string; /** diff --git a/frontend/src/__generated__/models/SimpleRomSchema.ts b/frontend/src/__generated__/models/SimpleRomSchema.ts index 8617cc8d7..0b6289508 100644 --- a/frontend/src/__generated__/models/SimpleRomSchema.ts +++ b/frontend/src/__generated__/models/SimpleRomSchema.ts @@ -253,6 +253,10 @@ export type SimpleRomSchema = { * True for an RPG Maker 2000 or 2003 game: a folder containing an `rpg_rt.ldb` database. */ is_easyrpg_game: boolean; + /** + * True when the ROM is a `.jsdos` bundle, or a folder with one at its top level. + */ + has_jsdos_bundle: boolean; /** * The path of the file or folder relative to the library root: `fs_path` joined with `fs_name`. */ diff --git a/frontend/src/components/Dialogs/ManualUploadTargetDialog.test.ts b/frontend/src/components/Dialogs/ManualUploadTargetDialog.test.ts index 6a5262101..126b9ae96 100644 --- a/frontend/src/components/Dialogs/ManualUploadTargetDialog.test.ts +++ b/frontend/src/components/Dialogs/ManualUploadTargetDialog.test.ts @@ -59,6 +59,7 @@ function manualFile(): NonNullable[number] { file_size_bytes: 1024, full_path: "switch/roms/Game/manual/guide.pdf", is_top_level: false, + missing_from_fs: false, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", last_modified: "2026-01-01T00:00:00Z", diff --git a/frontend/src/components/Gallery/listRowFixture.ts b/frontend/src/components/Gallery/listRowFixture.ts index a3b807883..12d82d27f 100644 --- a/frontend/src/components/Gallery/listRowFixture.ts +++ b/frontend/src/components/Gallery/listRowFixture.ts @@ -112,6 +112,7 @@ export const ROM_DEFAULTS: SimpleRom = { has_nested_single_file: false, has_multiple_files: false, is_easyrpg_game: false, + has_jsdos_bundle: false, full_path: "/romm/library/snes/Chrono Trigger.sfc", created_at: "2026-01-02T00:00:00Z", updated_at: "2026-01-02T00:00:00Z", diff --git a/frontend/src/components/GameDetails/RelatedGameCard.vue b/frontend/src/components/GameDetails/RelatedGameCard.vue index 6b615d0fa..1f16810d4 100644 --- a/frontend/src/components/GameDetails/RelatedGameCard.vue +++ b/frontend/src/components/GameDetails/RelatedGameCard.vue @@ -161,6 +161,7 @@ const syntheticRom = computed(() => ({ has_nested_single_file: false, has_multiple_files: false, is_easyrpg_game: false, + has_jsdos_bundle: false, full_path: "", created_at: "", updated_at: "", diff --git a/frontend/src/composables/useCanPlay/index.test.ts b/frontend/src/composables/useCanPlay/index.test.ts index 82837f78f..2089009c5 100644 --- a/frontend/src/composables/useCanPlay/index.test.ts +++ b/frontend/src/composables/useCanPlay/index.test.ts @@ -56,7 +56,7 @@ vi.mock("@/utils", () => ({ isEasyRpgEmulationSupported: support.easyRpg, isEasyRpgGame: support.easyRpgGame, isRuffleEmulationSupported: support.ruffle, - isJsDosBundle: support.jsDosBundle, + hasJsDosBundle: support.jsDosBundle, })); function playableRom(overrides: Partial = {}): SimpleRom { diff --git a/frontend/src/composables/useCanPlay/index.ts b/frontend/src/composables/useCanPlay/index.ts index 70eefac6f..de0c352d7 100644 --- a/frontend/src/composables/useCanPlay/index.ts +++ b/frontend/src/composables/useCanPlay/index.ts @@ -21,10 +21,10 @@ import { useNativeStore } from "@/stores/native"; import type { SimpleRom } from "@/stores/roms"; import { useStreamingStore } from "@/stores/streaming"; import { + hasJsDosBundle, isEasyRpgEmulationSupported, isEasyRpgGame, isEJSEmulationSupported, - isJsDosBundle, isJsDosEmulationSupported, isPico8EmulationSupported, isPico8Rom, @@ -64,7 +64,7 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): { // offer Play on files the player panics on. const onJsDosPlatform = supportedBy(isJsDosEmulationSupported); const canPlayJsDos = computed( - () => onJsDosPlatform.value && isJsDosBundle(getRom()), + () => onJsDosPlatform.value && hasJsDosBundle(getRom()), ); const onPico8Platform = supportedBy(isPico8EmulationSupported); diff --git a/frontend/src/utils/index.test.ts b/frontend/src/utils/index.test.ts index ad461290c..4e3cb1610 100644 --- a/frontend/src/utils/index.test.ts +++ b/frontend/src/utils/index.test.ts @@ -4,16 +4,17 @@ import type { Heartbeat } from "@/stores/heartbeat"; import { ejsCoresFixture } from "./ejsCores.fixtures"; import { getSupportedEJSCores, + hasJsDosBundle, isArcadeSystem, isEasyRpgEmulationSupported, isEasyRpgGame, - isJsDosBundle, isJsDosEmulationSupported, isPico8EmulationSupported, isPico8Rom, + jsDosBundleFileIds, languageToEmoji, } from "./index"; -import { romFixture } from "./rom.fixtures"; +import { detailedRomFixture, romFileFixture, romFixture } from "./rom.fixtures"; function makeHeartbeat( emulation: Partial = {}, @@ -71,24 +72,51 @@ describe("isJsDosEmulationSupported", () => { }); }); -describe("isJsDosBundle", () => { - const withExt = (fs_extension: string) => romFixture({ fs_extension }); - - it("accepts a .jsdos bundle regardless of case", () => { - expect(isJsDosBundle(withExt("jsdos"))).toBe(true); - expect(isJsDosBundle(withExt("JSDOS"))).toBe(true); - }); - - // js-dos panics with "Broken bundle" on anything that is not its own format. - it("rejects plain archives, bare executables and folders", () => { - expect(isJsDosBundle(withExt("zip"))).toBe(false); - expect(isJsDosBundle(withExt("exe"))).toBe(false); - expect(isJsDosBundle(withExt(""))).toBe(false); +describe("hasJsDosBundle", () => { + it("follows the backend's bundle flag", () => { + expect(hasJsDosBundle(romFixture({ has_jsdos_bundle: true }))).toBe(true); + expect(hasJsDosBundle(romFixture({ has_jsdos_bundle: false }))).toBe(false); }); it("rejects a missing rom", () => { - expect(isJsDosBundle(null)).toBe(false); - expect(isJsDosBundle(undefined)).toBe(false); + expect(hasJsDosBundle(null)).toBe(false); + expect(hasJsDosBundle(undefined)).toBe(false); + }); +}); + +describe("jsDosBundleFileIds", () => { + const file = (id: number, file_name: string, is_top_level = true) => + romFileFixture({ id, file_name, is_top_level }); + + it("picks the top-level bundle beside other files", () => { + const rom = detailedRomFixture({ + files: [ + file(1, "manual.pdf"), + file(2, "Game (1996).JSDOS"), + file(3, "extra.jsdos", false), + ], + }); + expect(jsDosBundleFileIds(rom)).toEqual([2]); + }); + + it("returns none without a top-level bundle", () => { + const rom = detailedRomFixture({ files: [file(3, "extra.jsdos", false)] }); + expect(jsDosBundleFileIds(rom)).toEqual([]); + }); + + it("skips a bundle missing from disk", () => { + const rom = detailedRomFixture({ + files: [ + romFileFixture({ + id: 1, + file_name: "A.jsdos", + is_top_level: true, + missing_from_fs: true, + }), + file(2, "B.jsdos"), + ], + }); + expect(jsDosBundleFileIds(rom)).toEqual([2]); }); }); diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts index dce3cfdcb..3210e6304 100644 --- a/frontend/src/utils/index.ts +++ b/frontend/src/utils/index.ts @@ -546,16 +546,33 @@ export function isJsDosEmulationSupported( } /** - * Check if a ROM file is a js-dos bundle. + * Check if a ROM is a js-dos bundle, or a folder with one at its top level. * * js-dos panics on anything that is not an archive carrying * `.jsdos/dosbox.conf`. * * @param rom The ROM to check. - * @returns True if the file is a js-dos bundle, false otherwise. + * @returns True if the ROM has a js-dos bundle to boot, false otherwise. */ -export function isJsDosBundle(rom: SimpleRom | null | undefined) { - return rom?.fs_extension.toLowerCase() === "jsdos"; +export function hasJsDosBundle(rom: SimpleRom | null | undefined) { + return rom?.has_jsdos_bundle === true; +} + +/** + * Pick the js-dos bundle to boot, so the server sends that file instead of + * zipping the folder. + * + * @param rom The ROM to boot. + * @returns The bundle's file ID in a list, or an empty list if there is none. + */ +export function jsDosBundleFileIds(rom: DetailedRom): number[] { + const bundle = rom.files.find( + (file) => + file.is_top_level && + !file.missing_from_fs && + file.file_name.toLowerCase().endsWith(".jsdos"), + ); + return bundle ? [bundle.id] : []; } /** diff --git a/frontend/src/utils/rom.fixtures.ts b/frontend/src/utils/rom.fixtures.ts index 318b911b0..ab69df791 100644 --- a/frontend/src/utils/rom.fixtures.ts +++ b/frontend/src/utils/rom.fixtures.ts @@ -61,6 +61,7 @@ export function romFileFixture( file_size_bytes: 0, full_path: "", is_top_level: false, + missing_from_fs: false, created_at: WRITTEN_AT, updated_at: WRITTEN_AT, last_modified: null, @@ -152,6 +153,7 @@ export function romFixture(overrides: Partial = {}): SimpleRom { has_nested_single_file: false, has_multiple_files: false, is_easyrpg_game: false, + has_jsdos_bundle: false, full_path: "", created_at: WRITTEN_AT, updated_at: WRITTEN_AT, diff --git a/frontend/src/utils/romFiles.test.ts b/frontend/src/utils/romFiles.test.ts index e68bb83f6..11583fda5 100644 --- a/frontend/src/utils/romFiles.test.ts +++ b/frontend/src/utils/romFiles.test.ts @@ -15,6 +15,7 @@ const file: RomFileSchema = { file_size_bytes: 10, full_path: "platform/roms/game/screenshots/title screen #1.png", is_top_level: false, + missing_from_fs: false, created_at: "2024-01-01T00:00:00Z", updated_at: "2024-02-03T04:05:06+00:00", last_modified: "2024-01-01T00:00:00Z", diff --git a/frontend/src/views/Player/JsDos.test.ts b/frontend/src/views/Player/JsDos.test.ts index 69b817b62..a5ac2d450 100644 --- a/frontend/src/views/Player/JsDos.test.ts +++ b/frontend/src/views/Player/JsDos.test.ts @@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({ routerReplace: vi.fn(() => Promise.resolve()), confirm: vi.fn(), galleryRom: null as Record | null, + jsDosBundleFileIds: vi.fn((): number[] => []), routeLeaveGuard: null as ((to: { fullPath: string }) => unknown) | null, setPlaying: vi.fn(), setStageActive: vi.fn(), @@ -56,7 +57,9 @@ vi.mock("@/stores/roms", () => ({ })); vi.mock("@/utils", () => ({ - getDownloadPath: () => "/api/roms/1/content/game.jsdos", + getDownloadPath: ({ fileIDs }: { fileIDs: number[] }) => + `/api/roms/1/content/game.jsdos?file_ids=${fileIDs.join(",")}`, + jsDosBundleFileIds: mocks.jsDosBundleFileIds, })); vi.mock("@/components/shared/GameCover.vue", () => ({ @@ -135,6 +138,7 @@ beforeEach(() => { setIsolated(true); mocks.loadRuntime.mockResolvedValue(LOCAL_BASE); mocks.galleryRom = null; + mocks.jsDosBundleFileIds.mockReset().mockReturnValue([]); mocks.routeLeaveGuard = null; mocks.userId = 7; mocks.confirm.mockResolvedValue(false); @@ -177,6 +181,10 @@ async function mountPlayer(handle: JsDosProps): Promise { return wrapper; } +function optionsOf(): Partial { + return vi.mocked(window.Dos!).mock.calls[0]![1]; +} + function makeHandle(saveResult = true) { return { save: vi.fn().mockResolvedValue(saveResult), @@ -197,8 +205,16 @@ describe("JsDos runtime loading", () => { mocks.loadRuntime.mockResolvedValue(CDN_BASE); const wrapper = await mountPlayer(makeHandle()); - const options = vi.mocked(window.Dos!).mock.calls[0]![1]; - expect(options.pathPrefix).toBe(`${CDN_BASE}/emulators/`); + expect(optionsOf().pathPrefix).toBe(`${CDN_BASE}/emulators/`); + wrapper.unmount(); + }); + + it("downloads only the bundle file of a folder ROM", async () => { + mocks.jsDosBundleFileIds.mockReturnValue([42]); + const wrapper = await mountPlayer(makeHandle()); + + expect(mocks.jsDosBundleFileIds).toHaveBeenCalledWith(rom); + expect(optionsOf().url).toContain("file_ids=42"); wrapper.unmount(); }); @@ -511,10 +527,6 @@ describe("JsDos player exit", () => { }); describe("JsDos save sync", () => { - function optionsOf(): Partial { - return vi.mocked(window.Dos!).mock.calls[0]![1]; - } - it("boots from the synced changes instead of browser storage", async () => { const changes = new Uint8Array([80, 75]); saveSyncMocks.prepare.mockResolvedValue([ diff --git a/frontend/src/views/Player/JsDos.vue b/frontend/src/views/Player/JsDos.vue index 2af9f2d78..3dc177b33 100644 --- a/frontend/src/views/Player/JsDos.vue +++ b/frontend/src/views/Player/JsDos.vue @@ -26,7 +26,7 @@ import { AUTOSAVE_SLOT } from "@/services/api/save"; import storeAuth from "@/stores/auth"; import type { DetailedRom } from "@/stores/roms"; import type { JsDosProps } from "@/types/js-dos"; -import { getDownloadPath } from "@/utils"; +import { getDownloadPath, jsDosBundleFileIds } from "@/utils"; import type { PlayerSaveFile } from "@/utils/saveSync"; import { loadJsDosRuntime } from "./jsDosRuntime"; @@ -159,7 +159,11 @@ async function onPlay() { // DOSBox-X provides Windows support. runtimeBound = true; dos = dosFactory(stage.value, { - url: getDownloadPath({ rom: currentRom, purpose: "play" }), + url: getDownloadPath({ + rom: currentRom, + fileIDs: jsDosBundleFileIds(currentRom), + purpose: "play", + }), backend: "dosboxX", backendLocked: true, pathPrefix: `${assetBase}/emulators/`,