From 9984f7dd278bbc169adac3388586a8d53f97cd7d Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 14:44:15 -0500 Subject: [PATCH 001/213] fix(streaming): scope session lookups to the platform and skip desktops A container can serve several platforms while holding one session, so a lookup that starts from the caller has to match the platform it was asked about. Otherwise a ps2 session shadows the same container's ngc row: the claim reads as a duplicate and 409s, status reports it active on a platform the caller holds nothing on, and an unnamed heartbeat or release lands on it. A desktop session is only reachable when the caller names its container, which is what the desktop view does, so a game tab no longer beats or releases an admin's desktop, and a desktop no longer blocks its admin's own game claim. Occupancy is still the reservation's job: the claim walk just fails that container's SET NX and moves on. --- backend/endpoints/streaming.py | 40 ++++++-- backend/handler/streaming/access.py | 34 ++++++- backend/handler/streaming/session_store.py | 14 +++ backend/tests/endpoints/test_streaming.py | 108 +++++++++++++++++++++ 4 files changed, 181 insertions(+), 15 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 968749cee..7cd575ad3 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -196,9 +196,12 @@ async def _session_status( platform: str, request: Request, candidates: list[ResolvedContainer] | None = None, + *, + include_desktop: bool = False, ) -> dict[str, Any]: - """Whether the caller holds a session among `candidates` (the platform's first - pool by default), and if not, why it ended. Read-only, so it is safe to poll.""" + """Whether the caller holds a session for this platform among `candidates` + (its first pool by default), and if not, why it ended. Read-only, so it is + safe to poll.""" if candidates is None: candidates = containers_for_platform(platform) if not candidates: @@ -206,7 +209,12 @@ async def _session_status( status_code=404, detail=f"No streaming container configured for platform '{platform}'", ) - found = await access.find_session_for_user(candidates, request.user.id) + found = await access.find_session_for_user( + candidates, + request.user.id, + platform=platform, + include_desktop=include_desktop, + ) if found is not None: container, _, session = found status: dict[str, Any] = {"status": "active", "platform": platform} @@ -320,9 +328,13 @@ async def _reserve_container( platform: str, ) -> ResolvedContainer: """Walk the platform's containers and claim the first one available.""" - # Status, heartbeat and release all resolve by platform and answer with the - # first match, so a second session for one user is one nothing can reach. - held = await access.find_session_for_user(candidates, request.user.id) + # Status, heartbeat and release resolve by platform and answer with the + # first match, so a second game session on one platform is one nothing can + # reach. A session of theirs elsewhere (another platform, or a desktop) is + # not in the way; that container simply fails the reservation below. + held = await access.find_session_for_user( + candidates, request.user.id, platform=platform + ) if held is not None: holder, _, mine = held if not session_is_stale(mine): @@ -957,16 +969,22 @@ async def heartbeat_session( """ user_id = request.user.id # A named claim answers for itself: another session the caller holds on the - # platform is not the one this client is beating. + # platform is not the one this client is beating. Naming the container is + # also the only way to reach a desktop, which a game tab must never beat. + named = container_key is not None candidates = ( [access.named_container(platform, container_key)] if container_key is not None else containers_for_platform(platform) ) - found = await access.find_session_for_user(candidates, user_id) + found = await access.find_session_for_user( + candidates, user_id, platform=platform, include_desktop=named + ) if found is None: return SessionStatusSchema( - **await _session_status(platform, request, candidates) + **await _session_status( + platform, request, candidates, include_desktop=named + ) ) _, session_key, _ = found @@ -985,7 +1003,9 @@ async def heartbeat_session( return SessionStatusSchema(status="active", platform=platform) if refreshed is None: return SessionStatusSchema( - **await _session_status(platform, request, candidates) + **await _session_status( + platform, request, candidates, include_desktop=named + ) ) await lifecycle.refresh_session_activity(session_key, refreshed) return SessionStatusSchema(status="active", platform=platform) diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index fefb2cbe4..7eb8ace43 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -12,7 +12,11 @@ from handler.streaming.config import ( containers_for_platform, entry_for_platform, ) -from handler.streaming.session_store import get_live_session +from handler.streaming.session_store import ( + get_live_session, + session_is_desktop, + session_platform_matches, +) from models.rom import Rom from models.user import Role @@ -89,19 +93,37 @@ def platform_is_visible(request: Request, platform_slug: str) -> bool: return get_permissions(request).can_see_platform(platform.id) +def _session_in_scope( + session: dict[str, Any], platform: str | None, include_desktop: bool +) -> bool: + """Whether a stored session is one the route asked about. A container serves + several platforms and holds one session, so the owner alone does not + identify it, and a desktop only answers to the caller that named it.""" + if not include_desktop and session_is_desktop(session): + return False + return platform is None or session_platform_matches(session, platform) + + async def find_session_for_user( - candidates: list[ResolvedContainer], user_id: int + candidates: list[ResolvedContainer], + user_id: int, + *, + platform: str | None = None, + include_desktop: bool = False, ) -> tuple[ResolvedContainer, str, dict[str, Any]] | None: """The candidate holding this user's session, as (container, key, session). With a pool the platform no longer identifies the container, the session - does. + does. `platform` scopes the match to sessions claimed for it, and a desktop + is only reachable when the caller named its container. """ for candidate in candidates: session_key = candidate.key session = await get_live_session(session_key) if session is None: continue + if not _session_in_scope(session, platform, include_desktop): + continue if session.get("user_id") == user_id: return candidate, session_key, session return None @@ -135,9 +157,9 @@ async def resolve_named_container( async def resolve_owned_session( - platform: str, request: Request + platform: str, request: Request, *, include_desktop: bool = False ) -> tuple[ResolvedContainer, str, dict[str, Any]]: - """Find the caller's session in the platform's first pool. + """Find the caller's session for this platform in its first pool. Returns (container, session_key, session). Raises 404 when the platform has no configured container or nothing is active, 403 when every active session @@ -156,6 +178,8 @@ async def resolve_owned_session( session = await get_live_session(session_key) if session is None: continue + if not _session_in_scope(session, platform, include_desktop): + continue if session.get("user_id") == request.user.id: return candidate, session_key, session others.append((candidate, session_key, session)) diff --git a/backend/handler/streaming/session_store.py b/backend/handler/streaming/session_store.py index 5a31506b9..e41fe1162 100644 --- a/backend/handler/streaming/session_store.py +++ b/backend/handler/streaming/session_store.py @@ -276,6 +276,20 @@ async def mutate_session( return session if outcome is _CasOutcome.WROTE else None +def session_platform_matches(session: dict[str, Any], platform: str) -> bool: + """Whether a session was claimed for this platform. A record written before + the field existed matches anything, so an upgrade cannot strand one.""" + stored = session.get("platform") + if not isinstance(stored, str) or not stored: + return True + return stored.lower() == platform.lower() + + +def session_is_desktop(session: dict[str, Any]) -> bool: + """Whether a session is an admin desktop rather than a game.""" + return bool(session.get("desktop")) + + def same_claim(session: dict[str, Any], claim: dict[str, Any]) -> bool: """Whether a session read back is still the one a route resolved. Identity is the holder plus the moment they took it, so a re-claim by the same user does diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index aea430cd1..8b2eddc88 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1255,6 +1255,38 @@ def test_a_pool_does_not_roll_its_own_holder_onto_a_second_container( assert free is None +def test_a_session_on_one_platform_does_not_block_a_claim_on_another( + client, access_token +): + """One container serves several platforms, so the caller's ps2 session sits + on a key the ngc walk visits too. It occupies that container, it does not + spend the player's one session.""" + ps2_rom = _rom_on("ps2") + ngc_rom = _rom_on("ngc") + second = _nested( + host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000" + ) + with _streaming(_nested(), second): + r1 = _claim_ok(client, access_token, ps2_rom.id) + r2 = _claim_ok(client, access_token, ngc_rom.id) + assert [r1.status_code, r2.status_code] == [202, 202] + assert r1.json()["container"] == _key_of(_nested()) + assert r2.json()["container"] == _key_of(second) + + +def test_status_does_not_report_a_session_on_another_platform(client, access_token): + """The ps2 claim shares its key with the container's ngc row, and a poll for + ngc must not read that as a session the caller holds there.""" + ps2_rom = _rom_on("ps2") + with _streaming(_nested()): + assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202 + r = client.get( + "/api/streaming/sessions/ngc/status", headers=_auth(access_token) + ) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + + @contextmanager def _claim_in_flight(platform: str, user_id: int) -> Iterator[None]: """Stand in for a claim from the same player that is inside the reserve and @@ -1913,6 +1945,81 @@ def test_desktop_and_a_game_block_each_other(client, access_token): assert _desktop(client, access_token, key)[0].status_code == 409 +def test_an_admins_desktop_does_not_block_their_game_claim(client, access_token): + """A desktop occupies its container, not the platform, so the claim rolls + onto the free pool member.""" + ps2_rom = _rom_on("ps2") + second = _webstation( + host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000" + ) + with _streaming(_webstation(), second): + assert ( + _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 + ) + r = _claim_webstation_ok(client, access_token, ps2_rom.id) + assert r.status_code == 202 + assert r.json()["container"] == _key_of(second) + + +def test_an_unnamed_heartbeat_skips_the_callers_desktop( + client, access_token, viewer_access_token +): + """An admin playing on one pool member while holding a desktop on another + beats their game session, not the desktop the walk reaches first.""" + ps2_rom = _rom_on("ps2") + second = _webstation( + host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000" + ) + with _streaming(_webstation(), second): + # The viewer takes the head of the pool, so the admin's game lands on + # the second member and the desktop gets the head once it is released. + assert ( + _claim_webstation_ok(client, viewer_access_token, ps2_rom.id).status_code + == 202 + ) + assert ( + _claim_webstation_ok(client, access_token, ps2_rom.id).json()["container"] + == _key_of(second) + ) + with ( + patch("handler.streaming.commands.stop", return_value=None), + patch("handler.streaming.background.spawn_sync_task"), + ): + client.delete( + "/api/streaming/sessions/ps2", headers=_auth(viewer_access_token) + ) + assert ( + _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 + ) + _age_session_on(_webstation(), 120) + _age_session_on(second, 120) + desktop_before = json.loads(_session_raw(_webstation()))["last_seen"] + game_before = json.loads(_session_raw(second))["last_seen"] + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", headers=_auth(access_token) + ) + desktop_after = json.loads(_session_raw(_webstation()))["last_seen"] + game_after = json.loads(_session_raw(second))["last_seen"] + assert r.json()["status"] == "active" + assert game_after > game_before + assert desktop_after == desktop_before + + +def test_an_unnamed_release_leaves_the_callers_desktop_alone(client, access_token): + """Desktop.vue names its container and a game tab never does, so an unnamed + release must not end the desktop the admin has open.""" + with _streaming(_webstation()): + key = _key_of(_webstation()) + assert _desktop(client, access_token, key)[0].status_code == 200 + with patch("handler.streaming.commands.stop", return_value=None): + r = client.delete( + "/api/streaming/sessions/ps2", headers=_auth(access_token) + ) + session = asyncio.run(session_store.get_session(key)) + assert r.json()["status"] == "not_found" + assert session is not None and session["desktop"] is True + + def test_desktop_is_admin_only(client, viewer_access_token): with _streaming(_webstation()): key = _key_of(_first_container("ps2")) @@ -1965,6 +2072,7 @@ def test_releasing_a_desktop_session_syncs_nothing_to_the_library(client, access ): response = client.delete( f"/api/streaming/sessions/{container.platform}", + params={"container": _key_of(container)}, headers=_auth(access_token), ) assert response.status_code == 200 From 09c8cf31f90c7ffa80016b77dafc6dd8296ada01 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 14:46:53 -0500 Subject: [PATCH 002/213] fix(streaming): tear a swept session down with its own container record The stale sweep ran the teardown against the claimant's candidate, which on a container serving several platforms is the wrong record: the stop, the card evacuation and the state pull all went out under the emulator the new claim wants rather than the one that was running. Resolve the record from the session being swept and keep the candidate for the reservation. --- backend/endpoints/streaming.py | 11 ++++++++- backend/tests/endpoints/test_streaming.py | 30 ++++++++++++++++++++--- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 7cd575ad3..9d07e5c17 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -392,8 +392,17 @@ async def _reserve_container( platform, existing.get("user_id"), ) + # A container serves several platforms, so the session being swept may + # be another one's: its state, saves and card belong to that emulator, + # not to the one this claim would run. + record = ( + container_for_session( + containers_by_key(), candidate.key, existing.get("platform") + ) + or candidate + ) if not await lifecycle.await_teardown_within_budget( - candidate, + record, candidate.key, existing, max(0.0, deadline - time.monotonic()), diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 8b2eddc88..ebfdfa44d 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1977,10 +1977,9 @@ def test_an_unnamed_heartbeat_skips_the_callers_desktop( _claim_webstation_ok(client, viewer_access_token, ps2_rom.id).status_code == 202 ) - assert ( - _claim_webstation_ok(client, access_token, ps2_rom.id).json()["container"] - == _key_of(second) - ) + assert _claim_webstation_ok(client, access_token, ps2_rom.id).json()[ + "container" + ] == _key_of(second) with ( patch("handler.streaming.commands.stop", return_value=None), patch("handler.streaming.background.spawn_sync_task"), @@ -2242,6 +2241,29 @@ def test_stale_session_taken_over_on_claim( stop_broker.assert_called_once() +def test_a_swept_session_is_torn_down_with_its_own_platforms_record( + client, access_token, viewer_access_token +): + """One container serves ps2 and ngc on different emulators, so an ngc claim + sweeping a stale ps2 session must tear it down as pcsx2: the state and the + card coming out of the container are that emulator's, not the claimant's.""" + ps2_rom = _rom_on("ps2") + ngc_rom = _rom_on("ngc") + with _streaming(_nested()): + _claim_ok(client, access_token, ps2_rom.id) + _age_session_on(_nested(), session_store._STREAMING_SESSION_STALE_SECONDS + 60) + with ( + patch("handler.streaming.commands.stop", return_value=3) as stop, + patch( + "handler.streaming.states.pull_state_to_library", new=AsyncMock() + ) as pull_state, + ): + r = _claim_ok(client, viewer_access_token, ngc_rom.id) + assert r.status_code == 202 + assert stop.call_args.args[0].emulator == "pcsx2" + assert pull_state.call_args.args[2].emulator == "pcsx2" + + def test_the_owner_of_a_stale_session_can_claim_it_again( client, access_token, rom: Rom ): From dd6b949b6a47fcd10c169bd60a2a9e57c8b2fa8e Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 14:50:32 -0500 Subject: [PATCH 003/213] fix(streaming): bind release and heartbeat to the caller's claim A claim is the holder plus the moment they took it, so a tab that missed its own takeover could still act on the claim that replaced it: its unload release ended the new session and its beat kept it alive. Both routes now take the claimed_at the claim answered with, and a mismatch reads as a session the caller no longer holds: the release is a no-op and the heartbeat reports ended, with the termination notice the displaced tab needs. Admin releases from the settings and activity panels end whatever is running and send no stamp. --- backend/endpoints/streaming.py | 40 +++++++++++-- backend/handler/streaming/access.py | 18 ++++-- backend/tests/endpoints/test_streaming.py | 69 +++++++++++++++++++++++ 3 files changed, 117 insertions(+), 10 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 9d07e5c17..2e30bae39 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -198,6 +198,7 @@ async def _session_status( candidates: list[ResolvedContainer] | None = None, *, include_desktop: bool = False, + claimed_at: str | None = None, ) -> dict[str, Any]: """Whether the caller holds a session for this platform among `candidates` (its first pool by default), and if not, why it ended. Read-only, so it is @@ -214,6 +215,7 @@ async def _session_status( request.user.id, platform=platform, include_desktop=include_desktop, + claimed_at=claimed_at, ) if found is not None: container, _, session = found @@ -962,6 +964,7 @@ async def heartbeat_session( request: Request, platform: str, container_key: str | None = Query(default=None, alias="container", max_length=300), + claimed_at: str | None = Query(default=None, max_length=64), ) -> SessionStatusSchema: """Refresh the session's liveness stamp and report whether it still exists. @@ -974,7 +977,9 @@ async def heartbeat_session( making rather than watching a dead stream. `container` names the claim to refresh, needed for a desktop on a container - outside the platform's first pool. + outside the platform's first pool. `claimed_at` is the stamp the claim + answered with: a tab that missed its own takeover reports ended rather than + keeping the claim that replaced it alive. """ user_id = request.user.id # A named claim answers for itself: another session the caller holds on the @@ -987,12 +992,20 @@ async def heartbeat_session( else containers_for_platform(platform) ) found = await access.find_session_for_user( - candidates, user_id, platform=platform, include_desktop=named + candidates, + user_id, + platform=platform, + include_desktop=named, + claimed_at=claimed_at, ) if found is None: return SessionStatusSchema( **await _session_status( - platform, request, candidates, include_desktop=named + platform, + request, + candidates, + include_desktop=named, + claimed_at=claimed_at, ) ) _, session_key, _ = found @@ -1003,7 +1016,9 @@ async def heartbeat_session( refreshed = await mutate_session( session_key, {"last_seen": datetime.now(timezone.utc).isoformat()}, - require=lambda s: not s.get("draining") and s.get("user_id") == user_id, + require=lambda s: not s.get("draining") + and s.get("user_id") == user_id + and (claimed_at is None or s.get("claimed_at") == claimed_at), ) except StreamingSessionContended: # A key too busy to write is a key that exists, so the session is live @@ -1013,7 +1028,11 @@ async def heartbeat_session( if refreshed is None: return SessionStatusSchema( **await _session_status( - platform, request, candidates, include_desktop=named + platform, + request, + candidates, + include_desktop=named, + claimed_at=claimed_at, ) ) await lifecycle.refresh_session_activity(session_key, refreshed) @@ -1232,6 +1251,7 @@ async def release_session( background_tasks: BackgroundTasks, reason: str | None = Query(default=None, max_length=200), container_key: str | None = Query(default=None, alias="container", max_length=300), + claimed_at: str | None = Query(default=None, max_length=64), save: bool = Query(default=True), ) -> ReleaseSessionResponse: """Release a session and tell the broker to stop the emulator. @@ -1244,6 +1264,9 @@ async def release_session( `save=false` is a player leaving deliberately without saving. It defaults on because the other way in here is a tab closing, where nobody chose anything and the last minutes of play would otherwise be gone. + + `claimed_at` is the stamp the claim answered with, which binds this release + to that claim. Admin panels end whatever is running and send none. """ if container_key is not None: container, session_key, session = await access.resolve_named_container( @@ -1264,6 +1287,13 @@ async def release_session( raise return ReleaseSessionResponse(status="not_found", platform=platform) + # A tab whose claim was replaced (taken over, or the player pressing Play + # again elsewhere) still releases on unload, and must not end the claim + # that took its place. + if claimed_at is not None and session.get("claimed_at") != claimed_at: + log.info("release ignored, the claim was replaced, platform=%s", platform) + return ReleaseSessionResponse(status="not_found", platform=platform) + # Teardown pulls the whole card off the broker and pushes a blank one back, # several seconds of broker round-trips. The player who quit does not need # the claim released to get their UI back, so it runs after the response is diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index 7eb8ace43..8fbe2c55d 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -94,13 +94,19 @@ def platform_is_visible(request: Request, platform_slug: str) -> bool: def _session_in_scope( - session: dict[str, Any], platform: str | None, include_desktop: bool + session: dict[str, Any], + platform: str | None, + include_desktop: bool, + claimed_at: str | None = None, ) -> bool: """Whether a stored session is one the route asked about. A container serves several platforms and holds one session, so the owner alone does not - identify it, and a desktop only answers to the caller that named it.""" + identify it, a desktop only answers to the caller that named it, and a claim + is the holder plus the moment they took it.""" if not include_desktop and session_is_desktop(session): return False + if claimed_at is not None and session.get("claimed_at") != claimed_at: + return False return platform is None or session_platform_matches(session, platform) @@ -110,19 +116,21 @@ async def find_session_for_user( *, platform: str | None = None, include_desktop: bool = False, + claimed_at: str | None = None, ) -> tuple[ResolvedContainer, str, dict[str, Any]] | None: """The candidate holding this user's session, as (container, key, session). With a pool the platform no longer identifies the container, the session - does. `platform` scopes the match to sessions claimed for it, and a desktop - is only reachable when the caller named its container. + does. `platform` scopes the match to sessions claimed for it, `claimed_at` + to the one claim the caller was given, and a desktop is only reachable when + the caller named its container. """ for candidate in candidates: session_key = candidate.key session = await get_live_session(session_key) if session is None: continue - if not _session_in_scope(session, platform, include_desktop): + if not _session_in_scope(session, platform, include_desktop, claimed_at): continue if session.get("user_id") == user_id: return candidate, session_key, session diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index ebfdfa44d..0c561eb82 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2368,6 +2368,40 @@ def test_heartbeat_refreshes_last_seen(client, access_token, rom: Rom): assert not session_store.session_is_stale(session) +def test_a_heartbeat_for_a_replaced_claim_reports_ended(client, access_token, rom: Rom): + """A tab that missed its takeover must not keep the claim that replaced it + alive: the stamp it was given is what identifies the claim it holds.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + _age_session(rom, 60) + before = json.loads(_session_raw(_container_for(rom)))["last_seen"] + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + after = json.loads(_session_raw(_container_for(rom)))["last_seen"] + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert after == before + + +def test_a_heartbeat_naming_its_own_claim_still_refreshes_it( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + _age_session(rom, 60) + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + session = json.loads(_session_raw(_container_for(rom))) + assert r.json()["status"] == "active" + assert not session_store.session_is_stale(session) + + def test_heartbeat_racing_a_teardown_reports_ended(client, access_token, rom: Rom): """The refresh finds nothing when the claim was released between the lookup and the write; answering "active" there would leave the client beating a @@ -2762,6 +2796,41 @@ def test_release_uses_container_key_not_platform(client, access_token, rom: Rom) assert r.json()["status"] == "released" +def test_a_release_for_a_replaced_claim_leaves_the_session( + client, access_token, rom: Rom +): + """A tab whose claim was taken over still releases on unload, and it must + not end the session that replaced it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch("handler.streaming.commands.stop", return_value=None) as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(_key_of(_container_for(rom)))) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + stop.assert_not_called() + assert session is not None + + +def test_a_release_naming_its_own_claim_still_ends_the_session( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + with patch("handler.streaming.commands.stop", return_value=None) as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + assert r.json()["status"] == "released" + stop.assert_called_once() + + def test_release_by_other_user_is_forbidden( client, access_token, viewer_access_token, rom: Rom ): From e3b529e21449df4a364615f3c7fdd00580d90655 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 15:04:27 -0500 Subject: [PATCH 004/213] fix(streaming): carry container and desktop on the session-ended notice The termination notice named only the platform, so a tab could not tell which of the account's claims had ended. One room carries them all: a player holding two sessions from a pool, or an admin with a desktop open alongside a game, tore down the wrong screen. The notice now names the container it ended and whether that claim was a desktop. Stream.vue ignores a desktop notice and one for a container it did not claim; Desktop.vue gains the listener it never had, so a force-released desktop says so at once instead of at the next heartbeat. The tombstone also moves ahead of the drain in both teardown paths: the session is over the moment the marker lands, and a poll during the seconds of broker round trips that follow found no reason at all. --- backend/endpoints/responses/streaming.py | 2 + backend/handler/streaming/lifecycle.py | 22 +-- backend/handler/streaming/session_store.py | 4 + backend/tests/endpoints/test_streaming.py | 73 ++++++++++ .../models/SessionTerminationSchema.ts | 2 + frontend/src/v2/views/Player/Desktop.test.ts | 132 ++++++++++++++++++ frontend/src/v2/views/Player/Desktop.vue | 27 +++- frontend/src/v2/views/Player/Stream.test.ts | 91 +++++++++++- frontend/src/v2/views/Player/Stream.vue | 10 ++ 9 files changed, 347 insertions(+), 16 deletions(-) create mode 100644 frontend/src/v2/views/Player/Desktop.test.ts diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index faa5723e9..6c617a4a3 100644 --- a/backend/endpoints/responses/streaming.py +++ b/backend/endpoints/responses/streaming.py @@ -50,6 +50,8 @@ class SessionTerminationSchema(BaseModel): platform: str | None = None rom_id: int | None = None rom_name: str | None = None + container: str | None = None + desktop: bool = False class SessionStatusSchema(BaseModel): diff --git a/backend/handler/streaming/lifecycle.py b/backend/handler/streaming/lifecycle.py index ba4061076..0294808f5 100644 --- a/backend/handler/streaming/lifecycle.py +++ b/backend/handler/streaming/lifecycle.py @@ -331,14 +331,13 @@ async def teardown_released_session( keepalive = _hold_reservation(session_key, token, session) try: - # The marker, or the claim it could not replace, holds the container - # throughout, so no concurrent claim can interleave. - state_slot = await quiesce_container(container, session, save=save) - # Leave a note when this is a force-release rather than a player closing # their own game. A different user is the obvious case; a reason covers # the rest, since only the admin panel sends one and an admin can be - # logged in as the same account that is playing in another tab. + # logged in as the same account that is playing in another tab. It goes + # out before the drain: the session ended when the marker landed, and + # the quiesce below is seconds of broker round trips in which the + # displaced player's poll would otherwise find no reason at all. if session.get("user_id") != acting_user_id or reason is not None: await record_termination( session, session_key, ended_by=acting_username, reason=reason @@ -351,6 +350,10 @@ async def teardown_released_session( reason or "-", ) + # The marker, or the claim it could not replace, holds the container + # throughout, so no concurrent claim can interleave. + state_slot = await quiesce_container(container, session, save=save) + await record_play_session(session) await clear_session_activity(session_key, session) @@ -406,14 +409,15 @@ async def _teardown_abandoned_session( keepalive = asyncio.ensure_future(hold_drain_marker(session_key, token)) try: - state_slot = await quiesce_container(container, session) - await record_play_session(session) - await clear_session_activity(session_key, session) # That tab may still be showing the stream, so leave the same note an - # admin force-release does rather than letting the picture simply stop. + # admin force-release does rather than letting the picture simply stop, + # and leave it before the drain so a poll inside that window finds it. await record_termination( session, session_key, ended_by=None, reason="abandoned" ) + state_slot = await quiesce_container(container, session) + await record_play_session(session) + await clear_session_activity(session_key, session) await collect_exit_state(container, session, state_slot) collect_exit_saves(container, session) except Exception: diff --git a/backend/handler/streaming/session_store.py b/backend/handler/streaming/session_store.py index e41fe1162..411a4dd44 100644 --- a/backend/handler/streaming/session_store.py +++ b/backend/handler/streaming/session_store.py @@ -581,6 +581,10 @@ async def record_termination( "platform": session.get("platform"), "rom_id": session.get("rom_id"), "rom_name": session.get("rom_name"), + # Which claim ended: a user can hold one per container, plus a desktop, + # and only the tab that holds this one should act on the notice. + "container": session_key, + "desktop": session_is_desktop(session), } await async_cache.set( _termination_redis_key(session_key, user_id), diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 0c561eb82..4507d0101 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2593,6 +2593,79 @@ def test_heartbeat_carries_termination_notice( assert body["termination"]["reason"] == "patching the host" +def test_a_termination_notice_names_the_container_it_ended( + client, access_token, viewer_access_token, rom: Rom +): + """A player can hold a session on several containers, so the notice has to + say which one ended for the right tab to act on it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, viewer_access_token, rom.id) + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"reason": "maintenance window"}, + headers=_auth(access_token), + ) + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + headers=_auth(viewer_access_token), + ) + notice = r.json()["termination"] + assert notice["container"] == _key_of(_container_for(rom)) + assert notice["desktop"] is False + + +def test_a_desktop_termination_notice_says_it_was_a_desktop(client, access_token): + """A game tab must not act on the end of the admin desktop it shares an + account with.""" + with _streaming(_webstation()): + key = _key_of(_webstation()) + assert _desktop(client, access_token, key)[0].status_code == 200 + with patch("handler.streaming.commands.stop", return_value=None): + client.delete( + "/api/streaming/sessions/ps2", + params={"container": key, "reason": "clearing the container"}, + headers=_auth(access_token), + ) + r = client.get( + "/api/streaming/sessions/ps2/status", headers=_auth(access_token) + ) + notice = r.json()["termination"] + assert notice["desktop"] is True + assert notice["container"] == key + + +def test_a_termination_notice_lands_before_the_drain( + client, access_token, viewer_access_token, rom: Rom +): + """The session is over the moment the drain marker is written, and the drain + itself is seconds of broker round trips, so a poll inside that window has to + be told why the stream stopped rather than getting a bare `ended`.""" + container = _container_for(rom) + seen: list[dict[str, Any] | None] = [] + + with _streaming(container): + _claim_ok(client, viewer_access_token, rom.id) + user_id = json.loads(_session_raw(container))["user_id"] + + async def capture(*args, **kwargs): + seen.append( + await session_store.get_termination(_key_of(container), user_id) + ) + return None + + with patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(side_effect=capture), + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"reason": "maintenance window"}, + headers=_auth(access_token), + ) + assert seen and seen[0] is not None + assert seen[0]["reason"] == "maintenance window" + + def test_force_release_all_leaves_termination_notice( client, access_token, viewer_access_token, rom: Rom ): diff --git a/frontend/src/__generated__/models/SessionTerminationSchema.ts b/frontend/src/__generated__/models/SessionTerminationSchema.ts index b66bc3b59..19b77c5b0 100644 --- a/frontend/src/__generated__/models/SessionTerminationSchema.ts +++ b/frontend/src/__generated__/models/SessionTerminationSchema.ts @@ -15,5 +15,7 @@ export type SessionTerminationSchema = { platform?: (string | null); rom_id?: (number | null); rom_name?: (string | null); + container?: (string | null); + desktop?: boolean; }; diff --git a/frontend/src/v2/views/Player/Desktop.test.ts b/frontend/src/v2/views/Player/Desktop.test.ts new file mode 100644 index 000000000..cdd893a2b --- /dev/null +++ b/frontend/src/v2/views/Player/Desktop.test.ts @@ -0,0 +1,132 @@ +import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { defineComponent } from "vue"; +import Desktop from "./Desktop.vue"; + +const mocks = vi.hoisted(() => ({ + claimDesktop: vi.fn(), + releaseSession: vi.fn(), + releaseSessionKeepalive: vi.fn(), + heartbeatSession: vi.fn(), + socketHandlers: {} as Record unknown>, +})); + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); + +vi.mock("vue-router", () => ({ + onBeforeRouteLeave: vi.fn(), + useRoute: () => ({ query: { container: "WEBSTATION-DEV" } }), + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("@/plugins/router", () => ({ + ROUTES: { ADMINISTRATION: "administration" }, +})); + +vi.mock("@/services/api/streaming", () => ({ + default: { + claimDesktop: mocks.claimDesktop, + releaseSession: mocks.releaseSession, + releaseSessionKeepalive: mocks.releaseSessionKeepalive, + }, +})); + +vi.mock("@/stores/streaming", () => ({ + useStreamingStore: () => ({ heartbeatSession: mocks.heartbeatSession }), +})); + +vi.mock("@/v2/composables/useConfirm", () => ({ + useConfirm: () => () => Promise.resolve(true), +})); + +vi.mock("@/v2/composables/usePageTitle", () => ({ usePageTitle: vi.fn() })); + +vi.mock("@/v2/composables/useSocketEvent", () => ({ + useSocketEvent: (event: string, handler: (payload: unknown) => unknown) => { + mocks.socketHandlers[event] = handler; + }, +})); + +const StreamStageStub = defineComponent({ + setup(_, { expose }) { + expose({ + leaveFullscreen: () => Promise.resolve(), + focusStream: () => {}, + }); + return () => null; + }, +}); + +type DesktopVm = { state: string; errorMessage: string }; + +// The view listens on window, so a mount left standing would answer the next +// test's pagehide too. +let mounted: VueWrapper | null = null; + +async function openDesktop(): Promise { + mocks.claimDesktop.mockResolvedValue({ + data: { host: "http://webstation-dev:8080", label: "PS2", platform: "ps2" }, + }); + mounted = mount(Desktop, { + shallow: true, + global: { stubs: { StreamStage: StreamStageStub } }, + }); + await flushPromises(); + return mounted; +} + +function vmOf(wrapper: VueWrapper): DesktopVm { + return wrapper.vm as unknown as DesktopVm; +} + +function endSession(notice: Record): void { + const handler = mocks.socketHandlers["streaming:session-ended"]; + expect(handler).toBeTypeOf("function"); + handler({ ended_by: "admin", reason: null, desktop: true, ...notice }); +} + +describe("Desktop session-ended notices", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + mounted?.unmount(); + mounted = null; + }); + + it("ends the desktop when the notice names its container", async () => { + const wrapper = await openDesktop(); + expect(vmOf(wrapper).state).toBe("running"); + + endSession({ platform: "ps2", container: "WEBSTATION-DEV" }); + await flushPromises(); + + expect(vmOf(wrapper).state).toBe("error"); + expect(vmOf(wrapper).errorMessage).toBe("play.session-ended-by"); + }); + + it("holds the claim when the notice names another container", async () => { + const wrapper = await openDesktop(); + + endSession({ platform: "ps2", container: "WEBSTATION-OTHER" }); + await flushPromises(); + + expect(vmOf(wrapper).state).toBe("running"); + }); + + it("releases nothing once a notice has ended the claim", async () => { + // The claim is gone, so an exit must not hand back whoever holds the + // container next. + await openDesktop(); + + endSession({ platform: "ps2", container: "WEBSTATION-DEV" }); + await flushPromises(); + window.dispatchEvent(new Event("pagehide")); + + expect(mocks.releaseSessionKeepalive).not.toHaveBeenCalled(); + expect(mocks.releaseSession).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/v2/views/Player/Desktop.vue b/frontend/src/v2/views/Player/Desktop.vue index 43bc8a93a..3f3cd4da0 100644 --- a/frontend/src/v2/views/Player/Desktop.vue +++ b/frontend/src/v2/views/Player/Desktop.vue @@ -15,10 +15,11 @@ import { useI18n } from "vue-i18n"; import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router"; import { ROUTES } from "@/plugins/router"; import streamingApi from "@/services/api/streaming"; -import { useStreamingStore } from "@/stores/streaming"; +import { type SessionTermination, useStreamingStore } from "@/stores/streaming"; import StreamStage from "@/v2/components/Player/StreamStage.vue"; import { useConfirm } from "@/v2/composables/useConfirm"; import { usePageTitle } from "@/v2/composables/usePageTitle"; +import { useSocketEvent } from "@/v2/composables/useSocketEvent"; const { t } = useI18n(); const route = useRoute(); @@ -97,19 +98,35 @@ async function release(): Promise { // stale window, and nothing else here touches the claim. const HEARTBEAT_MS = 30_000; +// Dropping the claim keeps a later exit from releasing whoever holds the +// container next, and the reason is the only sign the desktop was taken away +// rather than broken. +function noteSessionEnded(endedBy?: string | null): void { + holdsClaim.value = false; + state.value = "error"; + errorMessage.value = endedBy + ? t("play.session-ended-by", { user: endedBy }) + : t("play.session-ended"); +} + useIntervalFn(async () => { if (!holdsClaim.value) return; const status = await streamingStore.heartbeatSession( platform.value, containerKey.value, ); - // Ended elsewhere: dropping the claim keeps a later exit from releasing - // whoever holds the container next. if (status?.status !== "ended") return; - holdsClaim.value = false; - state.value = "exited"; + noteSessionEnded(status.termination?.ended_by); }, HEARTBEAT_MS); +// Pushed the moment someone else ends this claim, so the desktop does not sit +// dead until the next heartbeat. The room is per-user and covers every claim +// the account holds, so only a notice for this container is ours. +useSocketEvent("streaming:session-ended", (notice) => { + if (!holdsClaim.value || notice.container !== containerKey.value) return; + noteSessionEnded(notice.ended_by); +}); + function backToAdministration(): void { router.push({ name: ROUTES.ADMINISTRATION, query: { tab: "streaming" } }); } diff --git a/frontend/src/v2/views/Player/Stream.test.ts b/frontend/src/v2/views/Player/Stream.test.ts index 4e1760b08..17af4a43d 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({ fetchConfig: vi.fn(), getRom: vi.fn(), container: null as Record | null, + socketHandlers: {} as Record unknown>, })); vi.mock("vue-i18n", () => ({ @@ -121,7 +122,9 @@ vi.mock("@/v2/composables/useSnackbar", () => ({ })); vi.mock("@/v2/composables/useSocketEvent", () => ({ - useSocketEvent: vi.fn(), + useSocketEvent: (event: string, handler: (payload: unknown) => unknown) => { + mocks.socketHandlers[event] = handler; + }, })); vi.mock("@/v2/composables/useStageActive", () => ({ @@ -132,6 +135,18 @@ vi.mock("@/v2/composables/useUnloadGuard", () => ({ useUnloadGuard: vi.fn(), })); +// The stage owns fullscreen, which the ended path leaves before anything else. +const StreamStageStub = defineComponent({ + setup(_, { expose }) { + expose({ + enterFullscreen: () => Promise.resolve(), + leaveFullscreen: () => Promise.resolve(), + focusStream: () => {}, + }); + return () => null; + }, +}); + const GameCoverStub = defineComponent({ setup(_, { expose }) { expose({ playLoad: () => 0 }); @@ -198,7 +213,7 @@ async function launch(opts: { renderStubDefaultSlot: true, // The launch flourish calls into the cover before the claim, so this // one stub has to answer rather than be inert. - stubs: { GameCover: GameCoverStub }, + stubs: { GameCover: GameCoverStub, StreamStage: StreamStageStub }, }, }); await flushPromises(); @@ -335,3 +350,75 @@ describe("Stream save picker", () => { expect(saveList(wrapper)!.props("selectedId")).toBe(3); }); }); + +type StreamVm = { + onPlay: () => Promise; + playerState: string; + endedDialogOpen: boolean; +}; + +function vmOf(wrapper: VueWrapper): StreamVm { + return wrapper.vm as unknown as StreamVm; +} + +function endSession(notice: Record): void { + const handler = mocks.socketHandlers["streaming:session-ended"]; + expect(handler).toBeTypeOf("function"); + handler({ ended_by: "admin", reason: null, ...notice }); +} + +describe("Stream session-ended notices", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.claimSession.mockResolvedValue({ container: "WEBSTATION-DEV" }); + }); + + it("ends the game when the notice names the container it claimed", async () => { + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + + endSession({ platform: "gba", container: "WEBSTATION-DEV" }); + await flushPromises(); + + expect(vmOf(wrapper).playerState).toBe("exited"); + expect(vmOf(wrapper).endedDialogOpen).toBe(true); + }); + + it("keeps playing when the notice names another container", async () => { + // A pool serves one platform from several containers, so the player can + // hold a second session the same room hears about. + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + + endSession({ platform: "gba", container: "WEBSTATION-DEV-2" }); + await flushPromises(); + + expect(vmOf(wrapper).playerState).toBe("loading"); + expect(vmOf(wrapper).endedDialogOpen).toBe(false); + }); + + it("keeps launching when an admin's own desktop ends", async () => { + // The 202 has not landed, so the container is not known yet and the + // desktop flag is all that tells the two claims apart. + let claimed = (_: { container: string }) => {}; + mocks.claimSession.mockReturnValue( + new Promise<{ container: string }>((resolve) => { + claimed = resolve; + }), + ); + const wrapper = await launch({ picker: false }); + const playing = vmOf(wrapper).onPlay(); + await flushPromises(); + + endSession({ + platform: "gba", + container: "WEBSTATION-DEV-2", + desktop: true, + }); + await flushPromises(); + + expect(vmOf(wrapper).playerState).toBe("loading"); + claimed({ container: "WEBSTATION-DEV" }); + await playing; + }); +}); diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index 34f8cbef4..820d7d60c 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -554,6 +554,16 @@ const SESSION_POLL_MS = 30_000; // session (`_record_termination` in streaming.py), to the caller's own // `user:{id}` room. Near-instant, unlike the poll above. useSocketEvent("streaming:session-ended", (notice) => { + // The room carries every claim the account holds, and a platform can be + // served by a pool, so the container is what says this one was ours. An + // admin's desktop is never the game on screen. + if (notice.desktop) return; + if ( + notice.container && + claimedContainer.value && + notice.container !== claimedContainer.value + ) + return; void handleSessionStatus({ status: "ended", platform: notice.platform ?? "", From 13e65ec375b3924eb21eb98b7d14123b1568f077 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 15:07:24 -0500 Subject: [PATCH 005/213] fix(streaming): leave no ended notice when a player retakes their own session A crashed tab leaves a stale session, and pressing Play again sweeps it. The sweep left the same notice a force-release does, which went to the user, whose only tab was the one that had just claimed the container: it read the push as its own session ending and handed the claim straight back. The takeover now names the claimant, and the sweep skips the notice when it is the owner coming back. A takeover by anyone else still leaves it. --- backend/endpoints/streaming.py | 1 + backend/handler/streaming/lifecycle.py | 21 ++++++++++++++++----- backend/tests/endpoints/test_streaming.py | 23 +++++++++++++++++++++++ 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 2e30bae39..2db6b855a 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -408,6 +408,7 @@ async def _reserve_container( candidate.key, existing, max(0.0, deadline - time.monotonic()), + claimed_by=request.user.id, ): continue if await try_claim(candidate): diff --git a/backend/handler/streaming/lifecycle.py b/backend/handler/streaming/lifecycle.py index 0294808f5..8a56edab7 100644 --- a/backend/handler/streaming/lifecycle.py +++ b/backend/handler/streaming/lifecycle.py @@ -375,7 +375,11 @@ async def teardown_released_session( async def _teardown_abandoned_session( - container: ResolvedContainer, session_key: str, session: dict[str, Any] + container: ResolvedContainer, + session_key: str, + session: dict[str, Any], + *, + claimed_by: int | None = None, ) -> bool: """Free a container whose owner vanished without releasing (heartbeat went stale). Same order as an owner release: stop the emulator so the card is @@ -412,9 +416,12 @@ async def _teardown_abandoned_session( # That tab may still be showing the stream, so leave the same note an # admin force-release does rather than letting the picture simply stop, # and leave it before the drain so a poll inside that window finds it. - await record_termination( - session, session_key, ended_by=None, reason="abandoned" - ) + # Not for the owner coming back: the note would reach the tab that just + # claimed this container and end the claim it is starting. + if session.get("user_id") != claimed_by: + await record_termination( + session, session_key, ended_by=None, reason="abandoned" + ) state_slot = await quiesce_container(container, session) await record_play_session(session) await clear_session_activity(session_key, session) @@ -445,6 +452,8 @@ async def await_teardown_within_budget( session_key: str, session: dict[str, Any], budget: float, + *, + claimed_by: int | None = None, ) -> bool: """Tear down an abandoned session, but only wait `budget` seconds for it. @@ -454,7 +463,9 @@ async def await_teardown_within_budget( this leaves behind blocks a claim until the teardown drops it. """ task = background.spawn_sync_task( - _teardown_abandoned_session(container, session_key, session) + _teardown_abandoned_session( + container, session_key, session, claimed_by=claimed_by + ) ) try: return await asyncio.wait_for(asyncio.shield(task), timeout=budget) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 4507d0101..6a7f4d51e 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2302,6 +2302,29 @@ def test_takeover_leaves_the_displaced_owner_a_notice( assert notice["rom_id"] == rom.id +def test_taking_over_ones_own_stale_session_pushes_no_notice( + client, access_token, rom: Rom +): + """The notice goes to the user, whose only tab is now the one that just + claimed this container, and it would end that fresh claim.""" + container = _container_for(rom) + sent: list[str] = [] + + async def _capture(user_id: Any, event: str, payload: dict[str, Any]) -> None: + sent.append(event) + + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + with ( + patch("handler.streaming.commands.stop", return_value=None), + patch("handler.streaming.session_store.push_to_user", new=_capture), + ): + _claim_ok(client, access_token, rom.id) + + assert "streaming:session-ended" not in sent + + def test_takeover_aborts_when_the_owner_comes_back_first( client, access_token, viewer_access_token, rom: Rom ): From acdbcca41dab88eca4e560d0c793ec1320f555b8 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 15:11:55 -0500 Subject: [PATCH 006/213] fix(streaming): drop the claim when the session ended elsewhere The player view kept its claim flag set after the backend told it the session was gone, so the unload and unmount paths still sent a release. By then the container had usually been handed to somebody else, and an unnamed release reaches whatever the platform is running: their session, not the one this tab had lost. The ended path now clears the claim, and every release and heartbeat from the view names the container and the stamp its claim answered with, so a late one cannot reach a claim that replaced it. The launch-ready handler also awaits its release before deciding the claim is gone, instead of leaving the flag for the unmount path to act on again. --- frontend/src/services/api/streaming.ts | 21 +++- frontend/src/stores/streaming.ts | 37 ++++-- frontend/src/v2/views/Player/Stream.test.ts | 124 +++++++++++++++++--- frontend/src/v2/views/Player/Stream.vue | 54 ++++++++- 4 files changed, 205 insertions(+), 31 deletions(-) diff --git a/frontend/src/services/api/streaming.ts b/frontend/src/services/api/streaming.ts index 644cd34e4..110f38e95 100644 --- a/frontend/src/services/api/streaming.ts +++ b/frontend/src/services/api/streaming.ts @@ -114,9 +114,13 @@ async function releaseSession( reason?: string, container?: string, save?: boolean, + claimedAt?: string, ) { return api.delete(`/streaming/sessions/${platform}`, { params: { + // The claim this release is for, so a tab whose claim was taken over + // cannot end the one that replaced it. Admin releases send none. + ...(claimedAt !== undefined ? { claimed_at: claimedAt } : {}), // Sent whenever the caller supplied one, empty string included: the // backend treats the param's presence as "this is an admin force-release". ...(reason !== undefined ? { reason } : {}), @@ -151,11 +155,15 @@ async function saveAndExit(platform: string, slot = 0, wait = true) { }); } -async function heartbeatSession(platform: string, container?: string) { +async function heartbeatSession( + platform: string, + container?: string, + claimedAt?: string, +) { return api.post( `/streaming/sessions/${platform}/heartbeat`, undefined, - { params: { container } }, + { params: { container, claimed_at: claimedAt } }, ); } @@ -224,9 +232,14 @@ function saveAndExitKeepalive(platform: string, slot = 0): Promise { function releaseSessionKeepalive( platform: string, container?: string, + claimedAt?: string, ): Promise { - // Names which container to release, for the platforms a pool serves. - const query = container ? `?container=${encodeURIComponent(container)}` : ""; + // Names which container to release, for the platforms a pool serves, and + // which claim, so an unload cannot end the claim that replaced it. + const params = new URLSearchParams(); + if (container) params.set("container", container); + if (claimedAt) params.set("claimed_at", claimedAt); + const query = params.size > 0 ? `?${params}` : ""; return fetch(`/api/streaming/sessions/${platform}${query}`, { method: "DELETE", keepalive: true, diff --git a/frontend/src/stores/streaming.ts b/frontend/src/stores/streaming.ts index 4ad1cdf7f..bc7114ac6 100644 --- a/frontend/src/stores/streaming.ts +++ b/frontend/src/stores/streaming.ts @@ -252,10 +252,18 @@ export const useStreamingStore = defineStore("streaming", () => { async function releaseSession( platform: string, save = true, + container?: string | null, + claimedAt?: string | null, ): Promise { if (!platform) return false; try { - await streamingApi.releaseSession(platform, undefined, undefined, save); + await streamingApi.releaseSession( + platform, + undefined, + container ?? undefined, + save, + claimedAt ?? undefined, + ); launchingSession.value = null; return true; } catch (err) { @@ -302,11 +310,16 @@ export const useStreamingStore = defineStore("streaming", () => { */ async function heartbeatSession( platform: string, - container?: string, + container?: string | null, + claimedAt?: string | null, ): Promise { if (!platform) return null; try { - const { data } = await streamingApi.heartbeatSession(platform, container); + const { data } = await streamingApi.heartbeatSession( + platform, + container ?? undefined, + claimedAt ?? undefined, + ); return data; } catch (err) { console.warn("[streaming] Could not heartbeat session:", err); @@ -352,12 +365,22 @@ export const useStreamingStore = defineStore("streaming", () => { * releaseSession for the pagehide path. Fire-and-forget via fetch * keepalive. Best-effort, never throws. */ - function releaseSessionKeepalive(platform: string): void { + function releaseSessionKeepalive( + platform: string, + container?: string | null, + claimedAt?: string | null, + ): void { if (!platform) return; launchingSession.value = null; - streamingApi.releaseSessionKeepalive(platform).catch((err) => { - console.warn("[streaming] Could not release session (keepalive):", err); - }); + streamingApi + .releaseSessionKeepalive( + platform, + container ?? undefined, + claimedAt ?? undefined, + ) + .catch((err) => { + console.warn("[streaming] Could not release session (keepalive):", err); + }); } return { diff --git a/frontend/src/v2/views/Player/Stream.test.ts b/frontend/src/v2/views/Player/Stream.test.ts index 17af4a43d..6eec15a52 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -12,7 +12,11 @@ const mocks = vi.hoisted(() => ({ claimSession: vi.fn(), fetchConfig: vi.fn(), getRom: vi.fn(), + heartbeatSession: vi.fn(), + releaseSession: vi.fn(), + releaseSessionKeepalive: vi.fn(), container: null as Record | null, + presenceTick: null as (() => Promise) | null, socketHandlers: {} as Record unknown>, })); @@ -63,22 +67,25 @@ vi.mock("@/stores/streaming", () => ({ fetchConfig: mocks.fetchConfig, fetchSessionStatus: vi.fn(), forgetJoinableSession: vi.fn(), - heartbeatSession: vi.fn(), + heartbeatSession: mocks.heartbeatSession, joinSession: vi.fn(), - releaseSession: vi.fn(), - releaseSessionKeepalive: vi.fn(), + releaseSession: mocks.releaseSession, + releaseSessionKeepalive: mocks.releaseSessionKeepalive, saveAndExit: vi.fn(), saveAndExitKeepalive: vi.fn(), }), })); vi.mock("@/v2/composables/useActivityPresence", () => ({ - useActivityPresence: () => ({ - start: vi.fn(), - stopHeartbeat: vi.fn(), - emitStop: vi.fn(), - stop: vi.fn(), - }), + useActivityPresence: (_rom: unknown, tick: () => Promise) => { + mocks.presenceTick = tick; + return { + start: vi.fn(), + stopHeartbeat: vi.fn(), + emitStop: vi.fn(), + stop: vi.fn(), + }; + }, })); vi.mock("@/v2/composables/useBackgroundArt", () => ({ @@ -232,10 +239,15 @@ function saveList(wrapper: VueWrapper) { .find((s) => s.props("type") === "save"); } +const CLAIM = { + container: "WEBSTATION-DEV", + claimed_at: "2026-09-17T10:00:00", +}; + describe("Stream save picker", () => { beforeEach(() => { vi.clearAllMocks(); - mocks.claimSession.mockResolvedValue({ container: "WEBSTATION-DEV" }); + mocks.claimSession.mockResolvedValue(CLAIM); }); it("offers every archive, newest already picked", async () => { @@ -355,6 +367,7 @@ type StreamVm = { onPlay: () => Promise; playerState: string; endedDialogOpen: boolean; + holdsClaim: boolean; }; function vmOf(wrapper: VueWrapper): StreamVm { @@ -370,7 +383,7 @@ function endSession(notice: Record): void { describe("Stream session-ended notices", () => { beforeEach(() => { vi.clearAllMocks(); - mocks.claimSession.mockResolvedValue({ container: "WEBSTATION-DEV" }); + mocks.claimSession.mockResolvedValue(CLAIM); }); it("ends the game when the notice names the container it claimed", async () => { @@ -400,9 +413,9 @@ describe("Stream session-ended notices", () => { it("keeps launching when an admin's own desktop ends", async () => { // The 202 has not landed, so the container is not known yet and the // desktop flag is all that tells the two claims apart. - let claimed = (_: { container: string }) => {}; + let claimed = (_: typeof CLAIM) => {}; mocks.claimSession.mockReturnValue( - new Promise<{ container: string }>((resolve) => { + new Promise((resolve) => { claimed = resolve; }), ); @@ -418,7 +431,90 @@ describe("Stream session-ended notices", () => { await flushPromises(); expect(vmOf(wrapper).playerState).toBe("loading"); - claimed({ container: "WEBSTATION-DEV" }); + claimed(CLAIM); await playing; }); }); + +async function launchReady(): Promise { + const handler = mocks.socketHandlers["streaming:launch-ready"]; + expect(handler).toBeTypeOf("function"); + await handler({ + platform: "gba", + container: CLAIM.container, + host: "http://webstation-dev:8080", + resume: null, + }); +} + +describe("Stream claim hygiene", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.claimSession.mockResolvedValue(CLAIM); + mocks.releaseSession.mockResolvedValue(true); + }); + + it("names the claim it holds when it releases", async () => { + // An unnamed release reaches whatever the platform is running, which after + // a takeover is somebody else's session. + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + + wrapper.unmount(); + + expect(mocks.releaseSession).toHaveBeenCalledWith( + "gba", + false, + CLAIM.container, + CLAIM.claimed_at, + ); + }); + + it("releases nothing on unmount once the session ended elsewhere", async () => { + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + + endSession({ platform: "gba", container: CLAIM.container }); + await flushPromises(); + wrapper.unmount(); + + expect(vmOf(wrapper).holdsClaim).toBe(false); + expect(mocks.releaseSession).not.toHaveBeenCalled(); + }); + + it("hands the container back once when the game comes up after the exit", async () => { + const wrapper = await launch({ picker: false }); + const vm = vmOf(wrapper); + await vm.onPlay(); + vm.playerState = "exited"; + + await launchReady(); + await flushPromises(); + wrapper.unmount(); + + expect(mocks.releaseSession).toHaveBeenCalledTimes(1); + expect(mocks.releaseSession).toHaveBeenCalledWith( + "gba", + false, + CLAIM.container, + CLAIM.claimed_at, + ); + }); + + it("names the claim on the heartbeat", async () => { + // The heartbeat restamps whatever the platform is running otherwise, which + // keeps another player's session alive and lets this one go stale. + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + mocks.heartbeatSession.mockResolvedValue(null); + + await mocks.presenceTick?.(); + + expect(mocks.heartbeatSession).toHaveBeenCalledWith( + "gba", + CLAIM.container, + CLAIM.claimed_at, + ); + wrapper.unmount(); + }); +}); diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index 820d7d60c..e3056b7f6 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -480,7 +480,11 @@ const presence = useActivityPresence( heartbeatInFlight = true; try { await handleSessionStatus( - await streamingStore.heartbeatSession(rom.value.platform_slug), + await streamingStore.heartbeatSession( + rom.value.platform_slug, + claimedContainer.value, + claimedAt.value, + ), ); } finally { heartbeatInFlight = false; @@ -534,6 +538,12 @@ async function handleSessionStatus( playerState.value = "exited"; containerHost.value = ""; presence.stopHeartbeat(); + // Nothing is held any more, so the unload and unmount paths have nothing to + // hand back. Left standing, the claim would release whoever holds the + // container next. + holdsClaim.value = false; + claimedContainer.value = null; + claimedAt.value = null; endedNotice.value = status.termination ?? null; endedDialogOpen.value = true; @@ -608,6 +618,9 @@ const stopSessionPoll = sessionPoll.pause; // Which container the claim won, so a launch push can be told from another // tab's. Null until the 202 lands, which is before any push can arrive. const claimedContainer = ref(null); +// The stamp the 202 answered with, which every release and heartbeat sends +// back so a claim that replaced this one is never the one they reach. +const claimedAt = ref(null); function isOurLaunch(payload: { container?: string }): boolean { return payload.container === claimedContainer.value; @@ -624,8 +637,19 @@ useSocketEvent("streaming:launch-ready", async (payload) => { // The player left while the game was coming up. The claim is theirs and // still held, so hand the container back rather than entering the stream. if ((playerState.value as PlayerState) === "exited") { - claimedContainer.value = null; - void streamingStore.releaseSession(payload.platform, false); + const released = await streamingStore.releaseSession( + payload.platform, + false, + claimedContainer.value, + claimedAt.value, + ); + // Only a release the backend took clears the claim; the unmount path is + // the retry for one that failed. + holdsClaim.value = !released; + if (released) { + claimedContainer.value = null; + claimedAt.value = null; + } return; } if (payload.resume === false) snackbar.warning(t("play.resume-failed")); @@ -642,6 +666,7 @@ useSocketEvent("streaming:launch-failed", (payload) => { // The backend already released the claim, so there is nothing to hand back. holdsClaim.value = false; claimedContainer.value = null; + claimedAt.value = null; launchPhase.value = null; if ((playerState.value as PlayerState) === "exited") return; errorType.value = "server"; @@ -799,6 +824,7 @@ async function onPlay(cardImport?: MemoryCardImport): Promise { multiplayerOnPlay.value, ); claimedContainer.value = launching.container; + claimedAt.value = launching.claimed_at; holdsClaim.value = true; await flourish; } @@ -921,6 +947,8 @@ async function performStop(): Promise { const released = await streamingStore.releaseSession( rom.value?.platform_slug ?? "", false, + claimedContainer.value, + claimedAt.value, ); // The claim only goes when the backend says it went. Left standing, it // tells the user why the container is still busy and gives the unmount @@ -969,7 +997,12 @@ async function performSaveAndExit(): Promise { // The save-and-exit request failed, so the claim may still be held; // fall back to a plain release so the container is freed before the // player is marked exited. - released = await streamingStore.releaseSession(rom.value.platform_slug); + released = await streamingStore.releaseSession( + rom.value.platform_slug, + true, + claimedContainer.value, + claimedAt.value, + ); } } finally { isSavingAndExiting.value = false; @@ -1204,7 +1237,11 @@ function onPageHide(): void { } else { // Still loading, or exited with a release that failed: nothing to save, // and this is the last chance to hand the container back. - streamingStore.releaseSessionKeepalive(platform); + streamingStore.releaseSessionKeepalive( + platform, + claimedContainer.value, + claimedAt.value, + ); } // Guards the in-app unmount path from double-releasing if the page // comes back from the bfcache and is then navigated normally. @@ -1270,7 +1307,12 @@ onBeforeUnmount(() => { } else { // Nothing is running, so there is nothing worth a state: asking for one // here would only file whatever the last session left in the slot. - void streamingStore.releaseSession(rom.value?.platform_slug ?? "", false); + void streamingStore.releaseSession( + rom.value?.platform_slug ?? "", + false, + claimedContainer.value, + claimedAt.value, + ); } }); From 3c310fae1c229294e344f65f235c2c4fc4866977 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 15:25:08 -0500 Subject: [PATCH 007/213] fix(streaming): report a draining container as nobody's and still saving A drain marker holds a container key with no owner, so a 409 built from it named no holder and the fleet list showed it as an idle container nobody could claim. The claim refusal now reads every pool member, reports the drain, and takes the holder from a live session. The fleet list reports the drain as its own state, and the settings panel calls it saving while keeping the desktop shut until it clears. --- backend/endpoints/responses/streaming.py | 3 + backend/endpoints/streaming.py | 33 +++-- backend/tests/endpoints/test_streaming.py | 71 ++++++++++ .../models/AdminContainerSchema.ts | 1 + frontend/src/locales/bg_BG/settings.json | 1 + frontend/src/locales/cs_CZ/settings.json | 1 + frontend/src/locales/de_DE/settings.json | 1 + frontend/src/locales/en_GB/settings.json | 1 + frontend/src/locales/en_US/settings.json | 1 + frontend/src/locales/es_ES/settings.json | 1 + frontend/src/locales/fr_FR/settings.json | 1 + frontend/src/locales/hu_HU/settings.json | 1 + frontend/src/locales/it_IT/settings.json | 1 + frontend/src/locales/ja_JP/settings.json | 1 + frontend/src/locales/ko_KR/settings.json | 1 + frontend/src/locales/pl_PL/settings.json | 1 + frontend/src/locales/pt_BR/settings.json | 1 + frontend/src/locales/ro_RO/settings.json | 1 + frontend/src/locales/ru_RU/settings.json | 1 + frontend/src/locales/tr_TR/settings.json | 1 + frontend/src/locales/zh_CN/settings.json | 1 + frontend/src/locales/zh_TW/settings.json | 1 + .../Settings/StreamingSection.test.ts | 121 ++++++++++++++++++ .../components/Settings/StreamingSection.vue | 9 +- frontend/src/v2/views/Player/Desktop.test.ts | 46 +++++++ frontend/src/v2/views/Player/Desktop.vue | 10 +- 26 files changed, 300 insertions(+), 12 deletions(-) create mode 100644 frontend/src/v2/components/Settings/StreamingSection.test.ts diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index 6c617a4a3..cdaa31f3d 100644 --- a/backend/endpoints/responses/streaming.py +++ b/backend/endpoints/responses/streaming.py @@ -225,6 +225,9 @@ class AdminContainerSchema(BaseModel): configured: bool """False for a container with no usable broker address: it can never be claimed, and saying so beats listing it as idle.""" + draining: bool = False + """The previous session's exit work is still running, so the container is + held by nobody and about to come free.""" session: ContainerSessionSchema | None = None diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 2db6b855a..18662f135 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -414,16 +414,21 @@ async def _reserve_container( if await try_claim(candidate): return candidate - # Report the head of the pool as the holder: with one container that is the - # only holder, and with several the player just needs to know the platform - # is busy. - existing = await get_session(candidates[0].key) or {} # A drain marker belongs to nobody: the previous session is over and its - # exit state is still coming out of the container, so rom_name and - # claimed_at are both blank and "in use" would name no one. The player who - # just pressed save-and-exit sees this, and needs to be told to wait rather - # than that somebody else took their platform. - draining = bool(existing.get("draining")) + # exit state is still coming out of the container, so it carries no + # rom_name and no claimed_at. One member draining is worth telling the + # player about, since that container is about to come free, but the holder + # has to come from a live session or the message names no one. + snapshots = [await get_session(candidate.key) or {} for candidate in candidates] + draining = any(snapshot.get("draining") for snapshot in snapshots) + existing = next( + ( + snapshot + for snapshot in snapshots + if snapshot and not snapshot.get("draining") + ), + {}, + ) if draining: message = "The previous session is still saving, try again shortly" elif len(candidates) == 1: @@ -1330,7 +1335,11 @@ async def list_containers(request: Request) -> AdminContainersResponse: containers: list[dict[str, Any]] = [] for container_key, entries in containers_by_key().items(): first = entries[0] - session = await get_live_session(container_key) if container_key else None + held = await get_session(container_key) if container_key else None + # A drain marker holds the key with no owner. Reported as its own state + # rather than as a session, since there is nobody to name or release. + draining = bool(held and held.get("draining")) + session = None if draining else held user_id = session.get("user_id") if session else None user = db_user_handler.get_user(user_id) if isinstance(user_id, int) else None containers.append( @@ -1343,6 +1352,7 @@ async def list_containers(request: Request) -> AdminContainersResponse: # A container whose host has no scheme has an empty key and can # never be claimed, so surface it rather than listing it as idle. "configured": bool(container_key), + "draining": draining, "session": ( { "platform": session.get("platform"), @@ -1416,6 +1426,9 @@ async def claim_desktop_session( status_code=409, detail={ "message": "Container in use", + # Same shape as a game claim's 409: a drain marker means the + # previous session is still saving, not that anyone holds it. + "draining": bool(existing.get("draining")), "rom_name": access.visible_rom_name(request, existing), "claimed_at": existing.get("claimed_at"), }, diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 6a7f4d51e..a9ef59611 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1224,6 +1224,34 @@ def test_pool_409s_only_once_every_container_is_held( assert "2 containers" in r3.json()["detail"]["message"] +def test_a_busy_pool_names_the_holder_while_a_member_drains( + client, access_token, viewer_access_token, editor_access_token, rom: Rom +): + """A drain marker names nobody, so reading only the head of the pool told + the waiting player the platform was saving while another member played on.""" + head, tail = _pool_member(rom, 0), _pool_member(rom, 1) + with _streaming(head, tail): + _claim_ok(client, access_token, rom.id) + _claim_ok(client, viewer_access_token, rom.id) + holder = json.loads(_session_raw(tail)) + assert ( + asyncio.run( + session_store.claim_drain_marker( + _key_of(head), json.loads(_session_raw(head)) + ) + ) + is not None + ) + r = _claim_ok(client, editor_access_token, rom.id) + + assert r.status_code == 409 + detail = r.json()["detail"] + # One member is about to come free, which is what "try again shortly" says. + assert detail["draining"] is True + assert detail["rom_name"] == rom.name + assert detail["claimed_at"] == holder["claimed_at"] + + def test_a_claim_never_lands_in_a_later_pool( client, access_token, viewer_access_token, rom: Rom ): @@ -1855,6 +1883,49 @@ def _claim_webstation_ok(client, token, rom_id): return _claim(client, token, rom_id) +def test_containers_reports_a_container_that_is_still_saving( + client, access_token, rom: Rom +): + """A drain marker has no owner, so the row read as idle while the previous + session's state was still coming out of the container.""" + container = _container_for(rom) + with _streaming(container): + _claim_ok(client, access_token, rom.id) + assert ( + asyncio.run( + session_store.claim_drain_marker( + _key_of(container), json.loads(_session_raw(container)) + ) + ) + is not None + ) + rows = _containers(client, access_token).json()["containers"] + + assert rows[0]["draining"] is True + assert rows[0]["session"] is None + + +def test_a_desktop_refused_over_a_drain_says_it_is_saving(client, access_token): + """Nobody holds a draining container, so "in use" names no one and the + admin needs to hear that waiting is enough.""" + ps2_rom = _rom_on("ps2") + container = _webstation() + with _streaming(container): + _claim_webstation_ok(client, access_token, ps2_rom.id) + assert ( + asyncio.run( + session_store.claim_drain_marker( + _key_of(container), json.loads(_session_raw(container)) + ) + ) + is not None + ) + response, _ = _desktop(client, access_token, _key_of(container)) + + assert response.status_code == 409 + assert response.json()["detail"]["draining"] is True + + def test_containers_lists_one_row_per_container(client, access_token): """A container serves many platforms but hosts one session, so the fleet view counts containers, not the platform rows /config ships.""" diff --git a/frontend/src/__generated__/models/AdminContainerSchema.ts b/frontend/src/__generated__/models/AdminContainerSchema.ts index 9d9f072ab..a461f546b 100644 --- a/frontend/src/__generated__/models/AdminContainerSchema.ts +++ b/frontend/src/__generated__/models/AdminContainerSchema.ts @@ -10,6 +10,7 @@ export type AdminContainerSchema = { platforms: Array; supports_desktop: boolean; configured: boolean; + draining?: boolean; session?: (ContainerSessionSchema | null); }; diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index 9679b89e1..5a2c0e983 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index f4cbae83f..7dc66a38a 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index 0c86ac47b..a6043bec2 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index c2b4421ff..55e75ee68 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index da9c71557..673a1bcba 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index a22f5ea42..439de0881 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index 5ba10cdef..fa3c6239a 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index dc5e25971..093d7a8a2 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index 6345d79db..aa6bb65ad 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 827125c1c..98d0ccbdb 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index bc86ddccc..36d00de3c 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 795773409..f05b03742 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index f6bfa9640..6a64084de 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index f032e6a80..ee69bf7ee 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index 1409ab548..2110ef357 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index a27e913f5..4728de5f1 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 68e9a939b..6888d97a3 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "桌面会话", "streaming-disabled": "此服务器已禁用模拟器串流。", + "streaming-draining": "Saving the previous session", "streaming-idle": "空闲", "streaming-load-failed": "无法加载串流容器。", "streaming-none": "未配置任何串流容器。", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 7534c1834..b9f137fc1 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -456,6 +456,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Saving the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/v2/components/Settings/StreamingSection.test.ts b/frontend/src/v2/components/Settings/StreamingSection.test.ts new file mode 100644 index 000000000..e8806d297 --- /dev/null +++ b/frontend/src/v2/components/Settings/StreamingSection.test.ts @@ -0,0 +1,121 @@ +import { flushPromises, mount } from "@vue/test-utils"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import StreamingSection from "./StreamingSection.vue"; + +const { adminListContainers, releaseSession, confirm } = vi.hoisted(() => ({ + adminListContainers: vi.fn(), + releaseSession: vi.fn(), + confirm: vi.fn(), +})); + +vi.mock("@/services/api/streaming", () => ({ + default: { adminListContainers, releaseSession }, +})); + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ + t: (key: string, params?: Record) => + params ? `${key}::${JSON.stringify(params)}` : key, + locale: { value: "en_US" }, + }), +})); + +vi.mock("vue-router", () => ({ useRouter: () => ({ push: vi.fn() }) })); +vi.mock("@/plugins/router", () => ({ + ROUTES: { STREAM_DESKTOP: "stream-desktop" }, +})); + +vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirm })); +vi.mock("@/v2/composables/useSnackbar", () => ({ + useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), +})); + +// The auto-stub drops slot content, and the fleet rows live in the section's +// default slot. +const SettingsSectionStub = { + name: "SettingsSection", + template: '
', +}; + +const RBtnStub = { + name: "RBtn", + props: ["disabled", "prependIcon"], + template: "", +}; + +function container(overrides: Record = {}) { + return { + container: "WEBSTATION-DEV", + label: "Webstation", + host: "https://webstation:8080", + platforms: ["ps2"], + supports_desktop: true, + configured: true, + draining: false, + session: null, + ...overrides, + }; +} + +async function mountSection() { + const wrapper = mount(StreamingSection, { + global: { + stubs: { + SettingsSection: SettingsSectionStub, + RBtn: RBtnStub, + RIcon: true, + RSpinner: true, + }, + }, + }); + await flushPromises(); + return wrapper; +} + +function desktopButton(wrapper: Awaited>) { + return wrapper + .findAllComponents(RBtnStub) + .find((btn) => btn.props("prependIcon") === "mdi-desktop-classic"); +} + +describe("StreamingSection draining containers", () => { + beforeEach(() => { + confirm.mockReset(); + releaseSession.mockReset(); + adminListContainers.mockReset(); + adminListContainers.mockResolvedValue({ + data: { enabled: true, containers: [container()] }, + }); + }); + + it("calls a free container idle", async () => { + const wrapper = await mountSection(); + + expect(wrapper.find(".r-v2-streaming__state").text()).toBe( + "settings.streaming-idle", + ); + expect(desktopButton(wrapper)?.props("disabled")).toBe(false); + }); + + it("says a draining container is still saving", async () => { + adminListContainers.mockResolvedValue({ + data: { enabled: true, containers: [container({ draining: true })] }, + }); + + const wrapper = await mountSection(); + + expect(wrapper.find(".r-v2-streaming__state").text()).toBe( + "settings.streaming-draining", + ); + }); + + it("holds the desktop shut until the drain finishes", async () => { + adminListContainers.mockResolvedValue({ + data: { enabled: true, containers: [container({ draining: true })] }, + }); + + const wrapper = await mountSection(); + + expect(desktopButton(wrapper)?.props("disabled")).toBe(true); + }); +}); diff --git a/frontend/src/v2/components/Settings/StreamingSection.vue b/frontend/src/v2/components/Settings/StreamingSection.vue index ee9eb6932..e71378a46 100644 --- a/frontend/src/v2/components/Settings/StreamingSection.vue +++ b/frontend/src/v2/components/Settings/StreamingSection.vue @@ -92,6 +92,9 @@ async function release(container: AdminStreamingContainer): Promise { function sessionState(container: AdminStreamingContainer): string { const session = container.session; + // A drain marker holds the container with nobody behind it, so there is no + // session to describe and calling it idle invites a claim that still fails. + if (container.draining) return t("settings.streaming-draining"); if (!session) return t("settings.streaming-idle"); return [ session.desktop @@ -183,7 +186,11 @@ onMounted(load); variant="outlined" density="compact" prepend-icon="mdi-desktop-classic" - :disabled="!container.configured || !!container.session" + :disabled=" + !container.configured || + !!container.session || + !!container.draining + " @click="openDesktop(container)" > {{ t("settings.streaming-open-desktop") }} diff --git a/frontend/src/v2/views/Player/Desktop.test.ts b/frontend/src/v2/views/Player/Desktop.test.ts index cdd893a2b..fb7eb0b76 100644 --- a/frontend/src/v2/views/Player/Desktop.test.ts +++ b/frontend/src/v2/views/Player/Desktop.test.ts @@ -1,4 +1,5 @@ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { AxiosError } from "axios"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { defineComponent } from "vue"; import Desktop from "./Desktop.vue"; @@ -77,6 +78,20 @@ async function openDesktop(): Promise { return mounted; } +async function refuseDesktop(detail: unknown): Promise { + mocks.claimDesktop.mockRejectedValue( + Object.assign(new AxiosError("HTTP 409"), { + response: { status: 409, data: { detail } }, + }), + ); + mounted = mount(Desktop, { + shallow: true, + global: { stubs: { StreamStage: StreamStageStub } }, + }); + await flushPromises(); + return mounted; +} + function vmOf(wrapper: VueWrapper): DesktopVm { return wrapper.vm as unknown as DesktopVm; } @@ -130,3 +145,34 @@ describe("Desktop session-ended notices", () => { expect(mocks.releaseSession).not.toHaveBeenCalled(); }); }); + +describe("Desktop refused claims", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + mounted?.unmount(); + mounted = null; + }); + + it("names the game holding the container", async () => { + const wrapper = await refuseDesktop({ + rom_name: "Ico", + claimed_at: "2026-09-17T10:00:00", + draining: false, + }); + + expect(vmOf(wrapper).errorMessage).toBe("play.desktop-error-occupied"); + }); + + it("says to come back when the container is still saving", async () => { + const wrapper = await refuseDesktop({ + rom_name: null, + claimed_at: null, + draining: true, + }); + + expect(vmOf(wrapper).errorMessage).toBe("play.stream-occupied-draining"); + }); +}); diff --git a/frontend/src/v2/views/Player/Desktop.vue b/frontend/src/v2/views/Player/Desktop.vue index 3f3cd4da0..f9c502e4c 100644 --- a/frontend/src/v2/views/Player/Desktop.vue +++ b/frontend/src/v2/views/Player/Desktop.vue @@ -61,7 +61,15 @@ async function openDesktop(): Promise { } catch (err: unknown) { state.value = "error"; const status = isAxiosError(err) ? err.response?.status : undefined; - if (status === 409) errorMessage.value = t("play.desktop-error-occupied"); + const detail: unknown = isAxiosError(err) + ? err.response?.data?.detail + : undefined; + if (status === 409) + // A drain marker is nobody's claim: the container comes free on its own + // once the previous session has finished saving. + errorMessage.value = (detail as { draining?: boolean } | null)?.draining + ? t("play.stream-occupied-draining") + : t("play.desktop-error-occupied"); else if (status === 404) errorMessage.value = t("play.desktop-error-no-container"); else errorMessage.value = t("play.desktop-error-server"); From c2e599439fc9e8809ebd489263b05a90c49cc1b8 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 15:28:42 -0500 Subject: [PATCH 008/213] fix(streaming): answer with the container a claim would win /config listed containers with no key, so a platform whose only container is misconfigured showed a Play button that could never stream, and it listed a platform twice when two records spelled it in different case. configured_emulator read the first record in the file rather than the first member of the platform's pool, so the slot ceilings a save or load is checked against could come from an emulator no claim ever reaches. --- backend/endpoints/streaming.py | 10 ++++-- backend/handler/streaming/config.py | 11 ++++-- backend/tests/endpoints/test_streaming.py | 42 +++++++++++++++++++++++ 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 18662f135..a531ba602 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -263,13 +263,19 @@ async def get_config(request: Request) -> StreamingConfigSchema: # platform and the claim decides which container serves it. safe_containers: dict[str, dict[str, Any]] = {} for c in resolve_containers(): - if c.platform in safe_containers: + # No key, no claim: the Play button this entry puts on the platform + # could only ever fail. The fleet view is where the operator sees why. + if not c.key: + continue + # Platforms match case-insensitively everywhere else, so records + # differing only in case are one platform here too. + if c.platform.lower() in safe_containers: continue # The record carries the platform's label and capabilities, so a # platform hidden from this caller must not be listed here either. if not access.platform_is_visible(request, c.platform): continue - safe_containers[c.platform] = { + safe_containers[c.platform.lower()] = { "platform": c.platform, "host": c.host, "label": c.label, diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index f27435342..3bc06c857 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -610,9 +610,14 @@ def container_for_session( def configured_emulator(platform: str) -> str: - """The emulator a configured container serves this platform with, if any.""" - entry = entry_for_platform(resolve_containers(), platform) - return entry.emulator if entry else "" + """The emulator the container a claim wins serves this platform with. + + Empty when no container can be claimed for it: slot ceilings are read off + this, so the answer has to come from the pool a claim walks rather than + from whichever record the file happens to list first. + """ + pool = containers_for_platform(platform) + return pool[0].emulator if pool else "" def streaming_enabled() -> bool: diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index a9ef59611..4e21d66e3 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -53,6 +53,7 @@ from handler.streaming.capabilities import ( from handler.streaming.config import ( ResolvedContainer, _derive_broker_host, + configured_emulator, emulator_display_label, pools_for_platform, reset_cache, @@ -682,6 +683,47 @@ def test_get_config_offers_disc_swap_only_on_a_webstation_container( assert ws_caps["supports_disc_swap"] is True +def test_get_config_leaves_out_a_container_no_claim_can_reach(client, access_token): + """A host with no scheme resolves to no key, so every claim on it fails. + Listing it put a Play button on a platform that could never stream.""" + with _streaming({"platform": "ps2", "host": "192.168.1.10:3000"}): + response = client.get("/api/streaming/config", headers=_auth(access_token)) + assert response.status_code == 200 + assert response.json()["containers"] == [] + + +def test_get_config_lists_a_platform_once_whatever_the_case(client, access_token): + """Platforms are matched case-insensitively everywhere else, so two records + naming one platform in different case are one platform to every claim.""" + with _streaming( + {"platform": "PS2", "host": "http://box-a:3000"}, + {"platform": "ps2", "host": "http://box-b:3000"}, + ): + response = client.get("/api/streaming/config", headers=_auth(access_token)) + assert response.status_code == 200 + assert len(response.json()["containers"]) == 1 + + +def test_configured_emulator_names_the_container_a_claim_wins(client): + """Slot ceilings are read off this emulator, so it has to be the one on the + container a claim lands on, not the first record in the file.""" + with _streaming( + {"platform": "ps2", "host": "192.168.1.10:3000", "emulator": "retroarch"}, + { + "platform": "ps2", + "host": "http://box:3000", + "broker_host": "http://box:8000", + "emulator": "pcsx2", + }, + ): + assert configured_emulator("ps2") == "pcsx2" + + +def test_configured_emulator_is_empty_without_a_claimable_container(client): + with _streaming({"platform": "ps2", "host": "192.168.1.10:3000"}): + assert configured_emulator("ps2") == "" + + # ── Nested platform config ──────────────────────────────────────────────────── From 010e0fba4aba6e79aa19dee78ece9d2bef6d6b50 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 15:36:05 -0500 Subject: [PATCH 009/213] fix(streaming): let a tab that missed launch-ready find its way in The room URL only ever existed in the launch-ready push, so a socket that dropped while the game was coming up left the tab loading forever over a session that was running, with no way out but a release. The session now records the room the launch answered with, the status poll reports it along with the container it was found on, and a loading tab enters the stream on that answer. --- backend/endpoints/responses/streaming.py | 6 +++ backend/endpoints/streaming.py | 11 +++- backend/handler/streaming/launch.py | 5 +- backend/handler/streaming/session_store.py | 12 ++++- backend/tests/endpoints/test_streaming.py | 47 ++++++++++++----- .../models/SessionStatusSchema.ts | 2 + frontend/src/v2/views/Player/Stream.test.ts | 50 ++++++++++++++++++- frontend/src/v2/views/Player/Stream.vue | 23 ++++++++- 8 files changed, 135 insertions(+), 21 deletions(-) diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index cdaa31f3d..e73f064bf 100644 --- a/backend/endpoints/responses/streaming.py +++ b/backend/endpoints/responses/streaming.py @@ -60,6 +60,12 @@ class SessionStatusSchema(BaseModel): extraction_phase: str | None = None """Set while a webstation broker unpacks a pkg or archive, which is the part of a launch long enough that the player needs to see something.""" + host: str | None = None + """The room URL of a session already up, for a tab that missed the + launch-ready push. None until the launch returns.""" + container: str | None = None + """The container the session was found on, so a recovering tab names the + claim it holds on every release and heartbeat.""" termination: SessionTerminationSchema | None = None diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index a531ba602..fdf0c074c 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -219,7 +219,14 @@ async def _session_status( ) if found is not None: container, _, session = found - status: dict[str, Any] = {"status": "active", "platform": platform} + status: dict[str, Any] = { + "status": "active", + "platform": platform, + # 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"), + "container": container.key, + } # 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 # the rest of the session, which is the part that gets polled forever. @@ -1457,7 +1464,7 @@ async def claim_desktop_session( room_url = str(launch_result.get("url", "")) if launch_result else "" host = room_url_on(container.host, room_url) - await stamp_launched(session_key, session) + await stamp_launched(session_key, session, host=host) log.info("desktop session claimed, container=%s", session_key) return DesktopSessionSchema( container=session_key, diff --git a/backend/handler/streaming/launch.py b/backend/handler/streaming/launch.py index 07ff95a21..f064ced16 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -111,7 +111,8 @@ async def run_launch( claim_hold.cancel() log.info("session claimed, platform=%s rom=%s", platform, rom_name) - await stamp_launched(session_key, session) + host = container.protocol.stream_url(container.host, launch_result) + await stamp_launched(session_key, session, host=host) await lifecycle.publish_session_activity(session_key, session) # The webstation broker's deferred load waits for its emulator to report @@ -126,7 +127,7 @@ async def run_launch( LaunchReadyPayload( platform=platform, container=session_key, - host=container.protocol.stream_url(container.host, launch_result), + host=host, resume=resume_pushed if resume_state is not None else None, ).model_dump(), ) diff --git a/backend/handler/streaming/session_store.py b/backend/handler/streaming/session_store.py index 411a4dd44..d3588c652 100644 --- a/backend/handler/streaming/session_store.py +++ b/backend/handler/streaming/session_store.py @@ -425,10 +425,15 @@ async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None: return -async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None: +async def stamp_launched( + session_key: str, claim: dict[str, Any], host: str | None = None +) -> None: """Record that the activate returned, so the status poll stops asking the broker for an extraction phase. + The room URL is recorded with it: the launch reply is the only place it + exists, and the status poll is how a tab that missed the push gets in. + Guarded on the claim it was made for, like `set_session_disc`: an activate outlives the claim when a release lands while it runs, and an unguarded write would stamp a stranger's session or bring a short drain marker back @@ -440,7 +445,10 @@ async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None: try: await mutate_session( session_key, - {"launched_at": datetime.now(timezone.utc).isoformat()}, + { + "launched_at": datetime.now(timezone.utc).isoformat(), + **({"host": host} if host else {}), + }, require=lambda current: same_claim(current, claim), ) except StreamingSessionContended: diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 4e21d66e3..ca251f116 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2652,7 +2652,8 @@ def test_heartbeat_for_unknown_platform_returns_404(client, access_token, rom: R def test_status_reports_active_for_owner(client, access_token, rom: Rom): - with _streaming(_container_for(rom)): + container = _container_for(rom) + with _streaming(container): _claim_ok(client, access_token, rom.id) r = client.get( f"/api/streaming/sessions/{rom.platform_slug}/status", @@ -2664,9 +2665,37 @@ def test_status_reports_active_for_owner(client, access_token, rom: Rom): "platform": rom.platform_slug, "extraction_phase": None, "termination": None, + "host": container["host"], + "container": _key_of(container), } +def test_status_carries_the_room_the_launch_answered_with(client, access_token): + """launch-ready is pushed once: a tab that was reloading when the game came + up has only the poll to find its way back into the stream.""" + rom = _rom_on("ps2") + container = _webstation() + with _streaming(container): + assert _claim_webstation_ok(client, access_token, rom.id).status_code == 202 + r = client.get( + "/api/streaming/sessions/ps2/status", headers=_auth(access_token) + ) + assert r.status_code == 200 + assert r.json()["host"].endswith("/room/x") + assert r.json()["container"] == _key_of(container) + + +def test_a_desktop_records_the_room_it_opened(client, access_token): + """Same recovery for the desktop: the room the activate answered with is + only ever returned once, so the session has to keep it.""" + container = _webstation() + with _streaming(container): + response, _ = _desktop(client, access_token, _key_of(container)) + assert response.status_code == 200 + session = json.loads(_session_raw(container)) + assert session["host"] == response.json()["host"] + + def test_status_does_not_refresh_the_session(client, access_token, rom: Rom): """Status is read-only: polling it must not extend a claim, otherwise a background tab could keep a container hostage without playing.""" @@ -2958,12 +2987,8 @@ def test_status_stops_asking_the_broker_once_the_launch_returned(client, access_ r = client.get( "/api/streaming/sessions/ps2/status", headers=_auth(access_token) ) - assert r.json() == { - "status": "active", - "platform": "ps2", - "extraction_phase": None, - "termination": None, - } + assert r.json()["status"] == "active" + assert r.json()["extraction_phase"] is None broker.assert_not_called() @@ -2980,12 +3005,8 @@ def test_status_on_a_legacy_container_never_asks_for_a_phase( f"/api/streaming/sessions/{rom.platform_slug}/status", headers=_auth(access_token), ) - assert r.json() == { - "status": "active", - "platform": rom.platform_slug, - "extraction_phase": None, - "termination": None, - } + assert r.json()["status"] == "active" + assert r.json()["extraction_phase"] is None broker.assert_not_called() diff --git a/frontend/src/__generated__/models/SessionStatusSchema.ts b/frontend/src/__generated__/models/SessionStatusSchema.ts index 89dbda469..8c5196d31 100644 --- a/frontend/src/__generated__/models/SessionStatusSchema.ts +++ b/frontend/src/__generated__/models/SessionStatusSchema.ts @@ -7,6 +7,8 @@ export type SessionStatusSchema = { status: 'active' | 'ended'; platform: string; extraction_phase?: (string | null); + host?: (string | null); + container?: (string | null); termination?: (SessionTerminationSchema | null); }; diff --git a/frontend/src/v2/views/Player/Stream.test.ts b/frontend/src/v2/views/Player/Stream.test.ts index 6eec15a52..a2f751c4d 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({ claimSession: vi.fn(), fetchConfig: vi.fn(), getRom: vi.fn(), + fetchSessionStatus: vi.fn(), heartbeatSession: vi.fn(), releaseSession: vi.fn(), releaseSessionKeepalive: vi.fn(), @@ -65,7 +66,7 @@ vi.mock("@/stores/streaming", () => ({ containerForPlatform: () => mocks.container, platformCapabilities: () => ({}), fetchConfig: mocks.fetchConfig, - fetchSessionStatus: vi.fn(), + fetchSessionStatus: mocks.fetchSessionStatus, forgetJoinableSession: vi.fn(), heartbeatSession: mocks.heartbeatSession, joinSession: vi.fn(), @@ -368,6 +369,7 @@ type StreamVm = { playerState: string; endedDialogOpen: boolean; holdsClaim: boolean; + containerHost: string; }; function vmOf(wrapper: VueWrapper): StreamVm { @@ -518,3 +520,49 @@ describe("Stream claim hygiene", () => { wrapper.unmount(); }); }); + +describe("Stream launch recovery", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.claimSession.mockResolvedValue(CLAIM); + }); + + 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. + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + mocks.heartbeatSession.mockResolvedValue({ + status: "active", + platform: "gba", + host: "http://webstation-dev:8080/room/x", + container: CLAIM.container, + }); + + await mocks.presenceTick?.(); + await flushPromises(); + + expect(vmOf(wrapper).playerState).toBe("playing"); + expect(vmOf(wrapper).containerHost).toBe( + "http://webstation-dev:8080/room/x", + ); + wrapper.unmount(); + }); + + it("keeps waiting while the launch has no room yet", async () => { + const wrapper = await launch({ picker: false }); + await vmOf(wrapper).onPlay(); + mocks.heartbeatSession.mockResolvedValue({ + status: "active", + platform: "gba", + host: null, + container: CLAIM.container, + }); + + await mocks.presenceTick?.(); + await flushPromises(); + + expect(vmOf(wrapper).playerState).toBe("loading"); + wrapper.unmount(); + }); +}); diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index e3056b7f6..4cfe3952e 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -518,7 +518,7 @@ async function handleSessionStatus( ): Promise { // Null means the poll failed, not that the session is gone. A transient // network error must never tear down a live game. - if (!status || status.status !== "ended") return; + if (!status) return; // Already leaving under our own power (stop, save-and-exit, unload). if (!sessionActive.value) return; // The socket push arrives per-user, not per-platform (one room for every @@ -526,6 +526,11 @@ async function handleSessionStatus( // must not tear down the one actually on screen. if (rom.value && status.platform !== rom.value.platform_slug) return; + if (status.status === "active") { + await enterRunningSession(status); + return; + } + // Leave fullscreen before anything else. RDialog teleports to , // outside the stage, so the notice would otherwise be painted under a // fullscreened stage; and tearing the stage down first would unmount the @@ -549,6 +554,22 @@ async function handleSessionStatus( endedDialogOpen.value = true; } +// launch-ready is pushed once, so a socket that dropped while the game came up +// leaves the tab loading over a session that is running. The poll answers with +// the room the launch recorded, which is the way back in. +async function enterRunningSession(status: SessionStatus): Promise { + if (playerState.value !== "loading" || !status.host) return; + // The 202 named it, except for a tab that came back without one. + claimedContainer.value ??= status.container ?? null; + launchPhase.value = null; + containerHost.value = status.host; + playerState.value = "playing"; + if (fullscreenOnPlay.value) { + await nextTick(); + await stage.value?.enterFullscreen(); + } +} + function dismissEndedDialog(): void { endedDialogOpen.value = false; backToRom(); From f512bead7fe4bebf240c1bee3b85f3020a62def0 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 15:49:33 -0500 Subject: [PATCH 010/213] fix(streaming): hold a claim until the last session's saves are filed An exit pulls the in-game save archive off the container in a detached task, so a claim landing right behind the release hydrated the container from the archive before last and the player lost the session they just finished. The teardown marks the pull pending in Redis before spawning it and clears the marker when the task ends, and a claim waits the marker out before hydrating. The wait is capped so a wedged pull costs one stale hydrate rather than a claim that never answers. --- backend/endpoints/streaming.py | 8 +- backend/handler/streaming/lifecycle.py | 31 +++++-- backend/handler/streaming/saves.py | 45 ++++++++++ backend/tests/endpoints/test_streaming.py | 105 +++++++++++++++++++--- 4 files changed, 169 insertions(+), 20 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index fdf0c074c..375cc9fc6 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -822,6 +822,10 @@ async def claim_session( if resume_state is not None and not resume_after_launch: resume_pushed = await states.push_resume_state(container, resume_state) + # The previous session's exit pull files the archive this claim hydrates + # from, and it runs detached, so it may still be on its way in. + await saves.wait_for_save_pull(request.user.id, rom.id) + archive_path = await _hydrate_saves( request, container, @@ -966,7 +970,7 @@ async def save_and_exit_session( except StreamingSessionContended: released = False - lifecycle.collect_exit_saves(container, session) + await lifecycle.collect_exit_saves(container, session) if not released: log.error("save-and-exit could not give up session %s", session_key) @@ -1598,7 +1602,7 @@ async def force_release_all( await lifecycle.record_play_session(session) await lifecycle.clear_session_activity(container_key, session) await lifecycle.collect_exit_state(container, session, state_slot) - lifecycle.collect_exit_saves(container, session) + await lifecycle.collect_exit_saves(container, session) # Note who ended it before the key goes, so the player's next poll # can explain the stream vanishing. diff --git a/backend/handler/streaming/lifecycle.py b/backend/handler/streaming/lifecycle.py index 8a56edab7..cbb498e98 100644 --- a/backend/handler/streaming/lifecycle.py +++ b/backend/handler/streaming/lifecycle.py @@ -121,7 +121,23 @@ async def quiesce_container( return state_slot -def collect_exit_saves(container: ResolvedContainer, session: dict[str, Any]) -> None: +async def _pull_exit_saves( + user_id: int, + rom_id: int, + container: ResolvedContainer, + broker_session: str | None, +) -> None: + """The spawned half of `collect_exit_saves`, which lets the next claim + through however the pull ended.""" + try: + await saves.pull_saves_to_library(user_id, rom_id, container, broker_session) + finally: + await saves.clear_save_pull_pending(user_id, rom_id) + + +async def collect_exit_saves( + container: ResolvedContainer, session: dict[str, Any] +) -> None: """Start pulling the in-game save archive a stopped session left behind. Fire and forget: the broker keeps the archive after the emulator dies, so @@ -130,7 +146,9 @@ def collect_exit_saves(container: ResolvedContainer, session: dict[str, Any]) -> desktop) has nowhere to file one, so neither schedules anything. One home for the rule: every teardown path files a session's saves the same - way, and under the session's owner rather than whoever ended it. + way, and under the session's owner rather than whoever ended it. The pull is + marked pending here rather than inside the task, so a claim arriving on the + heels of the release waits for it whether the task has started or not. """ rom_id = session.get("rom_id") user_id = session.get("user_id") @@ -140,10 +158,9 @@ def collect_exit_saves(container: ResolvedContainer, session: dict[str, Any]) -> or not isinstance(user_id, int) ): return + await saves.mark_save_pull_pending(user_id, rom_id) background.spawn_sync_task( - saves.pull_saves_to_library( - user_id, rom_id, container, broker_session_id(session) - ) + _pull_exit_saves(user_id, rom_id, container, broker_session_id(session)) ) @@ -359,7 +376,7 @@ async def teardown_released_session( # Awaited, not spawned: the claim is released below. await collect_exit_state(container, session, state_slot) - collect_exit_saves(container, session) + await collect_exit_saves(container, session) log.info("session released, platform=%s", platform) except Exception: @@ -426,7 +443,7 @@ async def _teardown_abandoned_session( await record_play_session(session) await clear_session_activity(session_key, session) await collect_exit_state(container, session, state_slot) - collect_exit_saves(container, session) + await collect_exit_saves(container, session) except Exception: log.exception("abandoned session teardown failed, key=%s", session_key) finally: diff --git a/backend/handler/streaming/saves.py b/backend/handler/streaming/saves.py index a3b00cebb..daa428ead 100644 --- a/backend/handler/streaming/saves.py +++ b/backend/handler/streaming/saves.py @@ -7,12 +7,14 @@ a .zip extension so the whole card set travels as a unit. """ import asyncio +import time from datetime import datetime, timezone from fastapi import HTTPException from handler.database import db_rom_handler, db_save_handler, db_user_handler from handler.filesystem import fs_asset_handler +from handler.redis_handler import async_cache from handler.scan_handler import scan_save from handler.streaming import broker, webstation from handler.streaming.config import ResolvedContainer @@ -22,6 +24,49 @@ from models.rom import Rom from models.user import User from utils.filesystem import sanitize_filename +# An exit files its archive in the background, so a claim landing behind it would +# hydrate from the archive before last. The pull leaves a marker a claim waits out. +SAVE_PULL_WAIT_SECONDS = 20.0 +_SAVE_PULL_KEY_PREFIX = "romm:streaming:save-pull:" +# Backstop for a backend that dies mid-pull: a marker nobody clears would cost +# every later claim on that ROM the full wait. +_SAVE_PULL_TTL_SECONDS = 10 * 60 +_SAVE_PULL_POLL_SECONDS = 0.25 + + +def _save_pull_redis_key(user_id: int, rom_id: int) -> str: + return f"{_SAVE_PULL_KEY_PREFIX}{user_id}:{rom_id}" + + +async def mark_save_pull_pending(user_id: int, rom_id: int) -> None: + await async_cache.set( + _save_pull_redis_key(user_id, rom_id), "1", ex=_SAVE_PULL_TTL_SECONDS + ) + + +async def clear_save_pull_pending(user_id: int, rom_id: int) -> None: + await async_cache.delete(_save_pull_redis_key(user_id, rom_id)) + + +async def wait_for_save_pull( + user_id: int, rom_id: int, budget: float = SAVE_PULL_WAIT_SECONDS +) -> bool: + """Wait for a pull of this user's saves for this ROM to finish filing. + + Returns whether nothing is pending any more. A claim is interactive, so a + wedged pull times out rather than holding the request open. + """ + key = _save_pull_redis_key(user_id, rom_id) + deadline = time.monotonic() + budget + while await async_cache.exists(key): + if time.monotonic() >= deadline: + log.warning( + "gave up waiting for the previous session's saves, rom_id=%d", rom_id + ) + return False + await asyncio.sleep(_SAVE_PULL_POLL_SECONDS) + return True + def fetch_save_archive( container: ResolvedContainer, broker_session_id: str | None = None diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index ca251f116..b57c12b27 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -3107,9 +3107,7 @@ def test_save_and_exit_releases_session_once_the_state_is_pulled( with ( patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), patch("handler.streaming.states.pull_state_to_library", new=AsyncMock()), - # Plain MagicMock: the async original would auto-mock to AsyncMock, - # whose call handed to the mocked spawn is a never-awaited coroutine. - patch("handler.streaming.saves.pull_saves_to_library", new=MagicMock()), + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), patch( "handler.streaming.background.spawn_sync_task", side_effect=spawned.append, @@ -3326,7 +3324,7 @@ def test_save_and_exit_pulls_broker_effective_slot(client, access_token, rom: Ro patch( "handler.streaming.states.pull_state_to_library", new=MagicMock() ) as pull, - patch("handler.streaming.saves.pull_saves_to_library", new=MagicMock()), + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), ): r = client.post( f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", @@ -3353,7 +3351,8 @@ def test_save_and_exit_failed_blocking_save_skips_state_pull( "handler.streaming.states.pull_state_to_library", new=MagicMock() ) as state_pull, patch( - "handler.streaming.saves.pull_saves_to_library", new=MagicMock() + "handler.streaming.saves.pull_saves_to_library", + new_callable=AsyncMock, ) as save_pull, ): r = client.post( @@ -3361,10 +3360,11 @@ def test_save_and_exit_failed_blocking_save_skips_state_pull( json={"slot": 0, "wait": True}, headers=_auth(access_token), ) + spawn.assert_called_once() + asyncio.run(spawn.call_args[0][0]) assert r.status_code == 200 state_pull.assert_not_called() - save_pull.assert_called_once() - spawn.assert_called_once() + save_pull.assert_awaited_once() def test_save_and_exit_holds_the_container_until_the_state_is_pulled( @@ -3380,7 +3380,7 @@ def test_save_and_exit_holds_the_container_until_the_state_is_pulled( with ( patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), patch("handler.streaming.states.pull_state_to_library", new=MagicMock()), - patch("handler.streaming.saves.pull_saves_to_library", new=MagicMock()), + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), patch("handler.streaming.background.spawn_sync_task"), ): r = client.post( @@ -4558,16 +4558,99 @@ def test_release_spawns_saves_pull(client, access_token, rom: Rom): patch("handler.streaming.commands.stop", return_value=None), patch("handler.streaming.background.spawn_sync_task") as spawn, patch( - "handler.streaming.saves.pull_saves_to_library", new=MagicMock() + "handler.streaming.saves.pull_saves_to_library", + new_callable=AsyncMock, ) as pull, ): r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", headers=_auth(access_token), ) + spawn.assert_called_once() + asyncio.run(spawn.call_args[0][0]) assert r.status_code == 200 - spawn.assert_called_once() - assert pull.call_args[0][1] == rom.id + pull.assert_awaited_once() + assert pull.await_args_list[0].args[1] == rom.id + + +def test_an_exit_holds_the_next_claim_until_its_saves_are_filed( + client, access_token, admin_user: User, rom: Rom +): + """The pull runs detached, so a claim landing on the heels of the release + would hydrate the container from the archive before this one.""" + key = saves._save_pull_redis_key(admin_user.id, rom.id) + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + patch("handler.streaming.commands.stop", return_value=None), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.pull_saves_to_library", + new_callable=AsyncMock, + ), + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + # Set by the release itself, not by the task it spawned: a claim + # can arrive before that task has run at all. + assert asyncio.run(async_cache.exists(key)) == 1 + asyncio.run(spawn.call_args[0][0]) + assert asyncio.run(async_cache.exists(key)) == 0 + + +def test_a_claim_waits_for_a_running_save_pull(): + async def scenario() -> bool: + await saves.mark_save_pull_pending(1, 2) + waiter = asyncio.create_task(saves.wait_for_save_pull(1, 2, budget=5)) + await asyncio.sleep(saves._SAVE_PULL_POLL_SECONDS * 2) + assert not waiter.done() + await saves.clear_save_pull_pending(1, 2) + return await waiter + + assert asyncio.run(scenario()) is True + + +def test_a_wedged_save_pull_does_not_hang_the_claim(): + """A claim is an interactive request: a pull that never finishes costs the + player the previous archive, not a claim that never answers.""" + + async def scenario() -> bool: + await saves.mark_save_pull_pending(1, 2) + try: + return await saves.wait_for_save_pull(1, 2, budget=0.1) + finally: + await saves.clear_save_pull_pending(1, 2) + + assert asyncio.run(scenario()) is False + + +def test_a_claim_with_nothing_pending_hydrates_straight_away(): + assert asyncio.run(saves.wait_for_save_pull(1, 2, budget=5)) is True + + +def test_a_claim_waits_for_the_exit_pull_before_hydrating( + client, access_token, rom: Rom +): + order: list[str] = [] + + async def _wait(user_id: int, rom_id: int, budget: float = 0.0) -> bool: + order.append("wait") + return True + + async def _hydrate(*args, **kwargs) -> bool: + order.append("hydrate") + return True + + with _streaming(_container_for(rom)): + with ( + patch("handler.streaming.saves.wait_for_save_pull", new=_wait), + patch("handler.streaming.saves.hydrate_saves_to_broker", new=_hydrate), + ): + r = _claim_ok(client, access_token, rom.id) + assert r.status_code == 202 + assert order == ["wait", "hydrate"] # ── Resume-from-state ───────────────────────────────────────────────────────── From 5233649ebdffcd8079e1c0bc42af49e9f32675fa Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 15:59:57 -0500 Subject: [PATCH 011/213] fix(streaming): join the session the caller asked for An unnamed join stopped at the first pool member holding a live session, so a desktop, another platform's game, the caller's own session or a ROM they cannot see masked the session they were offered and the join answered 404 or handed back somebody else's room. The walk now skips a member that fails the same filter the joinable listing applies and keeps looking, and the Join button carries the container of the row it came from into the stream URL so the join names its session outright. --- backend/endpoints/streaming.py | 17 +++- backend/handler/streaming/access.py | 6 +- backend/tests/endpoints/test_streaming.py | 81 +++++++++++++++++++ .../v2/components/Home/LiveSessionCard.vue | 1 + .../composables/useGameActions/index.test.ts | 13 ++- .../v2/composables/useGameActions/index.ts | 1 + .../useJoinStreamConfirm/index.test.ts | 18 ++++- .../composables/useJoinStreamConfirm/index.ts | 7 +- frontend/src/v2/views/Player/Stream.test.ts | 40 ++++++++- frontend/src/v2/views/Player/Stream.vue | 10 ++- 10 files changed, 179 insertions(+), 15 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 375cc9fc6..390208979 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -93,6 +93,7 @@ from handler.streaming.session_store import ( release_own_session, session_disc_id, session_is_stale, + session_platform_matches, session_redis_key, set_session_disc, stamp_launched, @@ -1096,9 +1097,19 @@ async def join_session( session = await get_live_session(candidate.key) if session is None: continue - if session.get("multiplayer"): - found = (candidate, session) - break + # Same filter the joinable listing applies, so the button and the + # join agree on what is joinable. A member that fails it is not the + # answer and must not mask a later one that is. + if not session.get("multiplayer"): + continue + if not session_platform_matches(session, platform): + continue + if session.get("user_id") == request.user.id: + continue + if not access.session_rom_is_visible(request, session): + continue + found = (candidate, session) + break if found is None: raise HTTPException( diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index 8fbe2c55d..a79517735 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -54,7 +54,7 @@ def rom_is_visible(request: Request, rom: Rom | None) -> bool: return get_permissions(request).can_see_rom(rom.id, rom.platform_id) -def _session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool: +def session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool: """Can the caller see the ROM a session is running?""" rom_id = session.get("rom_id") if rom_id is None: @@ -66,14 +66,14 @@ def assert_session_rom_visible( request: Request, session: dict[str, Any], *, not_found_detail: str ) -> None: """Raise 404 when the session's ROM is hidden from the caller.""" - if not _session_rom_is_visible(request, session): + if not session_rom_is_visible(request, session): raise HTTPException(status_code=404, detail=not_found_detail) def visible_rom_name(request: Request, session: dict[str, Any]) -> str | None: """The name of the ROM a session is running, blanked when the caller cannot see that ROM. "Busy" is safe to report to anyone; what is running is not.""" - if not session or not _session_rom_is_visible(request, session): + if not session or not session_rom_is_visible(request, session): return None name = session.get("rom_name") return str(name) if name else None diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index b57c12b27..f108dade2 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -6679,6 +6679,87 @@ def test_joining_a_rom_on_a_hidden_platform_is_404_masked( join_broker.assert_not_called() +def _ws_pool_member(rom: Rom, index: int, **overrides) -> dict: + """One member of a pool of webstation containers, the broker a joiner + needs. Distinct hosts, so the room URL says which member answered.""" + return _webstation( + **{ + "host": f"http://192.168.1.1{index}:3000", + "broker_host": f"http://192.168.1.1{index}:8000", + "platforms": {rom.platform_slug: "pcsx2"}, + **overrides, + } + ) + + +def _joined_room(url: str = "/webstation/?token=abc"): + return patch("handler.streaming.webstation.join", return_value={"url": url}) + + +def test_joining_walks_past_a_session_whose_rom_is_hidden( + client, + access_token, + editor_access_token, + viewer_access_token, + viewer_user: User, + rom: Rom, + second_rom: Rom, +): + """A hidden ROM earlier in the pool is not the caller's answer, so it must + not mask the joinable session behind it.""" + _hide(PermEntity.ROMS, rom.id, viewer_user.id) + with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)): + _claim_multiplayer(client, access_token, rom.id) + _claim_multiplayer(client, editor_access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_walks_past_the_callers_own_session( + client, access_token, viewer_access_token, rom: Rom, second_rom: Rom +): + """Joining is for somebody else's game: the caller's own session is the one + they already hold, and the listing leaves it out for the same reason.""" + with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)): + _claim_multiplayer(client, viewer_access_token, rom.id) + _claim_multiplayer(client, access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_walks_past_a_session_on_another_platform( + client, + access_token, + editor_access_token, + viewer_access_token, + rom: Rom, + second_rom: Rom, +): + """A container serves several platforms and holds one session, so a member + busy with another platform is not this platform's session to join.""" + member = _ws_pool_member( + rom, 0, platforms={rom.platform_slug: "pcsx2", "ngc": "dolphin"} + ) + with _streaming(member, _ws_pool_member(rom, 1)): + _claim_multiplayer(client, access_token, rom.id) + key = session_store.session_redis_key(_key_of(member)) + session = json.loads(asyncio.run(async_cache.get(key))) + session["platform"] = "ngc" + asyncio.run(async_cache.set(key, json.dumps(session))) + _claim_multiplayer(client, editor_access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + def test_joining_a_solo_session_finds_nothing_to_join( client, access_token, viewer_access_token, rom: Rom ): diff --git a/frontend/src/v2/components/Home/LiveSessionCard.vue b/frontend/src/v2/components/Home/LiveSessionCard.vue index cdd53ac6c..732160240 100644 --- a/frontend/src/v2/components/Home/LiveSessionCard.vue +++ b/frontend/src/v2/components/Home/LiveSessionCard.vue @@ -57,6 +57,7 @@ async function join(): Promise { romId, romName: title.value, hostUsername: props.session.host_username ?? null, + container: props.session.container, }); } diff --git a/frontend/src/v2/composables/useGameActions/index.test.ts b/frontend/src/v2/composables/useGameActions/index.test.ts index 89decddb2..6efafe753 100644 --- a/frontend/src/v2/composables/useGameActions/index.test.ts +++ b/frontend/src/v2/composables/useGameActions/index.test.ts @@ -15,7 +15,7 @@ const canPlayPico8 = { value: false }; const canPlayRuffle = { value: false }; const streamContainer = { value: null as object | null }; const joinableSession = { - value: null as { host_username: string | null } | null, + value: null as { host_username: string | null; container?: string } | null, }; // Granted action keys — `null` means "everything" (the default). const grantedActions: { value: Set | null } = { value: null }; @@ -142,7 +142,10 @@ beforeEach(() => { describe("useGameActions.joinStream", () => { beforeEach(() => { streamContainer.value = { host: "http://stream" }; - joinableSession.value = { host_username: "ada" }; + joinableSession.value = { + host_username: "ada", + container: "http://box:8000", + }; }); it("does not navigate until the user confirms", async () => { @@ -161,7 +164,11 @@ describe("useGameActions.joinStream", () => { await actions.joinStream(); - expect(push).toHaveBeenCalledWith("/rom/1/stream?join=1"); + // The joinable row names the container, and a pool needs it: the stream + // view would otherwise walk the pool and could land on another session. + expect(push).toHaveBeenCalledWith( + "/rom/1/stream?join=1&container=http%3A%2F%2Fbox%3A8000", + ); }); it("names the host in the confirmation", async () => { diff --git a/frontend/src/v2/composables/useGameActions/index.ts b/frontend/src/v2/composables/useGameActions/index.ts index ee751d860..32a3caf2c 100644 --- a/frontend/src/v2/composables/useGameActions/index.ts +++ b/frontend/src/v2/composables/useGameActions/index.ts @@ -376,6 +376,7 @@ export function useGameActions( romId: rom.id, romName: rom.name ?? rom.fs_name_no_ext ?? "", hostUsername: joinHostLabel.value || null, + container: joinableSession.value?.container ?? null, }, ); } diff --git a/frontend/src/v2/composables/useJoinStreamConfirm/index.test.ts b/frontend/src/v2/composables/useJoinStreamConfirm/index.test.ts index 1fcbdef04..501e34353 100644 --- a/frontend/src/v2/composables/useJoinStreamConfirm/index.test.ts +++ b/frontend/src/v2/composables/useJoinStreamConfirm/index.test.ts @@ -14,7 +14,12 @@ vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirmFn, })); -const target = { romId: 1, romName: "Chrono Trigger", hostUsername: "ada" }; +const target = { + romId: 1, + romName: "Chrono Trigger", + hostUsername: "ada", + container: null, +}; describe("useJoinStreamConfirm", () => { beforeEach(() => { @@ -40,6 +45,17 @@ describe("useJoinStreamConfirm", () => { expect(push).toHaveBeenCalledWith("/rom/1/stream?join=1"); }); + it("carries the container into the join URL", async () => { + confirmFn.mockResolvedValue(true); + const { joinStream } = useJoinStreamConfirm(); + + await joinStream({ ...target, container: "http://box:8000" }); + + expect(push).toHaveBeenCalledWith( + "/rom/1/stream?join=1&container=http%3A%2F%2Fbox%3A8000", + ); + }); + it("names the host in the confirmation", async () => { confirmFn.mockResolvedValue(false); const { joinStream } = useJoinStreamConfirm(); diff --git a/frontend/src/v2/composables/useJoinStreamConfirm/index.ts b/frontend/src/v2/composables/useJoinStreamConfirm/index.ts index 0d219317e..5496222c2 100644 --- a/frontend/src/v2/composables/useJoinStreamConfirm/index.ts +++ b/frontend/src/v2/composables/useJoinStreamConfirm/index.ts @@ -11,6 +11,9 @@ export interface JoinStreamTarget { romId: number; romName: string; hostUsername: string | null; + // A pool holds a session per container, so the one being joined has to be + // named rather than left to the backend to pick. + container: string | null; } interface JoinStreamDeps { @@ -35,7 +38,9 @@ export async function confirmJoinStream( confirmText: t("rom.join-session"), }); if (!ok) return; - void router.push(`/rom/${target.romId}/stream?join=1`); + const query = new URLSearchParams({ join: "1" }); + if (target.container) query.set("container", target.container); + void router.push(`/rom/${target.romId}/stream?${query}`); } export function useJoinStreamConfirm() { diff --git a/frontend/src/v2/views/Player/Stream.test.ts b/frontend/src/v2/views/Player/Stream.test.ts index a2f751c4d..6ecd6eb3e 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -1,5 +1,5 @@ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { defineComponent } from "vue"; import type { SaveSchema } from "@/__generated__"; import type { DetailedRom } from "@/stores/roms"; @@ -14,11 +14,13 @@ const mocks = vi.hoisted(() => ({ getRom: vi.fn(), fetchSessionStatus: vi.fn(), heartbeatSession: vi.fn(), + joinSession: vi.fn(), releaseSession: vi.fn(), releaseSessionKeepalive: vi.fn(), container: null as Record | null, presenceTick: null as (() => Promise) | null, socketHandlers: {} as Record unknown>, + query: {} as Record, })); vi.mock("vue-i18n", () => ({ @@ -27,7 +29,7 @@ vi.mock("vue-i18n", () => ({ vi.mock("vue-router", () => ({ onBeforeRouteLeave: vi.fn(), - useRoute: () => ({ params: { rom: "3" }, query: {} }), + useRoute: () => ({ params: { rom: "3" }, query: mocks.query }), useRouter: () => ({ push: vi.fn(), replace: vi.fn() }), })); @@ -69,7 +71,7 @@ vi.mock("@/stores/streaming", () => ({ fetchSessionStatus: mocks.fetchSessionStatus, forgetJoinableSession: vi.fn(), heartbeatSession: mocks.heartbeatSession, - joinSession: vi.fn(), + joinSession: mocks.joinSession, releaseSession: mocks.releaseSession, releaseSessionKeepalive: mocks.releaseSessionKeepalive, saveAndExit: vi.fn(), @@ -566,3 +568,35 @@ describe("Stream launch recovery", () => { wrapper.unmount(); }); }); + +describe("Stream join", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.joinSession.mockResolvedValue({ host: "http://box:3000/room/x" }); + mocks.query = { join: "1", container: "http://box:8000" }; + }); + + afterEach(() => { + mocks.query = {}; + }); + + it("joins the session on the container the game page named", async () => { + // A pool has several sessions on one platform, so without the container + // the join lands on whichever the backend walks to first. + const wrapper = await launch({ picker: false }); + await flushPromises(); + + expect(mocks.joinSession).toHaveBeenCalledWith("gba", "http://box:8000"); + expect(vmOf(wrapper).playerState).toBe("playing"); + wrapper.unmount(); + }); + + it("joins without one when the page had no container to name", async () => { + mocks.query = { join: "1" }; + const wrapper = await launch({ picker: false }); + await flushPromises(); + + expect(mocks.joinSession).toHaveBeenCalledWith("gba", undefined); + wrapper.unmount(); + }); +}); diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index 4cfe3952e..3485aa607 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -137,6 +137,11 @@ useStageActive(gameRunning); // host's session out from under them. const isJoining = route.query.join === "1"; +// Named by the row that offered the join: a pool holds a session per container, +// and an unnamed join takes whichever one the backend walks to first. +const joinContainer = + typeof route.query.container === "string" ? route.query.container : undefined; + // True only while this tab's own claim is held. The teardown paths key off // this rather than the player state, because a joiner reaches "playing" too. const holdsClaim = ref(false); @@ -817,7 +822,10 @@ async function onPlay(cardImport?: MemoryCardImport): Promise { try { if (isJoining) { - const joined = await streamingStore.joinSession(rom.value.platform_slug); + const joined = await streamingStore.joinSession( + rom.value.platform_slug, + joinContainer, + ); await flourish; if ((playerState.value as PlayerState) === "exited") return; containerHost.value = joined.host; From 5021ef2fa027eb39f01b1f3a5894a4df68f404f4 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 16:09:13 -0500 Subject: [PATCH 012/213] fix(streaming): label the Play! emulator and the asset chips Play! served PS2 sessions under the raw id "play", since it was missing from the emulator display names, and the save and state chips showed whatever id the broker recorded because the names never reached the frontend. /config now ships the display names, and the chips and core group heads label an id through them, falling back to the id for one the backend does not name. --- backend/endpoints/responses/streaming.py | 3 +++ backend/endpoints/streaming.py | 5 ++++- backend/handler/streaming/config.py | 7 +++++++ backend/tests/endpoints/test_streaming.py | 10 ++++++++++ .../models/StreamingConfigSchema.ts | 1 + frontend/src/stores/streaming.test.ts | 20 +++++++++++++++++++ frontend/src/stores/streaming.ts | 12 +++++++++++ .../v2/components/shared/AssetChips.test.ts | 15 +++++++++++++- .../src/v2/components/shared/AssetChips.vue | 4 +++- .../v2/components/shared/AssetList.test.ts | 3 +++ .../v2/components/shared/AssetStrip.test.ts | 14 +++++++++++++ .../src/v2/components/shared/AssetStrip.vue | 4 +++- 12 files changed, 94 insertions(+), 4 deletions(-) diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index e73f064bf..49d5f6b8f 100644 --- a/backend/endpoints/responses/streaming.py +++ b/backend/endpoints/responses/streaming.py @@ -35,6 +35,9 @@ class StreamingContainerSchema(BaseModel): class StreamingConfigSchema(BaseModel): enabled: bool containers: list[StreamingContainerSchema] + emulator_labels: dict[str, str] + """Display name per emulator id, so a save or state tagged with one can be + labelled without a second copy of the map on the frontend.""" class SessionTerminationSchema(BaseModel): diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 390208979..f743586f5 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -71,6 +71,7 @@ from handler.streaming.config import ( container_for_session, containers_by_key, containers_for_platform, + emulator_labels, resolve_containers, streaming_enabled, ) @@ -302,7 +303,9 @@ async def get_config(request: Request) -> StreamingConfigSchema: } return StreamingConfigSchema( - enabled=streaming_enabled(), containers=list(safe_containers.values()) + enabled=streaming_enabled(), + containers=list(safe_containers.values()), + emulator_labels=emulator_labels(), ) diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 3bc06c857..f88315e80 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -52,6 +52,7 @@ _EMULATOR_DISPLAY_NAMES: dict[str, str] = { "eden": "Eden", "flycast": "Flycast", "pcsx2": "PCSX2", + "play": "Play!", "ppsspp": "PPSSPP", "rpcs3": "RPCS3", "shadps4": "shadPS4", @@ -121,6 +122,12 @@ _RETROARCH_CORE_NAMES: dict[str, str] = { } +def emulator_labels() -> dict[str, str]: + """Display name per emulator id, for surfaces that label an id they were + handed rather than one they resolved (a save's `emulator`, say).""" + return dict(_EMULATOR_DISPLAY_NAMES) + + def emulator_display_label(emulator: str, platform: str) -> str: """Play-button text for an emulator serving a platform, e.g. "PCSX2" or "RA PPSSPP". Unknown emulators fall back to their configured name.""" diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index f108dade2..bddf1d116 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -320,6 +320,16 @@ def test_get_config_ships_platform_capabilities(client, access_token): } +def test_get_config_ships_the_emulator_labels(client, access_token): + """Saves and states are tagged with the emulator that wrote them, so the + display names ride along rather than being copied into the frontend.""" + with _streaming({"platform": "ps2", "host": "http://192.168.1.10:3000"}): + r = client.get("/api/streaming/config", headers=_auth(access_token)) + labels = r.json()["emulator_labels"] + assert labels["pcsx2"] == "PCSX2" + assert labels["play"] == "Play!" + + def test_get_config_ships_capabilities_for_a_retroarch_platform(client, access_token): """RetroArch serves dozens of platforms, none of them listed by name. Without a fallback they all reported no states and the player offered no save diff --git a/frontend/src/__generated__/models/StreamingConfigSchema.ts b/frontend/src/__generated__/models/StreamingConfigSchema.ts index 30daad1bc..eb9b6bb09 100644 --- a/frontend/src/__generated__/models/StreamingConfigSchema.ts +++ b/frontend/src/__generated__/models/StreamingConfigSchema.ts @@ -6,5 +6,6 @@ import type { StreamingContainerSchema } from './StreamingContainerSchema'; export type StreamingConfigSchema = { enabled: boolean; containers: Array; + emulator_labels: Record; }; diff --git a/frontend/src/stores/streaming.test.ts b/frontend/src/stores/streaming.test.ts index 521593193..cdfe14500 100644 --- a/frontend/src/stores/streaming.test.ts +++ b/frontend/src/stores/streaming.test.ts @@ -14,6 +14,7 @@ describe("platformCapabilities disc flags", () => { const store = useStreamingStore(); store.config = { enabled: true, + emulator_labels: {}, containers: [ { platform: "dc", @@ -43,6 +44,25 @@ describe("platformCapabilities disc flags", () => { }); }); +describe("emulator labels", () => { + beforeEach(() => setActivePinia(createPinia())); + + it("names an emulator by the label the backend ships", () => { + const store = useStreamingStore(); + store.config = { + enabled: true, + containers: [], + emulator_labels: { play: "Play!" }, + }; + expect(store.emulatorLabel("play")).toBe("Play!"); + }); + + it("falls back to the id for an emulator it was told nothing about", () => { + const store = useStreamingStore(); + expect(store.emulatorLabel("snes9x")).toBe("snes9x"); + }); +}); + describe("joinable sessions", () => { const listJoinableSessions = streamingApi.listJoinableSessions as unknown as Mock; diff --git a/frontend/src/stores/streaming.ts b/frontend/src/stores/streaming.ts index bc7114ac6..f53080824 100644 --- a/frontend/src/stores/streaming.ts +++ b/frontend/src/stores/streaming.ts @@ -39,6 +39,7 @@ export const useStreamingStore = defineStore("streaming", () => { const config = ref({ enabled: false, containers: [], + emulator_labels: {}, }); const launchingSession = ref(null); const loading = ref(false); @@ -79,6 +80,15 @@ export const useStreamingStore = defineStore("streaming", () => { return container.label || container.emulator || null; } + /** + * What to call an emulator a save or state is tagged with. The backend owns + * the display names, so an id it does not name is shown as it stands. + */ + function emulatorLabel(emulator: string | null | undefined): string { + if (!emulator) return ""; + return config.value.emulator_labels[emulator] ?? emulator; + } + /** * Returns per-platform save-state capabilities for the streaming player UI, * sourced from the container config the backend ships in /config (the single @@ -121,6 +131,7 @@ export const useStreamingStore = defineStore("streaming", () => { config.value = { enabled: data.enabled ?? false, containers: data.containers ?? [], + emulator_labels: data.emulator_labels ?? {}, }; } catch (err) { error.value = String(err); @@ -392,6 +403,7 @@ export const useStreamingStore = defineStore("streaming", () => { isEnabled, containerForPlatform, containerLabelForPlatform, + emulatorLabel, platformCapabilities, fetchConfig, claimSession, diff --git a/frontend/src/v2/components/shared/AssetChips.test.ts b/frontend/src/v2/components/shared/AssetChips.test.ts index 14d21623e..c22b7f0b4 100644 --- a/frontend/src/v2/components/shared/AssetChips.test.ts +++ b/frontend/src/v2/components/shared/AssetChips.test.ts @@ -6,6 +6,11 @@ import AssetChips from "./AssetChips.vue"; vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }), })); +vi.mock("@/stores/streaming", () => ({ + useStreamingStore: () => ({ + emulatorLabel: (id: string) => (id === "play" ? "Play!" : id), + }), +})); const RTag = { props: { text: { type: String, default: "" } }, @@ -14,7 +19,9 @@ const RTag = { const save = { file_size_bytes: 2048, emulator: "snes9x" } as SaveSchema; -function chips(props: { latest?: boolean; showEmulator?: boolean } = {}) { +function chips( + props: { latest?: boolean; showEmulator?: boolean; asset?: SaveSchema } = {}, +) { return mount(AssetChips, { props: { asset: save, ...props }, global: { stubs: { RTag, RIcon: true } }, @@ -29,6 +36,12 @@ describe("AssetChips", () => { expect(wrapper.get(".r-asset-chips__size").text()).toContain("2 KB"); }); + it("names the emulator the way the backend labels it", () => { + const wrapper = chips({ asset: { ...save, emulator: "play" } }); + + expect(wrapper.findAll(".tag").map((el) => el.text())).toEqual(["Play!"]); + }); + it("tags the latest version and can hide the emulator", () => { const wrapper = chips({ latest: true, showEmulator: false }); diff --git a/frontend/src/v2/components/shared/AssetChips.vue b/frontend/src/v2/components/shared/AssetChips.vue index e3e92d6f5..1b2124119 100644 --- a/frontend/src/v2/components/shared/AssetChips.vue +++ b/frontend/src/v2/components/shared/AssetChips.vue @@ -3,6 +3,7 @@ // tag, emulator tag and file size, in one wrapping row. import { RIcon, RTag } from "@v2/lib"; import { useI18n } from "vue-i18n"; +import { useStreamingStore } from "@/stores/streaming"; import { formatBytes } from "@/utils"; import type { Asset } from "@/v2/utils/assets"; @@ -20,6 +21,7 @@ withDefaults( ); const { t } = useI18n(); +const { emulatorLabel } = useStreamingStore();