diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 664f1f697..3b1e7efd5 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -424,6 +424,11 @@ class StreamingPlatformOverride(TypedDict): label: NotRequired[str] memory_card_sync: NotRequired[bool] clears_stale_saves: NotRequired[bool] + # RetroArch only: the libretro core to boot instead of the broker's + # default, e.g. "bsnes". Shorthand: `snes: retroarch:bsnes`. + core: NotRequired[str] + # Lets a core the broker lists as known broken run anyway. + experimental_cores: NotRequired[bool] class StreamingContainer(TypedDict): @@ -449,6 +454,12 @@ class StreamingContainer(TypedDict): # Whether this broker empties the save tree before restoring an archive, # which is what lets the launch screen offer a save other than the newest. clears_stale_saves: NotRequired[bool] + # A single-platform entry's RetroArch core. Beside `platforms` it is + # ignored: set it on the platform instead. + core: NotRequired[str] + # Default for every platform this container serves; a platform block's + # own value wins. + experimental_cores: NotRequired[bool] # Broker dialect. Omitted (or "broker") is the per-emulator mod contract; # "webstation" is the LSIO webstation container's activate/exit contract. protocol: NotRequired[str] diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index 89e8b9334..99fbc6487 100644 --- a/backend/endpoints/responses/streaming.py +++ b/backend/endpoints/responses/streaming.py @@ -71,6 +71,9 @@ class SessionStatusSchema(BaseModel): # The room URL of a launched session, for a tab that missed launch-ready, reported by # the status poll only and left None by a heartbeat. host: str | None = None + # The launch's core warning, for that same tab. + core: str | None = None + core_tier: str | None = None termination: SessionTerminationSchema | None = None @@ -97,6 +100,11 @@ class LaunchReadyPayload(BaseModel): # None when no resume was asked for; False means the state could not be pushed and the # session started fresh. resume: bool | None = None + # The libretro core the platform asked for, None when it names none. + core: str | None = None + # How far the broker vouches for that core: "default", "vetted", + # "untested" or "blocked". None when no core was asked for. + core_tier: str | None = None class ImportRefusalSchema(BaseModel): diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index b9bdc779d..c4f332ecb 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -249,6 +249,8 @@ async def _session_status( # The room the launch answered with, so a tab that missed the # launch-ready push can enter the stream off a poll. "host": session.get("host"), + "core": session.get("core"), + "core_tier": session.get("core_tier"), } # An activate that has not returned yet leaves no launched_at behind. # Gating the broker round trip on it keeps this route pure Redis for diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 6b4a832c3..68aa079e1 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -11,6 +11,7 @@ from __future__ import annotations import hashlib import json +import re import secrets from collections.abc import Iterable, Sequence from dataclasses import dataclass @@ -44,8 +45,14 @@ PLATFORM_OVERRIDE_KEYS = ( "label", "memory_card_sync", "clears_stale_saves", + "core", + "experimental_cores", ) +# A libretro core as the broker's catalog names it, e.g. "parallel_n64". The +# broker owns the list and refuses an unknown one. +_CORE_NAME = re.compile(r"^[a-z0-9_]+$") + # Play-button text per emulator, used when a platform block sets no `label` # of its own. Keyed by emulator name as the broker registers it (lowercase). _EMULATOR_DISPLAY_NAMES: dict[str, str] = { @@ -67,9 +74,8 @@ _EMULATOR_DISPLAY_NAMES: dict[str, str] = { "xenia": "Xenia", } -# Display name of the libretro core the broker's RetroArch launcher picks for -# each platform (its retroarch_platforms.json). Display only: RomM never -# selects cores. A platform missing here is labelled by its slug instead. +# Display name of the core the broker's RetroArch launcher boots for each +# platform when config.yml sets none (its retroarch_platforms.json). _RETROARCH_CORE_NAMES: dict[str, str] = { "3do": "Opera", "3ds": "Azahar", @@ -135,13 +141,18 @@ def emulator_labels() -> dict[str, str]: return dict(_EMULATOR_DISPLAY_NAMES) -def emulator_display_label(emulator: str, platform: str) -> str: +def emulator_display_label( + emulator: str, platform: str, core: str | None = None +) -> str: """Play-button text for an emulator serving a platform, e.g. "PCSX2" or "RA PPSSPP". Unknown emulators fall back to their configured name.""" key = emulator.strip().lower() if key == "retroarch": - core = _RETROARCH_CORE_NAMES.get(platform.lower(), platform.upper()) - return f"RA {core}" + # A configured core names itself; the default's display name would be wrong. + if core: + return f"RA {core}" + name = _RETROARCH_CORE_NAMES.get(platform.lower(), platform.upper()) + return f"RA {name}" return _EMULATOR_DISPLAY_NAMES.get(key, emulator.strip()) @@ -177,6 +188,10 @@ class ResolvedContainer: """Where the container sees the ROM library, when it differs from RomM's.""" capabilities: PlatformCapabilities state_transfer: StateTransferLimits + core: str | None = None + """The libretro core the platform asks for, None for the broker's default.""" + experimental_cores: bool = False + """Whether a core the broker lists as known broken may run anyway.""" @property def is_webstation(self) -> bool: @@ -211,6 +226,10 @@ class ResolvedContainer: # Same-origin pool members are each proxied at their own path, so # they never carry the same protocol object. and self.protocol.name == other.protocol.name + # A member on another core would boot the game on it and file its + # states where the rest of the pool never looks. + and self.core == other.core + and self.experimental_cores == other.experimental_cores ) def memory_card_route(self) -> str: @@ -326,6 +345,22 @@ def _emulator_namespace(entry: dict[str, Any]) -> str: return str(value).strip().lower() +def _core_problem(emulator: str, core: Any) -> str | None: + """Why a configured core can't go to the broker, or None when it can. + + Worded to follow "container platform ''" in a warning. + """ + if core is None or (isinstance(core, str) and not core.strip()): + return "sets an empty core" + if not isinstance(core, str): + return "sets a core that is not a name" + if emulator.strip().lower() != "retroarch": + return f"sets core '{core.strip()}' but only retroarch takes a core" + if not _CORE_NAME.match(core.strip()): + return f"sets core '{core.strip()}', which must match {_CORE_NAME.pattern}" + return None + + def _resolve_one( entry: dict[str, Any], platform: str, container_label: Any ) -> ResolvedContainer: @@ -374,6 +409,24 @@ def _resolve_one( capabilities = {**capabilities, "supports_disc_swap": False} label = entry.get("label") + core = entry.get("core") or None + if core is not None and protocol.name != "webstation": + # Only the webstation broker is sent a core. + log.warning( + "container for platform '%s' sets core '%s' but only a webstation " + "container takes one, booting the default core instead", + platform, + core, + ) + core = None + opt_in = entry.get("experimental_cores") + if core is not None and opt_in is not None and not isinstance(opt_in, bool): + log.warning( + "container for platform '%s' sets experimental_cores to %r, only an " + "unquoted true opts in", + platform, + opt_in, + ) return ResolvedContainer( key=broker_host or "", host=raw_host, @@ -381,7 +434,7 @@ def _resolve_one( protocol=protocol, platform=platform, emulator=emulator, - label=str(label) if label else emulator_display_label(emulator, platform), + label=str(label) if label else emulator_display_label(emulator, platform, core), container_label=container_label if isinstance(container_label, str) else None, memory_card_sync=card_sync, clears_stale_saves=clears_stale_saves, @@ -389,6 +442,10 @@ def _resolve_one( library_path=str(entry.get("library_path") or LIBRARY_BASE_PATH).rstrip("/"), capabilities=capabilities, state_transfer=state_transfer_limits(emulator), + core=core, + # Only a real boolean opts in (a quoted "false" is truthy to bool()), + # and only beside a core, the one place it is ever sent. + experimental_cores=opt_in is True and core is not None, ) @@ -406,6 +463,12 @@ def _platform_entries(entry: dict[str, Any]) -> list[tuple[dict[str, Any], str]] "container missing platform/host, skipping: %s", _loggable(entry) ) return [] + if "core" in entry: + problem = _core_problem(_emulator_namespace(entry), entry["core"]) + if problem is not None: + log.warning("container platform '%s' %s, skipping", platform, problem) + return [] + entry = {**entry, "core": entry["core"].strip()} return [(entry, platform)] if not isinstance(platforms, dict): @@ -422,7 +485,15 @@ def _platform_entries(entry: dict[str, Any]) -> list[tuple[dict[str, Any], str]] _loggable(entry), ) - base = {k: v for k, v in entry.items() if k != "platforms"} + if "core" in entry: + # One core serves one platform; inheriting it would boot every + # platform in the map on it. + log.warning( + "container sets `core` beside `platforms`, ignoring it; set it on " + "the platform instead: %s", + _loggable(entry), + ) + base = {k: v for k, v in entry.items() if k not in ("platforms", "core")} rows: list[tuple[dict[str, Any], str]] = [] for platform, options in platforms.items(): if not isinstance(platform, str) or not platform.strip(): @@ -441,16 +512,22 @@ def _platform_overrides( `options` is either the emulator name or a block overriding container keys. """ + core: Any = None if isinstance(options, str): - emulator = options.strip() + # "retroarch:bsnes" is shorthand for a block naming both. + name, colon, core = options.partition(":") + emulator = name.strip() + has_core = bool(colon) overrides: dict[str, Any] = {} elif isinstance(options, dict): raw = options.get("emulator") emulator = raw.strip() if isinstance(raw, str) else "" + has_core = "core" in options + core = options.get("core") overrides = { k: v for k, v in options.items() - if k in PLATFORM_OVERRIDE_KEYS and k != "emulator" + if k in PLATFORM_OVERRIDE_KEYS and k not in ("emulator", "core") } for key in options: if key not in PLATFORM_OVERRIDE_KEYS: @@ -473,16 +550,27 @@ def _platform_overrides( log.warning("container platform '%s' has no emulator, skipping", platform) return None + if has_core: + problem = _core_problem(emulator, core) + if problem is not None: + log.warning("container platform '%s' %s, skipping", platform, problem) + return None + core = core.strip() + else: + core = None + # A platform block's own `label` wins; otherwise the emulator names the # button, not the container, so "Stream on PCSX2" rather than the box. - label = overrides.get("label") or emulator_display_label(emulator, platform) - return { + row = { **base, **overrides, "platform": platform, "emulator": emulator, - "label": label, + "label": overrides.get("label"), } + if core is not None: + row["core"] = core + return row def resolve_entry(entry: dict[str, Any]) -> ResolvedContainer | None: @@ -611,9 +699,9 @@ def _warn_about_later_pools( later = [c.key for pool in pools[1:] for c in pool] if later: log.warning( - "containers for platform '%s' disagree on emulator, memory card " - "sync, save picker or protocol, so game claims only use the first " - "pool; never claimed for a game: %s", + "containers for platform '%s' disagree on emulator, core, memory " + "card sync, save picker or protocol, so game claims only use the " + "first pool; never claimed for a game: %s", pools[0][0].platform, ", ".join(later), ) diff --git a/backend/handler/streaming/launch.py b/backend/handler/streaming/launch.py index d23de1cc5..a27ba4322 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -113,7 +113,12 @@ async def run_launch( resume_slot if resume_pushed else None, ) except Exception as exc: - log.exception("launch failed, platform=%s", platform) + if isinstance(exc, HTTPException): + # A deliberate refusal whose detail says what to fix; a traceback + # would dress it up as a crash. + log.warning("launch failed, platform=%s: %s", platform, exc.detail) + else: + log.exception("launch failed, platform=%s", platform) await lifecycle.abort_claim(session_key, session, blank_card_id) refused = exc if isinstance(exc, broker.ImportRefusedError) else None await push_to_user( @@ -135,7 +140,16 @@ async def run_launch( log.info("session claimed, platform=%s rom=%s", platform, rom_name) host = container.protocol.stream_url(container.host, launch_result) - await stamp_launched(session_key, session, host=host) + # Only a configured core is worth a word to the player: the broker reports + # its default's tier on every RetroArch launch. + core_tier = ( + launch_result.get("core_tier") + if container.core and isinstance(launch_result, dict) + else None + ) + await stamp_launched( + session_key, session, host=host, core=container.core, core_tier=core_tier + ) await lifecycle.publish_session_activity(session_key, session) # The webstation broker's deferred load waits for its emulator to report @@ -161,6 +175,8 @@ async def run_launch( claimed_at=session["claimed_at"], host=host, resume=resume_pushed if resume_state is not None else None, + core=container.core, + core_tier=core_tier, ).model_dump(), ) @@ -168,7 +184,11 @@ async def run_launch( # background, the stream should not wait on file transfers. background.spawn_sync_task( states.hydrate_states_to_broker( - user.id, rom.id, container, resume_pushed=resume_pushed + user.id, + rom.id, + container, + resume_pushed=resume_pushed, + core_tier=core_tier, ) ) diff --git a/backend/handler/streaming/session_store.py b/backend/handler/streaming/session_store.py index 4cf162b7f..011ed93c4 100644 --- a/backend/handler/streaming/session_store.py +++ b/backend/handler/streaming/session_store.py @@ -431,7 +431,11 @@ async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None: async def stamp_launched( - session_key: str, claim: dict[str, Any], host: str | None + session_key: str, + claim: dict[str, Any], + host: str | None, + core: str | None = None, + core_tier: str | None = None, ) -> None: """Record that the activate returned, so the status poll stops asking the broker for an extraction phase. @@ -447,6 +451,8 @@ async def stamp_launched( Args: host: a game's room URL, for the status poll to hand a tab that missed the push; None for a desktop, whose POST is the only reader. + core, core_tier: the configured core and its tier, so that tab still + hears the warning launch-ready carried. """ try: await mutate_session( @@ -454,6 +460,7 @@ async def stamp_launched( { "launched_at": datetime.now(timezone.utc).isoformat(), **({"host": host} if host else {}), + **({"core": core, "core_tier": core_tier} if core_tier else {}), }, require=lambda current: same_claim(current, claim), ) diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index 4c4cf6676..b7be9064b 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -481,6 +481,7 @@ async def hydrate_states_to_broker( rom_id: int, container: ResolvedContainer, resume_pushed: bool = False, + core_tier: str | None = None, ) -> int: """Background task: push the newest stored state for this ROM down to the freshly claimed container. Emulators read state files lazily, so pushing @@ -497,6 +498,14 @@ async def hydrate_states_to_broker( """ if resume_pushed or container.resumes_from_archive: return 0 + # Stored states don't record their core, so each is presumed the default's. + if container.core is not None and core_tier != "default": + log.info( + "not hydrating states into core %s (%s), they were made by the default", + container.core, + core_tier, + ) + return 0 user = db_user_handler.get_user(user_id) rom = db_rom_handler.get_rom(rom_id) diff --git a/backend/handler/streaming/webstation.py b/backend/handler/streaming/webstation.py index 76fcb0c43..e4964e3fe 100644 --- a/backend/handler/streaming/webstation.py +++ b/backend/handler/streaming/webstation.py @@ -27,7 +27,9 @@ import time import urllib.error from dataclasses import dataclass from typing import Any, Literal -from urllib.parse import quote +from urllib.parse import quote, urlencode + +from fastapi import HTTPException from config import STREAMING_LAUNCH_TIMEOUT, STREAMING_SAVE_TIMEOUT from handler.streaming import broker @@ -64,10 +66,12 @@ class ImportSpec: return kinds -# Per container, so one broker's answer never speaks for another. A 404 or 422 -# holds for the worker's life, an answer for one claim's checks, a failure not at all. +# Per container and core. A 404 or 422 holds for the worker's life, an answer +# or a refused core for one claim's checks, a failure not at all. _IMPORT_SPEC_TTL = 30.0 -_import_spec_cache: dict[tuple[str, str, str], tuple[float, ImportSpec | None]] = {} +_import_spec_cache: dict[ + tuple[str, str, str, str | None, bool], tuple[float, ImportSpec | None] +] = {} def _parse_import_spec(body: dict[str, Any]) -> ImportSpec | None: @@ -102,20 +106,36 @@ def import_spec( """What this broker accepts as a declared import, or None when nothing or unknown.""" if not container.is_webstation: return None - cache_key = (container.key, emulator, platform) + # The core is part of the key, so a config edit that changes the core is + # asked about afresh rather than read from the old core's answer. + cache_key = ( + container.key, + emulator, + platform, + container.core, + container.experimental_cores, + ) cached = _import_spec_cache.get(cache_key) if cached is not None and cached[0] > time.monotonic(): return cached[1] - path = container.protocol.session_route( - f"/import-spec?emulator={quote(emulator, safe='')}&platform={quote(platform, safe='')}" - ) + params = {"emulator": emulator, "platform": platform} + if container.core: + # Discovery has to answer for the core activate will boot. + params["core"] = container.core + if container.experimental_cores: + params["experimental_cores"] = "1" + path = container.protocol.session_route(f"/import-spec?{urlencode(params)}") try: resp = broker.request(container, path, method="GET", timeout=ACK_TIMEOUT) except urllib.error.HTTPError as exc: code = exc.code exc.close() if code in (404, 422): - _import_spec_cache[cache_key] = (math.inf, None) + # A refused core is fixed by upgrading the broker, so that answer + # expires like any other rather than lasting until a restart. + refused_core = code == 422 and container.core is not None + expires = time.monotonic() + _IMPORT_SPEC_TTL if refused_core else math.inf + _import_spec_cache[cache_key] = (expires, None) return None log.warning("import-spec check failed with HTTP %d, treating as unknown", code) return None @@ -162,8 +182,16 @@ def activate( "emulator": emulator, "multiplayer": multiplayer, } + # The core belongs to the platform's emulator; the desktop boots none. + core = ( + container.core if rom is not None and emulator == container.emulator else None + ) if rom is not None: - body["rom"] = rom + # Only a configured core goes out, so an unconfigured platform's body is + # what a broker without core support has always read. + body["rom"] = {**rom, "core": core} if core else rom + if core and container.experimental_cores: + body["rom"]["experimental_cores"] = True if gui_language: # Describes the player, not the rom, so it goes alongside `rom` rather # than inside it and is sent for a romless launch too. @@ -198,6 +226,30 @@ def activate( resp = resp if isinstance(resp, dict) else {} log.info("broker activated session, %s", resp) + if not isinstance(resp.get("core_tier"), str): + resp.pop("core_tier", None) + if core and resp.get("core") != core: + # An older broker drops the field and boots its default; a dump at exit + # would file that core's saves under this platform, so ask for none. + log.warning( + "broker booted core %s, not the configured %s, ending the session", + resp.get("core"), + core, + ) + # The broker refuses every activate while this game runs, and releasing + # the claim leaves nothing behind to stop it, so one lost exit is retried. + if exit_session(container, 0, save=False) is None and ( + exit_session(container, 0, save=False) is None + ): + log.error("wrong-core game on %s is still running", container.key) + raise HTTPException( + status_code=502, + detail=( + "This broker doesn't support `core:`. Upgrade the container, " + f"or remove `core: {core}` from the " + f"{container.platform} platform in config.yml." + ), + ) return resp diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 0fe0cca9d..1ee0983d1 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -430,6 +430,197 @@ def test_a_platform_entry_wins_over_the_emulator_fallback(): assert streaming.platform_capabilities("ngc")["max_slots"] == 7 +# ── RetroArch core override ────────────────────────────────────────────────── + + +def _snes(value, **container) -> ResolvedContainer: + """The snes record of a webstation container serving snes as `value`.""" + return _resolved(_webstation(platforms={"snes": value}, **container)) + + +def _warnings_of(caplog, build): + """Run `build` with the romm logger captured, returning its result.""" + romm_logger = logging.getLogger("romm") + romm_logger.addHandler(caplog.handler) + try: + with caplog.at_level(logging.WARNING, logger="romm"): + return build() + finally: + romm_logger.removeHandler(caplog.handler) + + +def test_the_shorthand_names_the_emulator_and_the_core(): + container = _snes("retroarch:bsnes") + assert (container.emulator, container.core) == ("retroarch", "bsnes") + assert container.label == "RA bsnes" + + +def test_the_shorthand_tolerates_spaces_around_the_colon(): + assert _snes(" retroarch : bsnes ").core == "bsnes" + + +def test_the_block_form_names_the_core(): + container = _snes({"emulator": "retroarch", "core": "parallel_n64"}) + assert (container.emulator, container.core) == ("retroarch", "parallel_n64") + + +def test_a_platform_label_wins_over_the_core_label(): + assert ( + _snes({"emulator": "retroarch", "core": "bsnes", "label": "SNES"}).label + == "SNES" + ) + + +def test_no_core_leaves_the_record_as_it_was(): + container = _snes("retroarch") + assert (container.core, container.experimental_cores) == (None, False) + assert container.label == "RA Snes9x" + + +def test_a_flat_entry_takes_a_core(): + entry = { + "platform": "snes", + "protocol": "webstation", + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", + "emulator": "retroarch", + "core": "bsnes", + } + assert _resolved(entry).core == "bsnes" + + +@pytest.mark.parametrize( + ("value", "reason"), + [ + ("pcsx2:bsnes", "only retroarch takes a core"), + ("retroarch:", "sets an empty core"), + ("retroarch:BSNES", "must match"), + ({"emulator": "dolphin", "core": "bsnes"}, "only retroarch takes a core"), + ({"emulator": "retroarch", "core": ""}, "sets an empty core"), + ({"emulator": "retroarch", "core": None}, "sets an empty core"), + ({"emulator": "retroarch", "core": 5}, "not a name"), + ({"emulator": "retroarch", "core": "../x"}, "must match"), + ], +) +def test_a_bad_core_skips_the_platform_with_a_warning(caplog, value, reason): + """Booting the default instead would hide the typo behind a working game.""" + resolved = _warnings_of( + caplog, lambda: resolve_entry(_webstation(platforms={"snes": value})) + ) + assert resolved is None + assert "container platform 'snes'" in caplog.text + assert reason in caplog.text + + +def test_a_bad_core_on_a_flat_entry_skips_it(caplog): + entry = { + "platform": "snes", + "host": "http://192.168.1.10:3000", + "emulator": "retroarch", + "core": "Bad Name", + } + assert _warnings_of(caplog, lambda: resolve_entry(entry)) is None + assert "must match" in caplog.text + + +def test_a_container_level_core_is_ignored_beside_platforms(caplog): + """One core serves one platform, so inheriting it would + boot every platform in the map on it.""" + container = _warnings_of(caplog, lambda: _snes("retroarch", core="bsnes")) + assert container.core is None + assert "`core` beside `platforms`" in caplog.text + + +def test_a_quoted_false_does_not_opt_in(): + """A quoted "false" is truthy to bool(), and this opt-in runs cores + known to be broken.""" + container = _snes( + {"emulator": "retroarch", "core": "bsnes", "experimental_cores": "false"} + ) + assert container.experimental_cores is False + + +def test_a_quoted_true_warns_that_it_does_not_opt_in(caplog): + """The broker's refusal tells the operator to set experimental_cores, which + they believe they did, so the log has to say why it didn't count.""" + container = _warnings_of( + caplog, + lambda: _snes( + {"emulator": "retroarch", "core": "bsnes", "experimental_cores": "true"} + ), + ) + assert container.experimental_cores is False + assert "experimental_cores" in caplog.text + + +def test_a_core_on_a_legacy_container_is_dropped_with_a_warning(caplog): + """Only the webstation broker is sent a core, so a legacy container boots + its default whatever is configured; the label must not claim otherwise.""" + entry = { + "platform": "snes", + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", + "emulator": "retroarch", + "core": "bsnes", + } + resolved = _warnings_of(caplog, lambda: _expand(entry)) + assert (resolved[0].core, resolved[0].label) == (None, "RA Snes9x") + assert "core" in caplog.text + + +def test_a_mapped_core_on_a_legacy_container_is_not_in_its_label(caplog): + entry = { + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", + "platforms": {"snes": "retroarch:bsnes"}, + } + resolved = _warnings_of(caplog, lambda: _expand(entry)) + assert (resolved[0].core, resolved[0].label) == (None, "RA Snes9x") + + +def test_an_explicit_label_survives_a_dropped_core(caplog): + entry = { + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", + "platforms": { + "snes": {"emulator": "retroarch", "core": "bsnes", "label": "Mine"} + }, + } + resolved = _warnings_of(caplog, lambda: _expand(entry)) + assert resolved[0].label == "Mine" + + +def test_the_platform_opt_in_wins_over_the_container(): + inherited = _snes("retroarch:bsnes", experimental_cores=True) + overridden = _snes( + {"emulator": "retroarch", "core": "bsnes", "experimental_cores": False}, + experimental_cores=True, + ) + assert inherited.experimental_cores is True + assert overridden.experimental_cores is False + + +def test_containers_on_different_cores_are_not_one_pool(): + """A claim landing on either would boot a different core + and file its states where the other never looks.""" + assert not _snes("retroarch:bsnes").interchangeable_with(_snes("retroarch")) + assert _snes("retroarch:bsnes").interchangeable_with(_snes("retroarch:bsnes")) + opted = _snes("retroarch:bsnes", experimental_cores=True) + assert not opted.interchangeable_with(_snes("retroarch:bsnes")) + + +def test_an_opt_in_without_a_core_does_not_split_a_pool(): + """The opt-in only goes out beside a core, so without one it changes + nothing a claim could land on.""" + opted = _snes("retroarch", experimental_cores=True) + assert opted.interchangeable_with(_snes("retroarch")) + + +def test_emulator_display_label_names_a_configured_core(): + assert emulator_display_label("retroarch", "snes", "bsnes") == "RA bsnes" + assert emulator_display_label("retroarch", "snes", None) == "RA Snes9x" + + def test_an_unconfigured_platform_still_has_no_states(): """The fallback keys off a configured container, so a platform nobody streams stays out of the save-state UI.""" @@ -3228,6 +3419,8 @@ def test_status_reports_active_for_owner(client, access_token, rom: Rom): "extraction_phase": None, "termination": None, "host": container["host"], + "core": None, + "core_tier": None, } @@ -4640,6 +4833,58 @@ def test_hydrate_skips_states_missing_on_disk(rom: Rom, admin_user: User): push.assert_not_called() +def _hydrate_ra(rom: Rom, user: User, value, core_tier): + """Hydrate a RetroArch container serving `rom` as `value`, returning the + count and the push mock.""" + db_state_handler.add_state(_state_for(rom, user, "Game.state", "retroarch")) + container = _resolved(_webstation(platforms={rom.platform_slug: value})) + with ( + patch( + "handler.filesystem.fs_asset_handler.read_file", + new=AsyncMock(return_value=b"state-bytes"), + ), + patch("handler.streaming.states.push_state_file", return_value=True) as push, + ): + pushed = asyncio.run( + states.hydrate_states_to_broker( + user.id, rom.id, container, core_tier=core_tier + ) + ) + return pushed, push + + +@pytest.mark.parametrize("tier", ["vetted", "untested", "blocked", None]) +def test_hydrate_pushes_nothing_into_a_non_default_core( + rom: Rom, admin_user: User, tier +): + """Stored states don't record their core yet, so every one is presumed the + default's; pushed into another core it lands where quick-load reads it.""" + pushed, push = _hydrate_ra(rom, admin_user, "retroarch:bsnes", tier) + assert pushed == 0 + push.assert_not_called() + + +def test_hydrate_still_pushes_when_the_configured_core_is_the_default( + rom: Rom, admin_user: User +): + pushed, _ = _hydrate_ra(rom, admin_user, "retroarch:snes9x", "default") + assert pushed == 1 + + +def test_hydrate_is_unchanged_without_a_core(rom: Rom, admin_user: User): + pushed, _ = _hydrate_ra(rom, admin_user, "retroarch", None) + assert pushed == 1 + + +def test_the_launch_hands_the_core_tier_to_hydration(client, access_token, rom: Rom): + with patch( + "handler.streaming.states.hydrate_states_to_broker", + new=AsyncMock(return_value=0), + ) as hydrate: + _ra_claim(client, access_token, rom, "retroarch:bsnes", _BSNES_REPLY) + assert hydrate.call_args.kwargs["core_tier"] == "untested" + + def _add_state_at(rom: Rom, user: User, file_name: str, day: int) -> State: """Add a state with an explicit updated_at, so history order is deterministic.""" state = _state_for(rom, user, file_name, "pcsx2") @@ -8378,6 +8623,61 @@ def test_import_spec_returns_none_and_caches_on_404(rom: Rom): assert urlopen.call_count == 1 +def _spec_path(container) -> str: + """The path import_spec asks the broker for.""" + with patch( + "handler.streaming.broker.request", side_effect=_http_error(404) + ) as request: + webstation.import_spec(container, "retroarch", "snes") + path: str = request.call_args.args[1] + return path + + +def test_import_spec_asks_about_the_configured_core(): + """Discovery must answer for the core activate boots, or the picker offers + imports that core refuses.""" + path = _spec_path(_snes("retroarch:bsnes")) + assert "&core=bsnes" in path + assert "experimental_cores" not in path + + +def test_import_spec_carries_the_opt_in(): + opted = _snes("retroarch:bsnes", experimental_cores=True) + assert _spec_path(opted).endswith("&core=bsnes&experimental_cores=1") + + +def test_import_spec_query_is_unchanged_without_a_core(): + assert "core=" not in _spec_path(_snes("retroarch")) + + +def test_import_spec_asks_again_when_the_core_changes(): + """A 404/422 is cached for the worker's life, so a key + without the core would keep the old core's answer after a config edit.""" + with patch( + "handler.streaming.broker.request", side_effect=_http_error(404) + ) as request: + webstation.import_spec(_snes("retroarch:bsnes"), "retroarch", "snes") + webstation.import_spec(_snes("retroarch"), "retroarch", "snes") + webstation.import_spec( + _snes("retroarch:bsnes", experimental_cores=True), "retroarch", "snes" + ) + assert request.call_count == 3 + + +def test_import_spec_asks_again_after_refusing_a_core(): + """A refused core is fixed by upgrading the broker, which must not take a + RomM restart to notice.""" + container = _snes("retroarch:bsnes") + later = time.monotonic() + webstation._IMPORT_SPEC_TTL + 1 + with patch( + "handler.streaming.broker.request", side_effect=_http_error(422) + ) as request: + webstation.import_spec(container, "retroarch", "snes") + with patch("handler.streaming.webstation.time.monotonic", return_value=later): + webstation.import_spec(container, "retroarch", "snes") + assert request.call_count == 2 + + def test_import_spec_never_asks_a_legacy_broker(rom: Rom): """Declared imports are a webstation contract; a per-emulator broker is never asked, so a foreign pick there is refused without a round trip.""" @@ -9265,6 +9565,199 @@ def test_kiosk_mode_can_still_read_config(client): assert client.get("/api/streaming/config").status_code == 200 +# ── RetroArch core on activate ────────────────────────────────────────────── + + +def _ra_claim(client, token, rom: Rom, value, reply: dict[str, Any]): + """Claim `rom` on a webstation container serving its platform as `value`, + with the broker transport answering `reply`. Returns the activate body, + what the launch pushed, and the exit_session mock. Stubs the transport + rather than `activate`, like `_activate_body`: the body is the point.""" + with _streaming(_webstation(platforms={rom.platform_slug: value})): + with ( + _pushes() as sent, + patch("handler.streaming.broker.request", return_value=reply) as request, + patch("handler.streaming.webstation.exit_session") as exit_session, + _spawns_nothing(), + ): + client.post( + "/api/streaming/sessions", + json={"rom_id": rom.id}, + headers=_auth(token), + ) + activate = next( + c for c in request.call_args_list if c.args[1].endswith("/activate") + ) + return activate.kwargs["body"], sent, exit_session + + +_BSNES_REPLY: dict[str, Any] = { + "url": "/room/x", + "core": "bsnes", + "core_tier": "untested", +} + + +def test_the_activate_body_carries_a_configured_core(client, access_token, rom: Rom): + body, _, _ = _ra_claim(client, access_token, rom, "retroarch:bsnes", _BSNES_REPLY) + assert body["rom"]["core"] == "bsnes" + assert "experimental_cores" not in body["rom"] + + +def test_status_warns_a_tab_that_missed_launch_ready_of_its_core( + client, access_token, rom: Rom +): + platforms = {rom.platform_slug: "retroarch:bsnes"} + with _streaming(_webstation(platforms=platforms)): + with ( + _pushes(), + patch("handler.streaming.broker.request", return_value=_BSNES_REPLY), + _spawns_nothing(), + ): + client.post( + "/api/streaming/sessions", + json={"rom_id": rom.id}, + headers=_auth(access_token), + ) + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + headers=_auth(access_token), + ) + assert r.json()["core"] == "bsnes" + assert r.json()["core_tier"] == "untested" + + +def test_the_activate_body_carries_the_opt_in(client, access_token, rom: Rom): + value = {"emulator": "retroarch", "core": "bsnes", "experimental_cores": True} + body, _, _ = _ra_claim(client, access_token, rom, value, _BSNES_REPLY) + assert body["rom"]["experimental_cores"] is True + + +def test_no_core_leaves_the_activate_body_unchanged(client, access_token, rom: Rom): + """An opt-in alone means nothing without a core, so it stays home too.""" + body, _, exit_session = _ra_claim( + client, + access_token, + rom, + {"emulator": "retroarch", "experimental_cores": True}, + {"url": "/room/x"}, + ) + assert "core" not in body["rom"] + assert "experimental_cores" not in body["rom"] + exit_session.assert_not_called() + + +def test_an_older_broker_that_drops_the_core_is_exited_asking_for_no_save( + client, access_token, rom: Rom +): + """Pydantic drops the unknown field and the broker boots + its default, which would file this session's saves under the wrong core.""" + _, sent, exit_session = _ra_claim( + client, access_token, rom, "retroarch:bsnes", {"url": "/room/x"} + ) + exit_session.assert_called_once() + assert exit_session.call_args.args[1] == 0 + assert exit_session.call_args.kwargs == {"save": False} + failed = next(p for event, p in sent if event == "streaming:launch-failed") + assert "doesn't support `core:`" in failed["detail"] + assert f"the {rom.platform_slug} platform" in failed["detail"] + assert _launch_ready(sent) == {} + + +def test_a_wrong_core_is_exited_again_when_the_first_exit_fails(): + """The broker refuses every activate while that game runs, so one lost exit + would wedge the container once the claim is released.""" + with ( + patch("handler.streaming.broker.request", return_value={"url": "/room/x"}), + patch( + "handler.streaming.webstation.exit_session", + side_effect=[None, {"state_saved": False}], + ) as exit_session, + pytest.raises(HTTPException), + ): + webstation.activate( + _snes("retroarch:bsnes"), + session_id="s", + user=MagicMock(id=1, username="u"), + emulator="retroarch", + rom={"id": 1, "name": "Game", "platform": "snes"}, + ) + assert exit_session.call_count == 2 + + +def test_a_broker_that_drops_the_core_logs_no_traceback( + client, access_token, rom: Rom, caplog +): + """The 502 is a config message for the operator, not a crash.""" + _warnings_of( + caplog, + lambda: _ra_claim( + client, access_token, rom, "retroarch:bsnes", {"url": "/room/x"} + ), + ) + failed = [r for r in caplog.records if r.getMessage().startswith("launch failed")] + assert failed + assert all(r.exc_info is None for r in failed) + + +def test_a_broker_that_echoes_the_core_launches(client, access_token, rom: Rom): + _, sent, exit_session = _ra_claim( + client, access_token, rom, "retroarch:bsnes", _BSNES_REPLY + ) + exit_session.assert_not_called() + assert _launch_ready(sent) != {} + + +def test_launch_ready_names_the_core_and_its_tier(client, access_token, rom: Rom): + _, sent, _ = _ra_claim(client, access_token, rom, "retroarch:bsnes", _BSNES_REPLY) + ready = _launch_ready(sent) + assert (ready["core"], ready["core_tier"]) == ("bsnes", "untested") + + +def test_launch_ready_has_no_tier_without_a_core(client, access_token, rom: Rom): + """A new broker reports the default's tier on every RetroArch launch; with + no core configured there is nothing to warn about.""" + reply = {"url": "/room/x", "core": "snes9x", "core_tier": "default"} + _, sent, _ = _ra_claim(client, access_token, rom, "retroarch", reply) + ready = _launch_ready(sent) + assert (ready["core"], ready["core_tier"]) == (None, None) + + +def test_a_malformed_core_tier_still_reaches_launch_ready( + client, access_token, rom: Rom +): + """The session is already running, so a bad tier must not cost the player + the room URL.""" + reply = {**_BSNES_REPLY, "core_tier": 3} + _, sent, _ = _ra_claim(client, access_token, rom, "retroarch:bsnes", reply) + ready = _launch_ready(sent) + assert (ready["core"], ready["core_tier"]) == ("bsnes", None) + + +def test_a_desktop_on_a_container_with_a_core_boots_no_core(client, access_token): + """The desktop runs on the container's first platform record, whose core + it never boots, so the broker's missing echo is not a skew.""" + container = _webstation(platforms={"snes": "retroarch:bsnes"}) + with _streaming(container): + with ( + patch( + "handler.streaming.broker.request", return_value={"url": "/room/x"} + ) as request, + patch("handler.streaming.webstation.exit_session") as exit_session, + ): + response = client.post( + "/api/streaming/desktop", + json={"container": _key_of(container)}, + headers=_auth(access_token), + ) + assert response.status_code == 200 + exit_session.assert_not_called() + activate = next( + c for c in request.call_args_list if c.args[1].endswith("/activate") + ) + assert "rom" not in activate.kwargs["body"] + + # ── multiplayer flag ───────────────────────────────────────────────────────── diff --git a/examples/config.example.yml b/examples/config.example.yml index 45cbe266b..200114249 100644 --- a/examples/config.example.yml +++ b/examples/config.example.yml @@ -221,7 +221,8 @@ # containers: # # One container can serve many platforms. Container keys are defaults # # for every platform it serves; a platform block may override emulator, -# # label, memory_card_sync, and clears_stale_saves. +# # label, memory_card_sync, clears_stale_saves, core and +# # experimental_cores. # - protocol: webstation # host: https://192.168.1.56:3010 # browser-facing UI, must be https # subfolder: /streaming # matches the container's SUBFOLDER @@ -241,3 +242,14 @@ # wii: # emulator: dolphin # clears_stale_saves: true +# # RetroArch boots the broker's best-tested core for each platform. +# # To pick another libretro core, name it after the emulator... +# gba: retroarch:gpsp +# # ...or set `core` in a block. The broker refuses a core it doesn't +# # know and warns about one nobody has tested yet; see +# # https://github.com/romm-streaming/romm-broker (retroarch-cores docs). +# n64: +# emulator: retroarch +# core: parallel_n64 +# # Lets a core listed as broken by the broker run anyway. +# # experimental_cores: true diff --git a/frontend/src/__generated__/models/LaunchReadyPayload.ts b/frontend/src/__generated__/models/LaunchReadyPayload.ts index 22fda9923..5f2a2fdaf 100644 --- a/frontend/src/__generated__/models/LaunchReadyPayload.ts +++ b/frontend/src/__generated__/models/LaunchReadyPayload.ts @@ -11,5 +11,7 @@ export type LaunchReadyPayload = { claimed_at: string; host: string; resume?: (boolean | null); + core?: (string | null); + core_tier?: (string | null); }; diff --git a/frontend/src/__generated__/models/SessionStatusSchema.ts b/frontend/src/__generated__/models/SessionStatusSchema.ts index 5c78470d7..6f047554e 100644 --- a/frontend/src/__generated__/models/SessionStatusSchema.ts +++ b/frontend/src/__generated__/models/SessionStatusSchema.ts @@ -8,6 +8,8 @@ export type SessionStatusSchema = { platform: string; extraction_phase?: (string | null); host?: (string | null); + core?: (string | null); + core_tier?: (string | null); termination?: (SessionTerminationSchema | null); }; diff --git a/frontend/src/locales/bg_BG/play.json b/frontend/src/locales/bg_BG/play.json index 9b0c68862..ed083ee85 100644 --- a/frontend/src/locales/bg_BG/play.json +++ b/frontend/src/locales/bg_BG/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} от {total} съвместими", "context-menu": "Контекстно меню", "control-settings": "Настройки на контролите", + "core-blocked": "{core} е известно като неработещо на тази платформа и работи само защото експерименталните ядра са включени. Записите и състоянията може да не работят.", "core-not-loadable": "Не може да се зареди с избраното ядро", + "core-untested": "{core} все още не е тествано на тази платформа. Записите и състоянията може да не работят както се очаква. Моля, съобщете как работи.", "create-memory-card": "Нова карта памет", "delete-memory-card": "Изтриване на карта памет", "delete-memory-card-body": "Това ще изтрие завинаги „{name}\" и всички запазени версии. Действието е необратимо.", diff --git a/frontend/src/locales/cs_CZ/play.json b/frontend/src/locales/cs_CZ/play.json index 030306c3e..1a461ef0c 100644 --- a/frontend/src/locales/cs_CZ/play.json +++ b/frontend/src/locales/cs_CZ/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} z {total} kompatibilních", "context-menu": "Kontextová nabídka", "control-settings": "Nastavení ovládání", + "core-blocked": "{core} je na této platformě známé jako nefunkční a běží jen proto, že jsou zapnutá experimentální jádra. Uložené hry a stavy nemusí fungovat.", "core-not-loadable": "Vybrané jádro to nedokáže načíst", + "core-untested": "{core} zatím nebylo na této platformě otestováno. Uložené hry a stavy nemusí fungovat podle očekávání. Dejte nám prosím vědět, jak běží.", "create-memory-card": "Nová paměťová karta", "delete-memory-card": "Odstranit paměťovou kartu", "delete-memory-card-body": "Tímto trvale odstraníte „{name}\" a všechny její uložené verze. Tuto akci nelze vrátit zpět.", diff --git a/frontend/src/locales/de_DE/play.json b/frontend/src/locales/de_DE/play.json index 00583673f..a1965b96c 100644 --- a/frontend/src/locales/de_DE/play.json +++ b/frontend/src/locales/de_DE/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} von {total} kompatibel", "context-menu": "Kontextmenü", "control-settings": "Steuerungseinstellungen", + "core-blocked": "{core} ist auf dieser Plattform als fehlerhaft bekannt und läuft nur, weil experimentelle Cores aktiviert sind. Spielstände und States funktionieren möglicherweise nicht.", "core-not-loadable": "Vom gewählten Core nicht ladbar", + "core-untested": "{core} wurde auf dieser Plattform noch nicht getestet. Spielstände und States funktionieren möglicherweise nicht wie erwartet. Bitte melde, wie er läuft.", "create-memory-card": "Neue Speicherkarte", "delete-memory-card": "Speicherkarte löschen", "delete-memory-card-body": "Dadurch werden „{name}\" und alle gespeicherten Versionen davon dauerhaft gelöscht. Dies kann nicht rückgängig gemacht werden.", diff --git a/frontend/src/locales/en_GB/play.json b/frontend/src/locales/en_GB/play.json index c43526bc6..9f6fbd256 100644 --- a/frontend/src/locales/en_GB/play.json +++ b/frontend/src/locales/en_GB/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} of {total} compatible", "context-menu": "Context menu", "control-settings": "Control settings", + "core-blocked": "{core} is known to be broken on this platform and runs only because experimental cores are on. Saves and states may not work.", "core-not-loadable": "Not loadable by the selected core", + "core-untested": "{core} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", "create-memory-card": "New memory card", "delete-memory-card": "Delete memory card", "delete-memory-card-body": "This permanently deletes \"{name}\" and every saved version of it. This cannot be undone.", diff --git a/frontend/src/locales/en_US/play.json b/frontend/src/locales/en_US/play.json index 8a8db64bf..ee4f25c9e 100644 --- a/frontend/src/locales/en_US/play.json +++ b/frontend/src/locales/en_US/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} of {total} compatible", "context-menu": "Context menu", "control-settings": "Control settings", + "core-blocked": "{core} is known to be broken on this platform and runs only because experimental cores are on. Saves and states may not work.", "core-not-loadable": "Not loadable by the selected core", + "core-untested": "{core} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", "create-memory-card": "New memory card", "delete-memory-card": "Delete memory card", "delete-memory-card-body": "This permanently deletes \"{name}\" and every saved version of it. This cannot be undone.", diff --git a/frontend/src/locales/es_ES/play.json b/frontend/src/locales/es_ES/play.json index 3328e28b2..27fdaa293 100644 --- a/frontend/src/locales/es_ES/play.json +++ b/frontend/src/locales/es_ES/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} de {total} compatibles", "context-menu": "Menú contextual", "control-settings": "Ajustes de control", + "core-blocked": "{core} tiene fallos conocidos en esta plataforma y solo se ejecuta porque los cores experimentales están activados. Es posible que las partidas guardadas y los estados no funcionen.", "core-not-loadable": "No se puede cargar con el core seleccionado", + "core-untested": "{core} aún no se ha probado en esta plataforma. Es posible que las partidas guardadas y los estados no funcionen como se espera. Cuéntanos cómo funciona.", "create-memory-card": "Nueva tarjeta de memoria", "delete-memory-card": "Eliminar tarjeta de memoria", "delete-memory-card-body": "Esto elimina permanentemente \"{name}\" y todas sus versiones guardadas. Esta acción no se puede deshacer.", diff --git a/frontend/src/locales/fr_FR/play.json b/frontend/src/locales/fr_FR/play.json index 56e705eb2..0aff39eab 100644 --- a/frontend/src/locales/fr_FR/play.json +++ b/frontend/src/locales/fr_FR/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} sur {total} compatibles", "context-menu": "Menu contextuel", "control-settings": "Paramètres des commandes", + "core-blocked": "{core} est connu pour mal fonctionner sur cette plateforme et ne s'exécute que parce que les cœurs expérimentaux sont activés. Les sauvegardes et les états peuvent ne pas fonctionner.", "core-not-loadable": "Non chargeable par le cœur sélectionné", + "core-untested": "{core} n'a pas encore été testé sur cette plateforme. Les sauvegardes et les états peuvent ne pas fonctionner comme prévu. Merci de nous dire comment il se comporte.", "create-memory-card": "Nouvelle carte mémoire", "delete-memory-card": "Supprimer la carte mémoire", "delete-memory-card-body": "Cela supprime définitivement « {name} » et toutes ses versions enregistrées. Cette action est irréversible.", diff --git a/frontend/src/locales/hu_HU/play.json b/frontend/src/locales/hu_HU/play.json index 0348765d8..c60b170c6 100644 --- a/frontend/src/locales/hu_HU/play.json +++ b/frontend/src/locales/hu_HU/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} / {total} kompatibilis", "context-menu": "Helyi menü", "control-settings": "Irányítás beállításai", + "core-blocked": "A(z) {core} ismerten hibás ezen a platformon, és csak azért fut, mert a kísérleti magok be vannak kapcsolva. A mentések és állapotok nem biztos, hogy működnek.", "core-not-loadable": "A kiválasztott mag nem tudja betölteni", + "core-untested": "A(z) {core} még nincs tesztelve ezen a platformon. A mentések és állapotok nem biztos, hogy a várt módon működnek. Kérjük, jelezd, hogyan fut.", "create-memory-card": "Új memóriakártya", "delete-memory-card": "Memóriakártya törlése", "delete-memory-card-body": "Ez véglegesen törli a(z) „{name}\" kártyát és annak minden mentett verzióját. A művelet nem vonható vissza.", diff --git a/frontend/src/locales/it_IT/play.json b/frontend/src/locales/it_IT/play.json index a5426fb7c..32bd08081 100644 --- a/frontend/src/locales/it_IT/play.json +++ b/frontend/src/locales/it_IT/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} di {total} compatibili", "context-menu": "Menu contestuale", "control-settings": "Impostazioni controlli", + "core-blocked": "{core} ha problemi noti su questa piattaforma e funziona solo perché i core sperimentali sono attivi. Salvataggi e stati potrebbero non funzionare.", "core-not-loadable": "Non caricabile dal core selezionato", + "core-untested": "{core} non è ancora stato testato su questa piattaforma. Salvataggi e stati potrebbero non funzionare come previsto. Facci sapere come funziona.", "create-memory-card": "Nuova memory card", "delete-memory-card": "Elimina memory card", "delete-memory-card-body": "Questa operazione elimina definitivamente \"{name}\" e tutte le sue versioni salvate. L'azione non può essere annullata.", diff --git a/frontend/src/locales/ja_JP/play.json b/frontend/src/locales/ja_JP/play.json index 993c76209..adfbe4195 100644 --- a/frontend/src/locales/ja_JP/play.json +++ b/frontend/src/locales/ja_JP/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{total} 件中 {compatible} 件が互換", "context-menu": "コンテキストメニュー", "control-settings": "操作設定", + "core-blocked": "{core} はこのプラットフォームで不具合が知られており、実験的コアが有効なため起動しています。セーブとステートが動作しない可能性があります。", "core-not-loadable": "選択中のコアでは読み込めません", + "core-untested": "{core} はこのプラットフォームでまだテストされていません。セーブとステートが期待どおりに動作しない可能性があります。動作状況をお知らせください。", "create-memory-card": "新しいメモリーカード", "delete-memory-card": "メモリーカードを削除", "delete-memory-card-body": "「{name}」とその保存済みバージョンをすべて完全に削除します。この操作は元に戻せません。", diff --git a/frontend/src/locales/ko_KR/play.json b/frontend/src/locales/ko_KR/play.json index 4072a1550..2a695b03f 100644 --- a/frontend/src/locales/ko_KR/play.json +++ b/frontend/src/locales/ko_KR/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{total}개 중 {compatible}개 호환", "context-menu": "컨텍스트 메뉴", "control-settings": "조작 설정", + "core-blocked": "{core}은(는) 이 플랫폼에서 문제가 있는 것으로 알려져 있으며, 실험적 코어가 켜져 있어서 실행됩니다. 세이브와 스테이트가 작동하지 않을 수 있습니다.", "core-not-loadable": "선택한 코어에서 불러올 수 없음", + "core-untested": "{core}은(는) 이 플랫폼에서 아직 테스트되지 않았습니다. 세이브와 스테이트가 예상대로 작동하지 않을 수 있습니다. 실행 결과를 알려 주세요.", "create-memory-card": "새 메모리 카드", "delete-memory-card": "메모리 카드 삭제", "delete-memory-card-body": "\"{name}\" 및 저장된 모든 버전을 영구적으로 삭제합니다. 이 작업은 되돌릴 수 없습니다.", diff --git a/frontend/src/locales/pl_PL/play.json b/frontend/src/locales/pl_PL/play.json index 5799abe92..2309c3add 100644 --- a/frontend/src/locales/pl_PL/play.json +++ b/frontend/src/locales/pl_PL/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} z {total} zgodnych", "context-menu": "Menu kontekstowe", "control-settings": "Ustawienia sterowania", + "core-blocked": "{core} ma znane problemy na tej platformie i działa tylko dlatego, że eksperymentalne rdzenie są włączone. Zapisy i stany mogą nie działać.", "core-not-loadable": "Nie do wczytania przez wybrany rdzeń", + "core-untested": "{core} nie został jeszcze przetestowany na tej platformie. Zapisy i stany mogą nie działać zgodnie z oczekiwaniami. Daj znać, jak działa.", "create-memory-card": "Nowa karta pamięci", "delete-memory-card": "Usuń kartę pamięci", "delete-memory-card-body": "Spowoduje to trwałe usunięcie „{name}\" oraz wszystkich zapisanych wersji. Tej operacji nie można cofnąć.", diff --git a/frontend/src/locales/pt_BR/play.json b/frontend/src/locales/pt_BR/play.json index 490fcd583..f4e1aae02 100644 --- a/frontend/src/locales/pt_BR/play.json +++ b/frontend/src/locales/pt_BR/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} de {total} compatíveis", "context-menu": "Menu de contexto", "control-settings": "Configurações de controle", + "core-blocked": "{core} tem problemas conhecidos nesta plataforma e só roda porque os cores experimentais estão ativados. Saves e estados podem não funcionar.", "core-not-loadable": "Não carregável pelo core selecionado", + "core-untested": "{core} ainda não foi testado nesta plataforma. Saves e estados podem não funcionar como esperado. Conte para nós como ele roda.", "create-memory-card": "Novo cartão de memória", "delete-memory-card": "Excluir cartão de memória", "delete-memory-card-body": "Isso exclui permanentemente \"{name}\" e todas as suas versões salvas. Esta ação não pode ser desfeita.", diff --git a/frontend/src/locales/ro_RO/play.json b/frontend/src/locales/ro_RO/play.json index fa5c62f88..74565ede2 100644 --- a/frontend/src/locales/ro_RO/play.json +++ b/frontend/src/locales/ro_RO/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} din {total} compatibile", "context-menu": "Meniu contextual", "control-settings": "Setări control", + "core-blocked": "{core} are probleme cunoscute pe această platformă și rulează doar pentru că nucleele experimentale sunt activate. Salvările și stările s-ar putea să nu funcționeze.", "core-not-loadable": "Nu poate fi încărcat de nucleul selectat", + "core-untested": "{core} nu a fost încă testat pe această platformă. Salvările și stările s-ar putea să nu funcționeze cum era de așteptat. Spune-ne cum rulează.", "create-memory-card": "Card de memorie nou", "delete-memory-card": "Șterge cardul de memorie", "delete-memory-card-body": "Această acțiune șterge definitiv „{name}\" și toate versiunile salvate ale acestuia. Acțiunea nu poate fi anulată.", diff --git a/frontend/src/locales/ru_RU/play.json b/frontend/src/locales/ru_RU/play.json index c225ec107..abdf4ecdf 100644 --- a/frontend/src/locales/ru_RU/play.json +++ b/frontend/src/locales/ru_RU/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{compatible} из {total} совместимы", "context-menu": "Контекстное меню", "control-settings": "Настройки управления", + "core-blocked": "{core} известно как неработающее на этой платформе и запускается только потому, что включены экспериментальные ядра. Сохранения и состояния могут не работать.", "core-not-loadable": "Выбранное ядро не может загрузить", + "core-untested": "{core} ещё не проверено на этой платформе. Сохранения и состояния могут работать не так, как ожидается. Сообщите, пожалуйста, как оно работает.", "create-memory-card": "Новая карта памяти", "delete-memory-card": "Удалить карту памяти", "delete-memory-card-body": "Это навсегда удалит «{name}» и все её сохранённые версии. Это действие нельзя отменить.", diff --git a/frontend/src/locales/tr_TR/play.json b/frontend/src/locales/tr_TR/play.json index b2f75b83a..3576aea19 100644 --- a/frontend/src/locales/tr_TR/play.json +++ b/frontend/src/locales/tr_TR/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{total} içinden {compatible} uyumlu", "context-menu": "Bağlam menüsü", "control-settings": "Kontrol ayarları", + "core-blocked": "{core} bu platformda bilinen sorunlara sahip ve yalnızca deneysel çekirdekler açık olduğu için çalışıyor. Kayıtlar ve durumlar çalışmayabilir.", "core-not-loadable": "Seçili çekirdek tarafından yüklenemez", + "core-untested": "{core} bu platformda henüz test edilmedi. Kayıtlar ve durumlar beklendiği gibi çalışmayabilir. Lütfen nasıl çalıştığını bildirin.", "create-memory-card": "Yeni hafıza kartı", "delete-memory-card": "Hafıza kartını sil", "delete-memory-card-body": "Bu işlem \"{name}\" öğesini ve tüm kayıtlı sürümlerini kalıcı olarak siler. Bu işlem geri alınamaz.", diff --git a/frontend/src/locales/zh_CN/play.json b/frontend/src/locales/zh_CN/play.json index 115131324..78f298b2c 100644 --- a/frontend/src/locales/zh_CN/play.json +++ b/frontend/src/locales/zh_CN/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{total} 个中 {compatible} 个兼容", "context-menu": "上下文菜单", "control-settings": "控制设置", + "core-blocked": "{core} 在此平台上已知存在问题,仅因启用了实验性核心才会运行。存档和即时存档可能无法使用。", "core-not-loadable": "所选核心无法加载", + "core-untested": "{core} 尚未在此平台上测试。存档和即时存档可能无法正常工作。请反馈它的运行情况。", "create-memory-card": "新建记忆卡", "delete-memory-card": "删除记忆卡", "delete-memory-card-body": "这将永久删除\"{name}\"及其所有已保存的版本。此操作无法撤消。", diff --git a/frontend/src/locales/zh_TW/play.json b/frontend/src/locales/zh_TW/play.json index 1acd89850..52c940a86 100644 --- a/frontend/src/locales/zh_TW/play.json +++ b/frontend/src/locales/zh_TW/play.json @@ -20,7 +20,9 @@ "compatible-of-total": "{total} 個中 {compatible} 個相容", "context-menu": "內容選單", "control-settings": "控制設定", + "core-blocked": "{core} 在此平台上已知有問題,僅因啟用了實驗性核心才會執行。存檔和即時存檔可能無法使用。", "core-not-loadable": "所選核心無法載入", + "core-untested": "{core} 尚未在此平台上測試。存檔和即時存檔可能無法正常運作。請回報它的執行情況。", "create-memory-card": "新增記憶卡", "delete-memory-card": "刪除記憶卡", "delete-memory-card-body": "這將永久刪除「{name}」及其所有已儲存的版本。此操作無法復原。", diff --git a/frontend/src/v2/views/Player/Stream.test.ts b/frontend/src/v2/views/Player/Stream.test.ts index 1c7c48e5c..834c3eb7b 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -28,10 +28,12 @@ const mocks = vi.hoisted(() => ({ presenceTick: null as (() => Promise) | null, socketHandlers: {} as Record unknown>, query: {} as Record, + snackbar: { success: vi.fn(), error: vi.fn(), warning: vi.fn() }, + t: vi.fn((key: string) => key), })); vi.mock("vue-i18n", () => ({ - useI18n: () => ({ t: (key: string) => key }), + useI18n: () => ({ t: mocks.t }), })); vi.mock("vue-router", () => ({ @@ -140,7 +142,7 @@ vi.mock("@/v2/composables/usePlaySession", () => ({ })); vi.mock("@/v2/composables/useSnackbar", () => ({ - useSnackbar: () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn() }), + useSnackbar: () => mocks.snackbar, })); vi.mock("@/v2/composables/useSocketEvent", () => ({ @@ -876,6 +878,43 @@ describe("Stream launch recovery", () => { mocks.claimSession.mockResolvedValue(CLAIM); }); + it("warns when the broker booted an untested core", async () => { + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + + await launchReady({ core: "bsnes", core_tier: "untested" }); + await flushPromises(); + + expect(mocks.snackbar.warning).toHaveBeenCalledWith("play.core-untested"); + expect(mocks.t).toHaveBeenCalledWith("play.core-untested", { + core: "bsnes", + }); + expect(vmOf(wrapper).playerState).toBe("playing"); + }); + + it("warns when the broker booted a known-broken core", async () => { + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + + await launchReady({ core: "bsnes", core_tier: "blocked" }); + await flushPromises(); + + expect(mocks.snackbar.warning).toHaveBeenCalledWith("play.core-blocked"); + expect(mocks.t).toHaveBeenCalledWith("play.core-blocked", { + core: "bsnes", + }); + }); + + it("says nothing about a default or vetted core", async () => { + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + + await launchReady({ core: "bsnes", core_tier: "vetted" }); + await flushPromises(); + + expect(mocks.snackbar.warning).not.toHaveBeenCalled(); + }); + it("enters the stream when the poll finds the game already up", async () => { // launch-ready is pushed once, so a socket that dropped during the launch // left the tab loading over a game that was running. @@ -901,6 +940,47 @@ describe("Stream launch recovery", () => { ); }); + it("warns of the core when the poll finds the game already up", async () => { + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + mocks.fetchSessionStatus.mockResolvedValue({ + status: "active", + platform: "gba", + host: "http://webstation-dev:8080/room/x", + core: "bsnes", + core_tier: "untested", + }); + + await pollStatus(); + + expect(mocks.snackbar.warning).toHaveBeenCalledExactlyOnceWith( + "play.core-untested", + ); + expect(mocks.t).toHaveBeenCalledWith("play.core-untested", { + core: "bsnes", + }); + }); + + it("warns of the core once when launch-ready follows the poll", async () => { + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + mocks.fetchSessionStatus.mockResolvedValue({ + status: "active", + platform: "gba", + host: "http://webstation-dev:8080/room/x", + core: "bsnes", + core_tier: "blocked", + }); + await pollStatus(); + + await launchReady({ core: "bsnes", core_tier: "blocked" }); + await flushPromises(); + + expect(mocks.snackbar.warning).toHaveBeenCalledExactlyOnceWith( + "play.core-blocked", + ); + }); + it("leaves a stream the poll entered alone when launch-ready follows", async () => { const wrapper = await launch({ picker: false }); await vmOf(wrapper).onPlay(); diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index cdac59886..a4d927cf0 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -591,9 +591,18 @@ async function enterStream(host: string): Promise { async function enterRunningSession(status: SessionStatus): Promise { if (playerState.value !== "loading" || !status.host) return; launchPhase.value = null; + warnOfCore(status.core, status.core_tier); await enterStream(status.host); } +// The broker boots an untested or opted-in broken core rather than refuse +// it, so this is where the player learns it may misbehave. +function warnOfCore(core?: string | null, tier?: string | null): void { + if (tier === "untested") snackbar.warning(t("play.core-untested", { core })); + else if (tier === "blocked") + snackbar.warning(t("play.core-blocked", { core })); +} + function dismissEndedDialog(): void { endedDialogOpen.value = false; backToRom(); @@ -718,8 +727,9 @@ useSocketEvent("streaming:launch-ready", async (payload) => { } if (payload.resume === false) snackbar.warning(t("play.resume-failed")); // A status poll can land between the launch stamp and this push and enter - // first; entering again would force fullscreen back on. + // first, core warning included; entering again would force fullscreen back on. if (playerState.value === "playing") return; + warnOfCore(payload.core, payload.core_tier); await enterStream(payload.host); });