From cdf2aba0dab6ba1a57ec19127bc2ba2a239aea67 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 09:49:01 -0500 Subject: [PATCH 01/12] feat(streaming): per-platform RetroArch core in the streaming config --- backend/config/config_manager.py | 11 ++ backend/handler/streaming/config.py | 95 +++++++++++++-- backend/tests/endpoints/test_streaming.py | 134 ++++++++++++++++++++++ examples/config.example.yml | 15 ++- 4 files changed, 244 insertions(+), 11 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index df55f8997..8c8130fc5 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -423,6 +423,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): @@ -448,6 +453,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/handler/streaming/config.py b/backend/handler/streaming/config.py index 6b4a832c3..161ce23ff 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,15 @@ 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". Only +# the shape is checked here: the broker owns the list and refuses an unknown +# core at activate with the options. +_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] = { @@ -135,13 +143,19 @@ 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.""" + "RA PPSSPP". A configured RetroArch core names itself, since the default's + display name would be wrong. 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}" + 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 +191,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 +229,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 +348,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 +412,7 @@ def _resolve_one( capabilities = {**capabilities, "supports_disc_swap": False} label = entry.get("label") + core = entry.get("core") or None return ResolvedContainer( key=broker_host or "", host=raw_host, @@ -381,7 +420,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 +428,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: this runs cores known to be broken, and + # a quoted "false" is truthy to bool(). + experimental_cores=entry.get("experimental_cores") is True, ) @@ -406,6 +449,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 +471,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 +498,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 +536,28 @@ 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 { + label = overrides.get("label") or emulator_display_label(emulator, platform, core) + row = { **base, **overrides, "platform": platform, "emulator": emulator, "label": label, } + if core is not None: + row["core"] = core + return row def resolve_entry(entry: dict[str, Any]) -> ResolvedContainer | None: diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index da139bd31..6913e3a33 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -430,6 +430,140 @@ 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): + """Review Focus 5: 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(): + """Review Focus 4: bool("false") is True, 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_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(): + """Review Focus 2: 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_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.""" diff --git a/examples/config.example.yml b/examples/config.example.yml index 45cbe266b..0399153b4 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,15 @@ # 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 the broker lists as known broken run anyway. Also +# # allowed on the container, as a default for every platform. +# # experimental_cores: true From a4d594404ab60b97bdc640bf0ad098a8fb781184 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 09:49:03 -0500 Subject: [PATCH 02/12] feat(streaming): send the RetroArch core on activate and end sessions a broker booted on another --- backend/handler/streaming/webstation.py | 26 +++++++ backend/tests/endpoints/test_streaming.py | 84 +++++++++++++++++++++++ 2 files changed, 110 insertions(+) diff --git a/backend/handler/streaming/webstation.py b/backend/handler/streaming/webstation.py index 76fcb0c43..52a000328 100644 --- a/backend/handler/streaming/webstation.py +++ b/backend/handler/streaming/webstation.py @@ -29,6 +29,8 @@ from dataclasses import dataclass from typing import Any, Literal from urllib.parse import quote +from fastapi import HTTPException + from config import STREAMING_LAUNCH_TIMEOUT, STREAMING_SAVE_TIMEOUT from handler.streaming import broker from handler.streaming.config import ResolvedContainer @@ -164,6 +166,12 @@ def activate( } if rom is not None: body["rom"] = rom + if container.core: + # 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": container.core} + if 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 +206,24 @@ def activate( resp = resp if isinstance(resp, dict) else {} log.info("broker activated session, %s", resp) + if container.core and resp.get("core") != container.core: + # A broker older than core support drops the field and boots its + # default core. Saving on the way out would file that core's files + # under this platform's archive, so the session ends without a dump. + log.warning( + "broker booted core %s, not the configured %s, ending the session", + resp.get("core"), + container.core, + ) + exit_session(container, 0, save=False) + raise HTTPException( + status_code=502, + detail=( + "This broker doesn't support `core:`. Upgrade the container, " + f"or remove `core: {container.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 6913e3a33..7c4138cb2 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -9396,6 +9396,90 @@ 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_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_without_saving( + client, access_token, rom: Rom +): + """Review Focus 3: 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_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) != {} + + # ── multiplayer flag ───────────────────────────────────────────────────────── From 007fb90e5370eb3aaa3d1ce832486bba33d2c6c1 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 09:49:08 -0500 Subject: [PATCH 03/12] feat(streaming): warn the player when the RetroArch core is untested or known broken --- backend/endpoints/responses/streaming.py | 5 +++ backend/handler/streaming/launch.py | 9 +++++ backend/tests/endpoints/test_streaming.py | 15 ++++++++ .../models/LaunchReadyPayload.ts | 2 ++ frontend/src/locales/bg_BG/play.json | 2 ++ frontend/src/locales/cs_CZ/play.json | 2 ++ frontend/src/locales/de_DE/play.json | 2 ++ frontend/src/locales/en_GB/play.json | 2 ++ frontend/src/locales/en_US/play.json | 2 ++ frontend/src/locales/es_ES/play.json | 2 ++ frontend/src/locales/fr_FR/play.json | 2 ++ frontend/src/locales/hu_HU/play.json | 2 ++ frontend/src/locales/it_IT/play.json | 2 ++ frontend/src/locales/ja_JP/play.json | 2 ++ frontend/src/locales/ko_KR/play.json | 2 ++ frontend/src/locales/pl_PL/play.json | 2 ++ frontend/src/locales/pt_BR/play.json | 2 ++ frontend/src/locales/ro_RO/play.json | 2 ++ frontend/src/locales/ru_RU/play.json | 2 ++ frontend/src/locales/tr_TR/play.json | 2 ++ frontend/src/locales/zh_CN/play.json | 2 ++ frontend/src/locales/zh_TW/play.json | 2 ++ frontend/src/v2/views/Player/Stream.test.ts | 34 ++++++++++++++++++- frontend/src/v2/views/Player/Stream.vue | 6 ++++ 24 files changed, 106 insertions(+), 1 deletion(-) diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index 89e8b9334..ef0cad580 100644 --- a/backend/endpoints/responses/streaming.py +++ b/backend/endpoints/responses/streaming.py @@ -97,6 +97,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/handler/streaming/launch.py b/backend/handler/streaming/launch.py index d23de1cc5..6aefd91ea 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -135,6 +135,13 @@ async def run_launch( log.info("session claimed, platform=%s rom=%s", platform, rom_name) host = container.protocol.stream_url(container.host, launch_result) + # 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) await lifecycle.publish_session_activity(session_key, session) @@ -161,6 +168,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(), ) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 7c4138cb2..e471f1e7d 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -9480,6 +9480,21 @@ def test_a_broker_that_echoes_the_core_launches(client, access_token, rom: Rom): 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) + + # ── multiplayer flag ───────────────────────────────────────────────────────── 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/locales/bg_BG/play.json b/frontend/src/locales/bg_BG/play.json index 9b0c68862..d0daefc11 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} 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": "Не може да се зареди с избраното ядро", + "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": "Нова карта памет", "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..7157ded43 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} 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": "Vybrané jádro to nedokáže načíst", + "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": "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..de6b66de4 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} 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": "Vom gewählten Core nicht ladbar", + "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": "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..e1ae1e763 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} 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": "No se puede cargar con el core seleccionado", + "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": "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..664f98615 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} 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": "Non chargeable par le cœur sélectionné", + "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": "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..003f83bb9 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": "{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": "A kiválasztott mag nem tudja betölteni", + "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": "Ú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..334183e26 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} 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": "Non caricabile dal core selezionato", + "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": "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..62ee09519 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} 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": "選択中のコアでは読み込めません", + "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": "新しいメモリーカード", "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..78100f99b 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} 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": "선택한 코어에서 불러올 수 없음", + "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": "새 메모리 카드", "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..bac6f6d3e 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} 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": "Nie do wczytania przez wybrany rdzeń", + "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": "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..851f307a7 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} 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": "Não carregável pelo core selecionado", + "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": "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..c594155e5 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} 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": "Nu poate fi încărcat de nucleul selectat", + "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": "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..1bcb1a6ae 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} 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": "Выбранное ядро не может загрузить", + "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": "Новая карта памяти", "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..c925fbf86 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} 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": "Seçili çekirdek tarafından yüklenemez", + "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": "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..a8b71c038 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} 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": "所选核心无法加载", + "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": "新建记忆卡", "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..401825308 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} 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": "所選核心無法載入", + "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": "新增記憶卡", "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..1e351ab37 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -28,6 +28,7 @@ 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() }, })); vi.mock("vue-i18n", () => ({ @@ -140,7 +141,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 +877,37 @@ 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(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"); + }); + + 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. diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index cdac59886..5b49edf02 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -717,6 +717,12 @@ useSocketEvent("streaming:launch-ready", async (payload) => { return; } if (payload.resume === false) snackbar.warning(t("play.resume-failed")); + // The broker boots an untested or opted-in broken core rather than refuse + // it, so this is where the player learns it may misbehave. + if (payload.core_tier === "untested") + snackbar.warning(t("play.core-untested", { core: payload.core })); + else if (payload.core_tier === "blocked") + snackbar.warning(t("play.core-blocked", { core: payload.core })); // A status poll can land between the launch stamp and this push and enter // first; entering again would force fullscreen back on. if (playerState.value === "playing") return; From 9f00d757a88ceb4f1e5d487f3c1fbb454841b5cb Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 09:49:13 -0500 Subject: [PATCH 04/12] fix(streaming): don't hydrate default-core states into another RetroArch core --- backend/handler/streaming/launch.py | 6 ++- backend/handler/streaming/states.py | 14 ++++++ backend/tests/endpoints/test_streaming.py | 52 +++++++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) diff --git a/backend/handler/streaming/launch.py b/backend/handler/streaming/launch.py index 6aefd91ea..db4e31348 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -177,7 +177,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/states.py b/backend/handler/streaming/states.py index 4c4cf6676..f9ac154a1 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 @@ -494,9 +495,22 @@ async def hydrate_states_to_broker( nothing to add here: any push would overwrite it before the broker's deferred load fires. A container that resumes from its save archive takes no state file at all, and the archive already carries the newest exit state. + + A container on a configured core other than the broker's default gets + nothing: stored states don't record which core wrote them, so each one is + presumed to be the default's, and pushing it lands where the other core's + quick-load reads it. `core_tier` is what the activate reply said; None + means it said nothing, which is treated as not the default. """ if resume_pushed or container.resumes_from_archive: return 0 + 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/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index e471f1e7d..fb616fa5a 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -4771,6 +4771,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") From 66e268cce903d13febb89a4738810c7c2607f75b Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 09:49:17 -0500 Subject: [PATCH 05/12] feat(streaming): ask import-spec about the configured RetroArch core --- backend/handler/streaming/webstation.py | 24 +++++++++++--- backend/tests/endpoints/test_streaming.py | 40 +++++++++++++++++++++++ 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/backend/handler/streaming/webstation.py b/backend/handler/streaming/webstation.py index 52a000328..1b9c4f9b2 100644 --- a/backend/handler/streaming/webstation.py +++ b/backend/handler/streaming/webstation.py @@ -69,7 +69,9 @@ class ImportSpec: # 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. _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: @@ -104,13 +106,25 @@ 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: a refusal is cached for the worker's life, + # and a config edit that changes the core must be asked about afresh. + 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='')}" - ) + query = f"emulator={quote(emulator, safe='')}&platform={quote(platform, safe='')}" + if container.core: + # Discovery has to answer for the core activate will boot. + query += f"&core={quote(container.core, safe='')}" + if container.experimental_cores: + query += "&experimental_cores=1" + path = container.protocol.session_route(f"/import-spec?{query}") try: resp = broker.request(container, path, method="GET", timeout=ACK_TIMEOUT) except urllib.error.HTTPError as exc: diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index fb616fa5a..fea4324b9 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -8561,6 +8561,46 @@ 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") + return request.call_args.args[1] + + +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(): + """Review Focus 1: 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_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.""" From cd813caeba417c0efd5afc217b1b7f4ae0821d8c Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 09:49:31 -0500 Subject: [PATCH 06/12] fix(streaming): tighten core override edge cases from review --- backend/handler/streaming/config.py | 23 +++++++- backend/handler/streaming/launch.py | 7 ++- backend/handler/streaming/webstation.py | 16 ++++-- backend/tests/endpoints/test_streaming.py | 66 ++++++++++++++++++++++- 4 files changed, 103 insertions(+), 9 deletions(-) diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 161ce23ff..9ac46e777 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -413,6 +413,24 @@ def _resolve_one( 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; the label would name one + # the legacy container never boots. + 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 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, @@ -430,8 +448,9 @@ def _resolve_one( state_transfer=state_transfer_limits(emulator), core=core, # Only a real boolean opts in: this runs cores known to be broken, and - # a quoted "false" is truthy to bool(). - experimental_cores=entry.get("experimental_cores") is True, + # a quoted "false" is truthy to bool(). Without a core it is never + # sent, so it must not tell pool members apart either. + experimental_cores=opt_in is True and core is not None, ) diff --git a/backend/handler/streaming/launch.py b/backend/handler/streaming/launch.py index db4e31348..168386e62 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( diff --git a/backend/handler/streaming/webstation.py b/backend/handler/streaming/webstation.py index 1b9c4f9b2..56b187430 100644 --- a/backend/handler/streaming/webstation.py +++ b/backend/handler/streaming/webstation.py @@ -67,7 +67,8 @@ class ImportSpec: # 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. +# 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, str | None, bool], tuple[float, ImportSpec | None] @@ -106,8 +107,8 @@ def import_spec( """What this broker accepts as a declared import, or None when nothing or unknown.""" if not container.is_webstation: return None - # The core is part of the key: a refusal is cached for the worker's life, - # and a config edit that changes the core must be asked about afresh. + # 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, @@ -131,7 +132,11 @@ def import_spec( 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 @@ -223,7 +228,8 @@ def activate( if container.core and resp.get("core") != container.core: # A broker older than core support drops the field and boots its # default core. Saving on the way out would file that core's files - # under this platform's archive, so the session ends without a dump. + # under this platform's archive, so the exit asks for no dump. It is + # best-effort and an old broker may not honour save=0. log.warning( "broker booted core %s, not the configured %s, ending the session", resp.get("core"), diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index fea4324b9..e89283231 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -540,6 +540,34 @@ def test_a_quoted_false_does_not_opt_in(): 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_the_platform_opt_in_wins_over_the_container(): inherited = _snes("retroarch:bsnes", experimental_cores=True) overridden = _snes( @@ -559,6 +587,13 @@ def test_containers_on_different_cores_are_not_one_pool(): 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" @@ -8601,6 +8636,20 @@ def test_import_spec_asks_again_when_the_core_changes(): 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.""" @@ -9547,7 +9596,7 @@ def test_no_core_leaves_the_activate_body_unchanged(client, access_token, rom: R exit_session.assert_not_called() -def test_an_older_broker_that_drops_the_core_is_exited_without_saving( +def test_an_older_broker_that_drops_the_core_is_exited_asking_for_no_save( client, access_token, rom: Rom ): """Review Focus 3: pydantic drops the unknown field and the broker boots @@ -9564,6 +9613,21 @@ def test_an_older_broker_that_drops_the_core_is_exited_without_saving( assert _launch_ready(sent) == {} +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 From 2d25618ee24fa4e3cb0360d6aa8a71fafb704bfb Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 14:29:47 -0500 Subject: [PATCH 07/12] fix(streaming): code-review pass on the RetroArch core override --- backend/handler/streaming/config.py | 20 +++---- backend/handler/streaming/launch.py | 4 ++ backend/handler/streaming/states.py | 7 +-- backend/handler/streaming/webstation.py | 18 +++--- backend/tests/endpoints/test_streaming.py | 67 +++++++++++++++++++++-- 5 files changed, 87 insertions(+), 29 deletions(-) diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 9ac46e777..966814387 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -75,9 +75,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", @@ -422,9 +421,11 @@ def _resolve_one( platform, core, ) + if label == emulator_display_label(emulator, platform, core): + label = None core = None opt_in = entry.get("experimental_cores") - if opt_in is not None and not isinstance(opt_in, bool): + 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", @@ -447,9 +448,8 @@ def _resolve_one( capabilities=capabilities, state_transfer=state_transfer_limits(emulator), core=core, - # Only a real boolean opts in: this runs cores known to be broken, and - # a quoted "false" is truthy to bool(). Without a core it is never - # sent, so it must not tell pool members apart either. + # 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, ) @@ -705,9 +705,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 168386e62..eaf36885f 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -147,6 +147,10 @@ async def run_launch( if container.core and isinstance(launch_result, dict) else None ) + if not isinstance(core_tier, str): + # The payload model takes a str only; a malformed tier must not + # strand an already running session without its launch-ready. + core_tier = None await stamp_launched(session_key, session, host=host) await lifecycle.publish_session_activity(session_key, session) diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index f9ac154a1..33a1e4039 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -496,11 +496,8 @@ async def hydrate_states_to_broker( deferred load fires. A container that resumes from its save archive takes no state file at all, and the archive already carries the newest exit state. - A container on a configured core other than the broker's default gets - nothing: stored states don't record which core wrote them, so each one is - presumed to be the default's, and pushing it lands where the other core's - quick-load reads it. `core_tier` is what the activate reply said; None - means it said nothing, which is treated as not the default. + A configured core gets nothing unless the activate reply's `core_tier` + says it is the default, since stored states are presumed to be the default's. """ if resume_pushed or container.resumes_from_archive: return 0 diff --git a/backend/handler/streaming/webstation.py b/backend/handler/streaming/webstation.py index 56b187430..6225a3cec 100644 --- a/backend/handler/streaming/webstation.py +++ b/backend/handler/streaming/webstation.py @@ -183,12 +183,14 @@ def activate( "emulator": emulator, "multiplayer": multiplayer, } + # A romless launch (the desktop) boots no core, whatever the platform sets. + core = container.core if rom is not None else None if rom is not None: body["rom"] = rom - if container.core: + if core: # 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": container.core} + body["rom"] = {**rom, "core": core} if container.experimental_cores: body["rom"]["experimental_cores"] = True if gui_language: @@ -225,22 +227,20 @@ def activate( resp = resp if isinstance(resp, dict) else {} log.info("broker activated session, %s", resp) - if container.core and resp.get("core") != container.core: - # A broker older than core support drops the field and boots its - # default core. Saving on the way out would file that core's files - # under this platform's archive, so the exit asks for no dump. It is - # best-effort and an old broker may not honour save=0. + 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"), - container.core, + core, ) exit_session(container, 0, save=False) raise HTTPException( status_code=502, detail=( "This broker doesn't support `core:`. Upgrade the container, " - f"or remove `core: {container.core}` from the " + f"or remove `core: {core}` from the " f"{container.platform} platform in config.yml." ), ) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index e89283231..0ad1f2583 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -524,7 +524,7 @@ def test_a_bad_core_on_a_flat_entry_skips_it(caplog): def test_a_container_level_core_is_ignored_beside_platforms(caplog): - """Review Focus 5: one core serves one platform, so inheriting it would + """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 @@ -532,7 +532,7 @@ def test_a_container_level_core_is_ignored_beside_platforms(caplog): def test_a_quoted_false_does_not_opt_in(): - """Review Focus 4: bool("false") is True, and this opt-in runs cores + """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"} @@ -568,6 +568,28 @@ def test_a_core_on_a_legacy_container_is_dropped_with_a_warning(caplog): 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( @@ -579,7 +601,7 @@ def test_the_platform_opt_in_wins_over_the_container(): def test_containers_on_different_cores_are_not_one_pool(): - """Review Focus 2: a claim landing on either would boot a different core + """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")) @@ -8623,7 +8645,7 @@ def test_import_spec_query_is_unchanged_without_a_core(): def test_import_spec_asks_again_when_the_core_changes(): - """Review Focus 1: a 404/422 is cached for the worker's life, so a key + """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) @@ -9599,7 +9621,7 @@ def test_no_core_leaves_the_activate_body_unchanged(client, access_token, rom: R def test_an_older_broker_that_drops_the_core_is_exited_asking_for_no_save( client, access_token, rom: Rom ): - """Review Focus 3: pydantic drops the unknown field and the broker boots + """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"} @@ -9651,6 +9673,41 @@ def test_launch_ready_has_no_tier_without_a_core(client, access_token, rom: Rom) 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 ───────────────────────────────────────────────────────── From 8336f127b6b1874051b889133bb9cabf91917b8d Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 14:39:13 -0500 Subject: [PATCH 08/12] refactor(streaming): simplify pass on the RetroArch core override --- backend/handler/streaming/config.py | 15 ++++------- backend/handler/streaming/launch.py | 4 --- backend/handler/streaming/states.py | 4 +-- backend/handler/streaming/webstation.py | 35 +++++++++++++------------ 4 files changed, 24 insertions(+), 34 deletions(-) diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 966814387..47a69a9a6 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -49,9 +49,8 @@ PLATFORM_OVERRIDE_KEYS = ( "experimental_cores", ) -# A libretro core as the broker's catalog names it, e.g. "parallel_n64". Only -# the shape is checked here: the broker owns the list and refuses an unknown -# core at activate with the options. +# 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` @@ -146,11 +145,10 @@ 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". A configured RetroArch core names itself, since the default's - display name would be wrong. Unknown emulators fall back to their - configured name.""" + "RA PPSSPP". Unknown emulators fall back to their configured name.""" key = emulator.strip().lower() if key == "retroarch": + # 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()) @@ -421,8 +419,6 @@ def _resolve_one( platform, core, ) - if label == emulator_display_label(emulator, platform, core): - label = None 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): @@ -566,13 +562,12 @@ def _platform_overrides( # 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, core) row = { **base, **overrides, "platform": platform, "emulator": emulator, - "label": label, + "label": overrides.get("label"), } if core is not None: row["core"] = core diff --git a/backend/handler/streaming/launch.py b/backend/handler/streaming/launch.py index eaf36885f..168386e62 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -147,10 +147,6 @@ async def run_launch( if container.core and isinstance(launch_result, dict) else None ) - if not isinstance(core_tier, str): - # The payload model takes a str only; a malformed tier must not - # strand an already running session without its launch-ready. - core_tier = None await stamp_launched(session_key, session, host=host) await lifecycle.publish_session_activity(session_key, session) diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index 33a1e4039..b7be9064b 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -495,12 +495,10 @@ async def hydrate_states_to_broker( nothing to add here: any push would overwrite it before the broker's deferred load fires. A container that resumes from its save archive takes no state file at all, and the archive already carries the newest exit state. - - A configured core gets nothing unless the activate reply's `core_tier` - says it is the default, since stored states are presumed to be the default's. """ 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", diff --git a/backend/handler/streaming/webstation.py b/backend/handler/streaming/webstation.py index 6225a3cec..8efd40a0e 100644 --- a/backend/handler/streaming/webstation.py +++ b/backend/handler/streaming/webstation.py @@ -27,7 +27,7 @@ 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 @@ -66,9 +66,8 @@ 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 or a refused core 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, str | None, bool], tuple[float, ImportSpec | None] @@ -119,13 +118,13 @@ def import_spec( cached = _import_spec_cache.get(cache_key) if cached is not None and cached[0] > time.monotonic(): return cached[1] - query = f"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. - query += f"&core={quote(container.core, safe='')}" + params["core"] = container.core if container.experimental_cores: - query += "&experimental_cores=1" - path = container.protocol.session_route(f"/import-spec?{query}") + 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: @@ -183,16 +182,16 @@ def activate( "emulator": emulator, "multiplayer": multiplayer, } - # A romless launch (the desktop) boots no core, whatever the platform sets. - core = container.core if rom is not None else None + # 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 - if core: - # 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 container.experimental_cores: - body["rom"]["experimental_cores"] = True + # 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. @@ -227,6 +226,8 @@ 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. From 3fbb746ded0f29d3c18f02ebb1f928d9e3551db7 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 14:44:09 -0500 Subject: [PATCH 09/12] test(streaming): review-polish pass, assert the core reaches the tier warning --- backend/handler/streaming/config.py | 3 +-- frontend/src/v2/views/Player/Stream.test.ts | 9 ++++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 47a69a9a6..68aa079e1 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -411,8 +411,7 @@ def _resolve_one( 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; the label would name one - # the legacy container never boots. + # 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", diff --git a/frontend/src/v2/views/Player/Stream.test.ts b/frontend/src/v2/views/Player/Stream.test.ts index 1e351ab37..023a7494d 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -29,10 +29,11 @@ const mocks = vi.hoisted(() => ({ 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", () => ({ @@ -885,6 +886,9 @@ describe("Stream launch recovery", () => { 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"); }); @@ -896,6 +900,9 @@ describe("Stream launch recovery", () => { 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 () => { From 21c5b65d1798372f3b1ccb32eb7b8e815aa1555e Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 27 Sep 2026 16:22:20 -0500 Subject: [PATCH 10/12] fix(streaming): address Greptile review of the RetroArch core override - Retry the exit once when a broker boots the wrong core and the first exit fails: the broker refuses every activate while that game runs, and the released claim leaves nothing behind to stop it. - Stamp the launch's core tier on the session and report it through the status poll, so a tab that missed launch-ready still warns about an untested or broken core, once. - Translate the core-untested and core-blocked warnings in every locale. --- backend/endpoints/responses/streaming.py | 3 ++ backend/endpoints/streaming.py | 2 + backend/handler/streaming/launch.py | 4 +- backend/handler/streaming/session_store.py | 9 +++- backend/handler/streaming/webstation.py | 7 ++- backend/tests/endpoints/test_streaming.py | 46 +++++++++++++++++++ .../models/SessionStatusSchema.ts | 2 + frontend/src/locales/bg_BG/play.json | 4 +- frontend/src/locales/cs_CZ/play.json | 4 +- frontend/src/locales/de_DE/play.json | 4 +- frontend/src/locales/es_ES/play.json | 4 +- frontend/src/locales/fr_FR/play.json | 4 +- frontend/src/locales/hu_HU/play.json | 4 +- frontend/src/locales/it_IT/play.json | 4 +- frontend/src/locales/ja_JP/play.json | 4 +- frontend/src/locales/ko_KR/play.json | 4 +- frontend/src/locales/pl_PL/play.json | 4 +- frontend/src/locales/pt_BR/play.json | 4 +- frontend/src/locales/ro_RO/play.json | 4 +- frontend/src/locales/ru_RU/play.json | 4 +- frontend/src/locales/tr_TR/play.json | 4 +- frontend/src/locales/zh_CN/play.json | 4 +- frontend/src/locales/zh_TW/play.json | 4 +- frontend/src/v2/views/Player/Stream.test.ts | 41 +++++++++++++++++ frontend/src/v2/views/Player/Stream.vue | 18 +++++--- 25 files changed, 154 insertions(+), 42 deletions(-) diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index ef0cad580..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 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/launch.py b/backend/handler/streaming/launch.py index 168386e62..a27ba4322 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -147,7 +147,9 @@ async def run_launch( if container.core and isinstance(launch_result, dict) else None ) - await stamp_launched(session_key, session, host=host) + 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 diff --git a/backend/handler/streaming/session_store.py b/backend/handler/streaming/session_store.py index 530df66ac..6845fb42a 100644 --- a/backend/handler/streaming/session_store.py +++ b/backend/handler/streaming/session_store.py @@ -433,7 +433,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. @@ -449,6 +453,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( @@ -456,6 +462,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/webstation.py b/backend/handler/streaming/webstation.py index 8efd40a0e..e4964e3fe 100644 --- a/backend/handler/streaming/webstation.py +++ b/backend/handler/streaming/webstation.py @@ -236,7 +236,12 @@ def activate( resp.get("core"), core, ) - exit_session(container, 0, save=False) + # 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=( diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 0ad1f2583..7e482ef07 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -3416,6 +3416,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, } @@ -9598,6 +9600,29 @@ def test_the_activate_body_carries_a_configured_core(client, access_token, rom: 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) @@ -9635,6 +9660,27 @@ def test_an_older_broker_that_drops_the_core_is_exited_asking_for_no_save( 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 ): 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 d0daefc11..ed083ee85 100644 --- a/frontend/src/locales/bg_BG/play.json +++ b/frontend/src/locales/bg_BG/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} от {total} съвместими", "context-menu": "Контекстно меню", "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-blocked": "{core} е известно като неработещо на тази платформа и работи само защото експерименталните ядра са включени. Записите и състоянията може да не работят.", "core-not-loadable": "Не може да се зареди с избраното ядро", - "core-untested": "{core} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 7157ded43..1a461ef0c 100644 --- a/frontend/src/locales/cs_CZ/play.json +++ b/frontend/src/locales/cs_CZ/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} z {total} kompatibilních", "context-menu": "Kontextová nabídka", "control-settings": "Nastavení ovládání", - "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-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} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 de6b66de4..a1965b96c 100644 --- a/frontend/src/locales/de_DE/play.json +++ b/frontend/src/locales/de_DE/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} von {total} kompatibel", "context-menu": "Kontextmenü", "control-settings": "Steuerungseinstellungen", - "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-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} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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/es_ES/play.json b/frontend/src/locales/es_ES/play.json index e1ae1e763..27fdaa293 100644 --- a/frontend/src/locales/es_ES/play.json +++ b/frontend/src/locales/es_ES/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} de {total} compatibles", "context-menu": "Menú contextual", "control-settings": "Ajustes de control", - "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-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} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 664f98615..0aff39eab 100644 --- a/frontend/src/locales/fr_FR/play.json +++ b/frontend/src/locales/fr_FR/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} sur {total} compatibles", "context-menu": "Menu contextuel", "control-settings": "Paramètres des commandes", - "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-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} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 003f83bb9..c60b170c6 100644 --- a/frontend/src/locales/hu_HU/play.json +++ b/frontend/src/locales/hu_HU/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} / {total} kompatibilis", "context-menu": "Helyi menü", "control-settings": "Irányítás beállításai", - "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-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": "{core} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 334183e26..32bd08081 100644 --- a/frontend/src/locales/it_IT/play.json +++ b/frontend/src/locales/it_IT/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} di {total} compatibili", "context-menu": "Menu contestuale", "control-settings": "Impostazioni controlli", - "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-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} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 62ee09519..adfbe4195 100644 --- a/frontend/src/locales/ja_JP/play.json +++ b/frontend/src/locales/ja_JP/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{total} 件中 {compatible} 件が互換", "context-menu": "コンテキストメニュー", "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-blocked": "{core} はこのプラットフォームで不具合が知られており、実験的コアが有効なため起動しています。セーブとステートが動作しない可能性があります。", "core-not-loadable": "選択中のコアでは読み込めません", - "core-untested": "{core} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 78100f99b..2a695b03f 100644 --- a/frontend/src/locales/ko_KR/play.json +++ b/frontend/src/locales/ko_KR/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{total}개 중 {compatible}개 호환", "context-menu": "컨텍스트 메뉴", "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-blocked": "{core}은(는) 이 플랫폼에서 문제가 있는 것으로 알려져 있으며, 실험적 코어가 켜져 있어서 실행됩니다. 세이브와 스테이트가 작동하지 않을 수 있습니다.", "core-not-loadable": "선택한 코어에서 불러올 수 없음", - "core-untested": "{core} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 bac6f6d3e..2309c3add 100644 --- a/frontend/src/locales/pl_PL/play.json +++ b/frontend/src/locales/pl_PL/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} z {total} zgodnych", "context-menu": "Menu kontekstowe", "control-settings": "Ustawienia sterowania", - "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-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} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 851f307a7..f4e1aae02 100644 --- a/frontend/src/locales/pt_BR/play.json +++ b/frontend/src/locales/pt_BR/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} de {total} compatíveis", "context-menu": "Menu de contexto", "control-settings": "Configurações de controle", - "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-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} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 c594155e5..74565ede2 100644 --- a/frontend/src/locales/ro_RO/play.json +++ b/frontend/src/locales/ro_RO/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} din {total} compatibile", "context-menu": "Meniu contextual", "control-settings": "Setări control", - "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-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} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 1bcb1a6ae..abdf4ecdf 100644 --- a/frontend/src/locales/ru_RU/play.json +++ b/frontend/src/locales/ru_RU/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{compatible} из {total} совместимы", "context-menu": "Контекстное меню", "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-blocked": "{core} известно как неработающее на этой платформе и запускается только потому, что включены экспериментальные ядра. Сохранения и состояния могут не работать.", "core-not-loadable": "Выбранное ядро не может загрузить", - "core-untested": "{core} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 c925fbf86..3576aea19 100644 --- a/frontend/src/locales/tr_TR/play.json +++ b/frontend/src/locales/tr_TR/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{total} içinden {compatible} uyumlu", "context-menu": "Bağlam menüsü", "control-settings": "Kontrol ayarları", - "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-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} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 a8b71c038..78f298b2c 100644 --- a/frontend/src/locales/zh_CN/play.json +++ b/frontend/src/locales/zh_CN/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{total} 个中 {compatible} 个兼容", "context-menu": "上下文菜单", "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-blocked": "{core} 在此平台上已知存在问题,仅因启用了实验性核心才会运行。存档和即时存档可能无法使用。", "core-not-loadable": "所选核心无法加载", - "core-untested": "{core} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 401825308..52c940a86 100644 --- a/frontend/src/locales/zh_TW/play.json +++ b/frontend/src/locales/zh_TW/play.json @@ -20,9 +20,9 @@ "compatible-of-total": "{total} 個中 {compatible} 個相容", "context-menu": "內容選單", "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-blocked": "{core} 在此平台上已知有問題,僅因啟用了實驗性核心才會執行。存檔和即時存檔可能無法使用。", "core-not-loadable": "所選核心無法載入", - "core-untested": "{core} has not been tested on this platform yet. Saves and states may not work as expected. Please report how it runs.", + "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 023a7494d..834c3eb7b 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -940,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 5b49edf02..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(); @@ -717,15 +726,10 @@ useSocketEvent("streaming:launch-ready", async (payload) => { return; } if (payload.resume === false) snackbar.warning(t("play.resume-failed")); - // The broker boots an untested or opted-in broken core rather than refuse - // it, so this is where the player learns it may misbehave. - if (payload.core_tier === "untested") - snackbar.warning(t("play.core-untested", { core: payload.core })); - else if (payload.core_tier === "blocked") - snackbar.warning(t("play.core-blocked", { core: payload.core })); // 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); }); From d2b49eeea64a74e2055a6ce0118ee5ad4374c84d Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi <3247106+gantoine@users.noreply.github.com> Date: Sun, 27 Sep 2026 20:13:04 -0400 Subject: [PATCH 11/12] Update examples/config.example.yml --- examples/config.example.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/config.example.yml b/examples/config.example.yml index 0399153b4..200114249 100644 --- a/examples/config.example.yml +++ b/examples/config.example.yml @@ -251,6 +251,5 @@ # n64: # emulator: retroarch # core: parallel_n64 -# # Lets a core the broker lists as known broken run anyway. Also -# # allowed on the container, as a default for every platform. +# # Lets a core listed as broken by the broker run anyway. # # experimental_cores: true From c10ae9815bcc8f9119619f724d615d229b5e1992 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sun, 27 Sep 2026 20:21:56 -0400 Subject: [PATCH 12/12] fix(mypy): type the spec path helper in streaming tests Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/tests/endpoints/test_streaming.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index b55d5ff78..1ee0983d1 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -8629,7 +8629,8 @@ def _spec_path(container) -> str: "handler.streaming.broker.request", side_effect=_http_error(404) ) as request: webstation.import_spec(container, "retroarch", "snes") - return request.call_args.args[1] + path: str = request.call_args.args[1] + return path def test_import_spec_asks_about_the_configured_core():