From 6cc3c09e02b4ca335f06746359a7e56790b6ffed Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 07:50:55 -0500 Subject: [PATCH 01/32] fix(streaming): stack the fleet row actions under the details on phones The two action buttons never shrink, so at phone width they squeezed the container details to nothing: the name wrapped a character at a time and the host and session lines disappeared. On xs the actions now take their own line. The session line also lost the space before the username, since Vue condenses away whitespace between adjacent template blocks; it is now built in script. --- .../components/Settings/StreamingSection.vue | 91 ++++++++++++------- 1 file changed, 56 insertions(+), 35 deletions(-) diff --git a/frontend/src/v2/components/Settings/StreamingSection.vue b/frontend/src/v2/components/Settings/StreamingSection.vue index d735824b6..486e34da2 100644 --- a/frontend/src/v2/components/Settings/StreamingSection.vue +++ b/frontend/src/v2/components/Settings/StreamingSection.vue @@ -93,8 +93,22 @@ async function release(container: AdminStreamingContainer): Promise { function sessionLabel(container: AdminStreamingContainer): string { const session = container.session; if (!session) return t("settings.streaming-idle"); - if (session.desktop) return t("settings.streaming-desktop-session"); - return session.rom_name ?? t("settings.streaming-unknown-game"); + const parts = [ + session.desktop + ? t("settings.streaming-desktop-session") + : (session.rom_name ?? t("settings.streaming-unknown-game")), + ]; + if (session.claimed_at) { + parts.push( + t("settings.streaming-since", { + time: formatTimestamp(session.claimed_at, locale.value), + }), + ); + } + if (session.username) { + parts.push(t("settings.streaming-by", { user: session.username })); + } + return parts.join(" "); } onMounted(load); @@ -164,42 +178,32 @@ onMounted(load); {{ sessionLabel(container) }} - - - - {{ t("settings.streaming-open-desktop") }} - - - {{ t("settings.streaming-release") }} - +
+ + {{ t("settings.streaming-open-desktop") }} + + + {{ t("settings.streaming-release") }} + +
@@ -255,6 +259,23 @@ onMounted(load); white-space: nowrap; } +.r-v2-streaming__actions { + display: flex; + align-items: center; + gap: 12px; + flex-shrink: 0; +} + +/* The actions do not shrink, so on a phone they take their own line under + the details, indented past the icon (18px) and the row gap (12px). */ +html[data-bp~="xs"] .r-v2-streaming__row { + flex-wrap: wrap; +} +html[data-bp~="xs"] .r-v2-streaming__actions { + flex-basis: 100%; + padding-inline-start: 30px; +} + .r-v2-streaming__warning { font-size: var(--r-font-size-xs); color: var(--r-color-danger-fg); From 339308d586f6463d5004953e0ca30c13f7cb5f94 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 07:58:07 -0500 Subject: [PATCH 02/32] fix(streaming): resolve a named container by key, not through the pool An admin ending a session names the container, but the lookup went through containers_for_platform, which drops any container that disagrees with the head of the pool. A second container with a different emulator, card sync, save picker or protocol then 404'd on release, surfacing as "Could not end the session." in the fleet panel, while its session kept holding it. The named lookup now goes through containers_by_key and only checks that the container serves the platform. Owner checks are unchanged. --- backend/handler/streaming/access.py | 14 ++++++++----- backend/tests/endpoints/test_streaming.py | 25 +++++++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index c202c2a0a..20522f252 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -111,15 +111,19 @@ async def resolve_named_container( ) -> tuple[ResolvedContainer, str, dict[str, Any] | None]: """One named container serving a platform, plus whatever session it holds. + Looked up by key rather than through the platform's pool: a container left + out of the pool can still hold a session, and naming it is how that + session gets ended. + Returns (container, session_key, session), the session being None when the container is free or draining. Raises 404 when the key names no container serving this platform. """ - for candidate in containers_for_platform(platform): - session_key = candidate.key - if session_key != container_key: - continue - return candidate, session_key, await get_live_session(session_key) + entries = containers_by_key().get(container_key, []) if container_key else [] + lower = platform.lower() + for candidate in entries: + if candidate.platform.lower() == lower: + return candidate, container_key, await get_live_session(container_key) raise HTTPException( status_code=404, detail=f"No streaming container '{container_key}' for platform '{platform}'", diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index ba723c0f3..786c4fef2 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1374,6 +1374,31 @@ def test_admin_release_rejects_a_container_that_serves_another_platform( assert r.status_code == 404 +def test_admin_release_ends_a_session_on_a_container_outside_the_pool( + client, access_token +): + """A second container that disagrees with the first on an emulator is not + a pool member, but its desktop is still a session an admin must be able to + end by naming the container.""" + outside = _webstation( + host="http://192.168.1.11:3000", + broker_host="http://192.168.1.11:8000", + platforms={"ps2": "play", "ngc": "dolphin"}, + ) + with _streaming(_webstation(), outside): + key = _key_of(outside) + 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", + params={"container": key}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "released" + assert _session_raw(outside) is None + + def test_status_finds_the_termination_on_whichever_container_held_it( client, access_token, viewer_access_token, rom: Rom ): From 67b54c6663d35502cd8c78cb393a1b19222ce073 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 08:09:43 -0500 Subject: [PATCH 03/32] review(pr-ready step 2): lay the fleet row on a grid, pin the pool exclusion The phone indent no longer hard-codes the icon size plus the row gap: the row is a grid and the actions span from the details column. sessionState names what the helper now returns, and the regression test asserts the container really is outside the ps2 pool. --- backend/tests/endpoints/test_streaming.py | 1 + .../components/Settings/StreamingSection.vue | 21 +++++++------------ 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 786c4fef2..c504fc669 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1387,6 +1387,7 @@ def test_admin_release_ends_a_session_on_a_container_outside_the_pool( ) with _streaming(_webstation(), outside): key = _key_of(outside) + assert key not in [c.key for c in streaming.containers_for_platform("ps2")] assert _desktop(client, access_token, key)[0].status_code == 200 with patch("handler.streaming.commands.stop", return_value=None): r = client.delete( diff --git a/frontend/src/v2/components/Settings/StreamingSection.vue b/frontend/src/v2/components/Settings/StreamingSection.vue index 486e34da2..3b7ddf996 100644 --- a/frontend/src/v2/components/Settings/StreamingSection.vue +++ b/frontend/src/v2/components/Settings/StreamingSection.vue @@ -90,7 +90,7 @@ async function release(container: AdminStreamingContainer): Promise { } } -function sessionLabel(container: AdminStreamingContainer): string { +function sessionState(container: AdminStreamingContainer): string { const session = container.session; if (!session) return t("settings.streaming-idle"); const parts = [ @@ -177,7 +177,7 @@ onMounted(load); {{ t("settings.streaming-unusable") }} - {{ sessionLabel(container) }} + {{ sessionState(container) }} @@ -219,7 +219,8 @@ onMounted(load); } .r-v2-streaming__row { - display: flex; + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 12px; padding: 12px 16px; @@ -231,7 +232,6 @@ onMounted(load); .r-v2-streaming__icon { color: var(--r-color-fg-muted); - flex-shrink: 0; } .r-v2-streaming__icon--busy { color: var(--r-color-brand-primary); @@ -241,8 +241,6 @@ onMounted(load); display: flex; flex-direction: column; gap: 2px; - flex: 1; - min-width: 0; } .r-v2-streaming__name { @@ -263,17 +261,12 @@ onMounted(load); display: flex; align-items: center; gap: 12px; - flex-shrink: 0; } -/* The actions do not shrink, so on a phone they take their own line under - the details, indented past the icon (18px) and the row gap (12px). */ -html[data-bp~="xs"] .r-v2-streaming__row { - flex-wrap: wrap; -} +/* On a phone the actions would squeeze the details to nothing, so they drop + to their own line under the details column. */ html[data-bp~="xs"] .r-v2-streaming__actions { - flex-basis: 100%; - padding-inline-start: 30px; + grid-column: 2 / -1; } .r-v2-streaming__warning { From bdd661d30ad9a1e17adc90f9bb64c1af13d28bc9 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 08:14:41 -0500 Subject: [PATCH 04/32] simplify(pr-ready step 3): share the per-platform entry lookup, build the state line in one place entry_for_platform backs both container_for_session and resolve_named_container, and the fleet row's state line is assembled in sessionState instead of split across template blocks. --- backend/handler/streaming/access.py | 8 ++++---- backend/handler/streaming/config.py | 16 ++++++++++------ .../v2/components/Settings/StreamingSection.vue | 16 ++++++---------- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index 20522f252..9552c15d1 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -10,6 +10,7 @@ from handler.streaming.config import ( ResolvedContainer, containers_by_key, containers_for_platform, + entry_for_platform, ) from handler.streaming.session_store import get_live_session from models.rom import Rom @@ -120,10 +121,9 @@ async def resolve_named_container( serving this platform. """ entries = containers_by_key().get(container_key, []) if container_key else [] - lower = platform.lower() - for candidate in entries: - if candidate.platform.lower() == lower: - return candidate, container_key, await get_live_session(container_key) + candidate = entry_for_platform(entries, platform) + if candidate is not None: + return candidate, container_key, await get_live_session(container_key) raise HTTPException( status_code=404, detail=f"No streaming container '{container_key}' for platform '{platform}'", diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index db47f958f..6fff5d6f5 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -560,6 +560,14 @@ def containers_by_key() -> dict[str, list[ResolvedContainer]]: return grouped +def entry_for_platform( + entries: list[ResolvedContainer], platform: str +) -> ResolvedContainer | None: + """The record among one container's entries that serves this platform.""" + lower = platform.lower() + return next((e for e in entries if e.platform.lower() == lower), None) + + def container_for_session( grouped: dict[str, list[ResolvedContainer]], container_key: str, platform: Any ) -> ResolvedContainer | None: @@ -569,12 +577,8 @@ def container_for_session( entries = grouped.get(container_key) if not entries: return None - if isinstance(platform, str): - lower = platform.lower() - for entry in entries: - if entry.platform.lower() == lower: - return entry - return entries[0] + entry = entry_for_platform(entries, platform) if isinstance(platform, str) else None + return entry or entries[0] def configured_emulator(platform: str) -> str: diff --git a/frontend/src/v2/components/Settings/StreamingSection.vue b/frontend/src/v2/components/Settings/StreamingSection.vue index 3b7ddf996..49283c71b 100644 --- a/frontend/src/v2/components/Settings/StreamingSection.vue +++ b/frontend/src/v2/components/Settings/StreamingSection.vue @@ -93,22 +93,18 @@ async function release(container: AdminStreamingContainer): Promise { function sessionState(container: AdminStreamingContainer): string { const session = container.session; if (!session) return t("settings.streaming-idle"); - const parts = [ + return [ session.desktop ? t("settings.streaming-desktop-session") : (session.rom_name ?? t("settings.streaming-unknown-game")), - ]; - if (session.claimed_at) { - parts.push( + session.claimed_at && t("settings.streaming-since", { time: formatTimestamp(session.claimed_at, locale.value), }), - ); - } - if (session.username) { - parts.push(t("settings.streaming-by", { user: session.username })); - } - return parts.join(" "); + session.username && t("settings.streaming-by", { user: session.username }), + ] + .filter(Boolean) + .join(" "); } onMounted(load); From 398c088d4930d52ddef86318236dad9b812cace2 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 08:19:22 -0500 Subject: [PATCH 05/32] polish(pr-ready step 4): wrap the fleet row's state line and actions, trim prose At 320px the End session button ran past the row, and below md the state line truncated away who holds the session. The actions now wrap and the state line wraps at every width. Docstrings and the xs comment are cut to the repo's two-line limit. --- backend/handler/streaming/access.py | 5 ++--- backend/tests/endpoints/test_streaming.py | 5 ++--- frontend/src/v2/components/Settings/StreamingSection.vue | 6 ++++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index 9552c15d1..9c0a31e13 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -112,9 +112,8 @@ async def resolve_named_container( ) -> tuple[ResolvedContainer, str, dict[str, Any] | None]: """One named container serving a platform, plus whatever session it holds. - Looked up by key rather than through the platform's pool: a container left - out of the pool can still hold a session, and naming it is how that - session gets ended. + Found by key rather than through the pool, so a session on a container left + out of the pool can still be ended. Returns (container, session_key, session), the session being None when the container is free or draining. Raises 404 when the key names no container diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index c504fc669..8295aabb4 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1377,9 +1377,8 @@ def test_admin_release_rejects_a_container_that_serves_another_platform( def test_admin_release_ends_a_session_on_a_container_outside_the_pool( client, access_token ): - """A second container that disagrees with the first on an emulator is not - a pool member, but its desktop is still a session an admin must be able to - end by naming the container.""" + """A container that disagrees with the pool on an emulator is left out of it, + but an admin can still end its session by naming it.""" outside = _webstation( host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000", diff --git a/frontend/src/v2/components/Settings/StreamingSection.vue b/frontend/src/v2/components/Settings/StreamingSection.vue index 49283c71b..ee9eb6932 100644 --- a/frontend/src/v2/components/Settings/StreamingSection.vue +++ b/frontend/src/v2/components/Settings/StreamingSection.vue @@ -248,6 +248,8 @@ onMounted(load); .r-v2-streaming__state { font-size: var(--r-font-size-xs); color: var(--r-color-fg-muted); +} +.r-v2-streaming__meta { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -255,12 +257,12 @@ onMounted(load); .r-v2-streaming__actions { display: flex; + flex-wrap: wrap; align-items: center; gap: 12px; } -/* On a phone the actions would squeeze the details to nothing, so they drop - to their own line under the details column. */ +/* On a phone the actions drop under the details instead of squeezing them out. */ html[data-bp~="xs"] .r-v2-streaming__actions { grid-column: 2 / -1; } From 753d7c5f43683734ea1edb35ac351c38b6007376 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 09:27:34 -0500 Subject: [PATCH 06/32] fix(streaming): let a desktop heartbeat name its container The heartbeat found the caller's session by scanning the platform's pool, so a desktop on a container the pool leaves out was never refreshed: its last_seen went stale and its claim lapsed with the 6h TTL while the admin was still configuring it. The heartbeat now takes the same optional container key as release and join, refreshes only a session the caller owns, and the desktop view sends its key. Game players still heartbeat by platform. --- backend/endpoints/streaming.py | 34 ++++++++++---- backend/tests/endpoints/test_streaming.py | 56 +++++++++++++++++++++-- frontend/src/services/api/streaming.ts | 8 +++- frontend/src/v2/views/Player/Desktop.vue | 2 +- 4 files changed, 82 insertions(+), 18 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 8af12d740..b5b820276 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -905,7 +905,11 @@ async def save_and_exit_session( @protected_route(router.post, "/sessions/{platform}/heartbeat", [Scope.ROMS_USER_WRITE]) -async def heartbeat_session(request: Request, platform: str) -> SessionStatusSchema: +async def heartbeat_session( + request: Request, + platform: str, + container_key: str | None = Query(default=None, alias="container", max_length=300), +) -> SessionStatusSchema: """Refresh the session's liveness stamp and report whether it still exists. The frontend calls this every ~30s while a session is active. A session @@ -915,17 +919,27 @@ async def heartbeat_session(request: Request, platform: str) -> SessionStatusSch Reports `ended` rather than raising 404 when the caller no longer holds the session, so a force-released player learns why on the poll they are already making rather than watching a dead stream. + + `container` names the claim to refresh, needed for a desktop on a container + the platform's pool leaves out. """ - candidates = containers_for_platform(platform) - if not candidates: - raise HTTPException( - status_code=404, - detail=f"No streaming container configured for platform '{platform}'", + if container_key is not None: + _, session_key, session = await access.resolve_named_container( + platform, container_key ) - found = await access.find_session_for_user(candidates, request.user.id) - if found is None: - return SessionStatusSchema(**await _session_status(platform, request)) - _, session_key, _ = found + if session is None or session.get("user_id") != request.user.id: + return SessionStatusSchema(**await _session_status(platform, request)) + else: + candidates = containers_for_platform(platform) + if not candidates: + raise HTTPException( + status_code=404, + detail=f"No streaming container configured for platform '{platform}'", + ) + found = await access.find_session_for_user(candidates, request.user.id) + if found is None: + return SessionStatusSchema(**await _session_status(platform, request)) + _, session_key, _ = found # Merging rather than writing the copy read above keeps a swap that landed # in between; refusing a draining session keeps a heartbeat from making a diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 8295aabb4..edef85797 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1374,16 +1374,22 @@ def test_admin_release_rejects_a_container_that_serves_another_platform( assert r.status_code == 404 +def _outside_the_ps2_pool() -> dict: + """A second webstation that disagrees with `_webstation()` on the ps2 + emulator, so the ps2 pool leaves it out.""" + return _webstation( + host="http://192.168.1.11:3000", + broker_host="http://192.168.1.11:8000", + platforms={"ps2": "play", "ngc": "dolphin"}, + ) + + def test_admin_release_ends_a_session_on_a_container_outside_the_pool( client, access_token ): """A container that disagrees with the pool on an emulator is left out of it, but an admin can still end its session by naming it.""" - outside = _webstation( - host="http://192.168.1.11:3000", - broker_host="http://192.168.1.11:8000", - platforms={"ps2": "play", "ngc": "dolphin"}, - ) + outside = _outside_the_ps2_pool() with _streaming(_webstation(), outside): key = _key_of(outside) assert key not in [c.key for c in streaming.containers_for_platform("ps2")] @@ -1399,6 +1405,46 @@ def test_admin_release_ends_a_session_on_a_container_outside_the_pool( assert _session_raw(outside) is None +def test_heartbeat_naming_the_container_refreshes_a_desktop_outside_the_pool( + client, access_token +): + """The platform's pool scan cannot see this container, so only the named key + keeps its desktop claim fresh.""" + outside = _outside_the_ps2_pool() + with _streaming(_webstation(), outside): + key = _key_of(outside) + assert _desktop(client, access_token, key)[0].status_code == 200 + _age_session_on(outside, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", + params={"container": key}, + headers=_auth(access_token), + ) + session = json.loads(_session_raw(outside)) + assert r.status_code == 200 + assert r.json()["status"] == "active" + assert not session_store.session_is_stale(session) + + +def test_heartbeat_naming_a_container_leaves_another_users_session_alone( + client, access_token, viewer_access_token +): + outside = _outside_the_ps2_pool() + with _streaming(_webstation(), outside): + key = _key_of(outside) + assert _desktop(client, access_token, key)[0].status_code == 200 + _age_session_on(outside, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", + params={"container": key}, + headers=_auth(viewer_access_token), + ) + session = json.loads(_session_raw(outside)) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert session_store.session_is_stale(session) + + def test_status_finds_the_termination_on_whichever_container_held_it( client, access_token, viewer_access_token, rom: Rom ): diff --git a/frontend/src/services/api/streaming.ts b/frontend/src/services/api/streaming.ts index ea6d99996..644cd34e4 100644 --- a/frontend/src/services/api/streaming.ts +++ b/frontend/src/services/api/streaming.ts @@ -151,8 +151,12 @@ async function saveAndExit(platform: string, slot = 0, wait = true) { }); } -async function heartbeatSession(platform: string) { - return api.post(`/streaming/sessions/${platform}/heartbeat`); +async function heartbeatSession(platform: string, container?: string) { + return api.post( + `/streaming/sessions/${platform}/heartbeat`, + undefined, + { params: { container } }, + ); } async function sessionStatus(platform: string) { diff --git a/frontend/src/v2/views/Player/Desktop.vue b/frontend/src/v2/views/Player/Desktop.vue index be55162fa..ea22c0fdf 100644 --- a/frontend/src/v2/views/Player/Desktop.vue +++ b/frontend/src/v2/views/Player/Desktop.vue @@ -98,7 +98,7 @@ const HEARTBEAT_MS = 30_000; useIntervalFn(() => { if (!holdsClaim.value || !platform.value) return; void streamingApi - .heartbeatSession(platform.value) + .heartbeatSession(platform.value, containerKey.value) .catch((err) => console.warn("[streaming] Could not heartbeat the desktop session:", err), ); From 260d8f4f30c55e147880aa70a19bff28aa436b39 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 09:36:14 -0500 Subject: [PATCH 07/32] review(pr-ready step 2): scope a named heartbeat's status to its container, re-check the owner on write, drop the desktop claim once ended A named heartbeat now reports ended for its own container instead of the pool's status, the refresh refuses a claim that changed hands, and the desktop view stops holding a claim the backend says is gone so its exit cannot release the next holder. --- backend/endpoints/streaming.py | 44 ++++++++++++++++------- backend/tests/endpoints/test_streaming.py | 25 +++++++++++++ frontend/src/v2/views/Player/Desktop.vue | 7 ++++ 3 files changed, 64 insertions(+), 12 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index b5b820276..f09490798 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -215,11 +215,20 @@ async def _session_status(platform: str, request: Request) -> dict[str, Any]: webstation.launch_phase, container ) return status + return await _ended_status( + platform, request.user.id, [candidate.key for candidate in candidates] + ) + + +async def _ended_status( + platform: str, user_id: int, session_keys: list[str] +) -> dict[str, Any]: + """An ended session's status, carrying the caller's termination notice.""" # The tombstone is keyed per container, so with a pool the caller's notice # can sit under any of them. termination = None - for candidate in candidates: - termination = await get_termination(candidate.key, request.user.id) + for session_key in session_keys: + termination = await get_termination(session_key, user_id) if termination is not None: break return { @@ -923,12 +932,23 @@ async def heartbeat_session( `container` names the claim to refresh, needed for a desktop on a container the platform's pool leaves out. """ + user_id = request.user.id + + async def gone() -> SessionStatusSchema: + # A named claim answers for itself: another session the caller holds on + # the platform is not the one this client is beating. + if container_key is None: + return SessionStatusSchema(**await _session_status(platform, request)) + return SessionStatusSchema( + **await _ended_status(platform, user_id, [container_key]) + ) + if container_key is not None: _, session_key, session = await access.resolve_named_container( platform, container_key ) - if session is None or session.get("user_id") != request.user.id: - return SessionStatusSchema(**await _session_status(platform, request)) + if session is None or session.get("user_id") != user_id: + return await gone() else: candidates = containers_for_platform(platform) if not candidates: @@ -936,21 +956,21 @@ async def heartbeat_session( 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, user_id) if found is None: - return SessionStatusSchema(**await _session_status(platform, request)) + return await gone() _, session_key, _ = found # Merging rather than writing the copy read above keeps a swap that landed - # in between; refusing a draining session keeps a heartbeat from making a - # container that is already being torn down look live. Either returns None, - # meaning the claim is gone and reporting "active" would leave the client - # beating a session it no longer holds. + # in between; refusing a draining session, or a claim that changed hands, + # keeps a heartbeat from making a container look live for the wrong holder. + # Either returns None, meaning the claim is gone and reporting "active" + # would leave the client beating a session it no longer holds. try: refreshed = await mutate_session( session_key, {"last_seen": datetime.now(timezone.utc).isoformat()}, - require=lambda s: not s.get("draining"), + require=lambda s: not s.get("draining") and s.get("user_id") == user_id, ) except StreamingSessionContended: # A key too busy to write is a key that exists, so the session is live @@ -958,7 +978,7 @@ async def heartbeat_session( log.warning("heartbeat could not stamp contended session %s", session_key) return SessionStatusSchema(status="active", platform=platform) if refreshed is None: - return SessionStatusSchema(**await _session_status(platform, request)) + return await gone() await lifecycle.refresh_session_activity(session_key, refreshed) return SessionStatusSchema(status="active", platform=platform) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index edef85797..97d820091 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1426,6 +1426,31 @@ def test_heartbeat_naming_the_container_refreshes_a_desktop_outside_the_pool( assert not session_store.session_is_stale(session) +def test_heartbeat_naming_a_released_container_reports_ended(client, access_token): + """A session the caller holds on another of the platform's containers must + not answer for the named one.""" + outside = _outside_the_ps2_pool() + with _streaming(_webstation(), outside): + assert ( + _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 + ) + assert _desktop(client, access_token, _key_of(outside))[0].status_code == 200 + with patch("handler.streaming.commands.stop", return_value=None): + released = client.delete( + "/api/streaming/sessions/ps2", + params={"container": _key_of(outside)}, + headers=_auth(access_token), + ) + assert released.status_code == 200 + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", + params={"container": _key_of(outside)}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + + def test_heartbeat_naming_a_container_leaves_another_users_session_alone( client, access_token, viewer_access_token ): diff --git a/frontend/src/v2/views/Player/Desktop.vue b/frontend/src/v2/views/Player/Desktop.vue index ea22c0fdf..2a977942f 100644 --- a/frontend/src/v2/views/Player/Desktop.vue +++ b/frontend/src/v2/views/Player/Desktop.vue @@ -99,6 +99,13 @@ useIntervalFn(() => { if (!holdsClaim.value || !platform.value) return; void streamingApi .heartbeatSession(platform.value, containerKey.value) + .then(({ data }) => { + // Ended elsewhere: dropping the claim keeps a later exit from releasing + // whoever holds the container next. + if (data.status !== "ended") return; + holdsClaim.value = false; + state.value = "exited"; + }) .catch((err) => console.warn("[streaming] Could not heartbeat the desktop session:", err), ); From e2e35835db7206c98e43f3927f309417876a891f Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 09:41:31 -0500 Subject: [PATCH 08/32] simplify(pr-ready step 3): run a named heartbeat through the pool's lookup, reuse the store heartbeat and entry_for_platform A named container is a one-entry candidate list, so the heartbeat has one lookup and one status answer instead of a closure branching on the key, and it no longer reads the session twice. The desktop view beats through the store wrapper, and configured_emulator shares the platform match. --- backend/endpoints/streaming.py | 65 +++++++++-------------- backend/handler/streaming/access.py | 35 +++++++----- backend/handler/streaming/config.py | 10 ++-- backend/tests/endpoints/test_streaming.py | 7 +-- frontend/src/stores/streaming.ts | 3 +- frontend/src/v2/views/Player/Desktop.vue | 27 +++++----- 6 files changed, 70 insertions(+), 77 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index f09490798..bd39d7d78 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -191,10 +191,16 @@ def _swappable_disc_file_ids(rom: Rom) -> set[int]: return {f.id for f in playlist_files(rom.files)} -async def _session_status(platform: str, request: Request) -> dict[str, Any]: +async def _session_status( + platform: str, + request: Request, + candidates: list[ResolvedContainer] | None = None, +) -> dict[str, Any]: """Whether the caller still holds this platform's session, and if not, why - it ended. Read-only, so it is safe to poll.""" - candidates = containers_for_platform(platform) + it ended. Read-only, so it is safe to poll. `candidates` defaults to the + platform's pool.""" + if candidates is None: + candidates = containers_for_platform(platform) if not candidates: raise HTTPException( status_code=404, @@ -215,20 +221,11 @@ async def _session_status(platform: str, request: Request) -> dict[str, Any]: webstation.launch_phase, container ) return status - return await _ended_status( - platform, request.user.id, [candidate.key for candidate in candidates] - ) - - -async def _ended_status( - platform: str, user_id: int, session_keys: list[str] -) -> dict[str, Any]: - """An ended session's status, carrying the caller's termination notice.""" # The tombstone is keyed per container, so with a pool the caller's notice # can sit under any of them. termination = None - for session_key in session_keys: - termination = await get_termination(session_key, user_id) + for candidate in candidates: + termination = await get_termination(candidate.key, request.user.id) if termination is not None: break return { @@ -933,33 +930,19 @@ async def heartbeat_session( the platform's pool leaves out. """ user_id = request.user.id - - async def gone() -> SessionStatusSchema: - # A named claim answers for itself: another session the caller holds on - # the platform is not the one this client is beating. - if container_key is None: - return SessionStatusSchema(**await _session_status(platform, request)) + # A named claim answers for itself: another session the caller holds on the + # platform is not the one this client is beating. + 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) + if found is None: return SessionStatusSchema( - **await _ended_status(platform, user_id, [container_key]) + **await _session_status(platform, request, candidates) ) - - if container_key is not None: - _, session_key, session = await access.resolve_named_container( - platform, container_key - ) - if session is None or session.get("user_id") != user_id: - return await gone() - else: - candidates = containers_for_platform(platform) - if not candidates: - raise HTTPException( - status_code=404, - detail=f"No streaming container configured for platform '{platform}'", - ) - found = await access.find_session_for_user(candidates, user_id) - if found is None: - return await gone() - _, session_key, _ = found + _, session_key, _ = found # Merging rather than writing the copy read above keeps a swap that landed # in between; refusing a draining session, or a claim that changed hands, @@ -978,7 +961,9 @@ async def heartbeat_session( log.warning("heartbeat could not stamp contended session %s", session_key) return SessionStatusSchema(status="active", platform=platform) if refreshed is None: - return await gone() + return SessionStatusSchema( + **await _session_status(platform, request, candidates) + ) 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 9c0a31e13..edf1b98e1 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -107,25 +107,34 @@ async def find_session_for_user( return None +def named_container(platform: str, container_key: str) -> ResolvedContainer: + """One named container serving a platform. + + Found by key rather than through the pool, so a session on a container left + out of the pool can still be reached. Raises 404 when the key names no + container serving this platform. + """ + candidate = entry_for_platform(containers_by_key().get(container_key, []), platform) + if candidate is None: + raise HTTPException( + status_code=404, + detail=f"No streaming container '{container_key}' for platform '{platform}'", + ) + return candidate + + async def resolve_named_container( platform: str, container_key: str ) -> tuple[ResolvedContainer, str, dict[str, Any] | None]: - """One named container serving a platform, plus whatever session it holds. - - Found by key rather than through the pool, so a session on a container left - out of the pool can still be ended. + """A named container plus whatever session it holds. Returns (container, session_key, session), the session being None when the - container is free or draining. Raises 404 when the key names no container - serving this platform. + container is free or draining. """ - entries = containers_by_key().get(container_key, []) if container_key else [] - candidate = entry_for_platform(entries, platform) - if candidate is not None: - return candidate, container_key, await get_live_session(container_key) - raise HTTPException( - status_code=404, - detail=f"No streaming container '{container_key}' for platform '{platform}'", + return ( + named_container(platform, container_key), + container_key, + await get_live_session(container_key), ) diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 6fff5d6f5..7fd527263 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -9,6 +9,7 @@ from __future__ import annotations import json import secrets +from collections.abc import Sequence from dataclasses import dataclass from typing import Any from urllib.parse import urlparse, urlunparse @@ -561,7 +562,7 @@ def containers_by_key() -> dict[str, list[ResolvedContainer]]: def entry_for_platform( - entries: list[ResolvedContainer], platform: str + entries: Sequence[ResolvedContainer], platform: str ) -> ResolvedContainer | None: """The record among one container's entries that serves this platform.""" lower = platform.lower() @@ -583,11 +584,8 @@ def container_for_session( def configured_emulator(platform: str) -> str: """The emulator a configured container serves this platform with, if any.""" - lower = platform.lower() - for container in resolve_containers(): - if container.platform.lower() == lower: - return container.emulator - return "" + entry = entry_for_platform(resolve_containers(), platform) + return entry.emulator if entry else "" def streaming_enabled() -> bool: diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 97d820091..f260497b3 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1431,20 +1431,21 @@ def test_heartbeat_naming_a_released_container_reports_ended(client, access_toke not answer for the named one.""" outside = _outside_the_ps2_pool() with _streaming(_webstation(), outside): + key = _key_of(outside) assert ( _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 ) - assert _desktop(client, access_token, _key_of(outside))[0].status_code == 200 + assert _desktop(client, access_token, key)[0].status_code == 200 with patch("handler.streaming.commands.stop", return_value=None): released = client.delete( "/api/streaming/sessions/ps2", - params={"container": _key_of(outside)}, + params={"container": key}, headers=_auth(access_token), ) assert released.status_code == 200 r = client.post( "/api/streaming/sessions/ps2/heartbeat", - params={"container": _key_of(outside)}, + params={"container": key}, headers=_auth(access_token), ) assert r.status_code == 200 diff --git a/frontend/src/stores/streaming.ts b/frontend/src/stores/streaming.ts index 12b189e99..4ad1cdf7f 100644 --- a/frontend/src/stores/streaming.ts +++ b/frontend/src/stores/streaming.ts @@ -302,10 +302,11 @@ export const useStreamingStore = defineStore("streaming", () => { */ async function heartbeatSession( platform: string, + container?: string, ): Promise { if (!platform) return null; try { - const { data } = await streamingApi.heartbeatSession(platform); + const { data } = await streamingApi.heartbeatSession(platform, container); return data; } catch (err) { console.warn("[streaming] Could not heartbeat session:", err); diff --git a/frontend/src/v2/views/Player/Desktop.vue b/frontend/src/v2/views/Player/Desktop.vue index 2a977942f..43bc8a93a 100644 --- a/frontend/src/v2/views/Player/Desktop.vue +++ b/frontend/src/v2/views/Player/Desktop.vue @@ -15,6 +15,7 @@ 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 StreamStage from "@/v2/components/Player/StreamStage.vue"; import { useConfirm } from "@/v2/composables/useConfirm"; import { usePageTitle } from "@/v2/composables/usePageTitle"; @@ -23,6 +24,7 @@ const { t } = useI18n(); const route = useRoute(); const router = useRouter(); const confirm = useConfirm(); +const streamingStore = useStreamingStore(); const containerKey = computed(() => String(route.query.container ?? "")); @@ -95,20 +97,17 @@ async function release(): Promise { // stale window, and nothing else here touches the claim. const HEARTBEAT_MS = 30_000; -useIntervalFn(() => { - if (!holdsClaim.value || !platform.value) return; - void streamingApi - .heartbeatSession(platform.value, containerKey.value) - .then(({ data }) => { - // Ended elsewhere: dropping the claim keeps a later exit from releasing - // whoever holds the container next. - if (data.status !== "ended") return; - holdsClaim.value = false; - state.value = "exited"; - }) - .catch((err) => - console.warn("[streaming] Could not heartbeat the desktop session:", err), - ); +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"; }, HEARTBEAT_MS); function backToAdministration(): void { From c62af756214299082228a0e75f200d95e5412b61 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 09:53:01 -0500 Subject: [PATCH 09/32] polish(pr-ready step 4): trim the heartbeat and named-container comments --- backend/endpoints/streaming.py | 12 ++++-------- backend/handler/streaming/access.py | 8 ++------ 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index bd39d7d78..a3d077f5e 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -196,9 +196,8 @@ async def _session_status( request: Request, candidates: list[ResolvedContainer] | None = None, ) -> dict[str, Any]: - """Whether the caller still holds this platform's session, and if not, why - it ended. Read-only, so it is safe to poll. `candidates` defaults to the - platform's pool.""" + """Whether the caller holds a session among `candidates` (the platform's 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: @@ -944,11 +943,8 @@ async def heartbeat_session( ) _, session_key, _ = found - # Merging rather than writing the copy read above keeps a swap that landed - # in between; refusing a draining session, or a claim that changed hands, - # keeps a heartbeat from making a container look live for the wrong holder. - # Either returns None, meaning the claim is gone and reporting "active" - # would leave the client beating a session it no longer holds. + # Merging keeps a swap that landed since the read. Refusing a draining or + # re-claimed session returns None, so the client stops beating a dead claim. try: refreshed = await mutate_session( session_key, diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index edf1b98e1..c070231b1 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -108,12 +108,8 @@ async def find_session_for_user( def named_container(platform: str, container_key: str) -> ResolvedContainer: - """One named container serving a platform. - - Found by key rather than through the pool, so a session on a container left - out of the pool can still be reached. Raises 404 when the key names no - container serving this platform. - """ + """A container serving a platform, found by key so one the pool leaves out + stays reachable. Raises 404 when the key names no such container.""" candidate = entry_for_platform(containers_by_key().get(container_key, []), platform) if candidate is None: raise HTTPException( From f947da377803104b7f52e3c2f78bd5e87a088d25 Mon Sep 17 00:00:00 2001 From: Stuart Anderson Date: Thu, 17 Sep 2026 10:50:28 -0500 Subject: [PATCH 10/32] chore: typecheck frontend/scripts via tsconfig.node.json --- docs/FRONTEND_ARCHITECTURE.md | 19 ++++++++++--------- frontend/package.json | 2 +- frontend/tsconfig.node.json | 14 ++++++++++++++ 3 files changed, 25 insertions(+), 10 deletions(-) create mode 100644 frontend/tsconfig.node.json diff --git a/docs/FRONTEND_ARCHITECTURE.md b/docs/FRONTEND_ARCHITECTURE.md index 47b2468a0..c3cc246ed 100644 --- a/docs/FRONTEND_ARCHITECTURE.md +++ b/docs/FRONTEND_ARCHITECTURE.md @@ -123,7 +123,8 @@ frontend/ ├── index.html # HTML entry point (
) ├── package.json # Dependencies & scripts ├── vite.config.js # Vite build config with plugins -├── tsconfig.json # TypeScript configuration +├── tsconfig.json # Vue app TypeScript (vue-tsc) +├── tsconfig.node.json # Node/Vite tooling TypeScript (tsc -p) ├── eslint.config.js # ESLint flat config ├── .nvmrc # Node 24 │ @@ -1099,14 +1100,14 @@ Procedural SVG generation for: ### Scripts -| Script | Command | Purpose | -| ----------- | ---------------------------- | ----------------------------------- | -| `dev` | `vite --host` | Development server | -| `build` | `vite build` | Production build | -| `preview` | `vite preview` | Preview production build | -| `typecheck` | `vue-tsc` | TypeScript validation | -| `generate` | `openapi-typescript-codegen` | Generate types from backend OpenAPI | -| `lint` | `eslint` | Lint `.vue`, `.js`, `.ts` files | +| Script | Command | Purpose | +| ----------- | -------------------------------------------------------- | ----------------------------------------------------------------------- | +| `dev` | `vite --host` | Development server | +| `build` | `vite build` | Production build | +| `preview` | `vite preview` | Preview production build | +| `typecheck` | `vue-tsc --noEmit && tsc --noEmit -p tsconfig.node.json` | App SFCs (`tsconfig.json`) and Node/Vite tooling (`tsconfig.node.json`) | +| `generate` | `openapi-typescript-codegen` | Generate types from backend OpenAPI | +| `lint` | `eslint` | Lint `.vue`, `.js`, `.ts` files | ### OpenAPI Code Generation diff --git a/frontend/package.json b/frontend/package.json index 27073b501..feeca9d46 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -26,7 +26,7 @@ "dev": "vite --host", "build": "vite build", "preview": "vite preview", - "typecheck": "vue-tsc --noEmit", + "typecheck": "vue-tsc --noEmit && tsc --noEmit -p tsconfig.node.json", "generate": "openapi --input http://127.0.0.1:3000/openapi.json --output ./src/__generated__ --client axios --useOptions --useUnionTypes --exportServices false --exportSchemas false --exportCore false", "test": "vitest run", "test:watch": "vitest", diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json new file mode 100644 index 000000000..c9a97cfe0 --- /dev/null +++ b/frontend/tsconfig.node.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "moduleResolution": "bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["node"] + }, + // Aids `npm run typecheck` in expanding typechecking + // to Node/Vite tooling that vue-tsc does not cover. + "include": ["scripts/**/*.ts"] +} From 9c1e9f4d75a0617c53be93cff8a01e5d8d5778da Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 11:42:18 -0500 Subject: [PATCH 11/32] fix(streaming): put every container in a pool, claim from the first A platform's containers are now grouped into pools of interchangeable members (same emulator, memory card sync, save picker and protocol), so a lone container is a pool of one instead of a skipped non-member. Game claims, status, heartbeats and joins still walk only the first pool, which matches the containers they reached before. The "not a pool member" warning fired on every lookup, one container at a time. It now fires once per config and names every container a game claim can never reach. Named lookups (desktop, admin release, named heartbeat) already reach a container in any pool. --- backend/endpoints/streaming.py | 4 +- backend/handler/streaming/access.py | 4 +- backend/handler/streaming/config.py | 75 +++++++++++------ backend/tests/endpoints/test_streaming.py | 99 +++++++++++++++-------- 4 files changed, 120 insertions(+), 62 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index a3d077f5e..4f9b187d3 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -625,7 +625,7 @@ async def claim_session( The ROM's filesystem path is derived server-side from its database row - the client only supplies a ROM id, never a path. Returns 404 if the ROM doesn't exist or no container serves its platform. - Returns 409 if every container serving the platform is occupied. + Returns 409 if every container in the platform's first pool is occupied. Returns 428 if the container's pre-existing memory card needs a decision. """ rom = db_rom_handler.get_rom(req.rom_id) @@ -926,7 +926,7 @@ async def heartbeat_session( making rather than watching a dead stream. `container` names the claim to refresh, needed for a desktop on a container - the platform's pool leaves out. + outside the platform's first pool. """ user_id = request.user.id # A named claim answers for itself: another session the caller holds on the diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index c070231b1..24f9da43c 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -108,8 +108,8 @@ async def find_session_for_user( def named_container(platform: str, container_key: str) -> ResolvedContainer: - """A container serving a platform, found by key so one the pool leaves out - stays reachable. Raises 404 when the key names no such container.""" + """A container serving a platform, found by key so one in a later pool stays + reachable. Raises 404 when the key names no such container.""" candidate = entry_for_platform(containers_by_key().get(container_key, []), platform) if candidate is None: raise HTTPException( diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 7fd527263..259b4118d 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -3,13 +3,15 @@ The raw YAML is loose: a container may serve one platform or a map of them, and may leave its broker host to be derived. Resolution is memoized until the config changes, so an unusable container is reported once rather than once per lookup. +A platform's containers form pools of interchangeable members, and a game claim +only walks the first. """ from __future__ import annotations import json import secrets -from collections.abc import Sequence +from collections.abc import Iterable, Sequence from dataclasses import dataclass from typing import Any from urllib.parse import urlparse, urlunparse @@ -518,38 +520,61 @@ def resolve_containers() -> tuple[ResolvedContainer, ...]: for row, platform in _platform_entries(dict(entry)): resolved.append(_resolve_one(row, platform, entry.get("label"))) + _warn_about_later_pools(resolved) _cache_fingerprint = fingerprint _cached = tuple(resolved) return _cached -def containers_for_platform(platform: str) -> list[ResolvedContainer]: - """Every container serving a platform, in config order. +def _pools(containers: Iterable[ResolvedContainer]) -> list[list[ResolvedContainer]]: + """Group containers into pools of interchangeable members. A pool sits at its + first member's config position, and members keep config order.""" + pools: list[list[ResolvedContainer]] = [] + for container in containers: + pool = next((p for p in pools if p[0].interchangeable_with(container)), None) + if pool is None: + pools.append([container]) + else: + pool.append(container) + return pools - More than one entry is a pool and the claim takes the first free one, so a - container that disagrees with the head on emulator or card sync is not a - pool member and is left out. - """ - lower = platform.lower() - candidates: list[ResolvedContainer] = [] - for container in resolve_containers(): - if container.platform.lower() != lower: - continue - if not container.key: - # Nothing to dial, so a claim would have nowhere to go. The fleet - # view still lists it, which is where the operator sees why. - continue - if candidates and not candidates[0].interchangeable_with(container): + +def _warn_about_later_pools(resolved: Sequence[ResolvedContainer]) -> None: + """Name every container a game claim can never reach, once per config.""" + by_platform: dict[str, list[ResolvedContainer]] = {} + for container in resolved: + if container.key: + by_platform.setdefault(container.platform.lower(), []).append(container) + for containers in by_platform.values(): + later = [c.key for pool in _pools(containers)[1:] for c in pool] + if later: log.warning( - "container for platform '%s' disagrees with the first one on " - "emulator, memory card sync or protocol, so it is not a pool " - "member, skipping: %s", - platform, - container.key, + "containers for platform '%s' disagree on emulator, memory card " + "sync, save picker or protocol, so game claims only use the first " + "pool; never claimed for a game: %s", + containers[0].platform, + ", ".join(later), ) - continue - candidates.append(container) - return candidates + + +def pools_for_platform(platform: str) -> list[list[ResolvedContainer]]: + """Every container serving a platform, grouped into pools. A container that + matches no other is a pool of one.""" + lower = platform.lower() + return _pools( + container + for container in resolve_containers() + # Nothing to dial, so a claim would have nowhere to go. The fleet view + # still lists it, which is where the operator sees why. + if container.key and container.platform.lower() == lower + ) + + +def containers_for_platform(platform: str) -> list[ResolvedContainer]: + """The platform's first pool, which a game claim walks for the first free + container, in config order.""" + pools = pools_for_platform(platform) + return pools[0] if pools else [] def containers_by_key() -> dict[str, list[ResolvedContainer]]: diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index f260497b3..432f621b0 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -54,6 +54,7 @@ from handler.streaming.config import ( ResolvedContainer, _derive_broker_host, emulator_display_label, + pools_for_platform, reset_cache, resolve_entry, ) @@ -536,7 +537,7 @@ def test_clears_stale_saves_has_no_picker_to_gate_on_a_legacy_container(caplog): assert "clears_stale_saves" in caplog.text -def test_a_container_that_disagrees_on_clearing_saves_is_not_a_pool_member(caplog): +def test_a_container_that_disagrees_on_clearing_saves_is_a_pool_of_its_own(caplog): """The picker is advertised from the head of the pool, so a member that keeps its own newer files would take the pick and silently discard it.""" first = { @@ -562,7 +563,7 @@ def test_a_container_that_disagrees_on_clearing_saves_is_not_a_pool_member(caplo finally: romm_logger.removeHandler(caplog.handler) assert [c.clears_stale_saves for c in candidates] == [True] - assert "not a pool" in caplog.text + assert "never claimed for a game" in caplog.text def test_legacy_containers_still_pool_under_an_inert_clearing_flag(): @@ -1223,6 +1224,21 @@ def test_pool_409s_only_once_every_container_is_held( assert "2 containers" in r3.json()["detail"]["message"] +def test_a_claim_never_lands_in_a_later_pool( + client, access_token, viewer_access_token, rom: Rom +): + """Only the first pool matches the settings a claim is validated against, + so a later pool stays out of reach even when it is the only one free.""" + later = {**_pool_member(rom, 1), "emulator": "other"} + with _streaming(_pool_member(rom, 0), later): + r1 = _claim_ok(client, access_token, rom.id) + r2 = _claim_ok(client, viewer_access_token, rom.id) + assert _session_raw(later) is None + assert r1.status_code == 202 + assert r1.json()["container"] == _key_of(_pool_member(rom, 0)) + assert r2.status_code == 409 + + def test_a_pool_does_not_roll_its_own_holder_onto_a_second_container( client, access_token, rom: Rom ): @@ -1374,9 +1390,9 @@ def test_admin_release_rejects_a_container_that_serves_another_platform( assert r.status_code == 404 -def _outside_the_ps2_pool() -> dict: +def _in_a_later_ps2_pool() -> dict: """A second webstation that disagrees with `_webstation()` on the ps2 - emulator, so the ps2 pool leaves it out.""" + emulator, so it forms a later ps2 pool.""" return _webstation( host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000", @@ -1384,14 +1400,14 @@ def _outside_the_ps2_pool() -> dict: ) -def test_admin_release_ends_a_session_on_a_container_outside_the_pool( +def test_admin_release_ends_a_session_on_a_container_in_a_later_pool( client, access_token ): - """A container that disagrees with the pool on an emulator is left out of it, - but an admin can still end its session by naming it.""" - outside = _outside_the_ps2_pool() - with _streaming(_webstation(), outside): - key = _key_of(outside) + """A game claim never reaches a later pool, but an admin can still end a + session there by naming the container.""" + later = _in_a_later_ps2_pool() + with _streaming(_webstation(), later): + key = _key_of(later) assert key not in [c.key for c in streaming.containers_for_platform("ps2")] assert _desktop(client, access_token, key)[0].status_code == 200 with patch("handler.streaming.commands.stop", return_value=None): @@ -1402,25 +1418,25 @@ def test_admin_release_ends_a_session_on_a_container_outside_the_pool( ) assert r.status_code == 200 assert r.json()["status"] == "released" - assert _session_raw(outside) is None + assert _session_raw(later) is None -def test_heartbeat_naming_the_container_refreshes_a_desktop_outside_the_pool( +def test_heartbeat_naming_the_container_refreshes_a_desktop_in_a_later_pool( client, access_token ): - """The platform's pool scan cannot see this container, so only the named key - keeps its desktop claim fresh.""" - outside = _outside_the_ps2_pool() - with _streaming(_webstation(), outside): - key = _key_of(outside) + """The platform's lookup only walks the first pool, so only the named key + keeps this desktop claim fresh.""" + later = _in_a_later_ps2_pool() + with _streaming(_webstation(), later): + key = _key_of(later) assert _desktop(client, access_token, key)[0].status_code == 200 - _age_session_on(outside, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + _age_session_on(later, session_store._STREAMING_SESSION_STALE_SECONDS + 60) r = client.post( "/api/streaming/sessions/ps2/heartbeat", params={"container": key}, headers=_auth(access_token), ) - session = json.loads(_session_raw(outside)) + session = json.loads(_session_raw(later)) assert r.status_code == 200 assert r.json()["status"] == "active" assert not session_store.session_is_stale(session) @@ -1429,9 +1445,9 @@ def test_heartbeat_naming_the_container_refreshes_a_desktop_outside_the_pool( def test_heartbeat_naming_a_released_container_reports_ended(client, access_token): """A session the caller holds on another of the platform's containers must not answer for the named one.""" - outside = _outside_the_ps2_pool() - with _streaming(_webstation(), outside): - key = _key_of(outside) + later = _in_a_later_ps2_pool() + with _streaming(_webstation(), later): + key = _key_of(later) assert ( _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 ) @@ -1455,17 +1471,17 @@ def test_heartbeat_naming_a_released_container_reports_ended(client, access_toke def test_heartbeat_naming_a_container_leaves_another_users_session_alone( client, access_token, viewer_access_token ): - outside = _outside_the_ps2_pool() - with _streaming(_webstation(), outside): - key = _key_of(outside) + later = _in_a_later_ps2_pool() + with _streaming(_webstation(), later): + key = _key_of(later) assert _desktop(client, access_token, key)[0].status_code == 200 - _age_session_on(outside, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + _age_session_on(later, session_store._STREAMING_SESSION_STALE_SECONDS + 60) r = client.post( "/api/streaming/sessions/ps2/heartbeat", params={"container": key}, headers=_auth(viewer_access_token), ) - session = json.loads(_session_raw(outside)) + session = json.loads(_session_raw(later)) assert r.status_code == 200 assert r.json()["status"] == "ended" assert session_store.session_is_stale(session) @@ -1511,9 +1527,9 @@ def test_heartbeat_refreshes_the_session_on_the_container_that_holds_it( assert after > before -def test_a_container_that_disagrees_on_the_emulator_is_not_a_pool_member(caplog): +def test_a_container_that_disagrees_on_the_emulator_is_a_later_pool(caplog): """Pool members file states and cards in one place, so an entry naming a - different emulator is a separate setup rather than a spare container.""" + different emulator is a pool of its own rather than a spare container.""" first = { "platform": "ps2", "host": "http://192.168.1.10:3000", @@ -1523,16 +1539,33 @@ def test_a_container_that_disagrees_on_the_emulator_is_not_a_pool_member(caplog) second = {**first, "host": "http://192.168.1.11:3000"} second["broker_host"] = "http://192.168.1.11:8000" second["emulator"] = "play" + third = {**first, "host": "http://192.168.1.12:3000"} + third["broker_host"] = "http://192.168.1.12:8000" romm_logger = logging.getLogger("romm") romm_logger.addHandler(caplog.handler) try: - with _streaming(first, second): + with _streaming(first, second, third): with caplog.at_level(logging.WARNING, logger="romm"): + pools = pools_for_platform("ps2") candidates = streaming.containers_for_platform("ps2") finally: romm_logger.removeHandler(caplog.handler) - assert [c.emulator for c in candidates] == ["pcsx2"] - assert "not a pool" in caplog.text + assert [[c.emulator for c in pool] for pool in pools] == [ + ["pcsx2", "pcsx2"], + ["play"], + ] + assert candidates == pools[0] + # Once per config, not once per lookup. + assert caplog.text.count("never claimed for a game") == 1 + assert _key_of(second) in caplog.text + + +def test_a_lone_container_is_a_pool_of_one(rom: Rom): + with _streaming(_pool_member(rom, 0)): + pools = pools_for_platform(rom.platform_slug) + assert [[c.key for c in pool] for pool in pools] == [ + [_key_of(_pool_member(rom, 0))] + ] def test_webstation_pool_members_at_different_subfolders_are_still_a_pool(caplog): @@ -1564,7 +1597,7 @@ def test_webstation_pool_members_at_different_subfolders_are_still_a_pool(caplog "http://192.168.1.10:8000", "http://192.168.1.11:8000", ] - assert "not a pool" not in caplog.text + assert "never claimed for a game" not in caplog.text def test_a_proxied_host_disagreeing_with_its_subfolder_cannot_be_claimed(caplog): From 33aa9080c278a22ba0fd26b158f5031d9b41fa7f Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 11:43:29 -0500 Subject: [PATCH 12/32] review(pr-ready step 2): pin that the later-pool claim test really has two pools --- backend/tests/endpoints/test_streaming.py | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 432f621b0..f45bff061 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1234,6 +1234,7 @@ def test_a_claim_never_lands_in_a_later_pool( r1 = _claim_ok(client, access_token, rom.id) r2 = _claim_ok(client, viewer_access_token, rom.id) assert _session_raw(later) is None + assert len(pools_for_platform(rom.platform_slug)) == 2 assert r1.status_code == 202 assert r1.json()["container"] == _key_of(_pool_member(rom, 0)) assert r2.status_code == 409 From 08f1e0001eff3b6df605a7a09baa57e930158625 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 11:46:22 -0500 Subject: [PATCH 13/32] simplify(pr-ready step 3): group dialable containers per platform in one place, point the claim comment at interchangeable_with --- backend/endpoints/streaming.py | 9 ++++---- backend/handler/streaming/access.py | 2 +- backend/handler/streaming/config.py | 28 ++++++++++++----------- backend/tests/endpoints/test_streaming.py | 7 ++++-- 4 files changed, 25 insertions(+), 21 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 4f9b187d3..44ab71ae4 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -196,8 +196,8 @@ async def _session_status( request: Request, candidates: list[ResolvedContainer] | None = None, ) -> dict[str, Any]: - """Whether the caller holds a session among `candidates` (the platform's pool - by default), and if not, why it ended. Read-only, so it is safe to poll.""" + """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.""" if candidates is None: candidates = containers_for_platform(platform) if not candidates: @@ -645,9 +645,8 @@ async def claim_session( detail=f"No streaming container configured for platform '{platform}'", ) - # Pool members are interchangeable on emulator and card sync (enforced by - # containers_for_platform), so the pre-claim validation below holds for - # whichever one the walk ends up winning. + # Pool members are interchangeable (`ResolvedContainer.interchangeable_with`), + # so the pre-claim validation below holds for whichever one the walk wins. reference = candidates[0] # Validate the resume pick before claiming so a bad state_id cannot diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index 24f9da43c..fefb2cbe4 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -137,7 +137,7 @@ async def resolve_named_container( async def resolve_owned_session( platform: str, request: Request ) -> tuple[ResolvedContainer, str, dict[str, Any]]: - """Find the caller's session among the platform's containers. + """Find the caller's session in the platform's 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 diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 259b4118d..f27435342 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -539,20 +539,29 @@ def _pools(containers: Iterable[ResolvedContainer]) -> list[list[ResolvedContain return pools -def _warn_about_later_pools(resolved: Sequence[ResolvedContainer]) -> None: - """Name every container a game claim can never reach, once per config.""" +def _pools_by_platform( + resolved: Iterable[ResolvedContainer], +) -> dict[str, list[list[ResolvedContainer]]]: + """Every platform's pools, keyed by the lowercased platform.""" by_platform: dict[str, list[ResolvedContainer]] = {} for container in resolved: + # Nothing to dial, so a claim would have nowhere to go. The fleet view + # still lists it, which is where the operator sees why. if container.key: by_platform.setdefault(container.platform.lower(), []).append(container) - for containers in by_platform.values(): - later = [c.key for pool in _pools(containers)[1:] for c in pool] + return {platform: _pools(members) for platform, members in by_platform.items()} + + +def _warn_about_later_pools(resolved: Sequence[ResolvedContainer]) -> None: + """Name every container a game claim can never reach, once per config.""" + for pools in _pools_by_platform(resolved).values(): + later = [c.key for pool in pools[1:] for c in pool] if later: log.warning( "containers for platform '%s' disagree on emulator, memory card " "sync, save picker or protocol, so game claims only use the first " "pool; never claimed for a game: %s", - containers[0].platform, + pools[0][0].platform, ", ".join(later), ) @@ -560,14 +569,7 @@ def _warn_about_later_pools(resolved: Sequence[ResolvedContainer]) -> None: def pools_for_platform(platform: str) -> list[list[ResolvedContainer]]: """Every container serving a platform, grouped into pools. A container that matches no other is a pool of one.""" - lower = platform.lower() - return _pools( - container - for container in resolve_containers() - # Nothing to dial, so a claim would have nowhere to go. The fleet view - # still lists it, which is where the operator sees why. - if container.key and container.platform.lower() == lower - ) + return _pools_by_platform(resolve_containers()).get(platform.lower(), []) def containers_for_platform(platform: str) -> list[ResolvedContainer]: diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index f45bff061..6e87f3ded 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1540,8 +1540,11 @@ def test_a_container_that_disagrees_on_the_emulator_is_a_later_pool(caplog): second = {**first, "host": "http://192.168.1.11:3000"} second["broker_host"] = "http://192.168.1.11:8000" second["emulator"] = "play" - third = {**first, "host": "http://192.168.1.12:3000"} - third["broker_host"] = "http://192.168.1.12:8000" + third = { + **first, + "host": "http://192.168.1.12:3000", + "broker_host": "http://192.168.1.12:8000", + } romm_logger = logging.getLogger("romm") romm_logger.addHandler(caplog.handler) try: From 5eb94afd6adfa074715eb09727c61c5da32fc987 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 11:50:59 -0500 Subject: [PATCH 14/32] polish(pr-ready step 4): build the lone-pool test's member once --- backend/tests/endpoints/test_streaming.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 6e87f3ded..7c6494cb0 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -1565,11 +1565,10 @@ def test_a_container_that_disagrees_on_the_emulator_is_a_later_pool(caplog): def test_a_lone_container_is_a_pool_of_one(rom: Rom): - with _streaming(_pool_member(rom, 0)): + member = _pool_member(rom, 0) + with _streaming(member): pools = pools_for_platform(rom.platform_slug) - assert [[c.key for c in pool] for pool in pools] == [ - [_key_of(_pool_member(rom, 0))] - ] + assert [[c.key for c in pool] for pool in pools] == [[_key_of(member)]] def test_webstation_pool_members_at_different_subfolders_are_still_a_pool(caplog): From 6c7e5875ba829917c8770b31e89e33c3c7605771 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Sep 2026 13:08:10 -0400 Subject: [PATCH 15/32] fix(docker): take the Alpine security patches the pinned bases do not carry The base images are pinned by digest, so the image ships whatever packages were current when upstream last rebuilt them. Alpine backports fixes to its 3.23 repo well ahead of that, leaving known-vulnerable curl, openssl, libexpat, util-linux, libpng and nghttp2 in the published image. `apk upgrade` in production-stage takes those patches, and the same call in python-alias keeps the /usr/lib copy from putting stale libs back. The Alpine digest is also refreshed to 3.23.5, for the builder stages. Co-Authored-By: Claude Opus 5 (1M context) --- docker/Dockerfile | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index cb113bb7e..74d47ac46 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -15,7 +15,7 @@ # ARGUMENT DECLARATIONS ARG ALPINE_VERSION=3.23 -ARG ALPINE_SHA256=25109184c71bdad752c8312a8623239686a9a2071e8825f20acb8f2198c3f659 +ARG ALPINE_SHA256=fd791d74b68913cbb027c6546007b3f0d3bc45125f797758156952bc2d6daf40 # Pins the base image tag, so it cannot read ../.python-version; keep the two in sync. ARG PYTHON_VERSION=3.14 ARG PYTHON_ALPINE_SHA256=8caa2adfeb414dfe68d8b257f7aea9e205a400521c2b13b2d2e5e731fb8e70e5 @@ -29,6 +29,10 @@ ARG UV_SHA256=eb47c391d3a252d9d912270dd2b5e234af5493e92039fedb483f1dd1cb5659ce FROM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION}@sha256:${PYTHON_ALPINE_SHA256} AS python-alias +# production-stage copies /usr/lib from here over its own, so this stage needs +# the same patches, or the stale libs land in the final image. +RUN apk upgrade --no-cache + # FRONTEND BUILD # Built on the native build platform: the output (/front/dist) is static JS/CSS, @@ -217,7 +221,9 @@ RUN git clone https://github.com/evanmiller/mod_zip.git && \ FROM nginx:${NGINX_VERSION}-alpine${ALPINE_VERSION}@sha256:${NGINX_SHA256} AS production-stage ARG WEBSERVER_FOLDER=/var/www/html -RUN apk add --no-cache \ +# Alpine backports security fixes to its repo faster than the base image is +# rebuilt, so the digest pin alone leaves known-vulnerable packages in the image. +RUN apk upgrade --no-cache && apk add --no-cache \ bash \ libarchive-tools \ libmagic \ From cdbc33f65f83506f878eb3c1b6094d8a05b4163e Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Sep 2026 13:08:16 -0400 Subject: [PATCH 16/32] chore(ci): scope workflow permissions to what each job actually uses `read-all` grants the token read on every scope, not just the one a job needs, so replace it with `contents: read`. The job-level `checks: write` and `pull-requests: write` in typecheck, pytest and migrations were writes no step makes; trunk-check keeps `checks: write` for its annotations, and update-hltb-api-url moves its write scopes down to the job that opens the PR. Co-Authored-By: Claude Opus 5 (1M context) --- .github/workflows/e2e.yml | 3 ++- .github/workflows/frontend-v1-frozen.yml | 3 ++- .github/workflows/frontend.yml | 3 ++- .github/workflows/i18n.yml | 3 ++- .github/workflows/migrations.yml | 9 ++------- .github/workflows/pytest.yml | 6 ++---- .github/workflows/trunk-check.yml | 3 ++- .github/workflows/typecheck.yml | 6 ++---- .github/workflows/update-hltb-api-url.yml | 6 ++++-- 9 files changed, 20 insertions(+), 22 deletions(-) diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 82f4f7785..1d09e8279 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -22,7 +22,8 @@ on: - uv.lock - .python-version -permissions: read-all +permissions: + contents: read jobs: e2e: diff --git a/.github/workflows/frontend-v1-frozen.yml b/.github/workflows/frontend-v1-frozen.yml index 9a7fb3593..abe0b50f8 100644 --- a/.github/workflows/frontend-v1-frozen.yml +++ b/.github/workflows/frontend-v1-frozen.yml @@ -16,7 +16,8 @@ on: - "frontend/src/console/**" - "frontend/src/layouts/**" -permissions: read-all +permissions: + contents: read jobs: check-v1-frozen: diff --git a/.github/workflows/frontend.yml b/.github/workflows/frontend.yml index 30cb2af0e..f6369f515 100644 --- a/.github/workflows/frontend.yml +++ b/.github/workflows/frontend.yml @@ -10,7 +10,8 @@ on: paths: - "frontend/**" -permissions: read-all +permissions: + contents: read jobs: test: diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml index 6d3323820..6d93df816 100644 --- a/.github/workflows/i18n.yml +++ b/.github/workflows/i18n.yml @@ -5,7 +5,8 @@ on: paths: - "frontend/src/locales/**/*.json" -permissions: read-all +permissions: + contents: read jobs: check-translations: diff --git a/.github/workflows/migrations.yml b/.github/workflows/migrations.yml index 1d603225a..601f49ea9 100644 --- a/.github/workflows/migrations.yml +++ b/.github/workflows/migrations.yml @@ -9,14 +9,12 @@ on: - uv.lock - .python-version -permissions: read-all +permissions: + contents: read jobs: migrate-postgres: runs-on: ubuntu-latest - permissions: - checks: write - pull-requests: write services: postgres: image: postgres:18 @@ -68,9 +66,6 @@ jobs: # migration SQL that a default utf8mb4 server accepts (issue #4350). name: migrate-mariadb (${{ matrix.mariadb }}, ${{ matrix.collation }}) runs-on: ubuntu-latest - permissions: - checks: write - pull-requests: write strategy: fail-fast: false matrix: diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index c127fc30f..5e96c1b27 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -22,14 +22,12 @@ on: - Dockerfile - docker/Dockerfile -permissions: read-all +permissions: + contents: read jobs: pytest: runs-on: ubuntu-latest - permissions: - checks: write - pull-requests: write strategy: fail-fast: false matrix: diff --git a/.github/workflows/trunk-check.yml b/.github/workflows/trunk-check.yml index 7f21098cb..443778ff8 100644 --- a/.github/workflows/trunk-check.yml +++ b/.github/workflows/trunk-check.yml @@ -10,7 +10,8 @@ concurrency: group: ${{ github.head_ref || github.run_id }} cancel-in-progress: true -permissions: read-all +permissions: + contents: read jobs: trunk_check: diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml index aa505a17f..756a0aa27 100644 --- a/.github/workflows/typecheck.yml +++ b/.github/workflows/typecheck.yml @@ -10,14 +10,12 @@ on: paths: - "frontend/**" -permissions: read-all +permissions: + contents: read jobs: typecheck: runs-on: ubuntu-latest - permissions: - checks: write - pull-requests: write steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/.github/workflows/update-hltb-api-url.yml b/.github/workflows/update-hltb-api-url.yml index 9b45293c3..df0a9e9ff 100644 --- a/.github/workflows/update-hltb-api-url.yml +++ b/.github/workflows/update-hltb-api-url.yml @@ -8,12 +8,14 @@ on: - cron: "0 6 * * 1" permissions: - contents: write - pull-requests: write + contents: read jobs: update-hltb-api-url: runs-on: ubuntu-latest + permissions: + contents: write # For create-pull-request to push the branch + pull-requests: write # For create-pull-request to open the PR steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 From 43ad55624b13e58cf075694989e989c6a715a94f Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Sep 2026 13:18:51 -0400 Subject: [PATCH 17/32] fix(docker): keep the release cache from serving a stale apk upgrade Release builds import a persistent registry cache, and an `apk upgrade` off a fixed base digest has no changing input, so the layer would be reused from a previous release and reship its package set. `no-cache-filters` forces both upgrade stages to run on every release. The Python-side upgrade moves into its own `python-runtime` stage so that busting it does not also rebuild the venv and the sigil bindings. Co-Authored-By: Claude Opus 5 (1M context) --- .github/workflows/build.yml | 5 +++++ docker/Dockerfile | 20 +++++++++++++------- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2341a4b81..70e480857 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -125,6 +125,10 @@ jobs: labels: ${{ steps.meta-slim.outputs.labels }} target: slim-image outputs: type=image,name=${{ env.DIGEST_IMAGE }},push-by-digest=true,name-canonical=true,push=true + # Both stages run `apk upgrade` off a fixed base digest, so nothing in + # them changes between releases and the cache would serve the package + # set of whenever the layer was first built. + no-cache-filters: python-runtime,production-stage # Deliberately not seeded from the preview cache: those layers are # built from PR head content and must not reach a release image. cache-from: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }} @@ -144,6 +148,7 @@ jobs: labels: ${{ steps.meta.outputs.labels }} target: full-image outputs: type=image,name=${{ env.DIGEST_IMAGE }},push-by-digest=true,name-canonical=true,push=true + no-cache-filters: python-runtime,production-stage cache-from: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }} cache-to: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }},mode=max build-args: | diff --git a/docker/Dockerfile b/docker/Dockerfile index 74d47ac46..76628a258 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,4 +1,5 @@ # Stages: +# - python-runtime: Patch the Python image's libraries before they ship # - frontend-build: Build frontend # - backend-build: Build backend environment # - backend-dev-build: Similar to `backend-build`, but also compiles and installs development dependencies @@ -29,8 +30,13 @@ ARG UV_SHA256=eb47c391d3a252d9d912270dd2b5e234af5493e92039fedb483f1dd1cb5659ce FROM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION}@sha256:${PYTHON_ALPINE_SHA256} AS python-alias -# production-stage copies /usr/lib from here over its own, so this stage needs -# the same patches, or the stale libs land in the final image. + +# PATCHED PYTHON RUNTIME +# production-stage copies /usr/lib from here over its own, so these libraries +# need the same patches, or the stale ones land in the final image. Kept apart +# from python-alias so that busting this layer's cache (see `no-cache-filters` +# in build.yml) does not also rebuild the venv and the sigil bindings. +FROM python-alias AS python-runtime RUN apk upgrade --no-cache @@ -240,11 +246,11 @@ RUN apk upgrade --no-cache && apk add --no-cache \ # TODO: Replace with a bundled installation of Python using `uv`, when it is supported. # Related issue: https://github.com/astral-sh/uv/issues/7865 ARG PYTHON_VERSION -COPY --from=python-alias /usr/lib/* /usr/lib/ -COPY --from=python-alias /usr/local/bin/* /usr/local/bin/ -COPY --from=python-alias /usr/local/include/python${PYTHON_VERSION} /usr/local/include/python${PYTHON_VERSION} -COPY --from=python-alias /usr/local/lib/libpython* /usr/local/lib/ -COPY --from=python-alias /usr/local/lib/python${PYTHON_VERSION} /usr/local/lib/python${PYTHON_VERSION} +COPY --from=python-runtime /usr/lib/* /usr/lib/ +COPY --from=python-runtime /usr/local/bin/* /usr/local/bin/ +COPY --from=python-runtime /usr/local/include/python${PYTHON_VERSION} /usr/local/include/python${PYTHON_VERSION} +COPY --from=python-runtime /usr/local/lib/libpython* /usr/local/lib/ +COPY --from=python-runtime /usr/local/lib/python${PYTHON_VERSION} /usr/local/lib/python${PYTHON_VERSION} COPY --from=rahasher-build /RALibretro/bin64/RAHasher /usr/bin/RAHasher COPY --from=nginx-build ./nginx/objs/ngx_http_zip_module.so /usr/lib/nginx/modules/ From 5fe383641f38316cd638b217a35867607db99709 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Thu, 17 Sep 2026 15:44:10 -0500 Subject: [PATCH 18/32] fix(docker): move the bases to Alpine 3.24 and nginx 1.30.5 The image logs a spurious notice on every start: [notice] 113#113: js vm init njs: 00007F16E1CA0B00 njs logs one line per config VM it initialises (nginx/ngx_js.c) and the config imports a single VM at the http level, so it is noise rather than a symptom. njs 0.9.7 removed the line (nginx/njs#1042, nginx/njs#1047), but nginx:1.29.8-alpine was built six days earlier and ships njs 0.9.6. nginx:1.30.5-alpine3.24 ships njs 1.0.1. 1.30 is nginx's stable branch: 1.29.8 was the last mainline of that tree and 1.30.0 the same code a week later. Both branches carry the same-day CVE-2026-90439 fix, so the move gives up no security fix. The nginx tag is what forces the Alpine move: each nginx release ships one Alpine flavour and there is no 1.29.8-alpine3.24. Alpine 3.24 is supported to 2028-06-01, 3.23 only to 2027-11-01. Verified: the repo's own config logs the notice on 1.29.8-alpine and does not on 1.30.5-alpine3.24; mod_zip compiles against release-1.30.5 on the new base; every apk add list in this file resolves on 3.24. Co-Authored-By: Claude Sonnet 5 --- docker/Dockerfile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index cb113bb7e..c32ed8db2 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -14,15 +14,15 @@ # ARGUMENT DECLARATIONS -ARG ALPINE_VERSION=3.23 -ARG ALPINE_SHA256=25109184c71bdad752c8312a8623239686a9a2071e8825f20acb8f2198c3f659 +ARG ALPINE_VERSION=3.24 +ARG ALPINE_SHA256=28bd5fe8b56d1bd048e5babf5b10710ebe0bae67db86916198a6eec434943f8b # Pins the base image tag, so it cannot read ../.python-version; keep the two in sync. ARG PYTHON_VERSION=3.14 -ARG PYTHON_ALPINE_SHA256=8caa2adfeb414dfe68d8b257f7aea9e205a400521c2b13b2d2e5e731fb8e70e5 +ARG PYTHON_ALPINE_SHA256=c6ead215bfd31f1e433d968853b7a769989117115b728874824e6c0a27cb96fc ARG NODE_VERSION=24.16 -ARG NODE_ALPINE_SHA256=2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 -ARG NGINX_VERSION=1.29.8 -ARG NGINX_SHA256=5616878291a2eed594aee8db4dade5878cf7edcb475e59193904b198d9b830de +ARG NODE_ALPINE_SHA256=21f403ab171f2dc89bad4dd69d7721bfd15f084ccb46cdd225f31f2bc59b5c9a +ARG NGINX_VERSION=1.30.5 +ARG NGINX_SHA256=25820c39dba41369486df729ad6697de2fab631ca809e0503e1d1e0c73d9a232 ARG UV_VERSION=0.12.13 ARG UV_SHA256=eb47c391d3a252d9d912270dd2b5e234af5493e92039fedb483f1dd1cb5659ce From c1183109c640c70ae8812ed01df3d4d94f144a6c Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Fri, 18 Sep 2026 00:52:31 +0000 Subject: [PATCH 19/32] build(frontend): prefix CSS in dev as well as production Vendor prefixes were generated only on the build's minify path, so the dev server served `backdrop-filter` with no `-webkit-` twin. caniuse has Safari 16.3-17.6 as supported-with-prefix, which left every glass surface unblurred while developing in Safari below 18.4. Two rules papered over it by hand, and that made production worse: Lightning CSS collapses such a pair to whichever is declared last, dropping the standard property for Chrome, Edge and Firefox. Lightning CSS as the CSS transformer covers both paths from one setting. Dev now serves both properties, verified against the running server. That also retires the hand-rolled browserslist-to-esbuild conversion. It existed because `target: "esnext"` was inherited by `cssTarget`, and Vite's `convertTargets` skips the `esnext` entry, leaving Lightning CSS with no targets at all. Vite's default target resolves to chrome111, edge111, firefox114, safari16.4, ios16.4, which both the transformer and the minifier read, so the converter, both explicit targets and the `browserslist` dependency all go. `.browserslistrc` goes with them: nothing reads it once the conversion is gone. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01BEtFQ17BQDS52wXosTjcUU --- frontend/.browserslistrc | 11 -------- frontend/package-lock.json | 1 - frontend/package.json | 1 - frontend/vite.config.js | 54 +++++++------------------------------- 4 files changed, 10 insertions(+), 57 deletions(-) delete mode 100644 frontend/.browserslistrc diff --git a/frontend/.browserslistrc b/frontend/.browserslistrc deleted file mode 100644 index e8391d6f3..000000000 --- a/frontend/.browserslistrc +++ /dev/null @@ -1,11 +0,0 @@ -# Browser support baseline for the RomM frontend. Matches Tailwind v4's -# minimum targets. This is the single source of truth for browser support: -# vite.config.js derives Lightning CSS's `build.cssTarget` from it (so the -# production build prefixes/down-levels CSS for exactly these browsers), and -# any other tooling reads the same file. Expressed as floors, not pinned -# versions, and the actual version data comes from caniuse-lite. -chrome >= 111 -edge >= 111 -firefox >= 128 -safari >= 16.4 -ios_saf >= 16.4 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 4c1953a30..103b4b64f 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -52,7 +52,6 @@ "@vue/test-utils": "^2.4.9", "@vue/tsconfig": "^0.7.0", "axe-core": "^4.12.1", - "browserslist": "^4.28.8", "eslint": "^10.0.3", "eslint-config-prettier": "^10.1.8", "eslint-plugin-vue": "^10.8.0", diff --git a/frontend/package.json b/frontend/package.json index 27073b501..b14214ccf 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -81,7 +81,6 @@ "@vue/test-utils": "^2.4.9", "@vue/tsconfig": "^0.7.0", "axe-core": "^4.12.1", - "browserslist": "^4.28.8", "eslint": "^10.0.3", "eslint-config-prettier": "^10.1.8", "eslint-plugin-vue": "^10.8.0", diff --git a/frontend/vite.config.js b/frontend/vite.config.js index a72aed72d..fe971f7d3 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -1,6 +1,5 @@ import tailwindcss from "@tailwindcss/vite"; import vue from "@vitejs/plugin-vue"; -import browserslist from "browserslist"; import { URL, fileURLToPath } from "node:url"; import { defineConfig, loadEnv } from "vite"; import mkcert from "vite-plugin-mkcert"; @@ -58,43 +57,6 @@ const VUETIFY_COMPONENTS = [ "vuetify/components/VWindow", ]; -// Maps browserslist browser ids to the esbuild-style ids that Vite's -// `build.cssTarget` understands. Engines not listed here (and_chr, samsung, -// kaios, ...) share a rendering engine with one of these or track "latest", -// so skipping them does not change the emitted prefixes. -const BROWSERSLIST_TO_ESBUILD = { - chrome: "chrome", - edge: "edge", - firefox: "firefox", - ios_saf: "ios", - opera: "opera", - safari: "safari", -}; - -// Translate the shared `.browserslistrc` baseline into Vite's CSS target -// format. Vite 8 minifies CSS with Lightning CSS, which auto-prefixes and -// down-levels from the standard property based on browser targets, but on the -// minify path it only reads `build.cssTarget` (esbuild-style ids), never -// `css.lightningcss.targets`. Deriving it here keeps `.browserslistrc` the -// single source of truth. Without targets Lightning CSS drops the generated -// `-webkit-backdrop-filter`, breaking every glass/blur surface in Safari. -function cssTargetsFromBrowserslist() { - const lowest = {}; - for (const entry of browserslist()) { - const [id, range] = entry.split(" "); - const name = BROWSERSLIST_TO_ESBUILD[id]; - if (!name) continue; - const version = range.split("-")[0]; // "16.4-16.5" -> "16.4" - const asNumber = Number.parseFloat(version); - if (lowest[name] === undefined || asNumber < lowest[name].asNumber) { - lowest[name] = { asNumber, version }; - } - } - return Object.entries(lowest).map( - ([name, { version }]) => `${name}${version}`, - ); -} - // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { // Load ENV variables from the parent directory and the current directory. @@ -113,16 +75,10 @@ export default defineConfig(({ mode }) => { include: VUETIFY_COMPONENTS, }, build: { - target: "esnext", // AudioWorklet.addModule is only dependable with a real URL, and Vite // inlines any asset under 4KB as a data: URI, so keep the worklet out. assetsInlineLimit: (filePath) => filePath.endsWith("pico8AudioWorklet.js") ? false : undefined, - // Browser targets for CSS (prefixing + down-leveling) come from the - // shared `.browserslistrc`. Never hand-write a `-webkit-` twin next to a - // standard property: Lightning CSS collapses the pair to whichever is - // declared last, so let it generate the prefixes from these targets. - cssTarget: cssTargetsFromBrowserslist(), }, plugins: [ tailwindcss(), @@ -157,6 +113,16 @@ export default defineConfig(({ mode }) => { hosts: ["localhost", "127.0.0.1", "romm.dev"], }), ], + // Lightning CSS transforms dev and build alike, so the vendor prefixes it + // generates from Vite's baseline targets reach the dev server too. With + // Vite's default postcss transformer they only appear on the build's + // minify path, and Safari below 18.4 loses every backdrop-filter surface + // while developing. Never hand-write a `-webkit-` twin to paper over that: + // Lightning CSS keeps only the last of the pair, dropping the standard + // property from the bundle. + css: { + transformer: "lightningcss", + }, define: { "process.env": {}, __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true, From ff3cbce1e9c047a2372b94669c5e3634cbe766cb Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Fri, 18 Sep 2026 01:03:27 +0000 Subject: [PATCH 20/32] test(frontend): cover the dev server's CSS prefixing Nothing exercised the dev CSS path: CI's e2e run serves a production build, and vitest.config.ts never loads vite.config.js, so dropping `css.transformer` would leave every check green while Safari below 18.4 lost its blur again. Drives the real config through Vite's programmatic server and asserts both the standard and prefixed properties. Removing the transformer fails it. Also trims the comment above the setting to the two lines the repo allows. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01BEtFQ17BQDS52wXosTjcUU --- frontend/test/devCssPrefixing.test.ts | 30 +++++++++++++++++++++++++ frontend/test/fixtures/prefix-probe.css | 5 +++++ frontend/vite.config.js | 9 ++------ 3 files changed, 37 insertions(+), 7 deletions(-) create mode 100644 frontend/test/devCssPrefixing.test.ts create mode 100644 frontend/test/fixtures/prefix-probe.css diff --git a/frontend/test/devCssPrefixing.test.ts b/frontend/test/devCssPrefixing.test.ts new file mode 100644 index 000000000..afc7e1dc5 --- /dev/null +++ b/frontend/test/devCssPrefixing.test.ts @@ -0,0 +1,30 @@ +import path from "node:path"; +import { createServer, type ViteDevServer } from "vite"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +// The dev server is the only place this is observable: CI's e2e run serves a +// production build, and vitest.config.ts never loads vite.config.js, so a +// dropped `css.transformer` would leave every other check green. +describe("dev server CSS", () => { + let server: ViteDevServer; + + beforeAll(async () => { + server = await createServer({ + configFile: path.resolve(process.cwd(), "vite.config.js"), + server: { middlewareMode: true }, + logLevel: "error", + }); + }, 60_000); + + afterAll(async () => { + await server?.close(); + }); + + it("generates vendor prefixes, not only on the build's minify path", async () => { + const result = await server.transformRequest( + "/test/fixtures/prefix-probe.css", + ); + expect(result?.code).toMatch(/-webkit-backdrop-filter:\s*blur\(1px\)/); + expect(result?.code).toMatch(/[^-]backdrop-filter:\s*blur\(1px\)/); + }); +}); diff --git a/frontend/test/fixtures/prefix-probe.css b/frontend/test/fixtures/prefix-probe.css new file mode 100644 index 000000000..c68eb67ad --- /dev/null +++ b/frontend/test/fixtures/prefix-probe.css @@ -0,0 +1,5 @@ +/* Probed by test/devCssPrefixing.test.ts. `backdrop-filter` needs a + `-webkit-` prefix below Safari 18.4, and the build targets cover it. */ +.prefix-probe { + backdrop-filter: blur(1px); +} diff --git a/frontend/vite.config.js b/frontend/vite.config.js index fe971f7d3..6d36eb58c 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -113,13 +113,8 @@ export default defineConfig(({ mode }) => { hosts: ["localhost", "127.0.0.1", "romm.dev"], }), ], - // Lightning CSS transforms dev and build alike, so the vendor prefixes it - // generates from Vite's baseline targets reach the dev server too. With - // Vite's default postcss transformer they only appear on the build's - // minify path, and Safari below 18.4 loses every backdrop-filter surface - // while developing. Never hand-write a `-webkit-` twin to paper over that: - // Lightning CSS keeps only the last of the pair, dropping the standard - // property from the bundle. + // Prefixes dev too, not just the build's minify path. Never hand-write a + // `-webkit-` twin: Lightning CSS keeps only the last of the pair. css: { transformer: "lightningcss", }, From 0c67e50e1307797ba05f6854fff68de9d66903ae Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Fri, 18 Sep 2026 20:15:13 -0500 Subject: [PATCH 21/32] test(streaming): pin the desktop heartbeat's named container and its ended claim drop (Greptile review) --- frontend/src/v2/views/Player/Desktop.test.ts | 135 +++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 frontend/src/v2/views/Player/Desktop.test.ts 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..83d1aa926 --- /dev/null +++ b/frontend/src/v2/views/Player/Desktop.test.ts @@ -0,0 +1,135 @@ +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(), + heartbeatTick: null as (() => Promise) | null, + routeLeave: null as (() => Promise | boolean) | null, +})); + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); + +vi.mock("vue-router", () => ({ + onBeforeRouteLeave: (guard: () => Promise) => { + mocks.routeLeave = guard; + }, + useRoute: () => ({ query: { container: "WEBSTATION-DEV" } }), + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("@vueuse/core", async (importOriginal) => ({ + ...(await importOriginal()), + // The beat is driven by hand; the pagehide listener stays real. + useIntervalFn: (tick: () => Promise) => { + mocks.heartbeatTick = tick; + }, +})); + +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() })); + +const StreamStageStub = defineComponent({ + props: { active: { type: Boolean, default: false } }, + setup(_, { expose }) { + expose({ + leaveFullscreen: () => Promise.resolve(), + focusStream: () => {}, + }); + return () => null; + }, +}); + +// The view listens on window, so a mount left standing would answer the next +// test's pagehide too. +let mounted: VueWrapper | null = null; + +beforeEach(() => { + vi.clearAllMocks(); +}); + +afterEach(() => { + mounted?.unmount(); + mounted = 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 streamIsLive(wrapper: VueWrapper): boolean | undefined { + return wrapper.findComponent(StreamStageStub).props("active"); +} + +describe("Desktop heartbeats", () => { + it("beats for the container it claimed", async () => { + // Unnamed, the beat only reaches the platform's first pool. + const wrapper = await openDesktop(); + mocks.heartbeatSession.mockResolvedValue({ status: "active" }); + + await mocks.heartbeatTick?.(); + + expect(mocks.heartbeatSession).toHaveBeenCalledWith( + "ps2", + "WEBSTATION-DEV", + ); + expect(streamIsLive(wrapper)).toBe(true); + }); + + it("stops the stream when the beat reports the session ended", async () => { + const wrapper = await openDesktop(); + mocks.heartbeatSession.mockResolvedValue({ status: "ended" }); + + await mocks.heartbeatTick?.(); + await flushPromises(); + + expect(streamIsLive(wrapper)).toBe(false); + }); + + it("releases nothing once the beat ended the claim", async () => { + // The claim is gone, so an exit must not hand back whoever holds the + // container next. + await openDesktop(); + mocks.heartbeatSession.mockResolvedValue({ status: "ended" }); + + await mocks.heartbeatTick?.(); + window.dispatchEvent(new Event("pagehide")); + + expect(await mocks.routeLeave?.()).toBe(true); + expect(mocks.releaseSessionKeepalive).not.toHaveBeenCalled(); + expect(mocks.releaseSession).not.toHaveBeenCalled(); + }); +}); From d7666043599d649bf87fbed49ccf115b065e05c3 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Sat, 19 Sep 2026 17:37:56 -0400 Subject: [PATCH 22/32] feat(frontend): tie gallery sorting to URL query params, add a grid sort-axis selector (#4641) --- frontend/src/locales/bg_BG/gallery.json | 1 + frontend/src/locales/cs_CZ/gallery.json | 1 + frontend/src/locales/de_DE/gallery.json | 1 + frontend/src/locales/en_GB/gallery.json | 1 + frontend/src/locales/en_US/gallery.json | 1 + frontend/src/locales/es_ES/gallery.json | 1 + frontend/src/locales/fr_FR/gallery.json | 1 + frontend/src/locales/hu_HU/gallery.json | 1 + frontend/src/locales/it_IT/gallery.json | 1 + frontend/src/locales/ja_JP/gallery.json | 1 + frontend/src/locales/ko_KR/gallery.json | 1 + frontend/src/locales/pl_PL/gallery.json | 1 + frontend/src/locales/pt_BR/gallery.json | 1 + frontend/src/locales/ro_RO/gallery.json | 1 + frontend/src/locales/ru_RU/gallery.json | 1 + frontend/src/locales/tr_TR/gallery.json | 1 + frontend/src/locales/zh_CN/gallery.json | 1 + frontend/src/locales/zh_TW/gallery.json | 1 + .../v2/components/Gallery/GalleryShell.vue | 56 +++--- .../components/Gallery/GalleryToolbar.test.ts | 96 +++++++++- .../v2/components/Gallery/GalleryToolbar.vue | 54 ++++++ .../v2/components/Gallery/listColumns.test.ts | 32 ++++ .../src/v2/components/Gallery/listColumns.ts | 16 +- .../useGalleryOrderUrl/index.test.ts | 180 ++++++++++++++++++ .../composables/useGalleryOrderUrl/index.ts | 61 ++++++ .../useGalleryViewModeUrl/index.ts | 15 +- .../useGalleryVirtualItems/index.ts | 4 +- .../letterGrouping.test.ts | 35 ++++ frontend/src/v2/stores/galleryRoms.ts | 47 +++-- frontend/src/v2/utils/routeQuery.ts | 13 ++ .../src/v2/views/Gallery/Collection.test.ts | 65 +++++-- frontend/src/v2/views/Gallery/Collection.vue | 6 +- .../src/v2/views/Gallery/Platform.test.ts | 61 +++++- frontend/src/v2/views/Gallery/Platform.vue | 6 +- 34 files changed, 685 insertions(+), 80 deletions(-) create mode 100644 frontend/src/v2/composables/useGalleryOrderUrl/index.test.ts create mode 100644 frontend/src/v2/composables/useGalleryOrderUrl/index.ts create mode 100644 frontend/src/v2/composables/useGalleryVirtualItems/letterGrouping.test.ts diff --git a/frontend/src/locales/bg_BG/gallery.json b/frontend/src/locales/bg_BG/gallery.json index 53cb27722..079732048 100644 --- a/frontend/src/locales/bg_BG/gallery.json +++ b/frontend/src/locales/bg_BG/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Премахни от любими", "selection-unfavorite-success": "{n} са премахнати от любими", "sort-ascending": "Сортирай възходящо", + "sort-by": "Сортирай по", "sort-descending": "Сортирай низходящо", "view-flat": "Плосък изглед", "view-grid": "Решетка", diff --git a/frontend/src/locales/cs_CZ/gallery.json b/frontend/src/locales/cs_CZ/gallery.json index 7d3b7089a..47e53a273 100644 --- a/frontend/src/locales/cs_CZ/gallery.json +++ b/frontend/src/locales/cs_CZ/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Odebrat z oblíbených", "selection-unfavorite-success": "{n} odebráno z oblíbených", "sort-ascending": "Seřadit vzestupně", + "sort-by": "Seřadit podle", "sort-descending": "Seřadit sestupně", "view-flat": "Plochý pohled", "view-grid": "Mřížka", diff --git a/frontend/src/locales/de_DE/gallery.json b/frontend/src/locales/de_DE/gallery.json index d47a44813..e3fc1da44 100644 --- a/frontend/src/locales/de_DE/gallery.json +++ b/frontend/src/locales/de_DE/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Aus Favoriten entfernen", "selection-unfavorite-success": "{n} aus Favoriten entfernt", "sort-ascending": "Aufsteigend sortieren", + "sort-by": "Sortieren nach", "sort-descending": "Absteigend sortieren", "view-flat": "Flache Ansicht", "view-grid": "Raster", diff --git a/frontend/src/locales/en_GB/gallery.json b/frontend/src/locales/en_GB/gallery.json index 101cda682..cf084c935 100644 --- a/frontend/src/locales/en_GB/gallery.json +++ b/frontend/src/locales/en_GB/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Remove from favourites", "selection-unfavorite-success": "{n} removed from favourites", "sort-ascending": "Sort ascending", + "sort-by": "Sort by", "sort-descending": "Sort descending", "view-flat": "Flat view", "view-grid": "Grid", diff --git a/frontend/src/locales/en_US/gallery.json b/frontend/src/locales/en_US/gallery.json index 526c98e66..9a7781dc3 100644 --- a/frontend/src/locales/en_US/gallery.json +++ b/frontend/src/locales/en_US/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Remove from favorites", "selection-unfavorite-success": "{n} removed from favorites", "sort-ascending": "Sort ascending", + "sort-by": "Sort by", "sort-descending": "Sort descending", "view-flat": "Flat view", "view-grid": "Grid", diff --git a/frontend/src/locales/es_ES/gallery.json b/frontend/src/locales/es_ES/gallery.json index 5f769e5c8..6c215a008 100644 --- a/frontend/src/locales/es_ES/gallery.json +++ b/frontend/src/locales/es_ES/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Quitar de favoritos", "selection-unfavorite-success": "{n} quitados de favoritos", "sort-ascending": "Orden ascendente", + "sort-by": "Ordenar por", "sort-descending": "Orden descendente", "view-flat": "Vista plana", "view-grid": "Cuadrícula", diff --git a/frontend/src/locales/fr_FR/gallery.json b/frontend/src/locales/fr_FR/gallery.json index 5ea254a67..7b0cd4799 100644 --- a/frontend/src/locales/fr_FR/gallery.json +++ b/frontend/src/locales/fr_FR/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Retirer des favoris", "selection-unfavorite-success": "{n} retiré(s) des favoris", "sort-ascending": "Trier par ordre croissant", + "sort-by": "Trier par", "sort-descending": "Trier par ordre décroissant", "view-flat": "Vue à plat", "view-grid": "Grille", diff --git a/frontend/src/locales/hu_HU/gallery.json b/frontend/src/locales/hu_HU/gallery.json index 15d96f174..9949047a6 100644 --- a/frontend/src/locales/hu_HU/gallery.json +++ b/frontend/src/locales/hu_HU/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Eltávolítás a kedvencek közül", "selection-unfavorite-success": "{n} eltávolítva a kedvencek közül", "sort-ascending": "Növekvő sorrend", + "sort-by": "Rendezés szerint", "sort-descending": "Csökkenő sorrend", "view-flat": "Sima nézet", "view-grid": "Rács", diff --git a/frontend/src/locales/it_IT/gallery.json b/frontend/src/locales/it_IT/gallery.json index d1420d159..c0aab8eeb 100644 --- a/frontend/src/locales/it_IT/gallery.json +++ b/frontend/src/locales/it_IT/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Rimuovi dai preferiti", "selection-unfavorite-success": "{n} rimossi dai preferiti", "sort-ascending": "Ordina in ordine crescente", + "sort-by": "Ordina per", "sort-descending": "Ordina in ordine decrescente", "view-flat": "Vista piatta", "view-grid": "Griglia", diff --git a/frontend/src/locales/ja_JP/gallery.json b/frontend/src/locales/ja_JP/gallery.json index e748f8469..aeeb2b351 100644 --- a/frontend/src/locales/ja_JP/gallery.json +++ b/frontend/src/locales/ja_JP/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "お気に入りから削除", "selection-unfavorite-success": "{n}件をお気に入りから削除しました", "sort-ascending": "昇順に並び替え", + "sort-by": "並び替え基準", "sort-descending": "降順に並び替え", "view-flat": "フラット表示", "view-grid": "グリッド", diff --git a/frontend/src/locales/ko_KR/gallery.json b/frontend/src/locales/ko_KR/gallery.json index fb7880a66..336cd930c 100644 --- a/frontend/src/locales/ko_KR/gallery.json +++ b/frontend/src/locales/ko_KR/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "즐겨찾기에서 제거", "selection-unfavorite-success": "{n}개를 즐겨찾기에서 제거했습니다", "sort-ascending": "오름차순 정렬", + "sort-by": "정렬 기준", "sort-descending": "내림차순 정렬", "view-flat": "단일 보기", "view-grid": "그리드", diff --git a/frontend/src/locales/pl_PL/gallery.json b/frontend/src/locales/pl_PL/gallery.json index d707121d8..5fea0901b 100644 --- a/frontend/src/locales/pl_PL/gallery.json +++ b/frontend/src/locales/pl_PL/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Usuń z ulubionych", "selection-unfavorite-success": "{n} usunięto z ulubionych", "sort-ascending": "Sortuj rosnąco", + "sort-by": "Sortuj według", "sort-descending": "Sortuj malejąco", "view-flat": "Widok płaski", "view-grid": "Siatka", diff --git a/frontend/src/locales/pt_BR/gallery.json b/frontend/src/locales/pt_BR/gallery.json index 7526a1ad0..adaaf9596 100644 --- a/frontend/src/locales/pt_BR/gallery.json +++ b/frontend/src/locales/pt_BR/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Remover dos favoritos", "selection-unfavorite-success": "{n} removido(s) dos favoritos", "sort-ascending": "Ordenar crescente", + "sort-by": "Ordenar por", "sort-descending": "Ordenar decrescente", "view-flat": "Visualização plana", "view-grid": "Grade", diff --git a/frontend/src/locales/ro_RO/gallery.json b/frontend/src/locales/ro_RO/gallery.json index 57295d695..865db6bde 100644 --- a/frontend/src/locales/ro_RO/gallery.json +++ b/frontend/src/locales/ro_RO/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Elimină din favorite", "selection-unfavorite-success": "{n} eliminate din favorite", "sort-ascending": "Sortează crescător", + "sort-by": "Sortează după", "sort-descending": "Sortează descrescător", "view-flat": "Vizualizare plată", "view-grid": "Grilă", diff --git a/frontend/src/locales/ru_RU/gallery.json b/frontend/src/locales/ru_RU/gallery.json index 7237a6119..d386572f3 100644 --- a/frontend/src/locales/ru_RU/gallery.json +++ b/frontend/src/locales/ru_RU/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Убрать из избранного", "selection-unfavorite-success": "{n} удалено из избранного", "sort-ascending": "Сортировать по возрастанию", + "sort-by": "Сортировать по", "sort-descending": "Сортировать по убыванию", "view-flat": "Плоский вид", "view-grid": "Сетка", diff --git a/frontend/src/locales/tr_TR/gallery.json b/frontend/src/locales/tr_TR/gallery.json index f64b74bfb..0e0260d81 100644 --- a/frontend/src/locales/tr_TR/gallery.json +++ b/frontend/src/locales/tr_TR/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "Favorilerden kaldır", "selection-unfavorite-success": "{n} favorilerden kaldırıldı", "sort-ascending": "Artan sırala", + "sort-by": "Sıralama ölçütü", "sort-descending": "Azalan sırala", "view-flat": "Düz görünüm", "view-grid": "Izgara", diff --git a/frontend/src/locales/zh_CN/gallery.json b/frontend/src/locales/zh_CN/gallery.json index 160285c06..ed8b62c0a 100644 --- a/frontend/src/locales/zh_CN/gallery.json +++ b/frontend/src/locales/zh_CN/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "从喜好中移除", "selection-unfavorite-success": "已从喜好中移除 {n} 个", "sort-ascending": "升序排列", + "sort-by": "排序方式", "sort-descending": "降序排列", "view-flat": "平铺视图", "view-grid": "网格", diff --git a/frontend/src/locales/zh_TW/gallery.json b/frontend/src/locales/zh_TW/gallery.json index 70de68c02..20567ac18 100644 --- a/frontend/src/locales/zh_TW/gallery.json +++ b/frontend/src/locales/zh_TW/gallery.json @@ -27,6 +27,7 @@ "selection-unfavorite": "從喜好中移除", "selection-unfavorite-success": "已從喜好中移除 {n} 個", "sort-ascending": "升冪排序", + "sort-by": "排序方式", "sort-descending": "降冪排序", "view-flat": "平面檢視", "view-grid": "網格", diff --git a/frontend/src/v2/components/Gallery/GalleryShell.vue b/frontend/src/v2/components/Gallery/GalleryShell.vue index f2aba9583..cfd643804 100644 --- a/frontend/src/v2/components/Gallery/GalleryShell.vue +++ b/frontend/src/v2/components/Gallery/GalleryShell.vue @@ -48,6 +48,7 @@ import GameListSkeletonRow from "@/v2/components/Gallery/GameListSkeletonRow.vue import SelectionBar from "@/v2/components/Gallery/SelectionBar.vue"; import { getListMinWidth, + getSortOptions, isListSortKey, LIST_HEADER_HEIGHT_PX, type ListSortKey, @@ -59,6 +60,7 @@ import { useDebugMode } from "@/v2/composables/useDebugMode"; import { useGalleryCoverRatios } from "@/v2/composables/useGalleryCoverRatios"; import { useGalleryFilterUrl } from "@/v2/composables/useGalleryFilterUrl"; import { useGalleryMode } from "@/v2/composables/useGalleryMode"; +import { useGalleryOrderUrl } from "@/v2/composables/useGalleryOrderUrl"; import { useGallerySelectAll } from "@/v2/composables/useGallerySelectAll"; import { useGalleryViewModeUrl } from "@/v2/composables/useGalleryViewModeUrl"; import { @@ -125,6 +127,7 @@ defineSlots<{ }>(); useGalleryFilterUrl(); +useGalleryOrderUrl(); useGalleryViewModeUrl(); const { t } = useI18n(); @@ -619,10 +622,10 @@ function setSearch(value: string) { }, 300); } -// ── List-mode sort ──────────────────────────────────────────────── -// Header click → store order params → invalidate + bootstrap metadata. -// The grid-mode sort goes through the same path (toolbar dropdown), so -// no separate code path; list just exposes the click affordance. +// ── Sort ────────────────────────────────────────────────────────── +// Both affordances (list column headers, grid direction toggle) only +// write the store; `useGalleryOrderUrl` mirrors it to the URL and the +// watch below owns the refetch. const listSortKey = computed(() => { const key = orderBy.value; return isListSortKey(key) ? key : null; @@ -631,20 +634,19 @@ const listSortKey = computed(() => { function onListSort(payload: { key: ListSortKey; dir: "asc" | "desc" }) { galleryRoms.setOrderBy(payload.key); galleryRoms.setOrderDir(payload.dir); - galleryRoms.invalidateWindows(); - void galleryRoms.fetchInitialMetadata(); } -// Grid-mode direction toggle — wires the toolbar asc/desc into the -// same `orderDir` the list column-header sort writes to, then triggers -// the same invalidate+refetch path. Sort axis stays whatever the list -// last set (default "name"); grid only exposes direction. -function onGridSortDir(dir: "asc" | "desc") { - if (galleryRoms.orderDir === dir) return; - galleryRoms.setOrderDir(dir); +// The toolbar's sort axes, matching the list column headers. +const sortOptions = computed(() => getSortOptions(props.showPlatformColumn)); + +// Watching the store rather than refetching inside the handlers also +// covers the URL-driven writes (back/forward, a pasted link). The +// initial URL hydration runs before this watch is set up, so it does +// not echo here. +watch([orderBy, orderDir], () => { galleryRoms.invalidateWindows(); void galleryRoms.fetchInitialMetadata(); -} +}); // ── Scroll restoration ───────────────────────────────────────────── async function applyRestoredScroll() { @@ -661,14 +663,12 @@ function saveCurrentScroll(routeFullPath: string) { if (root) scrollRestoration.save(routeFullPath, root.scrollTop); } -onBeforeRouteUpdate((_to, from) => { +onBeforeRouteUpdate((to, from) => { saveCurrentScroll(from.fullPath); - // Switching to a different gallery context (Platform A → B, Search - // query change that routes, Collection open) — the selection is - // bound to the previous context and would read as stale items if - // carried over. Filter / sort changes inside the same view do NOT - // route, so they keep the selection intact (matches the rule of - // "filter, select more, filter again"). + // Search, filters, sort and view mode live in the query, so they + // navigate without leaving the gallery and keep the selection. Only a + // path change is a real context switch, where it would read as stale. + if (to.path === from.path) return; gallerySelection.clear(); }); onBeforeRouteLeave((_to, from) => { @@ -837,6 +837,8 @@ defineExpose({ :layout="layout" :position="toolbarPosition" :sort-dir="orderDir" + :sort-key="listSortKey" + :sort-key-items="sortOptions" show-search :search="searchInput" :search-placeholder="searchPlaceholder" @@ -845,7 +847,8 @@ defineExpose({ :filter-active-count="filterActiveCount" @update:group-by="groupBy = $event" @update:layout="layout = $event" - @update:sort-dir="onGridSortDir" + @update:sort-dir="galleryRoms.setOrderDir" + @update:sort-key="galleryRoms.setOrderBy" @update:search="setSearch" @click:filter="filterDrawerOpen = true" /> @@ -854,8 +857,8 @@ defineExpose({ + so columns align. Header click cycles asc/desc into the + store's orderBy/orderDir. --> diff --git a/frontend/src/v2/components/Gallery/GalleryToolbar.test.ts b/frontend/src/v2/components/Gallery/GalleryToolbar.test.ts index 9b31764ff..8d82872ad 100644 --- a/frontend/src/v2/components/Gallery/GalleryToolbar.test.ts +++ b/frontend/src/v2/components/Gallery/GalleryToolbar.test.ts @@ -16,7 +16,17 @@ vi.mock("@/v2/composables/useInputModality", () => ({ useInputModality: () => ({ modality }), })); -function mountToolbar(props: Record = {}) { +// The sort-axis control lives inside an RMenu, so its entries only exist +// once the menu renders its slots. +const RMenuPassthrough = { + name: "RMenuPassthrough", + template: `
`, +}; + +function mountToolbar( + props: Record = {}, + menuStub: boolean | typeof RMenuPassthrough = true, +) { return mount(GalleryToolbar, { attachTo: document.body, props: { groupBy: "none", layout: "grid", showSearch: true, ...props }, @@ -25,13 +35,33 @@ function mountToolbar(props: Record = {}) { RBadge: true, RBtn: true, RIcon: true, - RMenu: true, + RMenu: menuStub, RSliderBtnGroup: true, }, }, }); } +const SORT_OPTIONS = [ + { key: "name", label: "Title" }, + { key: "fs_size_bytes", label: "Size" }, +] as const; + +function mountWithSortOptions(props: Record = {}) { + return mountToolbar( + { sortKey: "name", sortKeyItems: SORT_OPTIONS, ...props }, + RMenuPassthrough, + ); +} + +function sortItems(wrapper: ReturnType) { + return wrapper + .findAllComponents({ name: "RMenuItem" }) + .filter((item) => + SORT_OPTIONS.some((option) => option.label === item.props("label")), + ); +} + describe("GalleryToolbar search autofocus", () => { it("leaves the search field unfocused by default", () => { const wrapper = mountToolbar(); @@ -56,3 +86,65 @@ describe("GalleryToolbar search autofocus", () => { wrapper.unmount(); }); }); + +describe("GalleryToolbar sort axis", () => { + it("emits the picked axis so grid mode can change the sort key", async () => { + const wrapper = mountWithSortOptions(); + + const size = sortItems(wrapper).find( + (item) => item.props("label") === "Size", + ); + expect(size).toBeTruthy(); + await size!.trigger("click"); + + expect(wrapper.emitted("update:sortKey")).toEqual([["fs_size_bytes"]]); + wrapper.unmount(); + }); + + it("marks the active axis", () => { + const wrapper = mountWithSortOptions({ sortKey: "fs_size_bytes" }); + + const variants = Object.fromEntries( + sortItems(wrapper).map((item) => [ + item.props("label"), + item.props("variant"), + ]), + ); + + expect(variants).toMatchObject({ Size: "active", Title: "default" }); + wrapper.unmount(); + }); + + // Index views (Platforms / Collections) sort their own tiles and pass + // no axes; the control must not paint an empty menu for them. + it("hides the control when no axes are offered", () => { + const withAxes = mountWithSortOptions(); + const menusWithAxes = withAxes.findAllComponents(RMenuPassthrough).length; + withAxes.unmount(); + + const wrapper = mountWithSortOptions({ sortKeyItems: [] }); + + expect(wrapper.findAllComponents(RMenuPassthrough)).toHaveLength( + menusWithAxes - 1, + ); + expect(sortItems(wrapper)).toHaveLength(0); + wrapper.unmount(); + }); + + // List mode sorts through the column headers, so the toolbar's axis + // button has to stand down rather than offer a second, competing control. + it("disables the activator in list mode only", () => { + const activatorDisabled = (layout: string) => { + const wrapper = mountWithSortOptions({ layout }); + const disabled = wrapper + .findComponent(RMenuPassthrough) + .findComponent({ name: "RBtn" }) + .attributes("disabled"); + wrapper.unmount(); + return disabled; + }; + + expect(activatorDisabled("list")).toBe("true"); + expect(activatorDisabled("grid")).toBe("false"); + }); +}); diff --git a/frontend/src/v2/components/Gallery/GalleryToolbar.vue b/frontend/src/v2/components/Gallery/GalleryToolbar.vue index 253a992c0..fa83ead17 100644 --- a/frontend/src/v2/components/Gallery/GalleryToolbar.vue +++ b/frontend/src/v2/components/Gallery/GalleryToolbar.vue @@ -29,6 +29,7 @@ import type { } from "@/v2/composables/useGalleryMode"; import { useInputModality } from "@/v2/composables/useInputModality"; import { shouldAutofocusSearch } from "@/v2/utils/autofocus"; +import type { ListSortKey, SortOption } from "./listColumns"; defineOptions({ inheritAttrs: false }); @@ -76,6 +77,12 @@ const props = withDefaults( /** Direction toggle for grid-mode sort. Disabled in list mode * (list-mode sort is driven by the column-header clicks). */ sortDir?: Ref<"asc" | "desc"> | "asc" | "desc"; + /** Active sort axis. `null` when the gallery is ordered by a key the + * selector doesn't offer, which leaves no entry highlighted. */ + sortKey?: Ref | ListSortKey | null; + /** Axes for the sort selector. Empty hides the control, as on index + * views, which sort their tiles themselves. */ + sortKeyItems?: readonly SortOption[]; /** Show the search field on the left. v-model:search controls its value. */ showSearch?: boolean; search?: string; @@ -103,6 +110,8 @@ const props = withDefaults( // substitute downstream through `effectiveGroupByItems`. groupByItems: () => [], sortDir: "asc", + sortKey: null, + sortKeyItems: () => [], showSearch: false, search: "", searchPlaceholder: "", @@ -117,6 +126,7 @@ const emit = defineEmits<{ (e: "update:groupBy", value: GroupByMode): void; (e: "update:layout", value: LayoutMode): void; (e: "update:sortDir", value: "asc" | "desc"): void; + (e: "update:sortKey", value: ListSortKey): void; (e: "update:search", value: string): void; (e: "update:segmentFilter", payload: { key: string; value: string }): void; (e: "click:filter"): void; @@ -132,6 +142,7 @@ function toValue(source: Ref | T): T { const groupByValue = computed(() => toValue(props.groupBy)); const layoutValue = computed(() => toValue(props.layout)); const sortDirValue = computed(() => toValue(props.sortDir)); +const sortKeyValue = computed(() => toValue(props.sortKey)); const layoutItems = computed(() => [ { @@ -213,6 +224,10 @@ function setSortDir(value: "asc" | "desc") { emit("update:sortDir", value); } +function setSortKey(value: ListSortKey) { + emit("update:sortKey", value); +} + function setSearch(value: string) { emit("update:search", value); } @@ -302,6 +317,34 @@ const { smAndUp } = useBreakpoint(); @update:model-value="setGroupBy" /> + + + + + + + { expect(isListSortKey("last_played")).toBe(false); }); }); + +describe("grid-mode sort options", () => { + it("offers exactly the axes the list headers make clickable", () => { + expect(getSortOptions(true).map((option) => option.key)).toEqual([ + "name", + "platform_id", + "fs_size_bytes", + "created_at", + "first_release_date", + "average_rating", + "hltb_main_story", + ]); + }); + + it("labels each axis with its column header", () => { + const labels = new Map( + getListColumns(true) + .filter(isSortableColumn) + .map((column) => [column.key, column.label]), + ); + for (const option of getSortOptions(true)) { + expect(option.label).toBe(labels.get(option.key)); + } + }); + + it("drops the platform axis on single-platform surfaces", () => { + const keys = getSortOptions(false).map((option) => option.key); + expect(keys).not.toContain("platform_id"); + expect(keys).toContain("name"); + }); +}); diff --git a/frontend/src/v2/components/Gallery/listColumns.ts b/frontend/src/v2/components/Gallery/listColumns.ts index e9f8bf386..d3a7c7a75 100644 --- a/frontend/src/v2/components/Gallery/listColumns.ts +++ b/frontend/src/v2/components/Gallery/listColumns.ts @@ -226,10 +226,24 @@ export function isSortableColumn( return column.sortable; } +/** A sort axis offered by the toolbar's grid-mode selector. */ +export interface SortOption { + key: ListSortKey; + label: string; +} + +/** Sort axes for the grid-mode selector, derived from the same columns + * list mode makes clickable so the two surfaces can't drift. */ +export function getSortOptions(showPlatform: boolean): readonly SortOption[] { + return getListColumns(showPlatform) + .filter(isSortableColumn) + .map(({ key, label }) => ({ key, label })); +} + // The sort keys list mode can toggle, read off the columns themselves so a // sortable column cannot go missing from them. const LIST_SORT_KEYS: ReadonlySet = new Set( - LIST_COLUMNS.filter(isSortableColumn).map((column) => column.key), + getSortOptions(true).map((option) => option.key), ); /** Whether the gallery's current order key is one list mode can sort by. */ diff --git a/frontend/src/v2/composables/useGalleryOrderUrl/index.test.ts b/frontend/src/v2/composables/useGalleryOrderUrl/index.test.ts new file mode 100644 index 000000000..d1c0a3aa1 --- /dev/null +++ b/frontend/src/v2/composables/useGalleryOrderUrl/index.test.ts @@ -0,0 +1,180 @@ +import { flushPromises, mount } from "@vue/test-utils"; +import { createPinia, setActivePinia } from "pinia"; +import { beforeEach, describe, expect, it } from "vitest"; +import { createApp, h, nextTick } from "vue"; +import { + createMemoryHistory, + createRouter, + type Router, + RouterView, +} from "vue-router"; +import storeGalleryRoms from "@/v2/stores/galleryRoms"; +import { useGalleryOrderUrl } from "./index"; + +const Blank = { template: "
" }; + +const Host = { + setup() { + useGalleryOrderUrl(); + }, + template: "
", +}; + +async function mountAt(router: Router, path: string) { + await router.push(path); + await router.isReady(); + const wrapper = mount(Host, { global: { plugins: [router] } }); + await nextTick(); + return wrapper; +} + +function makeRouter() { + return createRouter({ + history: createMemoryHistory(), + routes: [ + { path: "/platform/:platform", name: "platform", component: Blank }, + ], + }); +} + +/** `patchQuery` batches its writes into a `nextTick` callback, and the + * `router.replace` it then issues resolves asynchronously. */ +async function flushQueryWrite() { + await nextTick(); + await flushPromises(); +} + +describe("useGalleryOrderUrl", () => { + beforeEach(() => { + setActivePinia(createPinia()); + }); + + it("hydrates the store from the URL before the first fetch", async () => { + const router = makeRouter(); + await mountAt(router, "/platform/1?orderBy=fs_size_bytes&orderDir=desc"); + + const gallery = storeGalleryRoms(); + expect(gallery.orderBy).toBe("fs_size_bytes"); + expect(gallery.orderDir).toBe("desc"); + }); + + it("falls back to the default sort for missing or unknown params", async () => { + const gallery = storeGalleryRoms(); + gallery.setOrderBy("created_at"); + gallery.setOrderDir("desc"); + + const router = makeRouter(); + await mountAt(router, "/platform/1?orderBy=not_a_column"); + + expect(gallery.orderBy).toBe("name"); + expect(gallery.orderDir).toBe("asc"); + }); + + it("writes a column-header sort into the query", async () => { + const router = makeRouter(); + await mountAt(router, "/platform/1"); + const gallery = storeGalleryRoms(); + + gallery.setOrderBy("average_rating"); + gallery.setOrderDir("desc"); + await flushQueryWrite(); + + expect(router.currentRoute.value.query).toMatchObject({ + orderBy: "average_rating", + orderDir: "desc", + }); + }); + + // Grid mode exposes only the direction toggle, so a direction-only + // write has to reach the URL on its own. + it("writes a direction-only change into the query", async () => { + const router = makeRouter(); + await mountAt(router, "/platform/1"); + const gallery = storeGalleryRoms(); + + gallery.setOrderDir("desc"); + await flushQueryWrite(); + + expect(router.currentRoute.value.query.orderDir).toBe("desc"); + expect(router.currentRoute.value.query.orderBy).toBeUndefined(); + }); + + it("drops the params when the sort returns to the default", async () => { + const router = makeRouter(); + await mountAt(router, "/platform/1?orderBy=created_at&orderDir=desc"); + const gallery = storeGalleryRoms(); + + gallery.setOrderBy("name"); + gallery.setOrderDir("asc"); + await flushQueryWrite(); + + expect(router.currentRoute.value.query.orderBy).toBeUndefined(); + expect(router.currentRoute.value.query.orderDir).toBeUndefined(); + }); + + it("follows the URL back to the previous sort on back-navigation", async () => { + const router = makeRouter(); + await mountAt(router, "/platform/1?orderBy=created_at&orderDir=desc"); + const gallery = storeGalleryRoms(); + + await router.push("/platform/1?orderBy=hltb_main_story&orderDir=asc"); + await flushPromises(); + expect(gallery.orderBy).toBe("hltb_main_story"); + + router.back(); + await flushPromises(); + expect(gallery.orderBy).toBe("created_at"); + expect(gallery.orderDir).toBe("desc"); + }); + + it("leaves unrelated query params alone", async () => { + const router = makeRouter(); + await mountAt(router, "/platform/1?search=zelda&layout=list"); + const gallery = storeGalleryRoms(); + + gallery.setOrderDir("desc"); + await flushQueryWrite(); + + expect(router.currentRoute.value.query).toMatchObject({ + search: "zelda", + layout: "list", + orderDir: "desc", + }); + }); +}); + +// `main.ts` mounts without awaiting `router.isReady()`, so setup-only +// hydration holds solely because RouterView withholds the matched component +// until the initial navigation resolves. +describe("useGalleryOrderUrl on a cold load", () => { + beforeEach(() => { + setActivePinia(createPinia()); + }); + + it("sees the URL in setup() without awaiting router.isReady", async () => { + const seenAtSetup: string[] = []; + const GalleryView = { + setup() { + useGalleryOrderUrl(); + seenAtSetup.push(storeGalleryRoms().orderBy); + return () => h("div"); + }, + }; + + const history = createMemoryHistory(); + history.replace("/platform/1?orderBy=average_rating&orderDir=desc"); + const router = createRouter({ + history, + routes: [{ path: "/platform/:platform", component: GalleryView }], + }); + + const app = createApp({ render: () => h(RouterView) }); + app.use(router); + app.mount(document.createElement("div")); + await flushPromises(); + + expect(seenAtSetup).toEqual(["average_rating"]); + expect(storeGalleryRoms().orderDir).toBe("desc"); + app.unmount(); + }); +}); diff --git a/frontend/src/v2/composables/useGalleryOrderUrl/index.ts b/frontend/src/v2/composables/useGalleryOrderUrl/index.ts new file mode 100644 index 000000000..50cde2b5b --- /dev/null +++ b/frontend/src/v2/composables/useGalleryOrderUrl/index.ts @@ -0,0 +1,61 @@ +// useGalleryOrderUrl - bookmarkable gallery sort via URL query params. +// +// ?orderBy=fs_size_bytes (omitted at "name", the default) +// ?orderDir=desc (omitted at "asc", the default) +// +// An unrecognised or absent param resolves to the default, so a link +// without them lands on the same sort whatever the last gallery left in +// the store. Hydration runs during setup, before the shell registers its +// refetch watch, so the first fetch carries the params without echoing. +import { storeToRefs } from "pinia"; +import { watch } from "vue"; +import { useRoute, useRouter } from "vue-router"; +import storeGalleryRoms, { + DEFAULT_ORDER_BY, + DEFAULT_ORDER_DIR, + type GalleryOrderDir, + type GalleryOrderKey, + isGalleryOrderDir, + isGalleryOrderKey, +} from "@/v2/stores/galleryRoms"; +import { syncQueryParam } from "@/v2/utils/routeQuery"; + +function parseOrderBy(value: unknown): GalleryOrderKey { + return typeof value === "string" && isGalleryOrderKey(value) + ? value + : DEFAULT_ORDER_BY; +} + +function parseOrderDir(value: unknown): GalleryOrderDir { + return typeof value === "string" && isGalleryOrderDir(value) + ? value + : DEFAULT_ORDER_DIR; +} + +export function useGalleryOrderUrl() { + const route = useRoute(); + const router = useRouter(); + const galleryRoms = storeGalleryRoms(); + const { orderBy, orderDir } = storeToRefs(galleryRoms); + + function applyFromUrl() { + const by = parseOrderBy(route.query.orderBy); + const dir = parseOrderDir(route.query.orderDir); + if (by !== orderBy.value) galleryRoms.setOrderBy(by); + if (dir !== orderDir.value) galleryRoms.setOrderDir(dir); + } + + applyFromUrl(); + + watch(() => [route.query.orderBy, route.query.orderDir], applyFromUrl); + + // Drop the param when the value is the default, which keeps URLs clean. + watch([orderBy, orderDir], ([by, dir]) => { + syncQueryParam(router, "orderBy", by === DEFAULT_ORDER_BY ? undefined : by); + syncQueryParam( + router, + "orderDir", + dir === DEFAULT_ORDER_DIR ? undefined : dir, + ); + }); +} diff --git a/frontend/src/v2/composables/useGalleryViewModeUrl/index.ts b/frontend/src/v2/composables/useGalleryViewModeUrl/index.ts index 511021e3a..49816a428 100644 --- a/frontend/src/v2/composables/useGalleryViewModeUrl/index.ts +++ b/frontend/src/v2/composables/useGalleryViewModeUrl/index.ts @@ -26,7 +26,7 @@ import { type LayoutMode, useGalleryMode, } from "@/v2/composables/useGalleryMode"; -import { patchQuery } from "@/v2/utils/routeQuery"; +import { syncQueryParam } from "@/v2/utils/routeQuery"; const VALID_GROUP_BY: readonly GroupByMode[] = [ "letter", @@ -67,20 +67,11 @@ export function useGalleryViewModeUrl() { watch(() => route.query.group, applyFromUrl); watch(() => route.query.layout, applyFromUrl); - function syncQuery(key: "group" | "layout", value: string | undefined) { - const current = - typeof route.query[key] === "string" - ? (route.query[key] as string) - : undefined; - if (value === current) return; - patchQuery(router, { [key]: value }); - } - // Drop the param when the value is the default — keeps URLs clean. watch(groupBy, (next) => { - syncQuery("group", next === "none" ? undefined : next); + syncQueryParam(router, "group", next === "none" ? undefined : next); }); watch(layout, (next) => { - syncQuery("layout", next === "grid" ? undefined : next); + syncQueryParam(router, "layout", next === "grid" ? undefined : next); }); } diff --git a/frontend/src/v2/composables/useGalleryVirtualItems/index.ts b/frontend/src/v2/composables/useGalleryVirtualItems/index.ts index 1af0e1eb4..4df7bc009 100644 --- a/frontend/src/v2/composables/useGalleryVirtualItems/index.ts +++ b/frontend/src/v2/composables/useGalleryVirtualItems/index.ts @@ -398,7 +398,9 @@ export function useGalleryVirtualItems(opts: Options) { void (opts.ratioVersion ? opts.ratioVersion.value : 0); const ratioAt = makeRatioAt(); - if (opts.groupBy.value === "letter") { + // A non-lexical sort (size, rating, a date) gets no server char index, + // so grouping would have no headers to build and would render nothing. + if (opts.groupBy.value === "letter" && ranges.length > 0) { // Header + own flow-packed rows per letter (rows restart per letter). for (const range of ranges) { items.push(shareHeader(range.letter)); diff --git a/frontend/src/v2/composables/useGalleryVirtualItems/letterGrouping.test.ts b/frontend/src/v2/composables/useGalleryVirtualItems/letterGrouping.test.ts new file mode 100644 index 000000000..d2ce56899 --- /dev/null +++ b/frontend/src/v2/composables/useGalleryVirtualItems/letterGrouping.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; +import { computed, ref } from "vue"; +import { useGalleryVirtualItems } from "./index"; + +// The backend only indexes letters for a lexically ordered result, so sorting +// the grid by size / rating / a date ships an empty `char_index`. +function build(charIndex: Record) { + const { virtualItems } = useGalleryVirtualItems({ + layout: ref("grid" as const), + groupBy: ref("letter" as const), + total: ref(5), + charIndex: ref(charIndex), + columns: ref(3), + loadingInitial: computed(() => false), + emptyMessage: ref("empty"), + rowWidth: 600, + }); + return virtualItems.value; +} + +describe("grid grouping without a char index", () => { + it("groups under letter headers when the server indexed them", () => { + const items = build({ a: 0, b: 3 }); + + expect(items.filter((it) => it.kind === "letter-header")).toHaveLength(2); + expect(items.some((it) => it.kind === "row")).toBe(true); + }); + + it("falls back to flat rows instead of rendering nothing", () => { + const items = build({}); + + expect(items.filter((it) => it.kind === "row").length).toBeGreaterThan(0); + expect(items.filter((it) => it.kind === "letter-header")).toHaveLength(0); + }); +}); diff --git a/frontend/src/v2/stores/galleryRoms.ts b/frontend/src/v2/stores/galleryRoms.ts index bc15e3393..8e257f2c6 100644 --- a/frontend/src/v2/stores/galleryRoms.ts +++ b/frontend/src/v2/stores/galleryRoms.ts @@ -44,17 +44,34 @@ export type SimpleRom = SimpleRomSchema; * `RomUser`, so this includes fields that aren't direct properties of * `SimpleRomSchema` (e.g. `first_release_date` lives on RomMetadata). * Keep this in sync with the columns the gallery surface exposes. */ -export type GalleryOrderKey = - | "name" - | "fs_name" - | "platform_id" - | "fs_size_bytes" - | "created_at" - | "updated_at" - | "first_release_date" - | "average_rating" - | "hltb_main_story" - | "last_played"; +const GALLERY_ORDER_KEYS = [ + "name", + "fs_name", + "platform_id", + "fs_size_bytes", + "created_at", + "updated_at", + "first_release_date", + "average_rating", + "hltb_main_story", + "last_played", +] as const; + +export type GalleryOrderKey = (typeof GALLERY_ORDER_KEYS)[number]; + +export type GalleryOrderDir = "asc" | "desc"; + +export const DEFAULT_ORDER_BY: GalleryOrderKey = "name"; +export const DEFAULT_ORDER_DIR: GalleryOrderDir = "asc"; + +/** Narrows an untrusted string (a URL query param) to a sort key. */ +export function isGalleryOrderKey(value: string): value is GalleryOrderKey { + return (GALLERY_ORDER_KEYS as readonly string[]).includes(value); +} + +export function isGalleryOrderDir(value: string): value is GalleryOrderDir { + return value === "asc" || value === "desc"; +} type GalleryFilterStore = ExtractPiniaStoreType; @@ -224,7 +241,7 @@ interface State { // Order params — gallery-list scoped (separate from v1's localStorage // keys so v1/v2 don't fight over the same value). orderBy: GalleryOrderKey; - orderDir: "asc" | "desc"; + orderDir: GalleryOrderDir; } const defaults = (): State => ({ @@ -243,8 +260,8 @@ const defaults = (): State => ({ initialFetching: false, metadataLoaded: false, selectingAll: false, - orderBy: "name", - orderDir: "asc", + orderBy: DEFAULT_ORDER_BY, + orderDir: DEFAULT_ORDER_DIR, }); function alignToWindow(offset: number): number { @@ -289,7 +306,7 @@ export default defineStore("v2GalleryRoms", { setOrderBy(key: GalleryOrderKey) { this.orderBy = key; }, - setOrderDir(dir: "asc" | "desc") { + setOrderDir(dir: GalleryOrderDir) { this.orderDir = dir; }, diff --git a/frontend/src/v2/utils/routeQuery.ts b/frontend/src/v2/utils/routeQuery.ts index 28640082e..aba4f70ba 100644 --- a/frontend/src/v2/utils/routeQuery.ts +++ b/frontend/src/v2/utils/routeQuery.ts @@ -45,3 +45,16 @@ export function patchQuery( void router.replace({ query }); }); } + +/** Write one URL-backed value, `undefined` dropping the param. The compare + * against the live query is what stops a loop with the watcher reading it. */ +export function syncQueryParam( + router: QueryRouter, + key: string, + value: string | undefined, +): void { + const raw = router.currentRoute.value.query[key]; + const current = typeof raw === "string" ? raw : undefined; + if (value === current) return; + patchQuery(router, { [key]: value }); +} diff --git a/frontend/src/v2/views/Gallery/Collection.test.ts b/frontend/src/v2/views/Gallery/Collection.test.ts index a437ca0b0..18741fa65 100644 --- a/frontend/src/v2/views/Gallery/Collection.test.ts +++ b/frontend/src/v2/views/Gallery/Collection.test.ts @@ -28,10 +28,10 @@ const { getRoms: vi.fn(), getVirtualCollection: vi.fn(), push: vi.fn(), - routeGuards: [] as ((to: { - name: string; - params: Record; - }) => unknown)[], + routeGuards: [] as (( + to: { name: string; path: string; params: Record }, + from: { name: string; path: string; params: Record }, + ) => unknown)[], snackbarError: vi.fn(), snackbarInfo: vi.fn(), })); @@ -150,6 +150,34 @@ async function mountView() { return wrapper; } +/** Drive the captured route guards the way vue-router does: both `to` and + * `from`, each carrying the path the guard compares. */ +/** A sort / filter / search change: same path, new query. */ +function runQueryOnlyGuards() { + const at = { + name: routeState.name, + path: `/collection/${routeState.params.collection}`, + params: { ...routeState.params }, + }; + routeGuards.forEach((guard) => guard({ ...at }, { ...at })); +} + +function runRouteGuards(name: string, collection: string) { + const from = { + name: routeState.name, + path: `/collection/${routeState.params.collection}`, + params: { ...routeState.params }, + }; + routeState.name = name; + routeState.params = { collection }; + const to = { + name, + path: `/collection/${collection}`, + params: { collection }, + }; + routeGuards.forEach((guard) => guard(to, from)); +} + describe("Collection view random rom", () => { beforeEach(() => { setActivePinia(createPinia()); @@ -245,10 +273,7 @@ describe("Collection view random rom", () => { const wrapper = await mountView(); await wrapper.get("button.random").trigger("click"); - routeState.params = { collection: "2" }; - routeGuards.forEach((guard) => - guard({ name: "collection", params: { collection: "2" } }), - ); + runRouteGuards("collection", "2"); await flushPromises(); resolvePick({ data: rom(42) }); @@ -270,10 +295,7 @@ describe("Collection view random rom", () => { const wrapper = await mountView(); await wrapper.get("button.random").trigger("click"); - routeState.params = { collection: "2" }; - routeGuards.forEach((guard) => - guard({ name: "collection", params: { collection: "2" } }), - ); + runRouteGuards("collection", "2"); await flushPromises(); failPick(new Error("boom")); @@ -420,11 +442,10 @@ describe("Collection view freshness", () => { vi.spyOn(galleryRoms, "fetchInitialMetadata").mockResolvedValue(); const wrapper = mount(CollectionView); - routeState.params = { collection: "2" }; getCollection.mockResolvedValueOnce({ data: { ...collection(2), rom_count: 22 }, }); - await routeGuards[0]?.({ name: "collection", params: { collection: "2" } }); + runRouteGuards("collection", "2"); await flushPromises(); settleFirst({ data: { ...collection(1), rom_count: 11 } }); @@ -454,3 +475,19 @@ describe("Collection view freshness", () => { expect(wrapper.get(".rom-count").text()).toBe("9000"); }); }); + +describe("Collection view query-only navigation", () => { + it("does not re-read or reset the collection when only the query changes", async () => { + const galleryRoms = storeGalleryRoms(); + const wrapper = await mountView(); + getCollection.mockClear(); + const resetGallery = vi.spyOn(galleryRoms, "resetGallery"); + + runQueryOnlyGuards(); + await flushPromises(); + + expect(getCollection).not.toHaveBeenCalled(); + expect(resetGallery).not.toHaveBeenCalled(); + expect(wrapper.get(".rom-count").text()).toBe("9000"); + }); +}); diff --git a/frontend/src/v2/views/Gallery/Collection.vue b/frontend/src/v2/views/Gallery/Collection.vue index 9760f594b..506524960 100644 --- a/frontend/src/v2/views/Gallery/Collection.vue +++ b/frontend/src/v2/views/Gallery/Collection.vue @@ -262,7 +262,11 @@ onMounted(() => { loadForRoute(kindFromRoute(route.name), String(route.params.collection)); }); -onBeforeRouteUpdate((to) => { +onBeforeRouteUpdate((to, from) => { + // `loadForRoute` resets the gallery, so running it for a query-only + // change (sort, filters, search) would blank and re-bootstrap the + // collection already on screen. + if (to.path === from.path) return; loadForRoute(kindFromRoute(to.name), String(to.params.collection)); }); diff --git a/frontend/src/v2/views/Gallery/Platform.test.ts b/frontend/src/v2/views/Gallery/Platform.test.ts index 6bcf1b99b..48513fe12 100644 --- a/frontend/src/v2/views/Gallery/Platform.test.ts +++ b/frontend/src/v2/views/Gallery/Platform.test.ts @@ -21,10 +21,20 @@ const { getRoms: vi.fn(), getPlatform: vi.fn(), push: vi.fn(), - routeGuards: [] as ((to: { - name: string; - params: Record; - }) => unknown)[], + routeGuards: [] as (( + to: { + name: string; + path: string; + params: Record; + query?: Record; + }, + from: { + name: string; + path: string; + params: Record; + query?: Record; + }, + ) => unknown)[], snackbarError: vi.fn(), snackbarInfo: vi.fn(), })); @@ -149,12 +159,35 @@ function deferRandomRomFailure() { } /** Moves the view to another platform the way the router would. */ +/** A sort / filter / search change: same path, new query. */ +async function navigateQueryOnly(query: Record) { + const from = { + name: routeState.name, + path: routeState.path, + params: { ...routeState.params }, + query: { ...routeState.query }, + }; + routeState.query = query; + const to = { ...from, query }; + routeGuards.forEach((guard) => guard(to, from)); + await flushPromises(); +} + async function navigateTo(platformId: number) { + // vue-router hands guards both sides, each with the path they compare. + const from = { + name: routeState.name, + path: routeState.path, + params: { ...routeState.params }, + }; routeState.params = { platform: String(platformId) }; routeState.path = `/platform/${platformId}`; - routeGuards.forEach((guard) => - guard({ name: "platform", params: { platform: String(platformId) } }), - ); + const to = { + name: "platform", + path: routeState.path, + params: { platform: String(platformId) }, + }; + routeGuards.forEach((guard) => guard(to, from)); await flushPromises(); } @@ -329,3 +362,17 @@ describe("Platform view random rom", () => { expect(push).toHaveBeenCalledTimes(1); }); }); + +// Sorting writes the URL, so it reaches this view's route guard. Reloading +// the platform there costs a request per sort click and, on Collection, a +// full gallery reset. +describe("Platform view query-only navigation", () => { + it("does not reload the platform when only the query changes", async () => { + await mountView(); + getPlatform.mockClear(); + + await navigateQueryOnly({ orderBy: "fs_size_bytes", orderDir: "desc" }); + + expect(getPlatform).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/v2/views/Gallery/Platform.vue b/frontend/src/v2/views/Gallery/Platform.vue index b56418b29..f3565e4d3 100644 --- a/frontend/src/v2/views/Gallery/Platform.vue +++ b/frontend/src/v2/views/Gallery/Platform.vue @@ -340,10 +340,12 @@ onMounted(() => { loadForId(Number(route.params.platform)); }); -onBeforeRouteUpdate((to) => { +onBeforeRouteUpdate((to, from) => { // Shell saves the previous route's scroll automatically via its own // beforeRouteUpdate guard (runs before this one); we just trigger - // the new platform's load. + // the new platform's load. A query-only change (sort, filters, + // search) stays on this platform and must not reload it. + if (to.path === from.path) return; if (to.name === "platform") loadForId(Number(to.params.platform)); }); From 8e61199d7b82ec3fb4372bd36068a177b26e9573 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Sun, 20 Sep 2026 10:01:56 -0400 Subject: [PATCH 23/32] fix(security): keep CSRF in force when a session cookie is present (#4648) --- .../auth/middleware/csrf_middleware.py | 10 ++++- .../handler/auth/test_csrf_middleware.py | 44 ++++++++++++++++++- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/backend/handler/auth/middleware/csrf_middleware.py b/backend/handler/auth/middleware/csrf_middleware.py index 83f2afc90..11a500645 100644 --- a/backend/handler/auth/middleware/csrf_middleware.py +++ b/backend/handler/auth/middleware/csrf_middleware.py @@ -16,6 +16,11 @@ from starlette.responses import PlainTextResponse, Response from starlette.types import ASGIApp, Message, Receive, Scope, Send +def _session_authenticated(request: Request) -> bool: + """Whether the session, resolved and maybe cleared upstream, names a user.""" + return bool((request.scope.get("session") or {}).get("sub")) + + class CSRFMiddleware: def __init__( self, @@ -60,9 +65,10 @@ class CSRFMiddleware: request = Request(scope, receive) - # Skip CSRF check if Authorization header is present + # HybridAuthBackend resolves the session before this header, so a + # session-authenticated request runs as the cookie's owner, not the bearer's. auth_scheme = request.headers.get("Authorization", "").split(" ", 1)[0].lower() - if auth_scheme == "bearer" or auth_scheme == "basic": + if auth_scheme in ("bearer", "basic") and not _session_authenticated(request): await self.app(scope, receive, send) return None diff --git a/backend/tests/handler/auth/test_csrf_middleware.py b/backend/tests/handler/auth/test_csrf_middleware.py index 1d59e12b0..066a3aaa9 100644 --- a/backend/tests/handler/auth/test_csrf_middleware.py +++ b/backend/tests/handler/auth/test_csrf_middleware.py @@ -1,5 +1,6 @@ import asyncio import re +from typing import Any from itsdangerous import URLSafeSerializer from starlette.applications import Starlette @@ -10,9 +11,10 @@ from starlette.requests import Request from starlette.responses import JSONResponse, PlainTextResponse from starlette.routing import Route from starlette.testclient import TestClient +from starlette.types import ASGIApp, Receive, Scope, Send from config import ROMM_AUTH_SECRET_KEY -from handler.auth.constants import ALGORITHM +from handler.auth.constants import ALGORITHM, SESSION_COOKIE_NAME from handler.auth.middleware.csrf_middleware import CSRFMiddleware from handler.auth.middleware.session_middleware import SessionMiddleware from models.user import User @@ -58,6 +60,30 @@ def create_test_app(**csrf_kwargs) -> Starlette: return Starlette(routes=routes, middleware=middleware) +def create_session_app(session: dict[str, Any]) -> Starlette: + """A CSRF app behind a resolved session, as `main.py` orders them.""" + + class StubSessionMiddleware: + def __init__(self, app: ASGIApp) -> None: + self.app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + scope["session"] = dict(session) + await self.app(scope, receive, send) + + async def post_handler(request: Request) -> JSONResponse: + return JSONResponse({"status": "success"}) + + return Starlette( + routes=[Route("/post", post_handler, methods=["POST"])], + middleware=[ + Middleware(StubSessionMiddleware), + Middleware(AuthenticationMiddleware, backend=BasicAuthBackend()), + Middleware(CSRFMiddleware, secret="test-secret"), + ], + ) + + class TestCSRFMiddleware: def test_csrf_cookie_set_on_first_get(self) -> None: """A GET request should set the CSRF cookie if none exists.""" @@ -203,6 +229,22 @@ class TestCSRFMiddleware: resp = client.post("/post", headers={"Authorization": "Bearer token"}) assert resp.status_code == 200 + def test_authenticated_session_keeps_csrf_on_despite_auth_header(self) -> None: + """The session authenticates first, so the header must not exempt it.""" + client = TestClient(create_session_app({"iss": "romm:auth", "sub": "victim"})) + client.cookies.set(SESSION_COOKIE_NAME, "live-session-id") + + resp = client.post("/post", headers={"Authorization": "Bearer anything"}) + assert resp.status_code == 403 + + def test_stale_session_still_lets_the_auth_header_through(self) -> None: + """A cookie the session store rejected leaves the header as the credential.""" + client = TestClient(create_session_app({})) + client.cookies.set(SESSION_COOKIE_NAME, "expired-session-id") + + resp = client.post("/post", headers={"Authorization": "Bearer token"}) + assert resp.status_code == 200 + def test_non_http_scope_bypass(self) -> None: """WebSocket (or other non-HTTP) scopes should pass through.""" # Manual ASGI call; TestClient doesn't expose WebSocket easily From 44962cd0466c933975e0aef22b6bc2e2005fc533 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Mon, 21 Sep 2026 07:05:42 -0400 Subject: [PATCH 24/32] docs: drop the Aikido badge from the readme Co-Authored-By: Claude Opus 5 (1M context) --- .github/resources/aikido-badge.svg | 16 ---------------- README.md | 1 - 2 files changed, 17 deletions(-) delete mode 100644 .github/resources/aikido-badge.svg diff --git a/.github/resources/aikido-badge.svg b/.github/resources/aikido-badge.svg deleted file mode 100644 index 343c746d7..000000000 --- a/.github/resources/aikido-badge.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - Secured with Aikido - - - OPEN SOURCE SECURITY - - - diff --git a/README.md b/README.md index a3718343e..b38827e9b 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,6 @@ These companies support us by providing their tools for free:
Greptile - Aikido
From 24bf1cc25dace775d15f50fbde4411256d54977a Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Mon, 21 Sep 2026 15:26:33 -0400 Subject: [PATCH 25/32] docs: add a draft-announcement skill Codifies the house format of the Discord release announcements from the last three years: the timely hook, the upgrade warning, two to five features in prose with the tail as bullets, community news, and the pointer to the release notes. The community news is the half of an announcement no diff contains, so the skill interviews the maintainer for it one step at a time, and refuses to invent a contributor, an app, a milestone or a handle. Co-Authored-By: Claude Opus 5 (1M context) --- .claude/skills/draft-announcement/SKILL.md | 155 ++++++++++++++++++ .claude/skills/draft-announcement/template.md | 69 ++++++++ CLAUDE.md | 1 + 3 files changed, 225 insertions(+) create mode 100644 .claude/skills/draft-announcement/SKILL.md create mode 100644 .claude/skills/draft-announcement/template.md diff --git a/.claude/skills/draft-announcement/SKILL.md b/.claude/skills/draft-announcement/SKILL.md new file mode 100644 index 000000000..a4e1546bf --- /dev/null +++ b/.claude/skills/draft-announcement/SKILL.md @@ -0,0 +1,155 @@ +--- +name: draft-announcement +description: Draft the Discord release announcement for a RomM release, from the release notes plus an interview about community news. Use when asked to "write the Discord announcement for 5.3.0", "draft the announcement post", "announce the beta in Discord", or to refresh an announcement draft. Interviews the user for the things no diff contains (new team members, third-party apps to spotlight, milestones, events, Discord housekeeping), writes in the house voice, and never posts to Discord. +argument-hint: "[version to announce, e.g. 5.3.0 | nothing to infer it]" +--- + +# Drafting a Discord announcement + +The release notes say what shipped. The announcement says why anyone should care, +in RomM's voice, in one Discord message. It is a short, warm, slightly unhinged +post: a hook, the few features worth naming, the community news, a pointer to the +notes, a sign-off. + +Half the content is not in the repository. **Interview the user for it.** Never +invent a contributor, an app, a milestone, a link or a handle. + +Write the draft to the session scratchpad and print it. **Never** post to Discord, +and never write into the maintainer's announcement archive (see section 1). + +--- + +## 1. Read before you write + +`$ARGUMENTS` is the version. If empty, take the newest tag and confirm it. + +The release notes are the feature source. + +```bash +TAG=5.3.0 +gh release view "$TAG" --json body --jq .body # the notes for this release +# for a release not yet published, use the draft in the scratchpad +``` + +Past announcements are the voice source, and a Discord post is not in the repo, so +they exist only wherever the maintainer archives them. Ask where that is if you do +not already know, and treat it as **read only**: drafts go to the scratchpad. + +Read the **two most recent** before drafting. They set the current voice, and they +tell you which third-party apps were already spotlighted. An app highlighted in +either one does not get spotlighted again. + +From the notes, pull: + +- the Highlights, as candidate features to name, +- every `> [!WARNING]`, which **must** survive into the announcement (`4.1.0` led + with the mandatory `config.yml`, `4.0.0` led with the RCE advisory), +- a rough PR count and whether the release is mostly fixes, which decides the hook. + +## 2. Interview the user, one step at a time + +The community news is names, URLs and handles that only the user has, so it gets +**typed, not picked**. Ask **one question per message** and wait for the answer +before asking the next. Never send the whole questionnaire as a numbered list, and +never collect the content answers as checkbox options. + +Number every step and say how many there are ("Step 2 of 6"), so the user can see +where the interview ends. Each step states exactly which fields you need, and how +to skip it. Take "skip", "none" or "n/a" as an answer, move on without arguing, and +drop that item from the draft. + +| # | Step | Ask for | +| --- | ------------------ | --------------------------------------------------------------------------------------------------------------- | +| 1 | Features | print the Highlights you found as a numbered list, ask which get named prose; the rest become bullets | +| 2 | App spotlight | name, repo URL, author's handle, one line on what it does. List the apps already spotlighted so nothing repeats | +| 3 | Team or role news | handle, what they built or do, what changes now (joined the team, project gone official, new Experts) | +| 4 | Milestone or event | what it is, the number or date, and the link | +| 5 | Anything else | housekeeping, a call to action, a beta bug-report ask; the exact wording they want | +| 6 | Pings and shape | the only genuinely multiple-choice step, so one `AskUserQuestion` call: who gets pinged, and one message or two | + +Ask for a handle as it is written in Discord, since `@Covin` and `@Covin90` are not +interchangeable. Never offer a sample answer that could be mistaken for a real one: +no invented app names, no placeholder URLs, no guessed star counts. + +If steps 2 through 5 all come back empty, drop the Community news section. Several +releases (`4.3.0`, `4.4.0`) have none, and a padded one reads worse than none. + +Skip a step only when the answer is already on the table, and say so rather than +silently dropping it: a user who opened with "announce 5.3.0, spotlight ``" has +answered step 2 already. + +## 3. The shape + +Always, in this order: + +1. **Hook.** One or two sentences, opening on something _timely_. Check today's + date first and use it: the season, a holiday, the month, or a self-aware nod to + the last release. `3.6.0` served Thanksgiving turkey, `3.10.0` opened on the + summer heat, `3.7.0` on the new year, `4.9.0` on being the last `4.x`, `5.1.0` + on arriving sooner than anyone expected. Then `@everyone` (if pinging), the + version in backticks, and what the release is _about_. Never open cold with + "version X is out". Keep the reference light and skip a holiday that is not + widely shared, and do not assert a date you have not checked ("the equinox is + today") when "the days are getting shorter" carries the same warmth. +2. **Any upgrade warning**, immediately after the hook. Imperative, and what to do, + not why. +3. **The features**, in one of two shapes: + - **Bullet list** for a release carried by a long tail (`5.1.0`, `4.3.0`): one + sentence of setup, then five to nine bullets of three to six words each. + - **`###` section per feature** for a release with two to five real headliners + (`3.10.0`, `4.4.0`, `3.5.0`): a heading and two or three sentences, saying what + it does and the one thing needed to use it. Close with an `Other notable +features:` bullet list when there is a tail. +4. **`## Community news`** (`### Community updates` also appears; match the last + one). Team additions first, then app spotlights, then milestones and events, then + housekeeping and calls to action. +5. **The pointer.** "More details on each of these features, and a complete list of + changes, can be found in the [release notes](url)." Link the tag URL. +6. **Sign-off.** "See you soon!", optionally with `:mario_here_we_go:`. + +## 4. Voice + +- Second person, present tense, contractions. Talking to friends, not users. +- One idea per sentence, and short paragraphs. Nothing here is a manual. +- Enthusiasm is earned by specifics, not adjectives. Name the feature, don't call + it revolutionary. No claim the release notes do not support. +- Emphasis is _italics_ on a single word, sparingly. Bold is for the thing that + will break someone's install. +- Backticks for versions, env vars, config keys, filenames. +- Credit by name every time: the contributor for a feature, the author for an app. +- No em-dashes. No AI throat-clearing, no "we're excited to announce" twice in one + post, no bullet list of benefits. + +## 5. Discord mechanics + +- **2000 characters**, hard. Past announcements run 1300 to 2100; treat 1800 as the + target and count before handing over (`wc -m`). +- Over the limit, pick one: split at a section boundary into message 1 (hook plus + features) and message 2 (community news plus sign-off), marking the split in the + draft; or do what `3.7.0` did and post a three-line teaser pointing at the GitHub + notes. Say which you did and why. +- `##`, `###`, `**bold**`, `*italics*`, `` `code` ``, `> quote`, `-`/`*` bullets and + `[text](url)` all render. Tables, images and HTML do not. +- `@everyone` goes in the first sentence or not at all. +- Custom emoji only from ones this server is known to have: + `:mario_here_we_go:` (the usual sign-off), `:linkEz:`, `:linkLove:`, `:peepoAlert:`, + `:snakeSalute:`, `:excuseme:`, `:okay:`, `:linuxNootNoot:`. Anything else renders as + literal text, so use plain unicode (🎊 👉 ⚠️ 🔥) instead of guessing a shortcode. +- Role pings (`@Expert`, `@Alpha Tester`, `@Beta Tester`) only when the user asked + for them, spelled as they gave them. + +## 6. Before handing it over + +- Every feature named appears in the release notes. +- The hook opens on something timely, and the reference matches today's date. +- Every warning in the notes appears in the announcement. +- Every handle, repo URL and number came from the user or from the notes, never + from you, and every URL is one you have actually seen. +- No app spotlighted in either of the last two announcements. +- The release notes link ends in the tag being announced. +- Under 2000 characters, or split deliberately. +- No em-dashes, no invented emoji shortcodes. + +Write to `/-announcement.md`, print it, and say what still needs a +human: a screenshot or GIF to attach, a link the user has not given you, a name you +could not confirm. diff --git a/.claude/skills/draft-announcement/template.md b/.claude/skills/draft-announcement/template.md new file mode 100644 index 000000000..f424a0942 --- /dev/null +++ b/.claude/skills/draft-announcement/template.md @@ -0,0 +1,69 @@ + + + + + +## Bullet shape (a long tail of changes) + +@everyone + + + +⚠️ + + + +- +- +- +- +- + +## Community news + + + + + + + +More details on each of these features, and a complete list of changes, can be +found in the [release notes](https://github.com/rommapp/romm/releases/tag/X.Y.Z). + +See you soon! :mario_here_we_go: + +--- + +## Section shape (two to five real headliners) + +@everyone + +### + + + +### + + + +Other notable features: + +- +- + +## Community news + + + +More details on each of these features, and a complete list of changes, can be +found in the [release notes](https://github.com/rommapp/romm/releases/tag/X.Y.Z). + +See you soon! :mario_here_we_go: diff --git a/CLAUDE.md b/CLAUDE.md index d59075454..941ca04e7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,6 +53,7 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha | `pr-ready` | Before opening a PR - the four passes in order: `security-audit`, `code-review xhigh --fix`, `simplify`, `review-polish`. Not auto-invoked. | | `address-bot-reviews` | After Greptile and Copilot review a PR - triage each finding, fix what holds up, reply with the fix or the reason, and resolve the threads. Not auto-invoked. | | `draft-release-notes` | Drafting the GitHub release notes for a release, stable or alpha/beta, from the diff since the previous stable tag. | +| `draft-announcement` | Drafting the Discord announcement for a release, from the release notes plus an interview about community news. Not auto-invoked. | --- From 80b83351398b0c3cf94b2df542139b601b3071fe Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 21 Sep 2026 20:06:09 +0000 Subject: [PATCH 26/32] chore(deps): update astral-sh/setup-uv action to v10.2.0 --- .github/workflows/copilot-setup-steps.yml | 2 +- .github/workflows/e2e.yml | 2 +- .github/workflows/i18n.yml | 2 +- .github/workflows/migrations.yml | 4 ++-- .github/workflows/pytest.yml | 2 +- .github/workflows/update-hltb-api-url.yml | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml index 8636222a2..9ff713112 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -27,7 +27,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install Python run: uv python install diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 82f4f7785..85045b95e 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -68,7 +68,7 @@ jobs: sudo apt-get install -y libmariadb3 libmariadb-dev - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: uv python install diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml index 6d3323820..f7b569136 100644 --- a/.github/workflows/i18n.yml +++ b/.github/workflows/i18n.yml @@ -16,7 +16,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: uv python install diff --git a/.github/workflows/migrations.yml b/.github/workflows/migrations.yml index 1d603225a..17fa7bda8 100644 --- a/.github/workflows/migrations.yml +++ b/.github/workflows/migrations.yml @@ -41,7 +41,7 @@ jobs: sudo apt-get install -y libmariadb3 libmariadb-dev - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: uv python install @@ -98,7 +98,7 @@ jobs: sudo apt-get install -y libmariadb3 libmariadb-dev - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: uv python install diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index c127fc30f..80d3b74a1 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -70,7 +70,7 @@ jobs: sudo apt-get install -y libmariadb3 libmariadb-dev 7zip - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: | diff --git a/.github/workflows/update-hltb-api-url.yml b/.github/workflows/update-hltb-api-url.yml index 9b45293c3..c8e6b864b 100644 --- a/.github/workflows/update-hltb-api-url.yml +++ b/.github/workflows/update-hltb-api-url.yml @@ -19,7 +19,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: | From 552cf7c213303eb6ea9ccb2be425a5a9c1192164 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Mon, 21 Sep 2026 19:52:40 -0400 Subject: [PATCH 27/32] fix(config): show folder mappings whose folder name is not lowercase (#4676) --- backend/config/config_manager.py | 24 ++- backend/endpoints/configs.py | 16 ++ backend/handler/database/platforms_handler.py | 12 +- .../handler/filesystem/platforms_handler.py | 19 +++ backend/handler/scan_handler.py | 12 +- backend/tests/config/test_config_loader.py | 79 +++++++-- backend/tests/endpoints/test_config.py | 42 ++++- .../database/test_platforms_handler.py | 26 +++ .../filesystem/test_platforms_handler.py | 18 ++ backend/tests/utils/test_platform_aliases.py | 18 ++ backend/utils/platform_aliases.py | 21 +++ .../Config/Dialog/CreateFolderMapping.vue | 9 +- .../Config/FolderMappings.vue | 36 ++-- frontend/src/services/api/config.ts | 8 +- frontend/src/stores/config.ts | 20 ++- .../Settings/FolderMappingsSection.test.ts | 160 ++++++++++++++++++ .../Settings/FolderMappingsSection.vue | 25 ++- 17 files changed, 480 insertions(+), 65 deletions(-) create mode 100644 frontend/src/v2/components/Settings/FolderMappingsSection.test.ts diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 043f07b37..b32ff1b4f 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -919,7 +919,17 @@ class ConfigManager: f"Invalid config.yml: {config_key}.{key} must be a non-empty string" ) sys.exit(3) - normalized[str(key).lower()] = value + folded = str(key).lower() + # One key covers `PSX` and `psx` alike, so a second spelling of the + # same folder silently replaces the first. + if folded in normalized and normalized[folded] != value: + log.warning( + f"{config_key}.{key} replaces a case variant of the same " + f"folder name: {hl(normalized[folded])} is dropped for " + f"{hl(value)}, since folder names are matched " + "case-insensitively" + ) + normalized[folded] = value return normalized @@ -1401,9 +1411,11 @@ class ConfigManager: def add_platform_binding(self, fs_slug: str, slug: str) -> None: fs_slug = fs_slug.lower() platform_bindings = self.config.PLATFORMS_BINDING - if fs_slug in platform_bindings: - log.warning(f"Binding for {hl(fs_slug)} already exists") + bound = platform_bindings.get(fs_slug) + if bound == slug: return None + if bound: + log.info(f"Rebinding {hl(fs_slug)} from {hl(bound)} to {hl(slug)}") platform_bindings[fs_slug] = slug self.config.PLATFORMS_BINDING = platform_bindings @@ -1423,9 +1435,11 @@ class ConfigManager: def add_platform_version(self, fs_slug: str, slug: str) -> None: fs_slug = fs_slug.lower() platform_versions = self.config.PLATFORMS_VERSIONS - if fs_slug in platform_versions: - log.warning(f"Version for {hl(fs_slug)} already exists") + parent = platform_versions.get(fs_slug) + if parent == slug: return None + if parent: + log.info(f"Reparenting {hl(fs_slug)} from {hl(parent)} to {hl(slug)}") platform_versions[fs_slug] = slug self.config.PLATFORMS_VERSIONS = platform_versions diff --git a/backend/endpoints/configs.py b/backend/endpoints/configs.py index bd081063c..418125b17 100644 --- a/backend/endpoints/configs.py +++ b/backend/endpoints/configs.py @@ -18,6 +18,7 @@ from endpoints.responses.config import ConfigResponse from exceptions.config_exceptions import ConfigNotWritableException from handler.auth.constants import Scope from handler.database import db_rom_handler +from handler.filesystem import fs_platform_handler from logger.logger import log from utils.router import APIRouter @@ -169,6 +170,19 @@ def get_config(request: Request) -> ConfigResponse: ) +async def _reject_ambiguous_folder(fs_slug: str) -> None: + """Refuse a mapping that several folders on disk would share.""" + ambiguous = await fs_platform_handler.find_ambiguous_folders(fs_slug) + if ambiguous: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=( + f"Folders {', '.join(ambiguous)} differ only by case and share a " + "single mapping. Rename one to map them to different platforms." + ), + ) + + @protected_route(router.post, "/system/platforms", [Scope.PLATFORMS_WRITE]) async def add_platform_binding( request: Request, payload: PlatformBindingPayload @@ -177,6 +191,7 @@ async def add_platform_binding( fs_slug = payload.fs_slug slug = payload.slug + await _reject_ambiguous_folder(fs_slug) try: cm.add_platform_binding(fs_slug, slug) @@ -208,6 +223,7 @@ async def add_platform_version( fs_slug = payload.fs_slug slug = payload.slug + await _reject_ambiguous_folder(fs_slug) try: cm.add_platform_version(fs_slug, slug) diff --git a/backend/handler/database/platforms_handler.py b/backend/handler/database/platforms_handler.py index d19e383a6..d61da9ad7 100644 --- a/backend/handler/database/platforms_handler.py +++ b/backend/handler/database/platforms_handler.py @@ -2,7 +2,7 @@ import functools from collections.abc import Sequence from datetime import datetime -from sqlalchemy import delete, or_, select, update +from sqlalchemy import delete, func, or_, select, update from sqlalchemy.orm import Query, Session, selectinload from decorators.database import begin_session @@ -103,7 +103,15 @@ class DBPlatformsHandler(DBBaseHandler): query: Query = None, # type: ignore session: Session = None, # type: ignore ) -> Platform | None: - return session.scalar(query.filter_by(fs_slug=fs_slug).limit(1)) + platform = session.scalar(query.filter_by(fs_slug=fs_slug).limit(1)) + if platform: + return platform + + # Folder names are matched case-insensitively everywhere else, so a + # folder renamed only in case is the same platform, not a new one. + return session.scalar( + query.filter(func.lower(Platform.fs_slug) == fs_slug.lower()).limit(1) + ) @begin_session @with_firmware diff --git a/backend/handler/filesystem/platforms_handler.py b/backend/handler/filesystem/platforms_handler.py index 38ed64814..a138a32a5 100644 --- a/backend/handler/filesystem/platforms_handler.py +++ b/backend/handler/filesystem/platforms_handler.py @@ -77,3 +77,22 @@ class FSPlatformsHandler(FSHandler): platforms = self._exclude_platforms(platforms) return platforms + + async def find_ambiguous_folders(self, fs_slug: str) -> list[str]: + """The folders a single config mapping would cover, when it covers several. + + Folder names key the config case-insensitively, so siblings differing + only by case (which only a case-sensitive filesystem allows) share one + entry and cannot be mapped apart. + + Args: + fs_slug: The folder name a mapping is being written for. + + Returns: + The matching folders, sorted, or empty when the name is unambiguous. + """ + folded = fs_slug.lower() + matches = sorted( + folder for folder in await self.get_platforms() if folder.lower() == folded + ) + return matches if len(matches) > 1 else [] diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 410e13b12..4e8f958a1 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -80,7 +80,11 @@ from models.user import User from utils import emoji from utils.audio_tags import persist_embedded_cover, remove_persisted_cover from utils.filesystem import sanitize_filename -from utils.platform_aliases import resolve_fs_slug, resolve_platform_slug +from utils.platform_aliases import ( + resolve_fs_folder, + resolve_fs_slug, + resolve_platform_slug, +) LOGGER_MODULE_NAME = {"module_name": "scan"} @@ -292,7 +296,11 @@ async def scan_platform( if platform: known_fs_slug = resolve_fs_slug(platform.slug, cnfg) if known_fs_slug: - platform_attrs["fs_slug"] = known_fs_slug + # `resolve_fs_slug` answers with a lowercased config key, but + # every path is built from the folder's own casing. + platform_attrs["fs_slug"] = ( + resolve_fs_folder(known_fs_slug, fs_platforms) or known_fs_slug + ) platform_attrs["slug"] = resolve_platform_slug(fs_slug, cnfg) diff --git a/backend/tests/config/test_config_loader.py b/backend/tests/config/test_config_loader.py index 325741c33..4e93b35f9 100644 --- a/backend/tests/config/test_config_loader.py +++ b/backend/tests/config/test_config_loader.py @@ -1,5 +1,6 @@ import logging import os +from contextlib import contextmanager from pathlib import Path import pytest @@ -16,6 +17,22 @@ from config.config_manager import ( ) +@contextmanager +def capture_romm_logs(caplog, level=logging.WARNING): + """Capture the `romm` logger, whose records never reach caplog on their own. + + It sets `propagate = False`, so caplog's handler has to be attached to it + directly rather than to the root logger. + """ + romm_logger = logging.getLogger("romm") + romm_logger.addHandler(caplog.handler) + try: + with caplog.at_level(level, logger="romm"): + yield caplog + finally: + romm_logger.removeHandler(caplog.handler) + + def test_config_loader(): loader = ConfigManager( os.path.join(Path(__file__).resolve().parent, "fixtures", "config/config.yml") @@ -524,15 +541,8 @@ def test_legacy_streaming_container_logs_deprecation_warning(caplog, tmp_path): " broker_host: http://192.168.1.51:8000\n" " label: PCSX2\n" ) - # The "romm" logger has propagate=False, so caplog's handler must be - # added directly to it rather than relying on root-logger propagation. - romm_logger = logging.getLogger("romm") - romm_logger.addHandler(caplog.handler) - try: - with caplog.at_level(logging.WARNING, logger="romm"): - loader = ConfigManager(str(config_file)) - finally: - romm_logger.removeHandler(caplog.handler) + with capture_romm_logs(caplog): + loader = ConfigManager(str(config_file)) assert loader.config.STREAMING_CONTAINERS assert "deprecated" in caplog.text @@ -552,13 +562,8 @@ def test_webstation_streaming_container_does_not_warn(caplog, tmp_path): " platforms:\n" " ps2: pcsx2\n" ) - romm_logger = logging.getLogger("romm") - romm_logger.addHandler(caplog.handler) - try: - with caplog.at_level(logging.WARNING, logger="romm"): - ConfigManager(str(config_file)) - finally: - romm_logger.removeHandler(caplog.handler) + with capture_romm_logs(caplog): + ConfigManager(str(config_file)) assert "deprecated" not in caplog.text @@ -630,6 +635,48 @@ def test_platform_binding_lookup_ignores_case(tmp_path): assert loader.config.PLATFORMS_BINDING == {} +def test_case_variant_folder_keys_collapse_with_a_warning(caplog, tmp_path): + """One key covers both, so the dropped mapping must not vanish silently.""" + with capture_romm_logs(caplog): + loader = _write_config( + tmp_path, ' platforms:\n PSX: "ps2"\n psx: "psx"\n' + ) + + assert loader.config.PLATFORMS_BINDING == {"psx": "psx"} + assert "case variant" in caplog.text + assert "ps2" in caplog.text + + +def test_identical_case_variant_mappings_do_not_warn(caplog, tmp_path): + with capture_romm_logs(caplog): + loader = _write_config( + tmp_path, ' platforms:\n PSX: "psx"\n psx: "psx"\n' + ) + + assert loader.config.PLATFORMS_BINDING == {"psx": "psx"} + assert "case variant" not in caplog.text + + +def test_rebinding_a_folder_replaces_the_existing_platform(tmp_path): + loader = _write_config(tmp_path, ' platforms:\n GameCube: "ngc"\n') + + loader.add_platform_binding("GameCube", "wii") + + assert loader.config.PLATFORMS_BINDING == {"gamecube": "wii"} + reloaded = ConfigManager(loader.config_file) + assert reloaded.config.PLATFORMS_BINDING == {"gamecube": "wii"} + + +def test_reparenting_a_folder_replaces_the_existing_version(tmp_path): + loader = _write_config(tmp_path, ' versions:\n NAOMI: "arcade"\n') + + loader.add_platform_version("naomi", "dc") + + assert loader.config.PLATFORMS_VERSIONS == {"naomi": "dc"} + reloaded = ConfigManager(loader.config_file) + assert reloaded.config.PLATFORMS_VERSIONS == {"naomi": "dc"} + + def _write_emulatorjs_config(tmp_path: Path, emulatorjs_block: str) -> ConfigManager: config_file = tmp_path / "config.yml" config_file.write_text(f"emulatorjs:\n{emulatorjs_block}") diff --git a/backend/tests/endpoints/test_config.py b/backend/tests/endpoints/test_config.py index 4222c3aa6..8ea1ddf27 100644 --- a/backend/tests/endpoints/test_config.py +++ b/backend/tests/endpoints/test_config.py @@ -1,4 +1,4 @@ -from unittest.mock import patch +from unittest.mock import AsyncMock, patch from fastapi import status @@ -87,6 +87,46 @@ def test_add_platform_version_payload_shape(client, access_token: str): add_platform_version.assert_called_once_with("n64", "1.0") +def test_mapping_a_folder_with_a_case_variant_sibling_is_rejected( + client, access_token: str +): + """One config key covers both, so the write would remap the sibling too.""" + with ( + patch( + "endpoints.configs.fs_platform_handler.find_ambiguous_folders", + AsyncMock(return_value=["PSX", "psx"]), + ), + patch.object(cm, "add_platform_binding") as add_platform_binding, + ): + response = client.post( + "/api/config/system/platforms", + headers={"Authorization": f"Bearer {access_token}"}, + json={"fs_slug": "PSX", "slug": "ps2"}, + ) + + assert response.status_code == status.HTTP_409_CONFLICT + assert "differ only by case" in response.json()["detail"] + add_platform_binding.assert_not_called() + + +def test_mapping_a_folder_whose_name_is_unique_is_allowed(client, access_token: str): + with ( + patch( + "endpoints.configs.fs_platform_handler.find_ambiguous_folders", + AsyncMock(return_value=[]), + ), + patch.object(cm, "add_platform_binding") as add_platform_binding, + ): + response = client.post( + "/api/config/system/platforms", + headers={"Authorization": f"Bearer {access_token}"}, + json={"fs_slug": "Nintendo 64", "slug": "n64"}, + ) + + assert response.status_code == status.HTTP_200_OK + add_platform_binding.assert_called_once_with("Nintendo 64", "n64") + + def test_add_exclusion_payload_shape(client, access_token: str): with patch.object(cm, "add_exclusion") as add_exclusion: response = client.post( diff --git a/backend/tests/handler/database/test_platforms_handler.py b/backend/tests/handler/database/test_platforms_handler.py index 195264373..6ede30241 100644 --- a/backend/tests/handler/database/test_platforms_handler.py +++ b/backend/tests/handler/database/test_platforms_handler.py @@ -2,6 +2,32 @@ from handler.database import db_platform_handler from models.platform import Platform +def test_lookup_finds_a_folder_renamed_only_in_case(): + """A rescan must reuse the row, not add a second platform beside it.""" + stored = db_platform_handler.add_platform( + Platform(name="N64", slug="n64", fs_slug="nintendo 64") + ) + + found = db_platform_handler.get_platform_by_fs_slug("Nintendo 64") + + assert found is not None + assert found.id == stored.id + + +def test_lookup_returns_the_exactly_named_folder_when_one_exists(): + """The exact spelling is tried first, for backends that can tell them apart. + + MariaDB and MySQL match case-insensitively by collation, so only the + exactly-named row is asserted here; PostgreSQL additionally distinguishes + the sibling. + """ + exact = db_platform_handler.add_platform( + Platform(name="PlayStation", slug="psx", fs_slug="psx") + ) + + assert db_platform_handler.get_platform_by_fs_slug("psx").id == exact.id + + def test_rescan_preserves_user_authored_fields(platform): """A rescan merges a freshly built Platform over the existing row. diff --git a/backend/tests/handler/filesystem/test_platforms_handler.py b/backend/tests/handler/filesystem/test_platforms_handler.py index 58448f70d..dffef35ad 100644 --- a/backend/tests/handler/filesystem/test_platforms_handler.py +++ b/backend/tests/handler/filesystem/test_platforms_handler.py @@ -205,6 +205,24 @@ class TestFSPlatformsHandler: assert "n64" in result assert "psx" not in result + async def test_find_ambiguous_folders_reports_case_variant_siblings( + self, handler: FSPlatformsHandler + ): + """One config key covers both, so they cannot be mapped apart.""" + with patch.object(handler, "get_platforms", return_value=["PSX", "n64", "psx"]): + assert await handler.find_ambiguous_folders("psx") == ["PSX", "psx"] + assert await handler.find_ambiguous_folders("PSX") == ["PSX", "psx"] + + async def test_find_ambiguous_folders_ignores_an_unshared_name( + self, handler: FSPlatformsHandler + ): + with patch.object( + handler, "get_platforms", return_value=["Nintendo 64", "psx"] + ): + assert await handler.find_ambiguous_folders("Nintendo 64") == [] + assert await handler.find_ambiguous_folders("nintendo 64") == [] + assert await handler.find_ambiguous_folders("absent") == [] + async def test_get_platforms_calls_list_directories_with_correct_path( self, handler: FSPlatformsHandler, config ): diff --git a/backend/tests/utils/test_platform_aliases.py b/backend/tests/utils/test_platform_aliases.py index 7d2c25c82..d1b0924e8 100644 --- a/backend/tests/utils/test_platform_aliases.py +++ b/backend/tests/utils/test_platform_aliases.py @@ -7,6 +7,7 @@ from config.config_manager import Config from utils.platform_aliases import ( PLATFORM_FS_ALIASES, PLATFORM_SLUG_FOLDERS, + resolve_fs_folder, resolve_fs_slug, resolve_platform_slug, ) @@ -85,6 +86,23 @@ def test_slug_reached_by_several_folders_has_no_reverse(): assert resolve_fs_slug("my-custom-slug", _config()) is None +def test_resolves_a_config_key_to_the_folder_on_disk(): + """Config keys are lowercased; paths need the folder's own casing.""" + assert resolve_fs_folder("nintendo 64", ["Nintendo 64", "psx"]) == "Nintendo 64" + + +def test_resolves_a_folder_that_is_not_on_disk_to_nothing(): + assert resolve_fs_folder("nintendo 64", ["psx"]) is None + + +def test_two_folders_differing_only_by_case_each_resolve_to_themselves(): + """A case-sensitive filesystem allows both; neither may claim the other.""" + folders = ["PSX", "psx"] + + assert resolve_fs_folder("psx", folders) == "psx" + assert resolve_fs_folder("PSX", folders) == "PSX" + + def test_reverse_map_agrees_with_alias_table(): for slug, fs_slug in PLATFORM_SLUG_FOLDERS.items(): assert PLATFORM_FS_ALIASES[fs_slug].value == slug diff --git a/backend/utils/platform_aliases.py b/backend/utils/platform_aliases.py index 4833a44ae..1f030c425 100644 --- a/backend/utils/platform_aliases.py +++ b/backend/utils/platform_aliases.py @@ -1,5 +1,6 @@ from __future__ import annotations +from collections.abc import Iterable from typing import TYPE_CHECKING, Final from utils.platform_slugs import UniversalPlatformSlug as UPS @@ -190,3 +191,23 @@ def resolve_fs_slug(slug: str, config: Config) -> str | None: if bound == slug: return fs_slug return PLATFORM_SLUG_FOLDERS.get(slug) + + +def resolve_fs_folder(fs_slug: str, fs_platforms: Iterable[str]) -> str | None: + """Resolve a folder name to the one on disk it names, ignoring case. + + Config keys are lowercased, but paths are built from the folder's own + casing. An exact match wins, so on a case-sensitive filesystem two folders + differing only by case each still resolve to themselves. + + Returns: + The folder as it is spelled on disk, or None when none matches. + """ + folded = fs_slug.lower() + fallback: str | None = None + for folder in fs_platforms: + if folder == fs_slug: + return folder + if fallback is None and folder.lower() == folded: + fallback = folder + return fallback diff --git a/frontend/src/components/Settings/LibraryManagement/Config/Dialog/CreateFolderMapping.vue b/frontend/src/components/Settings/LibraryManagement/Config/Dialog/CreateFolderMapping.vue index d17d97a75..0dad195f2 100644 --- a/frontend/src/components/Settings/LibraryManagement/Config/Dialog/CreateFolderMapping.vue +++ b/frontend/src/components/Settings/LibraryManagement/Config/Dialog/CreateFolderMapping.vue @@ -36,13 +36,10 @@ const availableFolders = computed(() => { } // Exclude folders that are already mapped as either an alias or a variant. - const isBound = Object.keys(configStore.config.PLATFORMS_BINDING).includes( - folder, + return ( + !configStore.getPlatformBinding(folder) && + !configStore.getPlatformVersion(folder) ); - const isVersion = Object.keys( - configStore.config.PLATFORMS_VERSIONS, - ).includes(folder); - return !isBound && !isVersion; }); }); diff --git a/frontend/src/components/Settings/LibraryManagement/Config/FolderMappings.vue b/frontend/src/components/Settings/LibraryManagement/Config/FolderMappings.vue index 47bde87a6..4a2bcb27c 100644 --- a/frontend/src/components/Settings/LibraryManagement/Config/FolderMappings.vue +++ b/frontend/src/components/Settings/LibraryManagement/Config/FolderMappings.vue @@ -1,4 +1,5 @@