Merge pull request #4631 from LoneAngelFayt/streaming-patches-5

fix(streaming): bind every session action to the claim that owns it
This commit is contained in:
Georges-Antoine Assi
2026-09-24 21:44:52 -04:00
committed by GitHub
98 changed files with 4738 additions and 599 deletions

View File

@@ -30,11 +30,15 @@ class StreamingContainerSchema(BaseModel):
emulator: str
supports_memory_cards: bool
supports_save_picker: bool
supports_live_states: bool
class StreamingConfigSchema(BaseModel):
enabled: bool
containers: list[StreamingContainerSchema]
emulator_labels: dict[str, str]
"""Display name per emulator id, so a save or state tagged with one can be
labelled without a second copy of the map on the frontend."""
class SessionTerminationSchema(BaseModel):
@@ -50,6 +54,9 @@ class SessionTerminationSchema(BaseModel):
platform: str | None = None
rom_id: int | None = None
rom_name: str | None = None
container: str | None = None
claimed_at: str | None = None
desktop: bool = False
class SessionStatusSchema(BaseModel):
@@ -58,6 +65,9 @@ class SessionStatusSchema(BaseModel):
extraction_phase: str | None = None
"""Set while a webstation broker unpacks a pkg or archive, which is the
part of a launch long enough that the player needs to see something."""
host: str | None = None
"""The room URL of a launched session, for a tab that missed launch-ready,
reported by the status poll only and left None by a heartbeat."""
termination: SessionTerminationSchema | None = None
@@ -78,6 +88,8 @@ class LaunchReadyPayload(BaseModel):
platform: str
container: str
claimed_at: str
"""The claim's stamp, since a re-claim of the same container shares its key."""
host: str
resume: bool | None = None
"""None when no resume was asked for; False means the state could not be
@@ -89,6 +101,7 @@ class LaunchFailedPayload(BaseModel):
platform: str
container: str
claimed_at: str
detail: str
@@ -97,9 +110,28 @@ class LaunchPhasePayload(BaseModel):
platform: str
container: str
claimed_at: str
phase: str | None = None
class ContainerBusyDetail(BaseModel):
"""The 409 body when a claim finds its container held."""
message: str
draining: bool
"""A previous session is still shutting down, rather than anyone holding it."""
rom_name: str | None
"""The game holding it, None when the caller may not see which."""
claimed_at: str | None
SOCKET_PAYLOADS: tuple[type[BaseModel], ...] = (
LaunchReadyPayload,
LaunchFailedPayload,
LaunchPhasePayload,
)
class DesktopSessionSchema(BaseModel):
container: str
platform: str
@@ -117,7 +149,7 @@ class JoinedSessionSchema(BaseModel):
class SaveAndExitResponse(BaseModel):
status: Literal["ok"]
status: Literal["ok", "not_found"]
saved: bool
platform: str
released: bool
@@ -223,6 +255,9 @@ class AdminContainerSchema(BaseModel):
configured: bool
"""False for a container with no usable broker address: it can never be
claimed, and saying so beats listing it as idle."""
draining: bool = False
"""The previous session's exit work is still running, so the container is
held by nobody and about to come free."""
session: ContainerSessionSchema | None = None

View File

@@ -25,6 +25,7 @@ from endpoints.responses.streaming import (
AdminContainersResponse,
AdminSessionSchema,
AdminSessionsResponse,
ContainerBusyDetail,
ContainerSessionSchema,
DesktopSessionSchema,
ForceReleaseResponse,
@@ -77,7 +78,8 @@ from handler.streaming.config import (
container_for_session,
containers_by_key,
containers_for_platform,
resolve_containers,
emulator_labels,
first_claim_targets,
streaming_enabled,
)
from handler.streaming.protocol import room_url_on
@@ -97,8 +99,11 @@ from handler.streaming.session_store import (
record_termination,
refresh_session,
release_own_session,
same_claim,
session_disc_id,
session_is_desktop,
session_is_stale,
session_platform_matches,
session_redis_key,
set_session_disc,
stamp_launched,
@@ -167,11 +172,21 @@ class LoadStateRequest(BaseModel):
slot: Annotated[int, Field(ge=1, le=MAX_SLOT)] = 1
CONTAINER_KEY_MAX_LENGTH = 300
CLAIMED_AT_MAX_LENGTH = 64
# A claim is named by its container and the stamp it was taken at.
ContainerQuery = Annotated[
str | None, Query(alias="container", max_length=CONTAINER_KEY_MAX_LENGTH)
]
ClaimedAtQuery = Annotated[str | None, Query(max_length=CLAIMED_AT_MAX_LENGTH)]
class DesktopStreamingSessionRequest(BaseModel):
# The container to open, named by the key GET /streaming/containers
# reports. Named rather than pooled: an admin configuring a container
# needs that one, not whichever is free.
container: Annotated[str, Field(min_length=1, max_length=300)]
container: Annotated[str, Field(min_length=1, max_length=CONTAINER_KEY_MAX_LENGTH)]
def platform_capabilities(platform: str) -> PlatformCapabilities:
@@ -202,9 +217,12 @@ async def _session_status(
platform: str,
request: Request,
candidates: list[ResolvedContainer] | None = None,
*,
include_desktop: bool = False,
claimed_at: str | None = None,
) -> dict[str, Any]:
"""Whether the caller holds a session among `candidates` (the platform's first
pool by default), and if not, why it ended. Read-only, so it is safe to poll."""
"""Whether the caller holds this platform's session among `candidates` (its
first pool by default) and, if not, why it ended, read-only so safe to poll."""
if candidates is None:
candidates = containers_for_platform(platform)
if not candidates:
@@ -212,10 +230,22 @@ async def _session_status(
status_code=404,
detail=f"No streaming container configured for platform '{platform}'",
)
found = await access.find_session_for_user(candidates, request.user.id)
found = await access.find_session_for_user(
candidates,
request.user.id,
platform=platform,
include_desktop=include_desktop,
claimed_at=claimed_at,
)
if found is not None:
container, _, session = found
status: dict[str, Any] = {"status": "active", "platform": platform}
status: dict[str, Any] = {
"status": "active",
"platform": platform,
# The room the launch answered with, so a tab that missed the
# launch-ready push can enter the stream off a poll.
"host": session.get("host"),
}
# An activate that has not returned yet leaves no launched_at behind.
# Gating the broker round trip on it keeps this route pure Redis for
# the rest of the session, which is the part that gets polled forever.
@@ -228,11 +258,14 @@ async def _session_status(
)
return status
# The tombstone is keyed per container, so with a pool the caller's notice
# can sit under any of them.
# can sit under any of them, and another claim's is not the answer.
termination = None
for candidate in candidates:
termination = await get_termination(candidate.key, request.user.id)
if termination is not None:
notice = await get_termination(candidate.key, request.user.id)
if notice is not None and access.session_in_scope(
notice, platform, include_desktop, claimed_at
):
termination = notice
break
return {
"status": "ended",
@@ -255,36 +288,41 @@ def _joinable_container_label(
@protected_route(router.get, "/config", [Scope.ROMS_READ])
async def get_config(request: Request) -> StreamingConfigSchema:
"""Return streaming configuration to the frontend"""
# Keyed by platform: a pool is a backend concern, the frontend picks a
# One row per platform: a pool is a backend concern, the frontend picks a
# platform and the claim decides which container serves it.
safe_containers: dict[str, StreamingContainerSchema] = {}
for c in resolve_containers():
if c.platform in safe_containers:
continue
safe_containers: list[StreamingContainerSchema] = []
for c in first_claim_targets():
# The record carries the platform's label and capabilities, so a
# platform hidden from this caller must not be listed here either.
if not access.platform_is_visible(request, c.platform):
continue
safe_containers[c.platform] = StreamingContainerSchema(
platform=c.platform,
host=c.host,
label=c.label,
# Ship slot capabilities so the frontend selector reads them
# instead of keeping its own hardcoded per-platform copy.
capabilities=SlotCapabilitiesSchema(**c.capabilities),
# State namespace for this container, so the frontend can
# filter the resume picker the same way hydration filters.
emulator=c.emulator,
# Whether this container syncs whole memory cards, so the
# frontend only offers the card picker where it applies.
supports_memory_cards=c.memory_card_sync,
# Whether an older save archive still lands here, so the frontend
# only offers the save picker where a pick means something.
supports_save_picker=c.supports_save_picker,
safe_containers.append(
StreamingContainerSchema(
platform=c.platform,
host=c.host,
label=c.label,
# Ship slot capabilities so the frontend selector reads them
# instead of keeping its own hardcoded per-platform copy.
capabilities=SlotCapabilitiesSchema(**c.capabilities),
# State namespace for this container, so the frontend can
# filter the resume picker the same way hydration filters.
emulator=c.emulator,
# Whether this container syncs whole memory cards, so the
# frontend only offers the card picker where it applies.
supports_memory_cards=c.memory_card_sync,
# Whether an older save archive still lands here, so the frontend
# only offers the save picker where a pick means something.
supports_save_picker=c.supports_save_picker,
# Whether the in-game Save and Load buttons reach a broker that
# honours them, which an exit-state emulator's does not.
supports_live_states=c.supports_live_states,
)
)
return StreamingConfigSchema(
enabled=streaming_enabled(), containers=list(safe_containers.values())
enabled=streaming_enabled(),
containers=safe_containers,
emulator_labels=emulator_labels(),
)
@@ -309,12 +347,12 @@ async def _win_container(
if not entered:
raise HTTPException(
status_code=409,
detail={
"message": "You already have a session on this platform",
"draining": False,
"rom_name": None,
"claimed_at": None,
},
detail=ContainerBusyDetail(
message="You already have a session on this platform",
draining=False,
rom_name=None,
claimed_at=None,
).model_dump(),
)
return await _reserve_container(request, candidates, session, platform)
@@ -326,24 +364,26 @@ async def _reserve_container(
platform: str,
) -> ResolvedContainer:
"""Walk the platform's containers and claim the first one available."""
# Status, heartbeat and release all resolve by platform and answer with the
# first match, so a second session for one user is one nothing can reach.
held = await access.find_session_for_user(candidates, request.user.id)
# Status, heartbeat and release reach one session per platform, so a second
# is unreachable. One elsewhere is no bar: its container fails the claim below.
held = await access.find_session_for_user(
candidates, request.user.id, platform=platform
)
if held is not None:
holder, _, mine = held
own_container, _, mine = held
if not session_is_stale(mine):
raise HTTPException(
status_code=409,
detail={
"message": "You already have a session on this platform",
"draining": False,
"rom_name": access.visible_rom_name(request, mine),
"claimed_at": mine.get("claimed_at"),
},
detail=ContainerBusyDetail(
message="You already have a session on this platform",
draining=False,
rom_name=access.visible_rom_name(request, mine),
claimed_at=mine.get("claimed_at"),
).model_dump(),
)
# Their own session, abandoned. Take that container back rather than
# rolling them onto a free one and stranding this one until its TTL.
candidates = [holder]
candidates = [own_container]
async def try_claim(candidate: ResolvedContainer) -> bool:
# SET NX is atomic: exactly one concurrent claim wins the key. The TTL
@@ -386,40 +426,56 @@ async def _reserve_container(
platform,
existing.get("user_id"),
)
# A container serves several platforms, so the swept session may be another
# one's, and its state, saves and card belong to that platform's emulator.
record = (
container_for_session(
containers_by_key(), candidate.key, existing.get("platform")
)
or candidate
)
if not await lifecycle.await_teardown_within_budget(
candidate,
record,
candidate.key,
existing,
max(0.0, deadline - time.monotonic()),
claimed_by=request.user.id,
):
continue
if await try_claim(candidate):
return candidate
# Report the head of the pool as the holder: with one container that is the
# only holder, and with several the player just needs to know the platform
# is busy.
existing = await get_session(candidates[0].key) or {}
# A drain marker belongs to nobody: the previous session is over and its
# exit state is still coming out of the container, so rom_name and
# claimed_at are both blank and "in use" would name no one. The player who
# just pressed save-and-exit sees this, and needs to be told to wait rather
# than that somebody else took their platform.
draining = bool(existing.get("draining"))
# A drain marker names no holder, so the holder comes from a live session,
# while `draining` still says a container is about to come free.
snapshots = [
snapshot or {}
for snapshot in await asyncio.gather(
*(get_session(candidate.key) for candidate in candidates)
)
]
draining = any(snapshot.get("draining") for snapshot in snapshots)
holder = next(
(
snapshot
for snapshot in snapshots
if snapshot and not snapshot.get("draining")
),
{},
)
if draining:
message = "The previous session is still saving, try again shortly"
message = "The previous session is still shutting down, try again shortly"
elif len(candidates) == 1:
message = "Session in use"
else:
message = f"All {len(candidates)} containers for this platform are in use"
raise HTTPException(
status_code=409,
detail={
"message": message,
"draining": draining,
"rom_name": access.visible_rom_name(request, existing),
"claimed_at": existing.get("claimed_at"),
},
detail=ContainerBusyDetail(
message=message,
draining=draining,
rom_name=access.visible_rom_name(request, holder),
claimed_at=holder.get("claimed_at"),
).model_dump(),
)
@@ -638,7 +694,10 @@ async def _hydrate_saves(
[Scope.ROMS_USER_WRITE],
# The prompt for a card the container still holds is a real body the client
# parses, so it is declared rather than left as an undocumented `detail`.
responses={428: {"model": MemoryCardImportRequired}},
responses={
409: {"model": ContainerBusyDetail},
428: {"model": MemoryCardImportRequired},
},
status_code=202,
)
async def claim_session(
@@ -786,6 +845,9 @@ async def claim_session(
if resume_state is not None and not resume_after_launch:
resume_pushed = await states.push_resume_state(container, resume_state)
# The last exit's detached save pull may still be filing the archive to hydrate.
await saves.wait_for_save_pull(request.user.id, rom.id)
archive_path = await _hydrate_saves(
request,
container,
@@ -833,16 +895,28 @@ async def claim_session(
router.post, "/sessions/{platform}/save-and-exit", [Scope.ROMS_USER_WRITE]
)
async def save_and_exit_session(
request: Request, platform: str, req: Annotated[SaveAndExitRequest, Body()]
request: Request,
platform: str,
req: Annotated[SaveAndExitRequest, Body()],
container_key: ContainerQuery = None,
claimed_at: ClaimedAtQuery = None,
) -> SaveAndExitResponse:
"""Save game state then release the session.
Args:
req: `wait` true (the default) blocks until the broker confirms the save
and kill, false has the broker do both in the background.
container_key: the claimed container, as on release.
claimed_at: the claim's stamp, as on release.
"""
Save game state then release the session.
wait=true (default): blocks until broker confirms save+kill complete.
wait=false: broker fires save+kill in background, returns immediately.
"""
container, session_key, session = await access.resolve_owned_session(
platform, request
target = await access.resolve_claim(
platform, request, container_key, claimed_at, game_only=True
)
if target is None:
return SaveAndExitResponse(
status="not_found", saved=False, platform=platform, released=True
)
container, session_key, session = target
if req.slot:
_assert_valid_slot(platform, req.slot)
@@ -852,7 +926,7 @@ async def save_and_exit_session(
# still writing, and the wipe can race its exit flush.
card_sync = container.memory_card_sync
effective_wait = True if card_sync else req.wait
saved, effective_slot = await asyncio.to_thread(
saved, effective_slot, settled = await asyncio.to_thread(
commands.save_and_exit, container, slot=req.slot, wait=effective_wait
)
@@ -866,6 +940,8 @@ async def save_and_exit_session(
await lifecycle.record_play_session(session)
await lifecycle.clear_session_activity(session_key, session)
# Before the key goes, so a claim that wins it next waits for the pull.
await lifecycle.start_exit_save_pull(container, session, settled=settled)
# Sync the exit save to the library. With wait=false the broker save may
# still be running; the pull blocks on the broker until it finishes.
@@ -930,8 +1006,6 @@ async def save_and_exit_session(
except StreamingSessionContended:
released = False
lifecycle.collect_exit_saves(container, session)
if not released:
log.error("save-and-exit could not give up session %s", session_key)
log.info("save-and-exit, platform=%s saved=%s", platform, saved)
@@ -946,65 +1020,85 @@ async def save_and_exit_session(
async def heartbeat_session(
request: Request,
platform: str,
container_key: str | None = Query(default=None, alias="container", max_length=300),
container_key: ContainerQuery = None,
claimed_at: ClaimedAtQuery = None,
) -> SessionStatusSchema:
"""Refresh the session's liveness stamp and report whether it still exists.
"""Refresh the liveness stamp the frontend beats every ~30s, without which the
claim is abandoned after _STREAMING_SESSION_STALE_SECONDS for the next to take.
The frontend calls this every ~30s while a session is active. A session
that stops refreshing counts as abandoned after _STREAMING_SESSION_STALE_SECONDS
and the next claim may take the container over.
Args:
container_key: the claim to beat, needed for any desktop, or for a
container outside the platform's first pool.
claimed_at: the claim's stamp, so a tab that missed its own takeover does
not keep the claim that replaced it alive.
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
outside the platform's first pool.
Returns:
`ended` rather than a 404 once the caller no longer holds the session, so
a force-released player learns why on the poll they already make.
"""
user_id = request.user.id
# A named claim answers for itself: another session the caller holds on the
# platform is not the one this client is beating.
# A named claim answers for itself, and naming the container is the only way
# to reach a desktop, which a game tab must never beat.
named = container_key is not None
candidates = (
[access.named_container(platform, container_key)]
if container_key is not None
else containers_for_platform(platform)
)
found = await access.find_session_for_user(candidates, user_id)
if found is None:
return SessionStatusSchema(
**await _session_status(platform, request, candidates)
found = await access.find_session_for_user(
candidates,
user_id,
platform=platform,
include_desktop=named,
claimed_at=claimed_at,
)
if found is not None:
_, session_key, held = found
# 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,
{"last_seen": datetime.now(timezone.utc).isoformat()},
require=lambda s: same_claim(s, held),
)
except StreamingSessionContended:
# A key too busy to write is a key that exists, so the session is live
# and the missed stamp is covered by the next beat.
log.warning("heartbeat could not stamp contended session %s", session_key)
return SessionStatusSchema(status="active", platform=platform)
if refreshed is not None:
await lifecycle.refresh_session_activity(session_key, refreshed)
return SessionStatusSchema(status="active", platform=platform)
return SessionStatusSchema(
**await _session_status(
platform,
request,
candidates,
include_desktop=named,
claimed_at=claimed_at,
)
_, session_key, _ = found
# 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,
{"last_seen": datetime.now(timezone.utc).isoformat()},
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
# and the missed stamp is covered by the next beat.
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, candidates)
)
await lifecycle.refresh_session_activity(session_key, refreshed)
return SessionStatusSchema(status="active", platform=platform)
)
@protected_route(router.get, "/sessions/{platform}/status", [Scope.ROMS_READ])
async def session_status(request: Request, platform: str) -> SessionStatusSchema:
async def session_status(
request: Request,
platform: str,
claimed_at: ClaimedAtQuery = None,
) -> SessionStatusSchema:
"""Does the caller still hold this platform's session?
Unlike the heartbeat this has no side effects, so a client can call it on
mount or after a reconnect without extending a claim it may not own.
Args:
claimed_at: the claim's stamp, so a tab never adopts a claim that
replaced its own.
"""
return SessionStatusSchema(**await _session_status(platform, request))
return SessionStatusSchema(
**await _session_status(platform, request, claimed_at=claimed_at)
)
@protected_route(router.post, "/sessions/{platform}/join", [Scope.ROMS_READ])
@@ -1024,16 +1118,26 @@ async def join_session(
candidate, _, session = await access.resolve_named_container(
platform, container
)
found = (candidate, session) if session is not None else None
found = (
(candidate, session)
if session is not None and session_platform_matches(session, platform)
else None
)
else:
found = None
for candidate in containers_for_platform(platform):
session = await get_live_session(candidate.key)
if session is None:
continue
if session.get("multiplayer"):
found = (candidate, session)
break
if not session_platform_matches(session, platform):
continue
# A member the caller cannot join is not the answer and must not
# mask a later one that is.
joinable, _ = access.joinable_session_rom(request, session)
if not joinable:
continue
found = (candidate, session)
break
if found is None:
raise HTTPException(
@@ -1074,10 +1178,16 @@ async def join_session(
@protected_route(router.post, "/sessions/{platform}/volume", [Scope.ROMS_USER_WRITE])
async def set_volume(
request: Request, platform: str, req: Annotated[VolumeRequest, Body()]
request: Request,
platform: str,
req: Annotated[VolumeRequest, Body()],
container_key: ContainerQuery = None,
claimed_at: ClaimedAtQuery = None,
) -> VolumeResponse:
"""Set emulator audio volume (0-100)."""
container, session_key, _ = await access.resolve_owned_session(platform, request)
container, session_key, _ = await access.require_claim(
platform, request, container_key, claimed_at
)
ok = await asyncio.to_thread(commands.set_volume, container, req.level)
if not ok:
@@ -1089,10 +1199,16 @@ async def set_volume(
@protected_route(router.post, "/sessions/{platform}/mute", [Scope.ROMS_USER_WRITE])
async def set_mute(
request: Request, platform: str, req: Annotated[MuteRequest, Body()]
request: Request,
platform: str,
req: Annotated[MuteRequest, Body()],
container_key: ContainerQuery = None,
claimed_at: ClaimedAtQuery = None,
) -> MuteResponse:
"""Toggle or explicitly set mute state. Omit body to toggle."""
container, session_key, _ = await access.resolve_owned_session(platform, request)
container, session_key, _ = await access.require_claim(
platform, request, container_key, claimed_at
)
confirmed = await asyncio.to_thread(commands.set_mute, container, req.mute)
if confirmed is None:
@@ -1106,15 +1222,19 @@ async def set_mute(
router.post, "/sessions/{platform}/save-state", [Scope.ROMS_USER_WRITE]
)
async def save_state(
request: Request, platform: str, req: Annotated[SaveStateRequest, Body()]
request: Request,
platform: str,
req: Annotated[SaveStateRequest, Body()],
container_key: ContainerQuery = None,
claimed_at: ClaimedAtQuery = None,
) -> SaveStateResponse:
"""Save game state to a slot without stopping the emulator.
The autosave slot is a valid target: the library keeps every capture, so
the player writes through one slot rather than picking one.
"""
container, session_key, session = await access.resolve_owned_session(
platform, request
container, session_key, session = await access.require_claim(
platform, request, container_key, claimed_at
)
_assert_valid_slot(platform, req.slot)
@@ -1145,10 +1265,16 @@ async def save_state(
router.post, "/sessions/{platform}/load-state", [Scope.ROMS_USER_WRITE]
)
async def load_state(
request: Request, platform: str, req: Annotated[LoadStateRequest, Body()]
request: Request,
platform: str,
req: Annotated[LoadStateRequest, Body()],
container_key: ContainerQuery = None,
claimed_at: ClaimedAtQuery = None,
) -> LoadStateResponse:
"""Load game state from a manual slot or the platform's autosave slot."""
container, session_key, _ = await access.resolve_owned_session(platform, request)
container, session_key, _ = await access.require_claim(
platform, request, container_key, claimed_at
)
_assert_valid_slot(platform, req.slot)
ok = await asyncio.to_thread(commands.load_state, container, req.slot)
@@ -1161,11 +1287,15 @@ async def load_state(
@protected_route(router.post, "/sessions/{platform}/swap-disc", [Scope.ROMS_USER_WRITE])
async def swap_disc(
request: Request, platform: str, req: Annotated[SwapDiscRequest, Body()]
request: Request,
platform: str,
req: Annotated[SwapDiscRequest, Body()],
container_key: ContainerQuery = None,
claimed_at: ClaimedAtQuery = None,
) -> SwapDiscResponse:
"""Change the mounted disc without restarting the emulator."""
container, session_key, session = await access.resolve_owned_session(
platform, request
container, session_key, session = await access.require_claim(
platform, request, container_key, claimed_at
)
# Container-scoped, not platform-scoped: only the webstation broker has a
# tray route, so a legacy container serving this platform gets the same
@@ -1208,38 +1338,27 @@ async def release_session(
platform: str,
background_tasks: BackgroundTasks,
reason: str | None = Query(default=None, max_length=200),
container_key: str | None = Query(default=None, alias="container", max_length=300),
container_key: ContainerQuery = None,
claimed_at: ClaimedAtQuery = None,
save: bool = Query(default=True),
) -> ReleaseSessionResponse:
"""Release a session and tell the broker to stop the emulator.
`reason` is only meaningful when an admin ends someone else's session; it
is surfaced to the displaced player. `container` names which container to
release, needed when a pool serves the platform and the admin is ending a
session they do not own; it is the key `GET /streaming/sessions` reports.
`save=false` is a player leaving deliberately without saving. It defaults
on because the other way in here is a tab closing, where nobody chose
anything and the last minutes of play would otherwise be gone.
Args:
reason: why an admin ended someone else's session, shown to that player.
container_key: which pool member to release: the holder sends the one it
claimed, an admin the key `GET /streaming/sessions` reports.
claimed_at: the stamp binding this release to one claim; admin panels end
whatever is running and send none.
save: false for a player leaving deliberately without saving; on by
default because a closing tab chose nothing and would lose recent play.
"""
if container_key is not None:
container, session_key, session = await access.resolve_named_container(
platform, container_key
)
if session is None:
return ReleaseSessionResponse(status="not_found", platform=platform)
access.assert_session_owner(session, request)
else:
try:
container, session_key, session = await access.resolve_owned_session(
platform, request
)
except HTTPException as exc:
# Nothing configured or nothing active: releasing is a no-op rather
# than an error, matching a repeated release from the same tab.
if exc.status_code != 404:
raise
return ReleaseSessionResponse(status="not_found", platform=platform)
target = await access.resolve_claim(
platform, request, container_key, claimed_at, game_only=False
)
if target is None:
return ReleaseSessionResponse(status="not_found", platform=platform)
container, session_key, session = target
# Teardown pulls the whole card off the broker and pushes a blank one back,
# several seconds of broker round-trips. The player who quit does not need
@@ -1276,7 +1395,11 @@ async def list_containers(request: Request) -> AdminContainersResponse:
containers: list[AdminContainerSchema] = []
for container_key, entries in containers_by_key().items():
first = entries[0]
session = await get_live_session(container_key) if container_key else None
held = await get_session(container_key) if container_key else None
# A drain marker holds the key with no owner. Reported as its own state
# rather than as a session, since there is nobody to name or release.
draining = bool(held and held.get("draining"))
session = None if draining else held
user_id = session.get("user_id") if session else None
user = db_user_handler.get_user(user_id) if isinstance(user_id, int) else None
containers.append(
@@ -1289,12 +1412,13 @@ async def list_containers(request: Request) -> AdminContainersResponse:
# A container whose host has no scheme has an empty key and can
# never be claimed, so surface it rather than listing it as idle.
configured=bool(container_key),
draining=draining,
session=(
ContainerSessionSchema(
platform=session.get("platform"),
rom_id=session.get("rom_id"),
rom_name=session.get("rom_name"),
desktop=bool(session.get("desktop")),
desktop=session_is_desktop(session),
claimed_at=session.get("claimed_at"),
user_id=user_id,
username=user.username if user else None,
@@ -1307,7 +1431,12 @@ async def list_containers(request: Request) -> AdminContainersResponse:
return AdminContainersResponse(enabled=streaming_enabled(), containers=containers)
@protected_route(router.post, "/desktop", [Scope.ROMS_USER_WRITE])
@protected_route(
router.post,
"/desktop",
[Scope.ROMS_USER_WRITE],
responses={409: {"model": ContainerBusyDetail}},
)
async def claim_desktop_session(
request: Request, req: Annotated[DesktopStreamingSessionRequest, Body()]
) -> DesktopSessionSchema:
@@ -1360,11 +1489,14 @@ async def claim_desktop_session(
existing = await get_session(session_key) or {}
raise HTTPException(
status_code=409,
detail={
"message": "Container in use",
"rom_name": access.visible_rom_name(request, existing),
"claimed_at": existing.get("claimed_at"),
},
detail=ContainerBusyDetail(
message="Container in use",
# A drain marker means the previous session is still shutting
# down, not that anyone holds it.
draining=bool(existing.get("draining")),
rom_name=access.visible_rom_name(request, existing),
claimed_at=existing.get("claimed_at"),
).model_dump(),
)
try:
@@ -1384,7 +1516,7 @@ async def claim_desktop_session(
room_url = str(launch_result.get("url", "")) if launch_result else ""
host = room_url_on(container.host, room_url)
await stamp_launched(session_key, session)
await stamp_launched(session_key, session, host=None)
log.info("desktop session claimed, container=%s", session_key)
return DesktopSessionSchema(
container=session_key,
@@ -1409,19 +1541,10 @@ async def list_joinable_sessions(
sessions: list[JoinableSessionSchema] = []
async for container_key, s in iter_live_sessions():
if not s.get("multiplayer"):
continue
if s.get("user_id") == request.user.id:
continue
if rom_id is not None and s.get("rom_id") != rom_id:
continue
session_rom_id = s.get("rom_id")
rom = (
db_rom_handler.get_rom_simple(session_rom_id)
if session_rom_id is not None
else None
)
if not access.rom_is_visible(request, rom):
joinable, rom = access.joinable_session_rom(request, s)
if not joinable:
continue
user_id = s.get("user_id")
@@ -1431,7 +1554,7 @@ async def list_joinable_sessions(
container=container_key,
label=_joinable_container_label(grouped, container_key),
platform=s.get("platform"),
rom_id=session_rom_id,
rom_id=s.get("rom_id"),
rom_name=s.get("rom_name"),
host_username=host.username if host else None,
claimed_at=s.get("claimed_at"),
@@ -1471,7 +1594,7 @@ async def list_sessions(request: Request) -> AdminSessionsResponse:
platform=s.get("platform"),
rom_id=s.get("rom_id"),
rom_name=s.get("rom_name"),
desktop=bool(s.get("desktop")),
desktop=session_is_desktop(s),
claimed_at=s.get("claimed_at"),
user_id=user_id,
username=user.username if user else None,
@@ -1513,12 +1636,16 @@ async def force_release_all(
# emulator anyway rather than leave it running.
await asyncio.to_thread(commands.stop, container)
else:
state_slot = await lifecycle.quiesce_container(container, session)
stopped = await lifecycle.quiesce_container(container, session)
# Credit playtime to the session's owner, not the admin.
await lifecycle.record_play_session(session)
await lifecycle.clear_session_activity(container_key, session)
await lifecycle.collect_exit_state(container, session, state_slot)
lifecycle.collect_exit_saves(container, session)
await lifecycle.collect_exit_state(
container, session, stopped.state_slot
)
await lifecycle.start_exit_save_pull(
container, session, settled=stopped.settled
)
# Note who ended it before the key goes, so the player's next poll
# can explain the stream vanishing.

View File

@@ -12,7 +12,12 @@ from handler.streaming.config import (
containers_for_platform,
entry_for_platform,
)
from handler.streaming.session_store import get_live_session
from handler.streaming.session_store import (
get_live_session,
session_is_desktop,
session_platform_matches,
)
from logger.logger import log
from models.rom import Rom
from models.user import Role
@@ -50,26 +55,40 @@ def rom_is_visible(request: Request, rom: Rom | None) -> bool:
return get_permissions(request).can_see_rom(rom.id, rom.platform_id)
def _session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool:
"""Can the caller see the ROM a session is running?"""
def session_rom(session: dict[str, Any]) -> Rom | None:
"""The ROM a session is running, None for a desktop or a deleted entry."""
rom_id = session.get("rom_id")
if rom_id is None:
return True
return rom_is_visible(request, db_rom_handler.get_rom_simple(rom_id))
return db_rom_handler.get_rom_simple(rom_id) if rom_id is not None else None
def session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool:
"""Can the caller see the ROM a session is running?"""
return rom_is_visible(request, session_rom(session))
def joinable_session_rom(
request: Request, session: dict[str, Any]
) -> tuple[bool, Rom | None]:
"""Whether a live session is one this caller may ask to join (its host opted
into multiplayer, it is somebody else's, its ROM is not hidden), with that ROM."""
if not session.get("multiplayer") or session.get("user_id") == request.user.id:
return False, None
rom = session_rom(session)
return rom_is_visible(request, rom), rom
def assert_session_rom_visible(
request: Request, session: dict[str, Any], *, not_found_detail: str
) -> None:
"""Raise 404 when the session's ROM is hidden from the caller."""
if not _session_rom_is_visible(request, session):
if not session_rom_is_visible(request, session):
raise HTTPException(status_code=404, detail=not_found_detail)
def visible_rom_name(request: Request, session: dict[str, Any]) -> str | None:
"""The name of the ROM a session is running, blanked when the caller cannot
see that ROM. "Busy" is safe to report to anyone; what is running is not."""
if not session or not _session_rom_is_visible(request, session):
if not session or not session_rom_is_visible(request, session):
return None
name = session.get("rom_name")
return str(name) if name else None
@@ -89,19 +108,45 @@ def platform_is_visible(request: Request, platform_slug: str) -> bool:
return get_permissions(request).can_see_platform(platform.id)
def session_in_scope(
session: dict[str, Any],
platform: str,
include_desktop: bool,
claimed_at: str | None = None,
) -> bool:
"""Whether a stored session, or the notice it left, is the one a route asked
about: same platform, a desktop only if named, the given claim."""
if not include_desktop and session_is_desktop(session):
return False
if claimed_at is not None and session.get("claimed_at") != claimed_at:
return False
return session_platform_matches(session, platform)
async def find_session_for_user(
candidates: list[ResolvedContainer], user_id: int
candidates: list[ResolvedContainer],
user_id: int,
*,
platform: str,
include_desktop: bool = False,
claimed_at: str | None = None,
) -> tuple[ResolvedContainer, str, dict[str, Any]] | None:
"""The candidate holding this user's session, as (container, key, session).
With a pool the platform no longer identifies the container, the session
does.
With a pool the platform no longer identifies the container, the session does.
Args:
platform: only sessions claimed for it match.
include_desktop: whether a desktop matches, only when its container is named.
claimed_at: only the one claim the caller was given matches.
"""
for candidate in candidates:
session_key = candidate.key
session = await get_live_session(session_key)
if session is None:
continue
if not session_in_scope(session, platform, include_desktop, claimed_at):
continue
if session.get("user_id") == user_id:
return candidate, session_key, session
return None
@@ -137,7 +182,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 in the platform's first pool.
"""Find the caller's session for this platform in its first pool.
Returns (container, session_key, session). Raises 404 when the platform has
no configured container or nothing is active, 403 when every active session
@@ -156,6 +201,9 @@ async def resolve_owned_session(
session = await get_live_session(session_key)
if session is None:
continue
# These routes act on a game; a desktop is reached by naming it.
if not session_in_scope(session, platform, include_desktop=False):
continue
if session.get("user_id") == request.user.id:
return candidate, session_key, session
others.append((candidate, session_key, session))
@@ -182,6 +230,70 @@ async def resolve_owned_session(
return others[0]
async def resolve_claim(
platform: str,
request: Request,
container_key: str | None,
claimed_at: str | None,
*,
game_only: bool,
) -> tuple[ResolvedContainer, str, dict[str, Any]] | None:
"""The session a route acting on a claim reaches, or None when that claim is gone.
Args:
container_key: the container the caller named, if any.
claimed_at: the stamp of the one claim the caller was given.
game_only: only a game of this platform matches a named container, while
a release ends whatever it holds.
"""
if container_key is not None:
container, session_key, session = await resolve_named_container(
platform, container_key
)
if session is None:
return None
if game_only and not session_in_scope(session, platform, include_desktop=False):
return None
else:
try:
container, session_key, session = await resolve_owned_session(
platform, request
)
except HTTPException as exc:
# Nothing of the caller's is active, so a stamped claim is gone and a
# repeated call from the same tab finds nothing: both are a no-op.
if exc.status_code != 404 and claimed_at is None:
raise
return None
# A tab whose claim was replaced (a takeover, or Play pressed again elsewhere)
# must not act on the claim that took its place.
if claimed_at is not None and session.get("claimed_at") != claimed_at:
log.info("%s ignored for a replaced claim", request.url.path)
return None
# After the stamp check, so another player's takeover reads as a gone claim.
if container_key is not None:
assert_session_owner(session, request)
return container, session_key, session
async def require_claim(
platform: str,
request: Request,
container_key: str | None,
claimed_at: str | None,
) -> tuple[ResolvedContainer, str, dict[str, Any]]:
"""The game a control route drives, raising 404 once the caller's claim is gone."""
target = await resolve_claim(
platform, request, container_key, claimed_at, game_only=True
)
if target is None:
raise HTTPException(
status_code=404, detail=f"No active session for platform '{platform}'"
)
return target
def container_by_key(container_key: str) -> tuple[ResolvedContainer, str]:
"""A configured container named by its key, plus the platform to file its
sessions under.

View File

@@ -172,6 +172,10 @@ _SAVE_PICKER_EMULATORS = frozenset(
{"eden", "retroarch", "rpcs3", "shadps4", "xemu", "xenia"}
)
# Emulators whose webstation broker writes a state only on exit and refuses one
# pushed in, so a resume is the slot on the activate plus the save archive.
_EXIT_STATE_EMULATORS = frozenset({"duckstation", "rpcs3"})
def slot_capabilities(platform: str, emulator: str = "") -> PlatformCapabilities:
"""Save-state and disc capabilities for a platform, or a no-slots default.
@@ -201,6 +205,12 @@ def emulator_clears_saves(emulator: str) -> bool:
return emulator.strip().lower() in _SAVE_PICKER_EMULATORS
def emulator_resumes_from_archive(emulator: str) -> bool:
"""Whether this emulator resumes from the state its save archive restores
rather than from a state file pushed into the container."""
return emulator.strip().lower() in _EXIT_STATE_EMULATORS
def known_to_lack_memory_card(platform: str) -> bool:
"""True only for a platform listed above as having no memory card.

View File

@@ -5,7 +5,7 @@ for the effect and never for the route that produces it.
"""
import urllib.error
from typing import Any
from typing import Any, NamedTuple
from config import STREAMING_SAVE_TIMEOUT
from handler.streaming import broker, webstation
@@ -50,14 +50,23 @@ def launch(
)
class SaveAndExitOutcome(NamedTuple):
"""What a save-and-exit reports back to the route."""
saved: bool
slot: int
# The broker answered once the emulator was done writing its saves.
settled: bool
def save_and_exit(
container: ResolvedContainer, slot: int = 0, wait: bool = True
) -> tuple[bool, int]:
) -> SaveAndExitOutcome:
"""
POST /save-and-exit to the broker. Best-effort, logs but never raises.
With wait=True the call blocks until save+kill completes (use for button press).
With wait=False the broker fires save+kill in the background (use for navigation away).
Returns (saved, slot). Brokers resolve slot 0 to their default autosave
Returns (saved, slot, settled). Brokers resolve slot 0 to their default autosave
slot and echo the effective slot back, which the state sync needs to pull
the right file afterwards.
"""
@@ -75,7 +84,7 @@ def save_and_exit(
if report is not None and isinstance(report.get("state_slot"), int):
effective_slot = report["state_slot"]
log.info("broker exit, saved=%s slot=%d", saved, effective_slot)
return saved, effective_slot
return SaveAndExitOutcome(saved, effective_slot, settled=report is not None)
body = broker.request_safe(
container,
@@ -91,7 +100,8 @@ def save_and_exit(
log.info(
"broker save-and-exit, saved=%s slot=%d wait=%s", saved, effective_slot, wait
)
return saved, effective_slot
# Only a confirmed save that blocked on the kill leaves nothing still writing.
return SaveAndExitOutcome(saved, effective_slot, settled=saved and wait)
def set_volume(container: ResolvedContainer, level: int) -> bool:
@@ -169,10 +179,18 @@ def swap_disc(container: ResolvedContainer, disc_path: str) -> bool:
return bool(body and body.get("status") == "ok")
def stop(container: ResolvedContainer, save: bool = True) -> int | None:
class StopOutcome(NamedTuple):
"""What a stop leaves for the teardown to collect."""
state_slot: int | None = None
# The broker answered once the emulator was done writing its saves.
settled: bool = False
def stop(container: ResolvedContainer, save: bool = True) -> StopOutcome:
"""Tell the broker to stop emulator. Best-effort, don't raise on failure.
Returns the slot a state was captured in, or None when none was. With
The outcome's slot is where a state was captured, if one was. With
`save` off no state is written at all, which is what a player leaving
without saving asked for; the game's own save data still travels either
way, so progress made at an in-game save point survives the stop.
@@ -183,11 +201,14 @@ def stop(container: ResolvedContainer, save: bool = True) -> int | None:
"""
if container.is_webstation:
report = webstation.exit_session(container, slot=0, save=save)
if save and report and report.get("state_saved"):
slot = report.get("state_slot")
return slot if isinstance(slot, int) else None
return None
if report is None:
return StopOutcome()
slot = report.get("state_slot")
if save and report.get("state_saved") and isinstance(slot, int):
return StopOutcome(slot, settled=True)
return StopOutcome(settled=True)
# These brokers ack before the emulator has flushed its saves.
broker.request_safe(
container, "/launch", "stop", method="DELETE", timeout=ACK_TIMEOUT
)
return None
return StopOutcome()

View File

@@ -22,6 +22,7 @@ from handler.streaming.capabilities import (
PlatformCapabilities,
StateTransferLimits,
emulator_clears_saves,
emulator_resumes_from_archive,
known_to_lack_memory_card,
slot_capabilities,
state_transfer_limits,
@@ -52,7 +53,10 @@ _EMULATOR_DISPLAY_NAMES: dict[str, str] = {
"eden": "Eden",
"flycast": "Flycast",
"pcsx2": "PCSX2",
"play": "Play!",
"ppsspp": "PPSSPP",
# Platform-less name; emulator_display_label names the core instead.
"retroarch": "RetroArch",
"rpcs3": "RPCS3",
"shadps4": "shadPS4",
"xemu": "xemu",
@@ -121,6 +125,12 @@ _RETROARCH_CORE_NAMES: dict[str, str] = {
}
def emulator_labels() -> dict[str, str]:
"""Display name per emulator id, for surfaces that label an id they were
handed rather than one they resolved (a save's `emulator`, say)."""
return dict(_EMULATOR_DISPLAY_NAMES)
def emulator_display_label(emulator: str, platform: str) -> str:
"""Play-button text for an emulator serving a platform, e.g. "PCSX2" or
"RA PPSSPP". Unknown emulators fall back to their configured name."""
@@ -173,6 +183,17 @@ class ResolvedContainer:
"""Whether the launch screen may offer a save other than the newest."""
return self.is_webstation and self.clears_stale_saves
@property
def resumes_from_archive(self) -> bool:
"""Whether a resume rides the save archive, with no state file to push."""
return self.is_webstation and emulator_resumes_from_archive(self.emulator)
@property
def supports_live_states(self) -> bool:
"""Whether the player may save or load a state while the game runs. An
exit-state broker refuses both, though its slot still backs the library."""
return self.capabilities["has_autosave"] and not self.resumes_from_archive
def interchangeable_with(self, other: ResolvedContainer) -> bool:
"""Whether two containers serving a platform are one pool: a player
landing on either finds the same saves and the same controls."""
@@ -579,6 +600,12 @@ def containers_for_platform(platform: str) -> list[ResolvedContainer]:
return pools[0] if pools else []
def first_claim_targets() -> list[ResolvedContainer]:
"""The first container a game claim tries, one per platform, in config
order."""
return [pools[0][0] for pools in _pools_by_platform(resolve_containers()).values()]
def containers_by_key() -> dict[str, list[ResolvedContainer]]:
"""Configured containers grouped by key. A container serving several
platforms has one record per platform, all sharing one key."""
@@ -610,9 +637,10 @@ def container_for_session(
def configured_emulator(platform: str) -> str:
"""The emulator a configured container serves this platform with, if any."""
entry = entry_for_platform(resolve_containers(), platform)
return entry.emulator if entry else ""
"""The emulator a claim's container serves this platform with, empty when none
can be claimed, taken from the pool a claim walks since slot ceilings read it."""
pool = containers_for_platform(platform)
return pool[0].emulator if pool else ""
def streaming_enabled() -> bool:

View File

@@ -61,6 +61,11 @@ async def run_launch(
phase_watch = asyncio.create_task(
_watch_launch_phase(container, session_key, session, platform)
)
# An exit-state broker resumes from the state its archive restores, so with
# no archive uploaded there is nothing of this player's to resume.
resume_on_activate = (resume_pushed or resume_after_launch) and not (
container.resumes_from_archive and archive_path is None
)
try:
# Wrapped in asyncio.to_thread because urllib is synchronous.
if container.is_webstation:
@@ -79,9 +84,7 @@ async def run_launch(
},
gui_language=gui_language,
archive_path=archive_path,
resume_slot=(
resume_slot if resume_pushed or resume_after_launch else None
),
resume_slot=resume_slot if resume_on_activate else None,
memory_card_synced=memory_card_synced,
multiplayer=multiplayer,
)
@@ -102,6 +105,7 @@ async def run_launch(
LaunchFailedPayload(
platform=platform,
container=session_key,
claimed_at=session["claimed_at"],
detail=_failure_detail(exc),
).model_dump(),
)
@@ -111,14 +115,19 @@ async def run_launch(
claim_hold.cancel()
log.info("session claimed, platform=%s rom=%s", platform, rom_name)
await stamp_launched(session_key, session)
host = container.protocol.stream_url(container.host, launch_result)
await stamp_launched(session_key, session, host=host)
await lifecycle.publish_session_activity(session_key, session)
# The webstation broker's deferred load waits for its emulator to report
# the game running, and holds off further until the state file is there, so
# this push lands ahead of it even though it runs after activate.
if resume_after_launch and resume_state is not None:
resume_pushed = await states.push_resume_state(container, resume_state)
if container.resumes_from_archive:
# The activate's slot already handed this broker the whole resume.
resume_pushed = resume_on_activate
else:
resume_pushed = await states.push_resume_state(container, resume_state)
await push_to_user(
session.get("user_id"),
@@ -126,7 +135,8 @@ async def run_launch(
LaunchReadyPayload(
platform=platform,
container=session_key,
host=container.protocol.stream_url(container.host, launch_result),
claimed_at=session["claimed_at"],
host=host,
resume=resume_pushed if resume_state is not None else None,
).model_dump(),
)
@@ -191,6 +201,9 @@ async def _watch_launch_phase(
session.get("user_id"),
"streaming:launch-phase",
LaunchPhasePayload(
platform=platform, container=session_key, phase=phase
platform=platform,
container=session_key,
claimed_at=session["claimed_at"],
phase=phase,
).model_dump(),
)

View File

@@ -107,30 +107,44 @@ async def release_after_state_pull(
async def quiesce_container(
container: ResolvedContainer, session: dict[str, Any], *, save: bool = True
) -> int | None:
) -> commands.StopOutcome:
"""Stop the emulator, then evacuate and wipe its memory card.
Every teardown path opens this way, and the order is load-bearing: stopping
first is what makes the card quiescent, and the wipe runs only where the
evacuation captured the card. Returns the slot the stop wrote an exit state
to, if any.
evacuation captured the card. Returns what the stop left to collect.
"""
state_slot = await asyncio.to_thread(commands.stop, container, save)
stopped = await asyncio.to_thread(commands.stop, container, save)
if await memory_cards.evacuate_session_card(session, container):
await memory_cards.wipe_session_card(container)
return state_slot
return stopped
def collect_exit_saves(container: ResolvedContainer, session: dict[str, Any]) -> None:
"""Start pulling the in-game save archive a stopped session left behind.
async def _pull_exit_saves(
container: ResolvedContainer,
mark: saves.SavePullMark,
broker_session: str | None,
settled: bool,
) -> None:
"""The spawned half of `collect_exit_saves`, which lets the next claim
through however the pull ended."""
try:
await saves.pull_saves_to_library(
mark.user_id, mark.rom_id, container, broker_session, settled=settled
)
finally:
await saves.clear_save_pull_pending(mark)
Fire and forget: the broker keeps the archive after the emulator dies, so
no teardown has to wait on it. Whole-card sync containers evacuate the card
instead and have no archive, and a session that ran no ROM (the admin
desktop) has nowhere to file one, so neither schedules anything.
One home for the rule: every teardown path files a session's saves the same
way, and under the session's owner rather than whoever ended it.
async def mark_exit_saves_pending(
container: ResolvedContainer, session: dict[str, Any]
) -> saves.SavePullMark | None:
"""Hold the owner's next claim on this ROM until the exit pull has filed.
Returns:
The mark for `collect_exit_saves`, or None when no pull will run: a
whole-card sync container evacuates the card instead, and a desktop ran
no ROM to file one under.
"""
rom_id = session.get("rom_id")
user_id = session.get("user_id")
@@ -139,14 +153,40 @@ def collect_exit_saves(container: ResolvedContainer, session: dict[str, Any]) ->
or not isinstance(rom_id, int)
or not isinstance(user_id, int)
):
return None
return await saves.mark_save_pull_pending(user_id, rom_id)
def collect_exit_saves(
container: ResolvedContainer,
session: dict[str, Any],
mark: saves.SavePullMark | None,
*,
settled: bool,
) -> None:
"""Pull a stopped session's save archive in the background, since the broker
keeps it after the emulator dies, filing it under the owner whoever ended it.
Args:
mark: cleared by the pull however it ends.
settled: the broker confirmed the emulator is done writing, so the first
answer is final.
"""
if mark is None:
return
background.spawn_sync_task(
saves.pull_saves_to_library(
user_id, rom_id, container, broker_session_id(session)
)
_pull_exit_saves(container, mark, broker_session_id(session), settled)
)
async def start_exit_save_pull(
container: ResolvedContainer, session: dict[str, Any], *, settled: bool
) -> None:
"""Mark the exit pull pending, then start it, for a stop that is already done."""
mark = await mark_exit_saves_pending(container, session)
collect_exit_saves(container, session, mark, settled=settled)
async def collect_exit_state(
container: ResolvedContainer, session: dict[str, Any], state_slot: int | None
) -> None:
@@ -332,15 +372,14 @@ async def teardown_released_session(
return
keepalive = _hold_reservation(session_key, token, session)
pull_mark: saves.SavePullMark | None = None
try:
# The marker, or the claim it could not replace, holds the container
# throughout, so no concurrent claim can interleave.
state_slot = await quiesce_container(container, session, save=save)
# Before anything slow: on a pool the player's next claim can land on a
# free sibling while this container drains.
pull_mark = await mark_exit_saves_pending(container, session)
# Leave a note when this is a force-release rather than a player closing
# their own game. A different user is the obvious case; a reason covers
# the rest, since only the admin panel sends one and an admin can be
# logged in as the same account that is playing in another tab.
# A force-release rather than the player quitting: another user, or a reason,
# which only the admin panel sends. Before the quiesce, so a poll finds it.
if session.get("user_id") != acting_user_id or reason is not None:
await record_termination(
session,
@@ -357,12 +396,18 @@ async def teardown_released_session(
reason or "-",
)
# The marker, or the claim it could not replace, holds the container
# throughout, so no concurrent claim can interleave.
stopped = await quiesce_container(container, session, save=save)
await record_play_session(session)
await clear_session_activity(session_key, session)
# Awaited, not spawned: the claim is released below.
await collect_exit_state(container, session, state_slot)
collect_exit_saves(container, session)
await collect_exit_state(container, session, stopped.state_slot)
collect_exit_saves(container, session, pull_mark, settled=stopped.settled)
# The pull clears it from here.
pull_mark = None
log.info("session released, platform=%s", platform)
except Exception:
@@ -375,10 +420,17 @@ async def teardown_released_session(
# whatever is still on the container; a phantom claim is not.
keepalive.cancel()
await _drop_reservation(session_key, token, session)
if pull_mark is not None:
# No pull is coming, so a claim has nothing to wait for.
await saves.clear_save_pull_pending(pull_mark)
async def _teardown_abandoned_session(
container: ResolvedContainer, session_key: str, session: dict[str, Any]
container: ResolvedContainer,
session_key: str,
session: dict[str, Any],
*,
claimed_by: int,
) -> bool:
"""Free a container whose owner vanished without releasing (heartbeat went
stale). Same order as an owner release: stop the emulator so the card is
@@ -411,17 +463,22 @@ async def _teardown_abandoned_session(
return False
keepalive = asyncio.ensure_future(hold_drain_marker(session_key, token))
pull_mark: saves.SavePullMark | None = None
try:
state_slot = await quiesce_container(container, session)
# Before anything slow, as a release does.
pull_mark = await mark_exit_saves_pending(container, session)
# That tab may still be showing the stream, so leave a force-release's note,
# but not for the owner coming back, whose new tab it would end.
if session.get("user_id") != claimed_by:
await record_termination(
session, session_key, ended_by=None, reason="abandoned"
)
stopped = await quiesce_container(container, session)
await record_play_session(session)
await clear_session_activity(session_key, session)
# That tab may still be showing the stream, so leave the same note an
# admin force-release does rather than letting the picture simply stop.
await record_termination(
session, session_key, ended_by=None, reason="abandoned"
)
await collect_exit_state(container, session, state_slot)
collect_exit_saves(container, session)
await collect_exit_state(container, session, stopped.state_slot)
collect_exit_saves(container, session, pull_mark, settled=stopped.settled)
pull_mark = None
except Exception:
log.exception("abandoned session teardown failed, key=%s", session_key)
finally:
@@ -431,6 +488,8 @@ async def _teardown_abandoned_session(
# goes, never a claim that replaced it in the meantime.
keepalive.cancel()
await drop_drain_marker(session_key, token)
if pull_mark is not None:
await saves.clear_save_pull_pending(pull_mark)
return True
@@ -447,6 +506,8 @@ async def await_teardown_within_budget(
session_key: str,
session: dict[str, Any],
budget: float,
*,
claimed_by: int,
) -> bool:
"""Tear down an abandoned session, but only wait `budget` seconds for it.
@@ -456,7 +517,9 @@ async def await_teardown_within_budget(
this leaves behind blocks a claim until the teardown drops it.
"""
task = background.spawn_sync_task(
_teardown_abandoned_session(container, session_key, session)
_teardown_abandoned_session(
container, session_key, session, claimed_by=claimed_by
)
)
try:
return await asyncio.wait_for(asyncio.shield(task), timeout=budget)

View File

@@ -7,12 +7,17 @@ a .zip extension so the whole card set travels as a unit.
"""
import asyncio
import secrets
import time
from datetime import datetime, timezone
from typing import NamedTuple
from fastapi import HTTPException
from redis.exceptions import WatchError
from handler.database import db_rom_handler, db_save_handler, db_user_handler
from handler.filesystem import fs_asset_handler
from handler.redis_handler import async_cache
from handler.scan_handler import scan_save
from handler.streaming import broker, webstation
from handler.streaming.config import ResolvedContainer
@@ -22,6 +27,78 @@ from models.rom import Rom
from models.user import User
from utils.filesystem import sanitize_filename
# An exit files its archive in the background, so a claim landing behind it would
# hydrate from the archive before last. The exit leaves a marker a claim waits out.
SAVE_PULL_WAIT_SECONDS = 20.0
_SAVE_PULL_KEY_PREFIX = "romm:streaming:save-pull:"
# Backstop for a backend that dies mid-pull: a marker nobody clears would cost
# every later claim on that ROM the full wait.
_SAVE_PULL_TTL_SECONDS = 10 * 60
_SAVE_PULL_POLL_SECONDS = 0.25
def _save_pull_redis_key(user_id: int, rom_id: int) -> str:
return f"{_SAVE_PULL_KEY_PREFIX}{user_id}:{rom_id}"
class SavePullMark(NamedTuple):
"""One exit's pending pull, whose token lets only that pull clear it."""
user_id: int
rom_id: int
token: str
async def mark_save_pull_pending(user_id: int, rom_id: int) -> SavePullMark:
"""Hold this user's claims on this ROM until the returned mark is cleared, a
later mark taking over so an earlier pull finishing cannot let a claim past it."""
token = secrets.token_hex(8)
await async_cache.set(
_save_pull_redis_key(user_id, rom_id), token, ex=_SAVE_PULL_TTL_SECONDS
)
return SavePullMark(user_id, rom_id, token)
async def clear_save_pull_pending(mark: SavePullMark) -> None:
"""Drop the marker, while it is still the one `mark` set."""
key = _save_pull_redis_key(mark.user_id, mark.rom_id)
async with async_cache.pipeline() as pipe:
await pipe.watch(key)
current = await pipe.get(key)
if isinstance(current, bytes):
current = current.decode()
if current != mark.token:
await pipe.unwatch()
return
pipe.multi()
await pipe.delete(key)
try:
await pipe.execute()
except WatchError:
# Only a later mark or the TTL moves the key, and neither is ours.
pass
async def wait_for_save_pull(
user_id: int, rom_id: int, budget: float = SAVE_PULL_WAIT_SECONDS
) -> bool:
"""Wait for a pull of this user's saves for this ROM to finish filing.
Returns:
Whether nothing is pending any more, False once `budget` runs out, since a
claim is interactive and must not hang on a wedged pull.
"""
key = _save_pull_redis_key(user_id, rom_id)
deadline = time.monotonic() + budget
while await async_cache.exists(key):
if time.monotonic() >= deadline:
log.warning(
"gave up waiting for the previous session's saves, rom_id=%d", rom_id
)
return False
await asyncio.sleep(_SAVE_PULL_POLL_SECONDS)
return True
def fetch_save_archive(
container: ResolvedContainer, broker_session_id: str | None = None
@@ -117,11 +194,17 @@ async def pull_saves_to_library(
rom_id: int,
container: ResolvedContainer,
broker_session_id: str | None = None,
*,
settled: bool = False,
) -> bool:
"""Background task: pull in-game saves from the broker and store them.
Best-effort by design, a sync failure must never surface to the player,
the save still exists inside the container.
Args:
settled: the emulator is done writing, so one attempt is final where the
retries would wait out one still writing.
"""
user = db_user_handler.get_user(user_id)
rom = db_rom_handler.get_rom(rom_id)
@@ -129,7 +212,7 @@ async def pull_saves_to_library(
return False
emulator = container.emulator
for attempt in range(broker.PULL_ATTEMPTS):
for attempt in range(1 if settled else broker.PULL_ATTEMPTS):
if attempt > 0:
await asyncio.sleep(broker.PULL_RETRY_DELAY)
content = await asyncio.to_thread(

View File

@@ -278,6 +278,20 @@ async def mutate_session(
return session if outcome is _CasOutcome.WROTE else None
def session_platform_matches(session: dict[str, Any], platform: str) -> bool:
"""Whether a session was claimed for this platform, a record from before the
field existed matching anything so an upgrade cannot strand one."""
stored = session.get("platform")
if not isinstance(stored, str) or not stored:
return True
return stored.lower() == platform.lower()
def session_is_desktop(session: dict[str, Any]) -> bool:
"""Whether a session is an admin desktop rather than a game."""
return bool(session.get("desktop"))
def same_claim(session: dict[str, Any], claim: dict[str, Any]) -> bool:
"""Whether a session read back is still the one a route resolved. Identity is
the holder plus the moment they took it, so a re-claim by the same user does
@@ -413,7 +427,9 @@ async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None:
return
async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None:
async def stamp_launched(
session_key: str, claim: dict[str, Any], host: str | None
) -> None:
"""Record that the activate returned, so the status poll stops asking the
broker for an extraction phase.
@@ -424,11 +440,18 @@ async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None:
Best-effort: a stamp that never lands only costs a few redundant broker
round trips, and failing a session that is already up would be worse.
Args:
host: a game's room URL, for the status poll to hand a tab that missed
the push; None for a desktop, whose POST is the only reader.
"""
try:
await mutate_session(
session_key,
{"launched_at": datetime.now(timezone.utc).isoformat()},
{
"launched_at": datetime.now(timezone.utc).isoformat(),
**({"host": host} if host else {}),
},
require=lambda current: same_claim(current, claim),
)
except StreamingSessionContended:
@@ -570,6 +593,12 @@ async def record_termination(
"platform": session.get("platform"),
"rom_id": session.get("rom_id"),
"rom_name": session.get("rom_name"),
# Which claim ended: a user can hold one per container, plus a desktop,
# and only the tab that holds this one should act on the notice.
"container": session_key,
# A re-claim of the container keeps its key, so the stamp names the claim.
"claimed_at": session.get("claimed_at"),
"desktop": session_is_desktop(session),
}
await async_cache.set(
_termination_redis_key(session_key, user_id),

View File

@@ -57,13 +57,16 @@ _SLOT_PATTERNS = {
# RetroArch leaves the number off its default slot: "GAME.state" is slot 0
# and "GAME.state3" is slot 3.
"retroarch": re.compile(r"\.state(\d{0,2})$"),
# DuckStation and RPCS3 write one exit state per game with no slot in the
# name, so the empty group reads as the working slot 0.
"duckstation": re.compile(r"()\.sav$"),
"rpcs3": re.compile(r"()\.SAVESTAT(?:\.zst|\.gz)?$"),
}
# Lowest slot each emulator's broker will actually address. Everything but
# RetroArch counts from 1, so a "0" in one of their names is a filename that
# happens to look like a state, not a slot they could load.
_MIN_SLOT = {"retroarch": 0}
# Lowest slot each emulator's broker addresses. The rest count from 1, so a "0"
# in one of their names is a filename that looks like a state, not a slot.
_MIN_SLOT = {"duckstation": 0, "retroarch": 0, "rpcs3": 0}
def slot_from_state_filename(emulator: str, filename: str) -> int | None:
@@ -482,9 +485,10 @@ async def hydrate_states_to_broker(
For the same reason, a resume pick already sent at claim time means there is
nothing to add here: any push would overwrite it before the broker's
deferred load fires.
deferred load fires. A container that resumes from its save archive takes no
state file at all, and the archive already carries the newest exit state.
"""
if resume_pushed:
if resume_pushed or container.resumes_from_archive:
return 0
user = db_user_handler.get_user(user_id)

View File

@@ -52,6 +52,7 @@ from endpoints.permissions import router as permissions_router
from endpoints.platform import router as platform_router
from endpoints.play_sessions import router as play_sessions_router
from endpoints.recommendations import router as recommendations_router
from endpoints.responses.streaming import SOCKET_PAYLOADS as STREAMING_SOCKET_PAYLOADS
from endpoints.roms import router as rom_router
from endpoints.saves import router as saves_router
from endpoints.screenshots import router as screenshots_router
@@ -77,6 +78,7 @@ from utils.context import (
set_context_middleware,
)
from utils.memory_cards import MEMORY_CARD_MAX_BYTES
from utils.openapi import publish_socket_payloads
logging.config.dictConfig(LOGGING_CONFIG)
@@ -219,6 +221,8 @@ app.include_router(streaming_router, prefix="/api")
app.mount("/ws", socket_handler.socket_app)
app.mount("/netplay", netplay_socket_handler.socket_app)
publish_socket_payloads(app, STREAMING_SOCKET_PAYLOADS)
# NOTE: This code is only executed when running the application directly,
# not by deployments using gunicorn.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,51 @@
from fastapi import FastAPI
from pydantic import BaseModel
from utils.openapi import publish_socket_payloads
class _Inner(BaseModel):
value: int
class _Payload(BaseModel):
name: str
inner: _Inner
class _Route(BaseModel):
ok: bool
def _app() -> FastAPI:
app = FastAPI()
@app.get("/route")
def route() -> _Route:
return _Route(ok=True)
publish_socket_payloads(app, [_Payload])
return app
def test_payload_and_its_nested_models_join_route_schemas():
schemas = _app().openapi()["components"]["schemas"]
assert "_Route" in schemas
assert schemas["_Payload"]["properties"]["inner"] == {
"$ref": "#/components/schemas/_Inner"
}
assert "_Inner" in schemas
def test_schema_is_built_once():
app = _app()
assert app.openapi() is app.openapi()
def test_app_without_routes_still_gets_the_payloads():
app = FastAPI()
publish_socket_payloads(app, [_Payload])
assert "_Payload" in app.openapi()["components"]["schemas"]

28
backend/utils/openapi.py Normal file
View File

@@ -0,0 +1,28 @@
from collections.abc import Sequence
from typing import Any
from fastapi import FastAPI
from pydantic import BaseModel
from pydantic.json_schema import models_json_schema
def publish_socket_payloads(app: FastAPI, models: Sequence[type[BaseModel]]) -> None:
"""Add Socket.IO payload models to the app's OpenAPI components.
No route references them, so FastAPI would leave them out, and the
frontend's generated types would lack the shapes its socket handlers read.
"""
build_schema = app.openapi
def openapi() -> dict[str, Any]:
if app.openapi_schema is None:
schema = build_schema()
_, definitions = models_json_schema(
[(model, "serialization") for model in models],
ref_template="#/components/schemas/{model}",
)
components = schema.setdefault("components", {}).setdefault("schemas", {})
components.update(definitions.get("$defs", {}))
return app.openapi_schema
app.openapi = openapi # type: ignore[method-assign]

View File

@@ -72,6 +72,7 @@ export type { ClientTokenSchema } from './models/ClientTokenSchema';
export type { CollectionRomsPayload } from './models/CollectionRomsPayload';
export type { CollectionSchema } from './models/CollectionSchema';
export type { ConfigResponse } from './models/ConfigResponse';
export type { ContainerBusyDetail } from './models/ContainerBusyDetail';
export type { ContainerSessionSchema } from './models/ContainerSessionSchema';
export type { ConversionStats } from './models/ConversionStats';
export type { ConversionTaskMeta } from './models/ConversionTaskMeta';
@@ -131,7 +132,10 @@ export type { JoinableSessionSchema } from './models/JoinableSessionSchema';
export type { JoinableSessionsResponse } from './models/JoinableSessionsResponse';
export type { JoinedSessionSchema } from './models/JoinedSessionSchema';
export type { LaunchboxImage } from './models/LaunchboxImage';
export type { LaunchFailedPayload } from './models/LaunchFailedPayload';
export type { LaunchingSessionSchema } from './models/LaunchingSessionSchema';
export type { LaunchPhasePayload } from './models/LaunchPhasePayload';
export type { LaunchReadyPayload } from './models/LaunchReadyPayload';
export type { LoadStateRequest } from './models/LoadStateRequest';
export type { LoadStateResponse } from './models/LoadStateResponse';
export type { LogEntrySchema } from './models/LogEntrySchema';

View File

@@ -10,6 +10,7 @@ export type AdminContainerSchema = {
platforms: Array<string>;
supports_desktop: boolean;
configured: boolean;
draining?: boolean;
session?: (ContainerSessionSchema | null);
};

View File

@@ -0,0 +1,14 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* The 409 body when a claim finds its container held.
*/
export type ContainerBusyDetail = {
message: string;
draining: boolean;
rom_name: (string | null);
claimed_at: (string | null);
};

View File

@@ -0,0 +1,14 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* `streaming:launch-failed`. The claim is already released.
*/
export type LaunchFailedPayload = {
platform: string;
container: string;
claimed_at: string;
detail: string;
};

View File

@@ -0,0 +1,14 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* `streaming:launch-phase`, while a broker unpacks a large title.
*/
export type LaunchPhasePayload = {
platform: string;
container: string;
claimed_at: string;
phase?: (string | null);
};

View File

@@ -0,0 +1,15 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* `streaming:launch-ready`, pushed once the game is up.
*/
export type LaunchReadyPayload = {
platform: string;
container: string;
claimed_at: string;
host: string;
resume?: (boolean | null);
};

View File

@@ -3,7 +3,7 @@
/* tslint:disable */
/* eslint-disable */
export type SaveAndExitResponse = {
status: string;
status: 'ok' | 'not_found';
saved: boolean;
platform: string;
released: boolean;

View File

@@ -7,6 +7,7 @@ export type SessionStatusSchema = {
status: 'active' | 'ended';
platform: string;
extraction_phase?: (string | null);
host?: (string | null);
termination?: (SessionTerminationSchema | null);
};

View File

@@ -15,5 +15,8 @@ export type SessionTerminationSchema = {
platform?: (string | null);
rom_id?: (number | null);
rom_name?: (string | null);
container?: (string | null);
claimed_at?: (string | null);
desktop?: boolean;
};

View File

@@ -6,5 +6,6 @@ import type { StreamingContainerSchema } from './StreamingContainerSchema';
export type StreamingConfigSchema = {
enabled: boolean;
containers: Array<StreamingContainerSchema>;
emulator_labels: Record<string, string>;
};

View File

@@ -14,5 +14,6 @@ export type StreamingContainerSchema = {
emulator: string;
supports_memory_cards: boolean;
supports_save_picker: boolean;
supports_live_states: boolean;
};

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "{rom} работи на този контейнер. Първо прекратете тази сесия.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Заглушаване",
"stream-occupied-body": "{rom} се играе от {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "Предишната сесия все още се затваря. Опитайте отново след малко.",
"stream-occupied-fallback": "В момента играе някой друг. Опитайте отново по-късно.",
"stream-occupied-title": "Сесията е заета",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Предишната сесия се затваря",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "Na tomto kontejneru běží {rom}. Nejprve tuto relaci ukončete.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Ztlumit",
"stream-occupied-body": "{rom} se hraje od {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "Předchozí relace se stále ukončuje. Zkuste to znovu za chvíli.",
"stream-occupied-fallback": "Právě hraje někdo jiný. Zkuste to později.",
"stream-occupied-title": "Relace se používá",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Ukončování předchozí relace",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "Auf diesem Container läuft {rom}. Beende zuerst diese Sitzung.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Stummschalten",
"stream-occupied-body": "{rom} wird seit {time} gespielt.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "Die vorherige Sitzung wird noch beendet. Versuche es gleich noch einmal.",
"stream-occupied-fallback": "Jemand anderes spielt gerade. Versuchen Sie es später erneut.",
"stream-occupied-title": "Sitzung in Benutzung",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Vorherige Sitzung wird beendet",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "{rom} is running on this container. End that session first.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Mute",
"stream-occupied-body": "{rom} has been playing since {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "The previous session is still shutting down. Try again in a moment.",
"stream-occupied-fallback": "Someone else is currently playing. Try again later.",
"stream-occupied-title": "Session in use",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Shutting down the previous session",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "{rom} is running on this container. End that session first.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Mute",
"stream-occupied-body": "{rom} has been playing since {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "The previous session is still shutting down. Try again in a moment.",
"stream-occupied-fallback": "Someone else is currently playing. Try again later.",
"stream-occupied-title": "Session in use",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Shutting down the previous session",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "{rom} se está ejecutando en este contenedor. Finaliza esa sesión primero.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Silenciar",
"stream-occupied-body": "{rom} se está jugando desde las {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "La sesión anterior aún se está cerrando. Inténtalo de nuevo en un momento.",
"stream-occupied-fallback": "Otra persona está jugando en este momento. Inténtalo de nuevo más tarde.",
"stream-occupied-title": "Sesión en uso",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Cerrando la sesión anterior",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "{rom} est en cours d'exécution sur ce conteneur. Terminez d'abord cette session.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Couper le son",
"stream-occupied-body": "{rom} est en cours de partie depuis {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "La session précédente est encore en cours de fermeture. Réessayez dans un instant.",
"stream-occupied-fallback": "Quelqu'un d'autre joue actuellement. Réessayez plus tard.",
"stream-occupied-title": "Session en cours d'utilisation",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Fermeture de la session précédente",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "Ezen a konténeren fut: {rom}. Előbb fejezd be azt a munkamenetet.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Némítás",
"stream-occupied-body": "A(z) {rom} játékban van {time} óta.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "Az előző munkamenet még leáll. Próbáld újra egy pillanat múlva.",
"stream-occupied-fallback": "Jelenleg valaki más játszik. Próbálja meg később.",
"stream-occupied-title": "A munkamenet használatban van",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Az előző munkamenet leállítása",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "{rom} è in esecuzione su questo container. Termina prima quella sessione.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Disattiva audio",
"stream-occupied-body": "{rom} è in gioco da {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "La sessione precedente è ancora in chiusura. Riprova tra un momento.",
"stream-occupied-fallback": "Qualcun altro sta giocando in questo momento. Riprova più tardi.",
"stream-occupied-title": "Sessione in uso",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Chiusura della sessione precedente",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "このコンテナでは {rom} が実行中です。先にそのセッションを終了してください。",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "ミュート",
"stream-occupied-body": "{rom} は {time} からプレイされています。",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "前のセッションはまだ終了処理中です。しばらくしてからもう一度お試しください。",
"stream-occupied-fallback": "現在、他の人がプレイ中です。後でもう一度お試しください。",
"stream-occupied-title": "セッション使用中",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "前のセッションを終了しています",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "이 컨테이너에서 {rom}이(가) 실행 중입니다. 먼저 해당 세션을 종료하세요.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "음소거",
"stream-occupied-body": "{rom}을(를) {time}부터 플레이하고 있습니다.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "이전 세션이 아직 종료되는 중입니다. 잠시 후 다시 시도하세요.",
"stream-occupied-fallback": "현재 다른 사람이 플레이 중입니다. 나중에 다시 시도하세요.",
"stream-occupied-title": "세션 사용 중",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "이전 세션을 종료하는 중",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "Na tym kontenerze działa {rom}. Najpierw zakończ tę sesję.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Wycisz",
"stream-occupied-body": "{rom} jest w grze od {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "Poprzednia sesja wciąż się zamyka. Spróbuj ponownie za chwilę.",
"stream-occupied-fallback": "Ktoś inny obecnie gra. Spróbuj ponownie później.",
"stream-occupied-title": "Sesja w użyciu",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Zamykanie poprzedniej sesji",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "{rom} está em execução neste contêiner. Encerre essa sessão primeiro.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Silenciar",
"stream-occupied-body": "{rom} está sendo jogado desde {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "A sessão anterior ainda está sendo encerrada. Tente novamente em instantes.",
"stream-occupied-fallback": "Outra pessoa está jogando no momento. Tente novamente mais tarde.",
"stream-occupied-title": "Sessão em uso",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Encerrando a sessão anterior",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "{rom} rulează pe acest container. Închide mai întâi acea sesiune.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Dezactivează sunetul",
"stream-occupied-body": "{rom} este jucat din {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "Sesiunea anterioară încă se închide. Încearcă din nou peste câteva momente.",
"stream-occupied-fallback": "Altcineva joacă în acest moment. Încercați din nou mai târziu.",
"stream-occupied-title": "Sesiune în uz",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Se închide sesiunea anterioară",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "На этом контейнере запущено: {rom}. Сначала завершите эту сессию.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Отключить звук",
"stream-occupied-body": "В {rom} играют с {time}.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "Предыдущая сессия ещё завершается. Попробуйте снова через несколько секунд.",
"stream-occupied-fallback": "Сейчас играет кто-то другой. Повторите попытку позже.",
"stream-occupied-title": "Сеанс занят",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Завершение предыдущей сессии",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "Bu konteynerde {rom} çalışıyor. Önce o oturumu sonlandırın.",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "Sessize al",
"stream-occupied-body": "{rom} {time} saatinden beri oynanıyor.",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "Önceki oturum hâlâ kapatılıyor. Birazdan tekrar deneyin.",
"stream-occupied-fallback": "Şu anda başka biri oynuyor. Daha sonra tekrar deneyin.",
"stream-occupied-title": "Oturum kullanımda",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "Önceki oturum kapatılıyor",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -29,6 +29,7 @@
"desktop-back": "返回管理后台",
"desktop-error-no-container": "未配置该串流容器。",
"desktop-error-occupied": "此容器正在使用中。请先结束占用它的会话。",
"desktop-error-occupied-by": "此容器上正在运行 {rom}。请先结束该会话。",
"desktop-error-release": "无法释放桌面会话。容器可能仍在使用中。",
"desktop-error-server": "无法打开桌面会话。",
"desktop-exit": "结束桌面会话",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "无法加载该状态。",
"stream-mute": "静音",
"stream-occupied-body": "{rom} 自 {time} 起一直在游玩。",
"stream-occupied-draining": "上一个会话仍在保存中。请稍后再试。",
"stream-occupied-draining": "上一个会话仍在关闭中。请稍后再试。",
"stream-occupied-fallback": "当前有其他人正在游玩。请稍后再试。",
"stream-occupied-title": "会话使用中",
"stream-release-failed": "无法释放会话。容器可能仍在使用中。",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "桌面会话",
"streaming-disabled": "此服务器已禁用模拟器串流。",
"streaming-draining": "正在关闭上一个会话",
"streaming-idle": "空闲",
"streaming-load-failed": "无法加载串流容器。",
"streaming-none": "未配置任何串流容器。",

View File

@@ -29,6 +29,7 @@
"desktop-back": "Back to administration",
"desktop-error-no-container": "That streaming container is not configured.",
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
"desktop-error-occupied-by": "此容器上正在執行 {rom}。請先結束該工作階段。",
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
"desktop-error-server": "The desktop session could not be opened.",
"desktop-exit": "End desktop session",
@@ -225,7 +226,7 @@
"stream-load-state-failed": "The state could not be loaded.",
"stream-mute": "靜音",
"stream-occupied-body": "{rom} 自 {time} 起一直在遊玩。",
"stream-occupied-draining": "The previous session is still saving. Try again in a moment.",
"stream-occupied-draining": "上一個工作階段仍在關閉中。請稍後再試。",
"stream-occupied-fallback": "目前有其他人正在遊玩。請稍後再試。",
"stream-occupied-title": "工作階段使用中",
"stream-release-failed": "The session could not be released. The container may still be in use.",

View File

@@ -462,6 +462,7 @@
"streaming-by": "({user})",
"streaming-desktop-session": "Desktop session",
"streaming-disabled": "Emulator streaming is disabled on this server.",
"streaming-draining": "正在關閉上一個工作階段",
"streaming-idle": "Idle",
"streaming-load-failed": "Could not load the streaming containers.",
"streaming-none": "No streaming containers are configured.",

View File

@@ -0,0 +1,99 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import streamingApi from "@/services/api/streaming";
const post = vi.hoisted(() => vi.fn());
vi.mock("@/services/api", () => ({
default: { post },
keepaliveHeaders: () => ({}),
}));
describe("releaseSessionKeepalive", () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response());
beforeEach(() => {
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
fetchMock.mockClear();
});
it("names the container and the claim where URLSearchParams has no size", async () => {
// Chrome 111-112 and Safari 16.4 are in .browserslistrc and predate it.
vi.spyOn(URLSearchParams.prototype, "size", "get").mockReturnValue(
undefined as unknown as number,
);
await streamingApi.releaseSessionKeepalive(
"ps2",
"WEBSTATION-DEV",
"2026-09-17T12:00:00+00:00",
);
expect(fetchMock.mock.calls[0][0]).toBe(
"/api/streaming/sessions/ps2?container=WEBSTATION-DEV&claimed_at=2026-09-17T12%3A00%3A00%2B00%3A00",
);
});
it("sends no query when there is nothing to name", async () => {
await streamingApi.releaseSessionKeepalive("ps2");
expect(fetchMock.mock.calls[0][0]).toBe("/api/streaming/sessions/ps2");
});
});
describe("saveAndExitKeepalive", () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response());
beforeEach(() => {
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
vi.unstubAllGlobals();
fetchMock.mockClear();
});
it("names the container and the claim it saves", async () => {
await streamingApi.saveAndExitKeepalive(
"ps2",
0,
"WEBSTATION-DEV",
"2026-09-17T12:00:00+00:00",
);
expect(fetchMock.mock.calls[0][0]).toBe(
"/api/streaming/sessions/ps2/save-and-exit?container=WEBSTATION-DEV&claimed_at=2026-09-17T12%3A00%3A00%2B00%3A00",
);
});
});
describe("saveAndExit", () => {
beforeEach(() => {
post.mockReset();
});
it("names the container and the claim it saves", async () => {
await streamingApi.saveAndExit(
"ps2",
0,
true,
"WEBSTATION-DEV",
"2026-09-17T12:00:00+00:00",
);
expect(post).toHaveBeenCalledWith(
"/streaming/sessions/ps2/save-and-exit",
{ slot: 0, wait: true },
{
params: {
container: "WEBSTATION-DEV",
claimed_at: "2026-09-17T12:00:00+00:00",
},
},
);
});
});

View File

@@ -1,16 +1,31 @@
import type {
AdminContainerSchema,
AdminContainersResponse,
AdminSessionSchema,
AdminSessionsResponse,
ClaimStreamingSessionRequest,
ContainerBusyDetail,
LaunchingSessionSchema,
DesktopSessionSchema,
JoinableSessionSchema,
JoinableSessionsResponse,
JoinedSessionSchema,
LaunchFailedPayload,
LaunchPhasePayload,
LaunchReadyPayload,
LoadStateResponse,
MemoryCardImportRequired,
MuteResponse,
ReleaseSessionResponse,
SaveAndExitResponse,
SaveStateResponse,
SessionStatusSchema,
SessionTerminationSchema,
SlotCapabilitiesSchema,
StreamingConfigSchema,
StreamingContainerSchema,
SwapDiscResponse,
VolumeResponse,
} from "@/__generated__";
import api, { keepaliveHeaders } from "@/services/api";
@@ -26,34 +41,12 @@ export type StreamingContainer = StreamingContainerSchema;
export type StreamingConfig = StreamingConfigSchema;
export type LaunchingSession = LaunchingSessionSchema;
// The launch's own result arrives on the socket, and socket payloads reach no
// route so they are not in the OpenAPI schema (constitution SS X.10, backend
// debt). The backend builds each of these from a model of the same name in
// endpoints/responses/streaming.py, so the shapes stay tied.
// Socket payloads reach no route, so the backend publishes them into the
// schema by hand (utils/openapi.py).
export type LaunchReady = LaunchReadyPayload;
export type LaunchFailed = LaunchFailedPayload;
export type LaunchPhase = LaunchPhasePayload;
/** `streaming:launch-ready`: the game is up, and `host` is the iframe URL. */
export interface LaunchReady {
platform: string;
container: string;
host: string;
/** null when no resume was asked for; false means the state could not be
* pushed and the session started fresh. */
resume: boolean | null;
}
/** `streaming:launch-failed`. The claim is already released. */
export interface LaunchFailed {
platform: string;
container: string;
detail: string;
}
/** `streaming:launch-phase`, while a broker unpacks a large title. */
export interface LaunchPhase {
platform: string;
container: string;
phase: string | null;
}
export type AdminStreamingSession = AdminSessionSchema;
export type AdminStreamingContainer = AdminContainerSchema;
export type DesktopSession = DesktopSessionSchema;
@@ -68,7 +61,9 @@ export type MemoryCardImportDetail = MemoryCardImportRequired;
/** The answer to that prompt, replayed on the retried claim. "discard" erases
* the card currently on the container. */
export type MemoryCardImport = "adopt" | "discard";
export type MemoryCardImport = NonNullable<
ClaimStreamingSessionRequest["card_import"]
>;
export function isMemoryCardImportDetail(
value: unknown,
@@ -80,6 +75,20 @@ export function isMemoryCardImportDetail(
);
}
/** Body of the 409 a claim returns when the container is taken. */
export type { ContainerBusyDetail };
/** The query naming a claim by its container and the stamp it was taken at. */
function claimParams(
container?: string | null,
claimedAt?: string | null,
): { container?: string; claimed_at?: string } {
return {
...(container != null ? { container } : {}),
...(claimedAt != null ? { claimed_at: claimedAt } : {}),
};
}
// ── Requests ──────────────────────────────────────────────────────────────────
async function fetchConfig() {
@@ -112,17 +121,18 @@ async function claimSession(
async function releaseSession(
platform: string,
reason?: string,
container?: string,
container?: string | null,
save?: boolean,
claimedAt?: string | null,
) {
return api.delete(`/streaming/sessions/${platform}`, {
return api.delete<ReleaseSessionResponse>(`/streaming/sessions/${platform}`, {
params: {
// The holder names its container and stamp so a taken-over tab cannot end
// the claim that replaced it. An admin names its pick and no stamp.
...claimParams(container, claimedAt),
// Sent whenever the caller supplied one, empty string included: the
// backend treats the param's presence as "this is an admin force-release".
...(reason !== undefined ? { reason } : {}),
// Names which container to release, needed when a pool serves the
// platform and the admin is ending a session they do not own.
...(container !== undefined ? { container } : {}),
// Only the player who deliberately stopped without saving sends this.
// Everything else leaves it off so the backend still autosaves.
...(save === false ? { save: false } : {}),
@@ -131,9 +141,7 @@ async function releaseSession(
}
async function listJoinableSessions() {
return api.get<{ sessions: JoinableSession[] }>(
"/streaming/sessions/joinable",
);
return api.get<JoinableSessionsResponse>("/streaming/sessions/joinable");
}
async function joinSession(platform: string, container?: string) {
@@ -144,61 +152,111 @@ async function joinSession(platform: string, container?: string) {
);
}
async function saveAndExit(platform: string, slot = 0, wait = true) {
return api.post(`/streaming/sessions/${platform}/save-and-exit`, {
slot,
wait,
});
async function saveAndExit(
platform: string,
slot = 0,
wait = true,
container?: string | null,
claimedAt?: string | null,
) {
return api.post<SaveAndExitResponse>(
`/streaming/sessions/${platform}/save-and-exit`,
{ slot, wait },
{ params: claimParams(container, claimedAt) },
);
}
async function heartbeatSession(platform: string, container?: string) {
async function heartbeatSession(
platform: string,
container?: string | null,
claimedAt?: string | null,
) {
return api.post<SessionStatus>(
`/streaming/sessions/${platform}/heartbeat`,
undefined,
{ params: { container } },
{ params: claimParams(container, claimedAt) },
);
}
async function sessionStatus(platform: string) {
return api.get<SessionStatus>(`/streaming/sessions/${platform}/status`);
}
async function setVolume(platform: string, level: number) {
return api.post(`/streaming/sessions/${platform}/volume`, {
level: Math.round(level),
async function sessionStatus(platform: string, claimedAt?: string | null) {
return api.get<SessionStatus>(`/streaming/sessions/${platform}/status`, {
params: { claimed_at: claimedAt },
});
}
async function setMute(platform: string, mute?: boolean) {
return api.post(
async function setVolume(
platform: string,
level: number,
container?: string | null,
claimedAt?: string | null,
) {
return api.post<VolumeResponse>(
`/streaming/sessions/${platform}/volume`,
{ level: Math.round(level) },
{ params: claimParams(container, claimedAt) },
);
}
async function setMute(
platform: string,
mute?: boolean,
container?: string | null,
claimedAt?: string | null,
) {
return api.post<MuteResponse>(
`/streaming/sessions/${platform}/mute`,
mute !== undefined ? { mute } : {},
{ params: claimParams(container, claimedAt) },
);
}
async function saveState(platform: string, slot = 1) {
return api.post(`/streaming/sessions/${platform}/save-state`, { slot });
async function saveState(
platform: string,
slot = 1,
container?: string | null,
claimedAt?: string | null,
) {
return api.post<SaveStateResponse>(
`/streaming/sessions/${platform}/save-state`,
{ slot },
{ params: claimParams(container, claimedAt) },
);
}
async function loadState(platform: string, slot = 1) {
return api.post(`/streaming/sessions/${platform}/load-state`, { slot });
async function loadState(
platform: string,
slot = 1,
container?: string | null,
claimedAt?: string | null,
) {
return api.post<LoadStateResponse>(
`/streaming/sessions/${platform}/load-state`,
{ slot },
{ params: claimParams(container, claimedAt) },
);
}
async function swapDisc(platform: string, fileId: number) {
return api.post(`/streaming/sessions/${platform}/swap-disc`, {
file_id: fileId,
});
async function swapDisc(
platform: string,
fileId: number,
container?: string | null,
claimedAt?: string | null,
) {
return api.post<SwapDiscResponse>(
`/streaming/sessions/${platform}/swap-disc`,
{ file_id: fileId },
{ params: claimParams(container, claimedAt) },
);
}
async function adminListSessions() {
return api.get<{ sessions: AdminStreamingSession[] }>("/streaming/sessions");
return api.get<AdminSessionsResponse>("/streaming/sessions");
}
async function adminListContainers() {
return api.get<{ enabled: boolean; containers: AdminStreamingContainer[] }>(
"/streaming/containers",
{ headers: { "Cache-Control": "no-cache" } },
);
return api.get<AdminContainersResponse>("/streaming/containers", {
headers: { "Cache-Control": "no-cache" },
});
}
async function claimDesktop(container: string) {
@@ -211,8 +269,28 @@ async function claimDesktop(container: string) {
// sendBeacon cannot carry the CSRF header, so the cookie-sourced header is
// set by hand (mirrors the axios interceptor).
function saveAndExitKeepalive(platform: string, slot = 0): Promise<Response> {
return fetch(`/api/streaming/sessions/${platform}/save-and-exit`, {
// Names which container and which claim, so an unload cannot end the claim
// that replaced it.
function claimQuery(
container?: string | null,
claimedAt?: string | null,
): string {
const search = new URLSearchParams(
Object.entries(claimParams(container, claimedAt)).filter(
([, value]) => value,
),
).toString();
return search ? `?${search}` : "";
}
function saveAndExitKeepalive(
platform: string,
slot = 0,
container?: string | null,
claimedAt?: string | null,
): Promise<Response> {
const query = claimQuery(container, claimedAt);
return fetch(`/api/streaming/sessions/${platform}/save-and-exit${query}`, {
method: "POST",
keepalive: true,
credentials: "same-origin",
@@ -223,10 +301,10 @@ function saveAndExitKeepalive(platform: string, slot = 0): Promise<Response> {
function releaseSessionKeepalive(
platform: string,
container?: string,
container?: string | null,
claimedAt?: string | null,
): Promise<Response> {
// Names which container to release, for the platforms a pool serves.
const query = container ? `?container=${encodeURIComponent(container)}` : "";
const query = claimQuery(container, claimedAt);
return fetch(`/api/streaming/sessions/${platform}${query}`, {
method: "DELETE",
keepalive: true,

View File

@@ -4,7 +4,11 @@ import streamingApi, { type JoinableSession } from "@/services/api/streaming";
import { useStreamingStore } from "@/stores/streaming";
vi.mock("@/services/api/streaming", () => ({
default: { listJoinableSessions: vi.fn() },
default: {
listJoinableSessions: vi.fn(),
saveAndExit: vi.fn(),
saveAndExitKeepalive: vi.fn(),
},
}));
describe("platformCapabilities disc flags", () => {
@@ -14,6 +18,7 @@ describe("platformCapabilities disc flags", () => {
const store = useStreamingStore();
store.config = {
enabled: true,
emulator_labels: {},
containers: [
{
platform: "dc",
@@ -22,6 +27,7 @@ describe("platformCapabilities disc flags", () => {
emulator: "retroarch",
supports_memory_cards: false,
supports_save_picker: false,
supports_live_states: true,
capabilities: {
max_slots: 0,
has_autosave: true,
@@ -43,6 +49,41 @@ describe("platformCapabilities disc flags", () => {
});
});
describe("emulator labels", () => {
beforeEach(() => setActivePinia(createPinia()));
it("names an emulator by the label the backend ships", () => {
const store = useStreamingStore();
store.config = {
enabled: true,
containers: [],
emulator_labels: { play: "Play!" },
};
expect(store.emulatorLabel("play")).toBe("Play!");
});
it("names an emulator configured in another case", () => {
const store = useStreamingStore();
store.config = {
enabled: true,
containers: [],
emulator_labels: { play: "Play!" },
};
expect(store.emulatorLabel("Play")).toBe("Play!");
});
it("falls back to the id for an emulator it was told nothing about", () => {
const store = useStreamingStore();
expect(store.emulatorLabel("snes9x")).toBe("snes9x");
});
it("falls back to the id for one named like an object's own members", () => {
const store = useStreamingStore();
expect(store.emulatorLabel("constructor")).toBe("constructor");
expect(store.emulatorLabel("__proto__")).toBe("__proto__");
});
});
describe("joinable sessions", () => {
const listJoinableSessions =
streamingApi.listJoinableSessions as unknown as Mock;
@@ -116,3 +157,53 @@ describe("joinable sessions", () => {
expect(store.joinableForRom(7)?.host_username).toBe("ana");
});
});
describe("save-and-exit", () => {
const saveAndExit = streamingApi.saveAndExit as unknown as Mock;
const saveAndExitKeepalive =
streamingApi.saveAndExitKeepalive as unknown as Mock;
beforeEach(() => {
setActivePinia(createPinia());
saveAndExit.mockReset();
saveAndExitKeepalive.mockReset();
});
it("names the claim it saves", async () => {
saveAndExit.mockResolvedValue({ data: { released: true, saved: true } });
await useStreamingStore().saveAndExit(
"ps2",
0,
false,
"ps2-1",
"2026-01-01T00:00:00Z",
);
expect(saveAndExit).toHaveBeenCalledWith(
"ps2",
0,
false,
"ps2-1",
"2026-01-01T00:00:00Z",
);
});
it("names the claim it saves on unload", () => {
saveAndExitKeepalive.mockResolvedValue(new Response());
useStreamingStore().saveAndExitKeepalive(
"ps2",
0,
"ps2-1",
"2026-01-01T00:00:00Z",
);
expect(saveAndExitKeepalive).toHaveBeenCalledWith(
"ps2",
0,
"ps2-1",
"2026-01-01T00:00:00Z",
);
});
});

View File

@@ -10,6 +10,7 @@ import type {
StreamingConfig,
StreamingContainer,
} from "@/services/api/streaming";
import { emulatorLabelFrom } from "@/v2/utils/assets";
export type {
LaunchingSession,
@@ -39,6 +40,7 @@ export const useStreamingStore = defineStore("streaming", () => {
const config = ref<StreamingConfig>({
enabled: false,
containers: [],
emulator_labels: {},
});
const launchingSession = ref<LaunchingSession | null>(null);
const loading = ref(false);
@@ -79,6 +81,11 @@ export const useStreamingStore = defineStore("streaming", () => {
return container.label || container.emulator || null;
}
/** The backend's display name for an emulator id, else the id as it stands. */
function emulatorLabel(emulator: string | null | undefined): string {
return emulatorLabelFrom(config.value.emulator_labels, emulator);
}
/**
* Returns per-platform save-state capabilities for the streaming player UI,
* sourced from the container config the backend ships in /config (the single
@@ -121,6 +128,7 @@ export const useStreamingStore = defineStore("streaming", () => {
config.value = {
enabled: data.enabled ?? false,
containers: data.containers ?? [],
emulator_labels: data.emulator_labels ?? {},
};
} catch (err) {
error.value = String(err);
@@ -252,10 +260,18 @@ export const useStreamingStore = defineStore("streaming", () => {
async function releaseSession(
platform: string,
save = true,
container?: string | null,
claimedAt?: string | null,
): Promise<boolean> {
if (!platform) return false;
try {
await streamingApi.releaseSession(platform, undefined, undefined, save);
await streamingApi.releaseSession(
platform,
undefined,
container,
save,
claimedAt,
);
launchingSession.value = null;
return true;
} catch (err) {
@@ -278,10 +294,18 @@ export const useStreamingStore = defineStore("streaming", () => {
platform: string,
slot = 0,
wait = true,
container?: string | null,
claimedAt?: string | null,
): Promise<{ released: boolean; saved: boolean }> {
if (!platform) return { released: false, saved: false };
try {
const { data } = await streamingApi.saveAndExit(platform, slot, wait);
const { data } = await streamingApi.saveAndExit(
platform,
slot,
wait,
container,
claimedAt,
);
const released = data.released ?? true;
if (released) launchingSession.value = null;
return { released, saved: data.saved ?? false };
@@ -302,11 +326,16 @@ export const useStreamingStore = defineStore("streaming", () => {
*/
async function heartbeatSession(
platform: string,
container?: string,
container?: string | null,
claimedAt?: string | null,
): Promise<SessionStatus | null> {
if (!platform) return null;
try {
const { data } = await streamingApi.heartbeatSession(platform, container);
const { data } = await streamingApi.heartbeatSession(
platform,
container,
claimedAt,
);
return data;
} catch (err) {
console.warn("[streaming] Could not heartbeat session:", err);
@@ -321,10 +350,11 @@ export const useStreamingStore = defineStore("streaming", () => {
*/
async function fetchSessionStatus(
platform: string,
claimedAt?: string,
): Promise<SessionStatus | null> {
if (!platform) return null;
try {
const { data } = await streamingApi.sessionStatus(platform);
const { data } = await streamingApi.sessionStatus(platform, claimedAt);
return data;
} catch (err) {
console.warn("[streaming] Could not fetch session status:", err);
@@ -338,26 +368,39 @@ export const useStreamingStore = defineStore("streaming", () => {
* is gone (wait=false; the backend forces a blocking save for card-sync
* containers anyway). Best-effort, never throws.
*/
function saveAndExitKeepalive(platform: string, slot = 0): void {
function saveAndExitKeepalive(
platform: string,
slot = 0,
container?: string | null,
claimedAt?: string | null,
): void {
if (!platform) return;
launchingSession.value = null;
// The caller is unloading and cannot await, so the rejection is caught on
// the promise itself; try/catch here would only see a synchronous throw.
streamingApi.saveAndExitKeepalive(platform, slot).catch((err) => {
console.warn("[streaming] Could not save-and-exit (keepalive):", err);
});
streamingApi
.saveAndExitKeepalive(platform, slot, container, claimedAt)
.catch((err) => {
console.warn("[streaming] Could not save-and-exit (keepalive):", err);
});
}
/**
* releaseSession for the pagehide path. Fire-and-forget via fetch
* keepalive. Best-effort, never throws.
*/
function releaseSessionKeepalive(platform: string): void {
function releaseSessionKeepalive(
platform: string,
container?: string | null,
claimedAt?: string | null,
): void {
if (!platform) return;
launchingSession.value = null;
streamingApi.releaseSessionKeepalive(platform).catch((err) => {
console.warn("[streaming] Could not release session (keepalive):", err);
});
streamingApi
.releaseSessionKeepalive(platform, container, claimedAt)
.catch((err) => {
console.warn("[streaming] Could not release session (keepalive):", err);
});
}
return {
@@ -369,6 +412,7 @@ export const useStreamingStore = defineStore("streaming", () => {
isEnabled,
containerForPlatform,
containerLabelForPlatform,
emulatorLabel,
platformCapabilities,
fetchConfig,
claimSession,

View File

@@ -1,7 +1,7 @@
import { AxiosError } from "axios";
/** A refused request as axios rejects it, carrying FastAPI's `detail`. */
export function serverError(detail: string, status = 503): AxiosError {
export function serverError(detail: unknown, status = 503): AxiosError {
return Object.assign(new AxiosError(`HTTP ${status}`), {
response: { status, data: { detail } },
});

View File

@@ -0,0 +1,14 @@
import { emulatorLabelFrom } from "@/v2/utils/assets";
// Stands in for `@/stores/streaming` via `vi.mock(path, () => import(...))`.
const EMULATOR_LABELS: Record<string, string> = {
play: "Play!",
retroarch: "RetroArch",
};
export function useStreamingStore() {
return {
emulatorLabel: (id: string | null | undefined) =>
emulatorLabelFrom(EMULATOR_LABELS, id),
};
}

View File

@@ -0,0 +1,76 @@
import { mount } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DetailedRomSchema, UserStateSchema } from "@/__generated__";
import storeAuth from "@/stores/auth";
import type { User } from "@/stores/users";
import SaveDataTab from "./SaveDataTab.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
vi.mock("vue-router", async (importOriginal) => ({
...(await importOriginal<typeof import("vue-router")>()),
useRoute: () => ({ query: {}, path: "/rom/1", params: {} }),
useRouter: () => ({ replace: vi.fn(), push: vi.fn() }),
}));
vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => vi.fn() }));
vi.mock("@/v2/composables/useRomSync", () => ({
useRomSync: () => ({ refetchRom: vi.fn() }),
}));
vi.mock("@/v2/composables/useSnackbar", () => ({
useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }),
}));
const UploadAssetDialog = {
props: { cores: { type: Array, default: () => [] } },
template: `<div class="upload-dialog" />`,
};
function state(id: number, emulator: string): UserStateSchema {
return {
id,
user_id: 1,
file_name: `state_${id}.state`,
updated_at: "2026-09-16T10:00:00Z",
emulator,
} as UserStateSchema;
}
function mountTab(states: UserStateSchema[]) {
return mount(SaveDataTab, {
props: {
rom: {
id: 1,
platform_slug: "ps2",
all_user_saves: [],
all_user_states: states,
} as unknown as DetailedRomSchema,
},
global: {
stubs: {
UploadAssetDialog,
SubtabNav: true,
AssetStrip: true,
AssetList: true,
RDropzone: true,
RBtn: true,
},
},
});
}
describe("SaveDataTab upload cores", () => {
beforeEach(() => {
setActivePinia(createPinia());
storeAuth().setCurrentUser({ id: 1 } as User);
});
it("offers an emulator configured in another case once", () => {
const wrapper = mountTab([state(1, "play"), state(2, "Play")]);
expect(wrapper.findComponent(UploadAssetDialog).props("cores")).toEqual([
"play",
]);
});
});

View File

@@ -48,7 +48,7 @@ import { useIdSelection } from "@/v2/composables/useIdSelection";
import { useRomSync } from "@/v2/composables/useRomSync";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { useSubtabQuery } from "@/v2/composables/useSubtabQuery";
import type { AssetType } from "@/v2/utils/assets";
import { emulatorKey, type AssetType } from "@/v2/utils/assets";
import { errorMessage } from "@/v2/utils/errorMessage";
// Slot payload from AssetList/AssetStrip is the full save|state union; these
@@ -128,18 +128,20 @@ function openUpload(type: AssetType, files: File[] = []) {
function closeUpload() {
uploadDialog.value = null;
}
// The cores the player offers plus whatever the existing states carry.
// The cores the player offers plus whatever the existing states carry, keyed
// case-insensitively as the backend matches them.
const uploadCores = computed(() => {
const cores = new Set(
getSupportedEJSCores(
props.rom.platform_slug,
configStore.config.EJS_NETPLAY_ENABLED,
),
const cores = new Map<string, string>();
const offered = getSupportedEJSCores(
props.rom.platform_slug,
configStore.config.EJS_NETPLAY_ENABLED,
);
for (const state of myStates.value) {
if (state.emulator) cores.add(state.emulator);
const carried = myStates.value.map((state) => state.emulator);
for (const core of [...offered, ...carried]) {
if (!core || cores.has(emulatorKey(core))) continue;
cores.set(emulatorKey(core), core);
}
return [...cores];
return [...cores.values()];
});
async function onUploadSubmit({
type,

View File

@@ -11,6 +11,7 @@ vi.mock("vue-i18n", () => ({
vi.mock("@/locales", () => ({
default: { global: { t: (key: string) => key } },
}));
vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore"));
const formValid = { value: true };
@@ -206,6 +207,18 @@ describe("UploadAssetDialog", () => {
});
});
it("names a streamed state's core by its emulator label", async () => {
const wrapper = mountDialog("state", [new File(["x"], "a.state")]);
await wrapper.setProps({ cores: ["play"] });
expect(wrapper.findAll("option").map((o) => o.text())).toEqual([
"play.any-core",
"Play!",
]);
await choose(wrapper, 0, 1);
expect(await submitted(wrapper)).toMatchObject({ emulator: "play" });
});
it("starts from the dropped files every time it opens", async () => {
const wrapper = mountDialog("save", [], false);
await wrapper.setProps({

View File

@@ -6,6 +6,7 @@ import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { SaveSchema } from "@/__generated__";
import { AUTOSAVE_SLOT, SAVE_SLOT_MAX_LENGTH } from "@/services/api/save";
import { useStreamingStore } from "@/stores/streaming";
import PendingFilesDropzone from "@/v2/components/shared/PendingFilesDropzone.vue";
import type { AssetType } from "@/v2/utils/assets";
import {
@@ -48,6 +49,7 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
const { emulatorLabel } = useStreamingStore();
const slot = ref<UploadSlot>(existingSlot(AUTOSAVE_SLOT));
const newSlotName = ref("");
@@ -78,7 +80,7 @@ function onSlot(value: unknown) {
const coreItems = computed(() => [
{ value: "", title: t("play.any-core") },
...props.cores.map((value) => ({ value, title: value })),
...props.cores.map((value) => ({ value, title: emulatorLabel(value) })),
]);
watch(

View File

@@ -57,6 +57,7 @@ async function join(): Promise<void> {
romId,
romName: title.value,
hostUsername: props.session.host_username ?? null,
container: props.session.container,
});
}
</script>

View File

@@ -0,0 +1,32 @@
import { mount } from "@vue/test-utils";
import { describe, expect, it, vi } from "vitest";
import { stateFixture } from "@/utils/assets.fixtures";
import AssetPreview from "./AssetPreview.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore"));
const RTag = {
props: { text: { type: String, default: "" } },
template: `<span class="tag">{{ text }}</span>`,
};
const state = stateFixture({
file_name: "slot1.state",
file_size_bytes: 2048,
emulator: "play",
updated_at: "2026-05-10T18:45:00Z",
});
describe("AssetPreview", () => {
it("names the emulator the way the backend labels it", () => {
const wrapper = mount(AssetPreview, {
props: { asset: state, type: "state" },
global: { stubs: { RTag, RIcon: true, RTooltip: true } },
});
expect(wrapper.findAll(".tag").map((el) => el.text())).toContain("Play!");
});
});

View File

@@ -6,6 +6,7 @@ import { RIcon, RTag } from "@v2/lib";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import type { SaveSchema, StateSchema } from "@/__generated__";
import { useStreamingStore } from "@/stores/streaming";
import { formatBytes } from "@/utils";
import AssetFavoriteMark from "@/v2/components/shared/AssetFavoriteMark.vue";
import AssetLabels from "@/v2/components/shared/AssetLabels.vue";
@@ -44,6 +45,7 @@ defineEmits<{
}>();
const { t } = useI18n();
const { emulatorLabel } = useStreamingStore();
const screenshotUrl = computed(() => {
if (!props.asset) return null;
@@ -177,7 +179,7 @@ const emptyText = computed(() =>
v-if="type === 'state' && asset.emulator"
tone="warning"
size="x-small"
:text="asset.emulator"
:text="emulatorLabel(asset.emulator)"
/>
<span class="r-asset-preview__chip">
{{ formatBytes(asset.file_size_bytes) }}

View File

@@ -14,6 +14,7 @@ const { confirm } = vi.hoisted(() => ({
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore"));
vi.mock("@/v2/composables/useConfirm", () => ({
useConfirm: () => confirm,
}));

View File

@@ -7,6 +7,7 @@ import SaveDataPanel from "./SaveDataPanel.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key, locale: "en_US" }),
}));
vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore"));
function mountPanel(props: { save: SaveSchema | null }) {
return mount(SaveDataPanel, {

View File

@@ -0,0 +1,18 @@
import { mount } from "@vue/test-utils";
import { describe, expect, it, vi } from "vitest";
import SessionEndedReason from "./SessionEndedReason.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
describe("SessionEndedReason", () => {
it("shows the reason under its label", () => {
const wrapper = mount(SessionEndedReason, {
props: { reason: "Maintenance" },
});
expect(wrapper.text()).toContain("play.session-ended-reason-label");
expect(wrapper.text()).toContain("Maintenance");
});
});

View File

@@ -0,0 +1,33 @@
<script setup lang="ts">
import { useI18n } from "vue-i18n";
defineProps<{ reason: string }>();
const { t } = useI18n();
</script>
<template>
<div class="r-v2-session-ended-reason">
<span class="r-v2-session-ended-reason__label">
{{ t("play.session-ended-reason-label") }}
</span>
<span>{{ reason }}</span>
</div>
</template>
<style scoped>
.r-v2-session-ended-reason {
display: flex;
flex-direction: column;
gap: 3px;
overflow-wrap: anywhere;
}
.r-v2-session-ended-reason__label {
font-size: var(--r-font-size-xs);
font-weight: var(--r-font-weight-bold);
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--r-color-fg-muted);
}
</style>

View File

@@ -0,0 +1,113 @@
import { flushPromises, mount } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
import StreamingSection from "./StreamingSection.vue";
const { adminListContainers, releaseSession, confirm } = vi.hoisted(() => ({
adminListContainers: vi.fn(),
releaseSession: vi.fn(),
confirm: vi.fn(),
}));
vi.mock("@/services/api/streaming", () => ({
default: { adminListContainers, releaseSession },
}));
vi.mock("vue-i18n", () => ({
useI18n: () => ({
t: (key: string, params?: Record<string, unknown>) =>
params ? `${key}::${JSON.stringify(params)}` : key,
locale: { value: "en_US" },
}),
}));
vi.mock("vue-router", () => ({ useRouter: () => ({ push: vi.fn() }) }));
vi.mock("@/plugins/router", () => ({
ROUTES: { STREAM_DESKTOP: "stream-desktop" },
}));
vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirm }));
vi.mock("@/v2/composables/useSnackbar", () => ({
useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }),
}));
const RBtnStub = {
name: "RBtn",
props: ["disabled", "prependIcon"],
template: "<button :disabled='disabled'><slot /></button>",
};
function container(overrides: Record<string, unknown> = {}) {
return {
container: "WEBSTATION-DEV",
label: "Webstation",
host: "https://webstation:8080",
platforms: ["ps2"],
supports_desktop: true,
configured: true,
draining: false,
session: null,
...overrides,
};
}
async function mountSection() {
const wrapper = mount(StreamingSection, {
global: {
stubs: {
RBtn: RBtnStub,
RIcon: true,
RSpinner: true,
},
},
});
await flushPromises();
return wrapper;
}
function desktopButton(wrapper: Awaited<ReturnType<typeof mountSection>>) {
return wrapper
.findAllComponents(RBtnStub)
.find((btn) => btn.props("prependIcon") === "mdi-desktop-classic");
}
describe("StreamingSection draining containers", () => {
beforeEach(() => {
confirm.mockReset();
releaseSession.mockReset();
adminListContainers.mockReset();
adminListContainers.mockResolvedValue({
data: { enabled: true, containers: [container()] },
});
});
it("calls a free container idle", async () => {
const wrapper = await mountSection();
expect(wrapper.find(".r-v2-streaming__state").text()).toBe(
"settings.streaming-idle",
);
expect(desktopButton(wrapper)?.props("disabled")).toBe(false);
});
it("says a draining container is still shutting down its last session", async () => {
adminListContainers.mockResolvedValue({
data: { enabled: true, containers: [container({ draining: true })] },
});
const wrapper = await mountSection();
expect(wrapper.find(".r-v2-streaming__state").text()).toBe(
"settings.streaming-draining",
);
});
it("holds the desktop shut until the drain finishes", async () => {
adminListContainers.mockResolvedValue({
data: { enabled: true, containers: [container({ draining: true })] },
});
const wrapper = await mountSection();
expect(desktopButton(wrapper)?.props("disabled")).toBe(true);
});
});

View File

@@ -111,6 +111,9 @@ async function release(container: AdminStreamingContainer): Promise<void> {
function sessionState(container: AdminStreamingContainer): string {
const session = container.session;
// A drain marker holds the container with nobody behind it, so there is no
// session to describe and calling it idle invites a claim that still fails.
if (container.draining) return t("settings.streaming-draining");
if (!session) return t("settings.streaming-idle");
return [
session.desktop
@@ -192,7 +195,11 @@ onMounted(load);
variant="outlined"
density="compact"
prepend-icon="mdi-desktop-classic"
:disabled="!container.configured || !!container.session"
:disabled="
!container.configured ||
!!container.session ||
!!container.draining
"
@click="openDesktop(container)"
>
{{ t("settings.streaming-open-desktop") }}

View File

@@ -1,11 +1,13 @@
import { mount } from "@vue/test-utils";
import { describe, expect, it, vi } from "vitest";
import type { SaveSchema } from "@/__generated__";
import { saveFixture } from "@/utils/assets.fixtures";
import AssetChips from "./AssetChips.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore"));
const RTag = {
props: { text: { type: String, default: "" } },
@@ -14,7 +16,9 @@ const RTag = {
const save = saveFixture({ file_size_bytes: 2048, emulator: "snes9x" });
function chips(props: { latest?: boolean; showEmulator?: boolean } = {}) {
function chips(
props: { latest?: boolean; showEmulator?: boolean; asset?: SaveSchema } = {},
) {
return mount(AssetChips, {
props: { asset: save, ...props },
global: { stubs: { RTag, RIcon: true } },
@@ -29,6 +33,12 @@ describe("AssetChips", () => {
expect(wrapper.get(".r-asset-chips__size").text()).toContain("2 KB");
});
it("names the emulator the way the backend labels it", () => {
const wrapper = chips({ asset: { ...save, emulator: "play" } });
expect(wrapper.findAll(".tag").map((el) => el.text())).toEqual(["Play!"]);
});
it("tags the latest version and can hide the emulator", () => {
const wrapper = chips({ latest: true, showEmulator: false });

View File

@@ -4,6 +4,7 @@
// <AssetFavoriteMark>.
import { RTag } from "@v2/lib";
import { useI18n } from "vue-i18n";
import { useStreamingStore } from "@/stores/streaming";
import { formatBytes } from "@/utils";
import type { Asset } from "@/v2/utils/assets";
@@ -22,6 +23,7 @@ withDefaults(
);
const { t } = useI18n();
const { emulatorLabel } = useStreamingStore();
</script>
<template>
@@ -36,7 +38,7 @@ const { t } = useI18n();
v-if="showEmulator && asset.emulator"
tone="warning"
size="x-small"
:text="asset.emulator"
:text="emulatorLabel(asset.emulator)"
/>
<span class="r-asset-chips__size">
{{ formatBytes(asset.file_size_bytes) }}

View File

@@ -12,6 +12,7 @@ vi.mock("vue-i18n", () => ({
locale: "en_US",
}),
}));
vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore"));
const RBtn = {
emits: ["click"],

View File

@@ -7,6 +7,7 @@ import AssetStrip from "./AssetStrip.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key, locale: "en_US" }),
}));
vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore"));
const RTag = {
props: { text: { type: String, default: "" } },
@@ -50,6 +51,29 @@ describe("AssetStrip grouped by core", () => {
]);
});
it("heads a group with the emulator's display name", () => {
const wrapper = mountStrip({
groupBy: "emulator",
assets: [state(5, "play", "2026-09-16T10:00:00Z")],
});
expect(wrapper.get(".r-asset-group-head__title").text()).toBe("Play!");
});
it("groups an emulator configured in another case with its own", () => {
const wrapper = mountStrip({
groupBy: "emulator",
assets: [
state(5, "play", "2026-09-16T10:00:00Z"),
state(6, "Play", "2026-09-15T10:00:00Z"),
],
});
expect(
wrapper.findAll(".r-asset-group-head__title").map((el) => el.text()),
).toEqual(["Play!"]);
});
it("tags exactly one Latest tile when timestamps tie", () => {
const wrapper = mountStrip({ groupBy: "emulator" });
const tagged = wrapper

View File

@@ -10,6 +10,7 @@ import {
} from "@v2/lib";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useStreamingStore } from "@/stores/streaming";
import AssetChips from "@/v2/components/shared/AssetChips.vue";
import AssetFavoriteMark from "@/v2/components/shared/AssetFavoriteMark.vue";
import AssetGroupHead from "@/v2/components/shared/AssetGroupHead.vue";
@@ -20,6 +21,7 @@ import PublicBadge from "@/v2/components/shared/PublicBadge.vue";
import { useGroupFold } from "@/v2/composables/useGroupFold";
import {
byFavoriteFirst,
emulatorKey,
ownerOf,
screenshotOf,
staggerIndex,
@@ -74,6 +76,7 @@ defineSlots<{
}>();
const { t } = useI18n();
const { emulatorLabel } = useStreamingStore();
const emptyLabel = computed(() =>
props.type === "save"
@@ -113,12 +116,12 @@ const groups = computed<AssetGroup[]>(() => {
}
const byKey = new Map<string, AssetGroup>();
for (const asset of props.assets) {
const key = asset.emulator ?? "";
const key = emulatorKey(asset.emulator);
let group = byKey.get(key);
if (!group) {
group = {
key,
label: key || t("play.any-core"),
label: emulatorLabel(asset.emulator) || t("play.any-core"),
assets: [],
disabled: true,
newest: "",

View File

@@ -16,7 +16,7 @@ const canPlayRuffle = { value: false };
const canPlayNative = { value: false };
const streamContainer = { value: null as object | null };
const joinableSession = {
value: null as { host_username: string | null } | null,
value: null as { host_username: string | null; container?: string } | null,
};
// Granted action keys — `null` means "everything" (the default).
const grantedActions: { value: Set<ActionKey> | null } = { value: null };
@@ -145,7 +145,10 @@ beforeEach(() => {
describe("useGameActions.joinStream", () => {
beforeEach(() => {
streamContainer.value = { host: "http://stream" };
joinableSession.value = { host_username: "ada" };
joinableSession.value = {
host_username: "ada",
container: "http://box:8000",
};
});
it("does not navigate until the user confirms", async () => {
@@ -164,7 +167,11 @@ describe("useGameActions.joinStream", () => {
await actions.joinStream();
expect(push).toHaveBeenCalledWith("/rom/1/stream?join=1");
// The joinable row names the container, and a pool needs it: the stream
// view would otherwise walk the pool and could land on another session.
expect(push).toHaveBeenCalledWith(
"/rom/1/stream?join=1&container=http%3A%2F%2Fbox%3A8000",
);
});
it("names the host in the confirmation", async () => {

View File

@@ -387,6 +387,7 @@ export function useGameActions(
romId: rom.id,
romName: rom.name ?? rom.fs_name_no_ext ?? "",
hostUsername: joinHostLabel.value || null,
container: joinableSession.value?.container ?? null,
},
);
}

View File

@@ -14,7 +14,12 @@ vi.mock("@/v2/composables/useConfirm", () => ({
useConfirm: () => confirmFn,
}));
const target = { romId: 1, romName: "Chrono Trigger", hostUsername: "ada" };
const target = {
romId: 1,
romName: "Chrono Trigger",
hostUsername: "ada",
container: null,
};
describe("useJoinStreamConfirm", () => {
beforeEach(() => {
@@ -40,6 +45,17 @@ describe("useJoinStreamConfirm", () => {
expect(push).toHaveBeenCalledWith("/rom/1/stream?join=1");
});
it("carries the container into the join URL", async () => {
confirmFn.mockResolvedValue(true);
const { joinStream } = useJoinStreamConfirm();
await joinStream({ ...target, container: "http://box:8000" });
expect(push).toHaveBeenCalledWith(
"/rom/1/stream?join=1&container=http%3A%2F%2Fbox%3A8000",
);
});
it("names the host in the confirmation", async () => {
confirmFn.mockResolvedValue(false);
const { joinStream } = useJoinStreamConfirm();

View File

@@ -11,6 +11,9 @@ export interface JoinStreamTarget {
romId: number;
romName: string;
hostUsername: string | null;
// A pool holds a session per container, so the one being joined has to be
// named rather than left to the backend to pick.
container: string | null;
}
interface JoinStreamDeps {
@@ -35,7 +38,9 @@ export async function confirmJoinStream(
confirmText: t("rom.join-session"),
});
if (!ok) return;
void router.push(`/rom/${target.romId}/stream?join=1`);
const query = new URLSearchParams({ join: "1" });
if (target.container) query.set("container", target.container);
void router.push(`/rom/${target.romId}/stream?${query}`);
}
export function useJoinStreamConfirm() {

View File

@@ -5,9 +5,14 @@ import { saveFixture, stateFixture } from "@/utils/assets.fixtures";
import { useSaveStateTabs } from "./index";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
useI18n: () => ({
t: (key: string, params?: { emulator?: string }) =>
params?.emulator ? `${key}:${params.emulator}` : key,
}),
}));
vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore"));
function makeSave(overrides: Partial<SaveSchema> = {}): SaveSchema {
return saveFixture({ id: 1, file_name: "1.srm", ...overrides });
}
@@ -50,7 +55,7 @@ describe("useSaveStateTabs", () => {
);
expect(stateDisabledReason(makeState("bsnes"))).toBe(
"play.state-incompatible-core",
"play.state-incompatible-core:bsnes",
);
expect(stateDisabledReason(makeState("snes9x"))).toBeNull();
@@ -58,4 +63,23 @@ describe("useSaveStateTabs", () => {
expect(compatibleStates.value).toHaveLength(1);
expect(stateDisabledReason(makeState("bsnes"))).toBeNull();
});
it("loads a state its core wrote under another case", () => {
const { stateDisabledReason, allStatesCompatible } = useSaveStateTabs(
[],
[makeState("SNES9x")],
"snes9x",
);
expect(stateDisabledReason(makeState("SNES9x"))).toBeNull();
expect(allStatesCompatible.value).toBe(true);
});
it("names another emulator's state the way the backend labels it", () => {
const { stateDisabledReason } = useSaveStateTabs([], [], "snes9x");
expect(stateDisabledReason(makeState("retroarch"))).toBe(
"play.state-incompatible-core:RetroArch",
);
});
});

View File

@@ -1,6 +1,7 @@
import { computed, toValue, type MaybeRefOrGetter } from "vue";
import { useI18n } from "vue-i18n";
import type { SaveSchema, StateSchema } from "@/__generated__";
import { useStreamingStore } from "@/stores/streaming";
import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types";
import { isCoreCompatible, type AssetType } from "@/v2/utils/assets";
@@ -14,6 +15,7 @@ export function useSaveStateTabs(
core: MaybeRefOrGetter<string | null>,
) {
const { t } = useI18n();
const { emulatorLabel } = useStreamingStore();
const stateCount = computed(() => toValue(states).length);
const compatibleStates = computed(() =>
@@ -43,7 +45,9 @@ export function useSaveStateTabs(
// Other emulators' states stay listed, disabled, so the count adds up.
function stateDisabledReason(asset: { emulator?: string | null }) {
if (isCoreCompatible(asset, toValue(core))) return null;
return t("play.state-incompatible-core", { emulator: asset.emulator });
return t("play.state-incompatible-core", {
emulator: emulatorLabel(asset.emulator),
});
}
return {

View File

@@ -29,7 +29,7 @@ export function isCoreCompatible(
asset: { emulator?: string | null },
core: string | null | undefined,
): boolean {
return !asset.emulator || asset.emulator === core;
return !asset.emulator || emulatorKey(asset.emulator) === emulatorKey(core);
}
/** ISO timestamps sort lexically. */
@@ -64,3 +64,18 @@ export function staggerIndex(
}
return order;
}
/** Emulator ids match case-insensitively, as the backend matches them. */
export function emulatorKey(emulator: string | null | undefined): string {
return (emulator ?? "").toLowerCase();
}
/** The label a map gives an emulator id, else the id as it stands. */
export function emulatorLabelFrom(
labels: Record<string, string>,
emulator: string | null | undefined,
): string {
if (!emulator) return "";
const key = emulatorKey(emulator);
return Object.hasOwn(labels, key) ? labels[key] : emulator;
}

View File

@@ -1,6 +1,7 @@
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent } from "vue";
import { serverError } from "@/test-utils/serverError";
import Desktop from "./Desktop.vue";
const mocks = vi.hoisted(() => ({
@@ -10,10 +11,14 @@ const mocks = vi.hoisted(() => ({
heartbeatSession: vi.fn(),
heartbeatTick: null as (() => Promise<void>) | null,
routeLeave: null as (() => Promise<boolean> | boolean) | null,
socketHandlers: {} as Record<string, (payload: unknown) => unknown>,
}));
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
useI18n: () => ({
t: (key: string, params?: Record<string, unknown>) =>
params ? `${key}:${Object.values(params).join(",")}` : key,
}),
}));
vi.mock("vue-router", () => ({
@@ -54,8 +59,13 @@ vi.mock("@/v2/composables/useConfirm", () => ({
vi.mock("@/v2/composables/usePageTitle", () => ({ usePageTitle: vi.fn() }));
vi.mock("@/v2/composables/useSocketEvent", () => ({
useSocketEvent: (event: string, handler: (payload: unknown) => unknown) => {
mocks.socketHandlers[event] = handler;
},
}));
const StreamStageStub = defineComponent({
props: { active: { type: Boolean, default: false } },
setup(_, { expose }) {
expose({
leaveFullscreen: () => Promise.resolve(),
@@ -65,10 +75,14 @@ const StreamStageStub = defineComponent({
},
});
type DesktopVm = { state: string; errorMessage: string; endedReason: string };
// The view listens on window, so a mount left standing would answer the next
// test's pagehide too.
let mounted: VueWrapper | null = null;
const CLAIMED_AT = "2026-09-17T10:00:00";
beforeEach(() => {
vi.clearAllMocks();
});
@@ -78,10 +92,7 @@ afterEach(() => {
mounted = null;
});
async function openDesktop(): Promise<VueWrapper> {
mocks.claimDesktop.mockResolvedValue({
data: { host: "http://webstation-dev:8080", label: "PS2", platform: "ps2" },
});
async function mountDesktop(): Promise<VueWrapper> {
mounted = mount(Desktop, {
shallow: true,
global: { stubs: { StreamStage: StreamStageStub } },
@@ -90,13 +101,104 @@ async function openDesktop(): Promise<VueWrapper> {
return mounted;
}
function streamIsLive(wrapper: VueWrapper): boolean | undefined {
return wrapper.findComponent(StreamStageStub).props("active");
async function openDesktop(): Promise<VueWrapper> {
mocks.claimDesktop.mockResolvedValue({
data: {
host: "http://webstation-dev:8080",
label: "PS2",
platform: "ps2",
claimed_at: CLAIMED_AT,
},
});
return mountDesktop();
}
async function refuseDesktop(detail: unknown): Promise<VueWrapper> {
mocks.claimDesktop.mockRejectedValue(serverError(detail, 409));
return mountDesktop();
}
function vmOf(wrapper: VueWrapper): DesktopVm {
return wrapper.vm as unknown as DesktopVm;
}
function endSession(notice: Record<string, unknown>): void {
const handler = mocks.socketHandlers["streaming:session-ended"];
expect(handler).toBeTypeOf("function");
handler({
ended_by: "admin",
reason: null,
desktop: true,
claimed_at: CLAIMED_AT,
...notice,
});
}
describe("Desktop session-ended notices", () => {
it("ends the desktop when the notice names its container", async () => {
const wrapper = await openDesktop();
expect(vmOf(wrapper).state).toBe("running");
endSession({ platform: "ps2", container: "WEBSTATION-DEV" });
await flushPromises();
expect(vmOf(wrapper).state).toBe("error");
expect(vmOf(wrapper).errorMessage).toBe("play.session-ended-by:admin");
});
it("shows the reason the notice gives", async () => {
const wrapper = await openDesktop();
endSession({
platform: "ps2",
container: "WEBSTATION-DEV",
reason: "Maintenance",
});
await flushPromises();
expect(vmOf(wrapper).endedReason).toBe("Maintenance");
});
it("holds the claim when the notice names another container", async () => {
const wrapper = await openDesktop();
endSession({ platform: "ps2", container: "WEBSTATION-OTHER" });
await flushPromises();
expect(vmOf(wrapper).state).toBe("running");
});
it("holds the claim when the notice names one this claim replaced", async () => {
const wrapper = await openDesktop();
endSession({
platform: "ps2",
container: "WEBSTATION-DEV",
claimed_at: "2026-09-17T09:55:00",
});
await flushPromises();
expect(vmOf(wrapper).state).toBe("running");
});
it("releases nothing once a notice has ended the claim", async () => {
// The claim is gone, so an exit must not hand back whoever holds the
// container next.
await openDesktop();
endSession({ platform: "ps2", container: "WEBSTATION-DEV" });
await flushPromises();
window.dispatchEvent(new Event("pagehide"));
expect(mocks.releaseSessionKeepalive).not.toHaveBeenCalled();
expect(mocks.releaseSession).not.toHaveBeenCalled();
});
});
describe("Desktop heartbeats", () => {
it("beats for the container it claimed", async () => {
// Unnamed, the beat only reaches the platform's first pool.
it("beats for the claim it made", async () => {
// Unstamped, the beat keeps alive whatever this admin runs on the
// container, such as a game that swept a stale desktop off it.
const wrapper = await openDesktop();
mocks.heartbeatSession.mockResolvedValue({ status: "active" });
@@ -105,31 +207,116 @@ describe("Desktop heartbeats", () => {
expect(mocks.heartbeatSession).toHaveBeenCalledWith(
"ps2",
"WEBSTATION-DEV",
CLAIMED_AT,
);
expect(streamIsLive(wrapper)).toBe(true);
expect(vmOf(wrapper).state).toBe("running");
});
it("stops the stream when the beat reports the session ended", async () => {
it("drops the claim 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" });
mocks.heartbeatSession.mockResolvedValue({
status: "ended",
termination: { ended_by: "admin", reason: "Maintenance" },
});
await mocks.heartbeatTick?.();
window.dispatchEvent(new Event("pagehide"));
expect(await mocks.routeLeave?.()).toBe(true);
expect(vmOf(wrapper).state).toBe("error");
expect(vmOf(wrapper).errorMessage).toBe("play.session-ended-by:admin");
expect(vmOf(wrapper).endedReason).toBe("Maintenance");
expect(mocks.releaseSessionKeepalive).not.toHaveBeenCalled();
});
it("keeps the exit a release made while a beat was in flight", async () => {
const wrapper = await openDesktop();
mocks.releaseSession.mockResolvedValue({});
let answer = (_: unknown) => {};
mocks.heartbeatSession.mockReturnValue(
new Promise((resolve) => {
answer = resolve;
}),
);
const beat = mocks.heartbeatTick?.();
expect(await mocks.routeLeave?.()).toBe(true);
answer({ status: "ended" });
await beat;
expect(vmOf(wrapper).state).toBe("exited");
});
it("leaves the view without a release once the beat ended the claim", async () => {
await openDesktop();
mocks.heartbeatSession.mockResolvedValue({ status: "ended" });
await mocks.heartbeatTick?.();
expect(await mocks.routeLeave?.()).toBe(true);
expect(mocks.releaseSession).not.toHaveBeenCalled();
});
});
describe("Desktop releases", () => {
// Unstamped, a release reaches whichever session took the container.
it("names the claim it releases on exit", async () => {
mocks.releaseSession.mockResolvedValue({});
await openDesktop();
expect(await mocks.routeLeave?.()).toBe(true);
expect(mocks.releaseSession).toHaveBeenCalledWith(
"ps2",
undefined,
"WEBSTATION-DEV",
undefined,
CLAIMED_AT,
);
});
it("names the claim it releases when the tab closes", async () => {
await openDesktop();
window.dispatchEvent(new Event("pagehide"));
expect(mocks.releaseSessionKeepalive).toHaveBeenCalledWith(
"ps2",
"WEBSTATION-DEV",
CLAIMED_AT,
);
});
});
describe("Desktop refused claims", () => {
it("names the game holding the container", async () => {
const wrapper = await refuseDesktop({
rom_name: "Ico",
claimed_at: "2026-09-17T10:00:00",
draining: false,
});
expect(vmOf(wrapper).errorMessage).toBe(
"play.desktop-error-occupied-by:Ico",
);
});
it("says the container is in use when the game is not the admin's to see", async () => {
const wrapper = await refuseDesktop({
rom_name: null,
claimed_at: "2026-09-17T10:00:00",
draining: false,
});
expect(vmOf(wrapper).errorMessage).toBe("play.desktop-error-occupied");
});
it("says to come back when the container is still shutting down", async () => {
const wrapper = await refuseDesktop({
rom_name: null,
claimed_at: null,
draining: true,
});
expect(vmOf(wrapper).errorMessage).toBe("play.stream-occupied-draining");
});
});

View File

@@ -14,11 +14,15 @@ import { computed, onMounted, ref } from "vue";
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 streamingApi, {
type ContainerBusyDetail,
} from "@/services/api/streaming";
import { type SessionTermination, useStreamingStore } from "@/stores/streaming";
import SessionEndedReason from "@/v2/components/Player/SessionEndedReason.vue";
import StreamStage from "@/v2/components/Player/StreamStage.vue";
import { useConfirm } from "@/v2/composables/useConfirm";
import { usePageTitle } from "@/v2/composables/usePageTitle";
import { useSocketEvent } from "@/v2/composables/useSocketEvent";
const { t } = useI18n();
const route = useRoute();
@@ -31,6 +35,7 @@ const containerKey = computed(() => String(route.query.container ?? ""));
const stage = ref<InstanceType<typeof StreamStage> | null>(null);
const state = ref<"loading" | "running" | "error" | "exited">("loading");
const errorMessage = ref("");
const endedReason = ref("");
const containerHost = ref("");
const label = ref("");
// The platform the backend filed the session under, which the release route
@@ -41,6 +46,9 @@ const isExiting = ref(false);
// describes the view: a release that failed leaves an "error" screen over a
// claim that is very much still standing.
const holdsClaim = ref(false);
// The stamp the claim answered with, which every release and heartbeat sends
// back so a claim that replaced this one is never the one they reach.
const claimedAt = ref("");
usePageTitle(() => t("play.desktop-title"));
@@ -55,13 +63,27 @@ async function openDesktop(): Promise<void> {
containerHost.value = data.host;
label.value = data.label;
platform.value = data.platform;
claimedAt.value = data.claimed_at;
holdsClaim.value = true;
state.value = "running";
} catch (err: unknown) {
state.value = "error";
const status = isAxiosError(err) ? err.response?.status : undefined;
if (status === 409) errorMessage.value = t("play.desktop-error-occupied");
else if (status === 404)
const detail: unknown = isAxiosError(err)
? err.response?.data?.detail
: undefined;
if (status === 409) {
const busy = detail as ContainerBusyDetail | null;
// A drain marker is nobody's claim: the container comes free on its own
// once the previous session has finished shutting down.
if (busy?.draining)
errorMessage.value = t("play.stream-occupied-draining");
else if (busy?.rom_name)
errorMessage.value = t("play.desktop-error-occupied-by", {
rom: busy.rom_name,
});
else errorMessage.value = t("play.desktop-error-occupied");
} else if (status === 404)
errorMessage.value = t("play.desktop-error-no-container");
else errorMessage.value = t("play.desktop-error-server");
}
@@ -79,6 +101,8 @@ async function release(): Promise<boolean> {
platform.value,
undefined,
containerKey.value,
undefined,
claimedAt.value,
);
holdsClaim.value = false;
state.value = "exited";
@@ -97,19 +121,41 @@ async function release(): Promise<boolean> {
// stale window, and nothing else here touches the claim.
const HEARTBEAT_MS = 30_000;
// Dropping the claim keeps a later exit from releasing the next holder, and the
// notice is the only sign the desktop was taken away rather than broken.
function noteSessionEnded(notice?: SessionTermination | null): void {
holdsClaim.value = false;
state.value = "error";
errorMessage.value = notice?.ended_by
? t("play.session-ended-by", { user: notice.ended_by })
: t("play.session-ended");
endedReason.value = notice?.reason ?? "";
}
useIntervalFn(async () => {
if (!holdsClaim.value) return;
const status = await streamingStore.heartbeatSession(
platform.value,
containerKey.value,
claimedAt.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";
// A release that landed while this beat was in flight already said how it ended.
if (!holdsClaim.value || status?.status !== "ended") return;
noteSessionEnded(status.termination);
}, HEARTBEAT_MS);
// Pushed when someone else ends this claim, sooner than the next heartbeat.
// The user's room carries all their claims, so the container and stamp name ours.
useSocketEvent<SessionTermination>("streaming:session-ended", (notice) => {
if (
!holdsClaim.value ||
notice.container !== containerKey.value ||
notice.claimed_at !== claimedAt.value
)
return;
noteSessionEnded(notice);
});
function backToAdministration(): void {
router.push({ name: ROUTES.ADMINISTRATION, query: { tab: "streaming" } });
}
@@ -156,7 +202,11 @@ function onPageHide(): void {
if (!holdsClaim.value) return;
holdsClaim.value = false;
state.value = "exited";
streamingApi.releaseSessionKeepalive(platform.value, containerKey.value);
streamingApi.releaseSessionKeepalive(
platform.value,
containerKey.value,
claimedAt.value,
);
}
useEventListener(window, "pagehide", onPageHide);
@@ -173,8 +223,13 @@ onMounted(() => {
type="error"
variant="translucent"
class="r-v2-desktop__error"
:text="errorMessage"
>
{{ errorMessage }}
<SessionEndedReason
v-if="endedReason"
:reason="endedReason"
class="r-v2-desktop__ended-reason"
/>
<template #append>
<RBtn variant="text" @click="backToAdministration">
{{ t("play.desktop-back") }}
@@ -238,6 +293,10 @@ onMounted(() => {
max-width: 560px;
}
.r-v2-desktop__ended-reason {
margin-top: 8px;
}
.r-v2-desktop__spinner {
display: block;
margin: 64px auto;

View File

@@ -66,6 +66,7 @@ vi.mock("@/stores/playing", async () => {
const { ref } = await import("vue");
return { default: () => ({ playing: ref(false) }) };
});
vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore"));
vi.mock("@/stores/native", async () => {
const { reactive } = await import("vue");

View File

@@ -1,6 +1,7 @@
import { RBtn } from "@v2/lib";
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent, type Slots, type VNodeChild } from "vue";
import type { SaveSchema } from "@/__generated__";
import type { DetailedRom } from "@/stores/roms";
import { saveFixture } from "@/utils/assets.fixtures";
@@ -13,7 +14,20 @@ const mocks = vi.hoisted(() => ({
claimSession: vi.fn(),
fetchConfig: vi.fn(),
getRom: vi.fn(),
fetchSessionStatus: vi.fn(),
heartbeatSession: vi.fn(),
joinSession: vi.fn(),
releaseSession: vi.fn(),
releaseSessionKeepalive: vi.fn(),
saveAndExit: vi.fn(),
saveAndExitKeepalive: vi.fn(),
loadState: vi.fn(),
saveState: vi.fn(),
container: null as Record<string, unknown> | null,
capabilities: {} as Record<string, unknown>,
presenceTick: null as (() => Promise<void>) | null,
socketHandlers: {} as Record<string, (payload: unknown) => unknown>,
query: {} as Record<string, string>,
}));
vi.mock("vue-i18n", () => ({
@@ -22,7 +36,7 @@ vi.mock("vue-i18n", () => ({
vi.mock("vue-router", () => ({
onBeforeRouteLeave: vi.fn(),
useRoute: () => ({ params: { rom: "3" }, query: {} }),
useRoute: () => ({ params: { rom: "3" }, query: mocks.query }),
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
}));
@@ -35,7 +49,10 @@ vi.mock("@/services/api/rom", () => ({
}));
vi.mock("@/services/api/streaming", () => ({
default: {},
default: {
loadState: mocks.loadState,
saveState: mocks.saveState,
},
isMemoryCardImportDetail: () => false,
}));
@@ -59,26 +76,29 @@ vi.mock("@/stores/streaming", () => ({
useStreamingStore: () => ({
claimSession: mocks.claimSession,
containerForPlatform: () => mocks.container,
platformCapabilities: () => ({}),
platformCapabilities: () => mocks.capabilities,
fetchConfig: mocks.fetchConfig,
fetchSessionStatus: vi.fn(),
fetchSessionStatus: mocks.fetchSessionStatus,
forgetJoinableSession: vi.fn(),
heartbeatSession: vi.fn(),
joinSession: vi.fn(),
releaseSession: vi.fn(),
releaseSessionKeepalive: vi.fn(),
saveAndExit: vi.fn(),
saveAndExitKeepalive: vi.fn(),
heartbeatSession: mocks.heartbeatSession,
joinSession: mocks.joinSession,
releaseSession: mocks.releaseSession,
releaseSessionKeepalive: mocks.releaseSessionKeepalive,
saveAndExit: mocks.saveAndExit,
saveAndExitKeepalive: mocks.saveAndExitKeepalive,
}),
}));
vi.mock("@/v2/composables/useActivityPresence", () => ({
useActivityPresence: () => ({
start: vi.fn(),
stopHeartbeat: vi.fn(),
emitStop: vi.fn(),
stop: vi.fn(),
}),
useActivityPresence: (_rom: unknown, tick: () => Promise<void>) => {
mocks.presenceTick = tick;
return {
start: vi.fn(),
stopHeartbeat: vi.fn(),
emitStop: vi.fn(),
stop: vi.fn(),
};
},
}));
vi.mock("@/v2/composables/useBackgroundArt", () => ({
@@ -122,7 +142,9 @@ vi.mock("@/v2/composables/useSnackbar", () => ({
}));
vi.mock("@/v2/composables/useSocketEvent", () => ({
useSocketEvent: vi.fn(),
useSocketEvent: (event: string, handler: (payload: unknown) => unknown) => {
mocks.socketHandlers[event] = handler;
},
}));
vi.mock("@/v2/composables/useStageActive", () => ({
@@ -133,12 +155,36 @@ vi.mock("@/v2/composables/useUnloadGuard", () => ({
useUnloadGuard: vi.fn(),
}));
const GameCoverStub = defineComponent({
setup(_, { expose }) {
expose({ playLoad: () => 0 });
return () => null;
/**
* Renders nothing, or whichever slots `render` picks, and answers the methods
* the view calls on the real child.
*/
function exposingStub(
api: Record<string, unknown>,
render: (slots: Slots) => VNodeChild = () => null,
) {
return defineComponent({
// A rendered slot is a fragment root, which has nowhere to put attrs.
inheritAttrs: false,
setup(_, { expose, slots }) {
expose(api);
return () => render(slots);
},
});
}
// The stage owns fullscreen, which the ended path leaves before anything else.
// It also renders the control bar the view fills in, where the state buttons live.
const StreamStageStub = exposingStub(
{
enterFullscreen: () => Promise.resolve(),
leaveFullscreen: () => Promise.resolve(),
focusStream: () => {},
},
});
(slots) => slots.bar?.({ isFullscreen: false, toggleFullscreen: () => {} }),
);
const GameCoverStub = exposingStub({ playLoad: () => 0 });
function save(
id: number,
@@ -179,15 +225,27 @@ function romWith(saves: SaveSchema[]): DetailedRom {
} as unknown as DetailedRom;
}
// The view listens on document and window, so a mount left standing would
// answer the next test's visibilitychange and pagehide too.
const mounted: VueWrapper[] = [];
afterEach(() => {
for (const wrapper of mounted.splice(0)) {
if (wrapper.exists()) wrapper.unmount();
}
});
async function launch(opts: {
picker: boolean;
saves?: SaveSchema[];
liveStates?: boolean;
}): Promise<VueWrapper> {
mocks.container = {
name: "WEBSTATION-DEV",
emulator: "retroarch",
protocol: "webstation",
supports_save_picker: opts.picker,
supports_live_states: opts.liveStates ?? true,
supports_memory_cards: false,
supports_multiplayer: false,
};
@@ -198,9 +256,10 @@ async function launch(opts: {
renderStubDefaultSlot: true,
// The launch flourish calls into the cover before the claim, so this
// one stub has to answer rather than be inert.
stubs: { GameCover: GameCoverStub },
stubs: { GameCover: GameCoverStub, StreamStage: StreamStageStub },
},
});
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
@@ -217,10 +276,26 @@ function saveList(wrapper: VueWrapper) {
.find((s) => s.props("type") === "save");
}
const CLAIM = {
container: "WEBSTATION-DEV",
claimed_at: "2026-09-17T10:00:00",
};
// Holds the claim's 202 until the test lands it.
function deferClaim(): (claim: typeof CLAIM) => void {
let land = (_: typeof CLAIM) => {};
mocks.claimSession.mockReturnValue(
new Promise<typeof CLAIM>((resolve) => {
land = resolve;
}),
);
return land;
}
describe("Stream save picker", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.claimSession.mockResolvedValue({ container: "WEBSTATION-DEV" });
mocks.claimSession.mockResolvedValue(CLAIM);
});
it("offers every archive, newest already picked", async () => {
@@ -335,3 +410,543 @@ describe("Stream save picker", () => {
expect(saveList(wrapper)!.props("selectedId")).toBe(3);
});
});
type StreamVm = {
onPlay: () => Promise<void>;
performStop: () => Promise<void>;
performSaveAndExit: () => Promise<void>;
handleSaveState: () => Promise<void>;
handleLoadState: () => Promise<void>;
claimedAt: string | null;
playerState: string;
endedDialogOpen: boolean;
holdsClaim: boolean;
containerHost: string;
};
function vmOf(wrapper: VueWrapper): StreamVm {
return wrapper.vm as unknown as StreamVm;
}
function endSession(notice: Record<string, unknown>): void {
const handler = mocks.socketHandlers["streaming:session-ended"];
expect(handler).toBeTypeOf("function");
handler({
ended_by: "admin",
reason: null,
claimed_at: CLAIM.claimed_at,
...notice,
});
}
async function launchReady(
payload: Record<string, unknown> = {},
): Promise<void> {
const handler = mocks.socketHandlers["streaming:launch-ready"];
expect(handler).toBeTypeOf("function");
await handler({
platform: "gba",
...CLAIM,
host: "http://webstation-dev:8080",
resume: null,
...payload,
});
}
describe("Stream session-ended notices", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.claimSession.mockResolvedValue(CLAIM);
});
it("ends the game when the notice names the container it claimed", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
endSession({ platform: "gba", container: "WEBSTATION-DEV" });
await flushPromises();
expect(vmOf(wrapper).playerState).toBe("exited");
expect(vmOf(wrapper).endedDialogOpen).toBe(true);
});
it("keeps playing when the notice names another container", async () => {
// A pool serves one platform from several containers, so the player can
// hold a second session the same room hears about.
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady();
expect(vmOf(wrapper).playerState).toBe("playing");
endSession({ platform: "gba", container: "WEBSTATION-DEV-2" });
await flushPromises();
expect(vmOf(wrapper).playerState).toBe("playing");
expect(vmOf(wrapper).endedDialogOpen).toBe(false);
});
it("keeps launching when an admin's own desktop ends", async () => {
// The 202 has not landed, so the container is not known yet and the
// desktop flag is all that tells the two claims apart.
const claimed = deferClaim();
const wrapper = await launch({ picker: false });
const playing = vmOf(wrapper).onPlay();
await flushPromises();
endSession({
platform: "gba",
container: "WEBSTATION-DEV-2",
desktop: true,
});
await flushPromises();
expect(vmOf(wrapper).playerState).toBe("loading");
claimed(CLAIM);
await playing;
});
it("keeps playing when the notice names a claim this one replaced", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady();
endSession({
platform: "gba",
container: CLAIM.container,
claimed_at: "2026-09-17T09:55:00",
});
await flushPromises();
expect(vmOf(wrapper).playerState).toBe("playing");
expect(vmOf(wrapper).endedDialogOpen).toBe(false);
});
it("ends the launch when its own claim ended before the 202 landed", async () => {
const claimed = deferClaim();
const wrapper = await launch({ picker: false });
const playing = vmOf(wrapper).onPlay();
await flushPromises();
endSession({ platform: "gba", container: CLAIM.container });
claimed(CLAIM);
await playing;
await flushPromises();
expect(vmOf(wrapper).playerState).toBe("exited");
expect(vmOf(wrapper).endedDialogOpen).toBe(true);
});
it("keeps launching when the container's last claim ends before the 202", async () => {
const claimed = deferClaim();
const wrapper = await launch({ picker: false });
const playing = vmOf(wrapper).onPlay();
await flushPromises();
endSession({
platform: "gba",
container: CLAIM.container,
claimed_at: "2026-09-17T09:55:00",
});
await flushPromises();
expect(vmOf(wrapper).playerState).toBe("loading");
claimed(CLAIM);
await playing;
});
});
describe("Stream claim hygiene", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.claimSession.mockResolvedValue(CLAIM);
mocks.releaseSession.mockResolvedValue(true);
});
it("names the claim it holds when it releases", async () => {
// An unnamed release reaches whatever the platform is running, which after
// a takeover is somebody else's session.
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
wrapper.unmount();
expect(mocks.releaseSession).toHaveBeenCalledWith(
"gba",
false,
CLAIM.container,
CLAIM.claimed_at,
);
});
it("releases nothing on unmount once the session ended elsewhere", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
endSession({ platform: "gba", container: CLAIM.container });
await flushPromises();
wrapper.unmount();
expect(vmOf(wrapper).holdsClaim).toBe(false);
expect(mocks.releaseSession).not.toHaveBeenCalled();
});
it("hands the container back once when the game comes up after the exit", async () => {
const wrapper = await launch({ picker: false });
const vm = vmOf(wrapper);
await vm.onPlay();
vm.playerState = "exited";
await launchReady();
await flushPromises();
wrapper.unmount();
expect(mocks.releaseSession).toHaveBeenCalledTimes(1);
expect(mocks.releaseSession).toHaveBeenCalledWith(
"gba",
false,
CLAIM.container,
CLAIM.claimed_at,
);
});
it("hands the container back when the claim lands after the player left", async () => {
// Leaving mid-claim unmounts the view, so no socket or unmount path is left
// to release what the 202 then grants.
const claimed = deferClaim();
const wrapper = await launch({ picker: false });
const playing = vmOf(wrapper).onPlay();
await flushPromises();
await vmOf(wrapper).performStop();
wrapper.unmount();
claimed(CLAIM);
await playing;
await flushPromises();
expect(mocks.releaseSession).toHaveBeenCalledWith(
"gba",
false,
CLAIM.container,
CLAIM.claimed_at,
);
});
it("names the claim it saves when it leaves a running game", async () => {
mocks.saveAndExit.mockResolvedValue({ released: true, saved: true });
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady();
wrapper.unmount();
const [platform, , wait, container, claimedAt] =
mocks.saveAndExit.mock.calls[0];
expect([platform, wait, container, claimedAt]).toEqual([
"gba",
false,
CLAIM.container,
CLAIM.claimed_at,
]);
});
it("names the claim it saves when the tab closes on a running game", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady();
window.dispatchEvent(new Event("pagehide"));
const [platform, , container, claimedAt] =
mocks.saveAndExitKeepalive.mock.calls[0];
expect([platform, container, claimedAt]).toEqual([
"gba",
CLAIM.container,
CLAIM.claimed_at,
]);
});
it("names the claim it saves on Save & Exit", async () => {
mocks.saveAndExit.mockResolvedValue({ released: true, saved: true });
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady();
await vmOf(wrapper).performSaveAndExit();
const [platform, , wait, container, claimedAt] =
mocks.saveAndExit.mock.calls[0];
expect([platform, wait, container, claimedAt]).toEqual([
"gba",
true,
CLAIM.container,
CLAIM.claimed_at,
]);
});
it("names the claim it releases when Save & Exit fails", async () => {
mocks.saveAndExit.mockResolvedValue({ released: false, saved: false });
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady();
await vmOf(wrapper).performSaveAndExit();
expect(mocks.releaseSession).toHaveBeenCalledWith(
"gba",
true,
CLAIM.container,
CLAIM.claimed_at,
);
});
it("names the claim it releases on Stop", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady();
await vmOf(wrapper).performStop();
expect(mocks.releaseSession).toHaveBeenCalledWith(
"gba",
false,
CLAIM.container,
CLAIM.claimed_at,
);
});
it("names the claim it saves and loads states on", async () => {
// A tab that missed its takeover would otherwise drive the claim that
// replaced it.
mocks.saveState.mockResolvedValue(null);
mocks.loadState.mockResolvedValue(null);
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady();
await vmOf(wrapper).handleSaveState();
await vmOf(wrapper).handleLoadState();
const claim = [CLAIM.container, CLAIM.claimed_at];
expect(mocks.saveState.mock.calls[0]?.slice(2)).toEqual(claim);
expect(mocks.loadState.mock.calls[0]?.slice(2)).toEqual(claim);
});
it("names the claim it releases when the tab closes while loading", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
window.dispatchEvent(new Event("pagehide"));
expect(mocks.releaseSessionKeepalive).toHaveBeenCalledWith(
"gba",
CLAIM.container,
CLAIM.claimed_at,
);
});
it("names the claim on the heartbeat", async () => {
// The heartbeat restamps whatever the platform is running otherwise, which
// keeps another player's session alive and lets this one go stale.
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
mocks.heartbeatSession.mockResolvedValue(null);
await mocks.presenceTick?.();
expect(mocks.heartbeatSession).toHaveBeenCalledWith(
"gba",
CLAIM.container,
CLAIM.claimed_at,
);
});
});
describe("Stream state controls", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.claimSession.mockResolvedValue(CLAIM);
mocks.capabilities = { maxSlots: 0, hasAutosave: true, autosaveSlot: 10 };
});
afterEach(() => {
mocks.capabilities = {};
});
async function barIcons(liveStates: boolean): Promise<unknown[]> {
const wrapper = await launch({ picker: false, liveStates });
await vmOf(wrapper).onPlay();
await launchReady();
await flushPromises();
return wrapper.findAllComponents(RBtn).map((b) => b.props("icon"));
}
it("offers Save and Load where the broker takes a state mid-game", async () => {
const icons = await barIcons(true);
expect(icons).toContain("mdi-content-save-outline");
expect(icons).toContain("mdi-restore");
});
it("offers neither where the emulator writes its state only on exit", async () => {
// DuckStation and RPCS3 keep an autosave slot for their state library,
// so that slot alone must not bring the buttons back.
const icons = await barIcons(false);
expect(icons).not.toContain("mdi-content-save-outline");
expect(icons).not.toContain("mdi-restore");
expect(icons).toContain("mdi-content-save-move-outline");
});
});
// The heartbeat only runs once the game is on screen, so while loading the
// status poll is what can find it; a tab coming back to the front runs one.
async function pollStatus(): Promise<void> {
document.dispatchEvent(new Event("visibilitychange"));
await flushPromises();
}
describe("Stream launch recovery", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.claimSession.mockResolvedValue(CLAIM);
});
it("enters the stream when the poll finds the game already up", async () => {
// launch-ready is pushed once, so a socket that dropped during the launch
// left the tab loading over a game that was running.
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
mocks.fetchSessionStatus.mockResolvedValue({
status: "active",
platform: "gba",
host: "http://webstation-dev:8080/room/x",
});
await pollStatus();
// With one container per platform a re-claim lands on the same container,
// so only the stamp keeps the poll from answering with another tab's claim.
expect(mocks.fetchSessionStatus).toHaveBeenCalledExactlyOnceWith(
"gba",
CLAIM.claimed_at,
);
expect(vmOf(wrapper).playerState).toBe("playing");
expect(vmOf(wrapper).containerHost).toBe(
"http://webstation-dev:8080/room/x",
);
});
it("leaves a stream the poll entered alone when launch-ready follows", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
mocks.fetchSessionStatus.mockResolvedValue({
status: "active",
platform: "gba",
host: "http://webstation-dev:8080/room/x",
});
await pollStatus();
await launchReady({ host: "http://webstation-dev:8080/room/other" });
await flushPromises();
expect(vmOf(wrapper).playerState).toBe("playing");
expect(vmOf(wrapper).containerHost).toBe(
"http://webstation-dev:8080/room/x",
);
});
it("keeps waiting when the launch-ready is for a claim that replaced its own", async () => {
// Tab A missed its launch-failed, and tab B re-claimed the same container.
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady({ claimed_at: "2026-09-17T10:05:00" });
await flushPromises();
expect(vmOf(wrapper).playerState).toBe("loading");
expect(vmOf(wrapper).containerHost).toBe("");
});
it("keeps waiting when the poll answers before the claim does", async () => {
// Without the 202's stamp the poll reports any session the player holds on
// the platform, which can be another tab's.
const claimed = deferClaim();
const wrapper = await launch({ picker: false });
const playing = vmOf(wrapper).onPlay();
await flushPromises();
mocks.fetchSessionStatus.mockResolvedValue({
status: "active",
platform: "gba",
host: "http://webstation-dev:8080/room/y",
});
await pollStatus();
expect(mocks.fetchSessionStatus).not.toHaveBeenCalled();
expect(vmOf(wrapper).playerState).toBe("loading");
expect(vmOf(wrapper).containerHost).toBe("");
claimed(CLAIM);
await playing;
});
it("ignores a poll that answers for the claim this tab has since replaced", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
await launchReady();
let answer = (_: unknown) => {};
mocks.fetchSessionStatus.mockReturnValue(
new Promise((resolve) => {
answer = resolve;
}),
);
await pollStatus();
vmOf(wrapper).claimedAt = "2026-09-17T10:05:00";
answer({ status: "ended", platform: "gba" });
await flushPromises();
expect(vmOf(wrapper).playerState).toBe("playing");
});
it("keeps waiting while the launch has no room yet", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
mocks.fetchSessionStatus.mockResolvedValue({
status: "active",
platform: "gba",
host: null,
});
await pollStatus();
expect(vmOf(wrapper).playerState).toBe("loading");
});
});
describe("Stream join", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.joinSession.mockResolvedValue({ host: "http://box:3000/room/x" });
mocks.query = { join: "1", container: "http://box:8000" };
});
afterEach(() => {
mocks.query = {};
});
it("joins the session on the container the game page named", async () => {
// A pool has several sessions on one platform, so without the container
// the join lands on whichever the backend walks to first.
const wrapper = await launch({ picker: false });
await flushPromises();
expect(mocks.joinSession).toHaveBeenCalledWith("gba", "http://box:8000");
expect(vmOf(wrapper).playerState).toBe("playing");
});
it("joins without one when the page had no container to name", async () => {
mocks.query = { join: "1" };
await launch({ picker: false });
await flushPromises();
expect(mocks.joinSession).toHaveBeenCalledWith("gba", undefined);
});
});

View File

@@ -42,6 +42,7 @@ import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
import type { SaveSchema, UserStateSchema } from "@/__generated__";
import romApi from "@/services/api/rom";
import streamingApi, {
type ContainerBusyDetail,
isMemoryCardImportDetail,
type LaunchFailed,
type LaunchPhase,
@@ -61,6 +62,7 @@ import AssetPreview from "@/v2/components/Player/AssetPreview.vue";
import MemoryCardImportDialog from "@/v2/components/Player/MemoryCardImportDialog.vue";
import MemoryCardPicker from "@/v2/components/Player/MemoryCardPicker.vue";
import SaveDataPanel from "@/v2/components/Player/SaveDataPanel.vue";
import SessionEndedReason from "@/v2/components/Player/SessionEndedReason.vue";
import StreamStage from "@/v2/components/Player/StreamStage.vue";
import AssetList from "@/v2/components/shared/AssetList.vue";
import AssetStrip, {
@@ -83,6 +85,7 @@ import { useStageActive } from "@/v2/composables/useStageActive";
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types";
import storeGalleryRoms from "@/v2/stores/galleryRoms";
import { emulatorKey } from "@/v2/utils/assets";
import { bootableFiles } from "@/v2/utils/playerDisc";
type PlayerState = "idle" | "loading" | "playing" | "error" | "exited";
@@ -113,7 +116,9 @@ const containerHost = ref<string>("");
const isSavingAndExiting = ref(false);
const isSavingState = ref(false);
const isLoadingState = ref(false);
const volume = ref(100);
// Matches the room's first-visit level: retro games mix far louder than a
// webcam mic. Never sent on its own, so the room's saved level still wins.
const volume = ref(60);
const isMuted = ref(false);
// Set from a 428 on claim: the container holds a memory card nobody has
// decided about yet. The claim is not held open, the answer is replayed on a
@@ -138,6 +143,11 @@ useStageActive(gameRunning);
// host's session out from under them.
const isJoining = route.query.join === "1";
// Named by the row that offered the join: a pool holds a session per container,
// and an unnamed join takes whichever one the backend walks to first.
const joinContainer =
typeof route.query.container === "string" ? route.query.container : undefined;
// True only while this tab's own claim is held. The teardown paths key off
// this rather than the player state, because a joiner reaches "playing" too.
const holdsClaim = ref(false);
@@ -297,13 +307,12 @@ const selectedState = ref<UserStateSchema | null>(null);
// created_at because user_saves arrives on updated_at, which a rehash moves;
// the rows are dated on created_at to match.
const restorableSaves = computed<SaveSchema[]>(() => {
const emulator = container.value?.emulator?.toLowerCase();
const emulator = emulatorKey(container.value?.emulator);
if (!rom.value || !emulator) return [];
return (rom.value.user_saves ?? [])
.filter(
(s) =>
(s.emulator ?? "").toLowerCase() === emulator &&
s.file_name.endsWith(".zip"),
emulatorKey(s.emulator) === emulator && s.file_name.endsWith(".zip"),
)
.sort(
(a, b) =>
@@ -336,10 +345,10 @@ const selectedSave = computed<SaveSchema | null>(
);
const streamStates = computed<UserStateSchema[]>(() => {
const emulator = container.value?.emulator?.toLowerCase();
const emulator = emulatorKey(container.value?.emulator);
if (!rom.value || !emulator) return [];
return (rom.value.all_user_states ?? []).filter(
(s) => (s.emulator ?? "").toLowerCase() === emulator,
(s) => emulatorKey(s.emulator) === emulator,
);
});
@@ -481,7 +490,11 @@ const presence = useActivityPresence(
heartbeatInFlight = true;
try {
await handleSessionStatus(
await streamingStore.heartbeatSession(rom.value.platform_slug),
await streamingStore.heartbeatSession(
rom.value.platform_slug,
claimedContainer.value,
claimedAt.value,
),
);
} finally {
heartbeatInFlight = false;
@@ -515,7 +528,7 @@ async function handleSessionStatus(
): Promise<void> {
// Null means the poll failed, not that the session is gone. A transient
// network error must never tear down a live game.
if (!status || status.status !== "ended") return;
if (!status) return;
// Already leaving under our own power (stop, save-and-exit, unload).
if (!sessionActive.value) return;
// The socket push arrives per-user, not per-platform (one room for every
@@ -523,6 +536,11 @@ async function handleSessionStatus(
// must not tear down the one actually on screen.
if (rom.value && status.platform !== rom.value.platform_slug) return;
if (status.status === "active") {
await enterRunningSession(status);
return;
}
// Leave fullscreen before anything else. RDialog teleports to <body>,
// outside the stage, so the notice would otherwise be painted under a
// fullscreened stage; and tearing the stage down first would unmount the
@@ -535,11 +553,31 @@ async function handleSessionStatus(
playerState.value = "exited";
containerHost.value = "";
presence.stopHeartbeat();
// Left standing, the claim would have the unload and unmount paths release
// whoever holds the container next.
forgetClaim();
endedNotice.value = status.termination ?? null;
endedDialogOpen.value = true;
}
async function enterStream(host: string): Promise<void> {
containerHost.value = host;
playerState.value = "playing";
if (fullscreenOnPlay.value) {
await nextTick();
await stage.value?.enterFullscreen();
}
}
// launch-ready is pushed once, so a tab that missed it sits loading over a
// running session; the room the poll reports is its way back in.
async function enterRunningSession(status: SessionStatus): Promise<void> {
if (playerState.value !== "loading" || !status.host) return;
launchPhase.value = null;
await enterStream(status.host);
}
function dismissEndedDialog(): void {
endedDialogOpen.value = false;
backToRom();
@@ -555,22 +593,42 @@ const SESSION_POLL_MS = 30_000;
// session (`_record_termination` in streaming.py), to the caller's own
// `user:{id}` room. Near-instant, unlike the poll above.
useSocketEvent<SessionTermination>("streaming:session-ended", (notice) => {
void handleSessionStatus({
// The room carries every claim the account holds, and an admin's desktop is
// never the game on screen.
if (notice.desktop) return;
if (!claimedAt.value) {
if (playerState.value === "loading") earlyNotices.push(notice);
return;
}
if (isOurClaim(notice)) void endFromNotice(notice);
});
// Notices that beat the 202, held until it says which claim is ours.
const earlyNotices: SessionTermination[] = [];
async function endFromNotice(notice: SessionTermination): Promise<void> {
await handleSessionStatus({
status: "ended",
platform: notice.platform ?? "",
termination: notice,
});
});
}
let sessionPollInFlight = false;
async function pollSessionStatus(): Promise<void> {
// Skip rather than queue: a slow reply must not stack up requests.
if (sessionPollInFlight || !sessionActive.value || !rom.value) return;
// Unstamped, the answer can be another tab's claim on the platform.
const stamp = claimedAt.value;
if (!stamp) return;
sessionPollInFlight = true;
try {
await handleSessionStatus(
await streamingStore.fetchSessionStatus(rom.value.platform_slug),
const status = await streamingStore.fetchSessionStatus(
rom.value.platform_slug,
stamp,
);
if (stamp !== claimedAt.value) return;
await handleSessionStatus(status);
} finally {
sessionPollInFlight = false;
}
@@ -592,49 +650,69 @@ const stopSessionPoll = sessionPoll.pause;
// The claim only reserves the container; the backend runs the launch detached
// and pushes what happened. A launch can take minutes on a title the broker
// has to unpack, and these are the only progress the player sees.
//
// The room is per-user, so a second tab streaming something else receives
// these too. The container is what identifies a launch: a pool can serve one
// platform from more than one, and the claim's 202 said which we got.
// Which container the claim won, so a launch push can be told from another
// tab's. Null until the 202 lands, which is before any push can arrive.
const claimedContainer = ref<string | null>(null);
// The stamp the 202 answered with. Every request and push about the claim
// carries it, since a re-claim of the same container shares its key.
const claimedAt = ref<string | null>(null);
function isOurLaunch(payload: { container?: string }): boolean {
return payload.container === claimedContainer.value;
function forgetClaim(): void {
holdsClaim.value = false;
claimedContainer.value = null;
claimedAt.value = null;
}
// The room is per-user, so a second tab hears about this tab's claim too.
function isOurClaim(payload: {
container?: string | null;
claimed_at?: string | null;
}): boolean {
return (
payload.container === claimedContainer.value &&
payload.claimed_at === claimedAt.value
);
}
// For a claim the player walked away from while it came up. Only a release the
// backend took clears it, and the unmount path retries one that failed.
async function handBackClaim(platform: string): Promise<void> {
const released = await streamingStore.releaseSession(
platform,
false,
claimedContainer.value,
claimedAt.value,
);
if (released) forgetClaim();
else holdsClaim.value = true;
}
useSocketEvent<LaunchPhase>("streaming:launch-phase", (payload) => {
if (!isOurLaunch(payload) || playerState.value !== "loading") return;
launchPhase.value = payload.phase;
if (!isOurClaim(payload) || playerState.value !== "loading") return;
launchPhase.value = payload.phase ?? null;
});
useSocketEvent<LaunchReady>("streaming:launch-ready", async (payload) => {
if (!isOurLaunch(payload)) return;
if (!isOurClaim(payload)) return;
launchPhase.value = null;
// The player left while the game was coming up. The claim is theirs and
// still held, so hand the container back rather than entering the stream.
if ((playerState.value as PlayerState) === "exited") {
claimedContainer.value = null;
void streamingStore.releaseSession(payload.platform, false);
if (playerState.value === "exited") {
await handBackClaim(payload.platform);
return;
}
if (payload.resume === false) snackbar.warning(t("play.resume-failed"));
containerHost.value = payload.host;
playerState.value = "playing";
if (fullscreenOnPlay.value) {
await nextTick();
await stage.value?.enterFullscreen();
}
// A status poll can land between the launch stamp and this push and enter
// first; entering again would force fullscreen back on.
if (playerState.value === "playing") return;
await enterStream(payload.host);
});
useSocketEvent<LaunchFailed>("streaming:launch-failed", (payload) => {
if (!isOurLaunch(payload)) return;
if (!isOurClaim(payload)) return;
// The backend already released the claim, so there is nothing to hand back.
holdsClaim.value = false;
claimedContainer.value = null;
forgetClaim();
launchPhase.value = null;
if ((playerState.value as PlayerState) === "exited") return;
if (playerState.value === "exited") return;
errorType.value = "server";
errorMessage.value = t("play.stream-error-generic");
errorHint.value = payload.detail;
@@ -679,7 +757,7 @@ function sendVolumeToBroker(level: number): void {
const platform = rom.value?.platform_slug;
if (platform)
streamingApi
.setVolume(platform, level)
.setVolume(platform, level, claimedContainer.value, claimedAt.value)
.catch((err) => console.warn("[streaming] Could not set volume:", err));
}, 150);
}
@@ -698,7 +776,7 @@ function toggleMute(): void {
const platform = rom.value?.platform_slug;
if (platform)
streamingApi
.setMute(platform, isMuted.value)
.setMute(platform, isMuted.value, claimedContainer.value, claimedAt.value)
.catch((err) => console.warn("[streaming] Could not set mute:", err));
}
@@ -759,15 +837,13 @@ async function onPlay(cardImport?: MemoryCardImport): Promise<void> {
try {
if (isJoining) {
const joined = await streamingStore.joinSession(rom.value.platform_slug);
const joined = await streamingStore.joinSession(
rom.value.platform_slug,
joinContainer,
);
await flourish;
if ((playerState.value as PlayerState) === "exited") return;
containerHost.value = joined.host;
playerState.value = "playing";
if (fullscreenOnPlay.value) {
await nextTick();
await stage.value?.enterFullscreen();
}
await enterStream(joined.host);
} else {
// The backend derives the ROM's filesystem path and platform from the id.
// It answers as soon as the container is reserved; the room URL follows
@@ -787,7 +863,15 @@ async function onPlay(cardImport?: MemoryCardImport): Promise<void> {
multiplayerOnPlay.value,
);
claimedContainer.value = launching.container;
claimedAt.value = launching.claimed_at;
holdsClaim.value = true;
// Every exit path ran before there was a claim to hand back.
if ((playerState.value as PlayerState) === "exited") {
await handBackClaim(rom.value.platform_slug);
return;
}
const endedEarly = earlyNotices.splice(0).find(isOurClaim);
if (endedEarly) await endFromNotice(endedEarly);
await flourish;
}
} catch (err: unknown) {
@@ -835,14 +919,10 @@ async function onPlay(cardImport?: MemoryCardImport): Promise<void> {
errorType.value = "occupied";
const busy =
detail && typeof detail === "object"
? (detail as {
rom_name: string | null;
claimed_at: string | null;
draining?: boolean;
})
? (detail as ContainerBusyDetail)
: null;
// A draining container is nobody's: the previous session is over and its
// exit state is still being collected, so there is no holder to name.
// A draining container is nobody's: the previous session is over and the
// container is still shutting it down, so there is no holder to name.
draining.value = busy?.draining === true;
occupiedBy.value =
busy && busy.rom_name && busy.claimed_at
@@ -877,7 +957,7 @@ async function onPlay(cardImport?: MemoryCardImport): Promise<void> {
// Start timing the session once the claim succeeds and playback is live.
// The session is ingested on unmount, which updates last_played /
// now_playing / status server-side.
if (rom.value && playerState.value === "playing") {
if (rom.value && (playerState.value as PlayerState) === "playing") {
playSession.start(rom.value);
}
}
@@ -909,6 +989,8 @@ async function performStop(): Promise<void> {
const released = await streamingStore.releaseSession(
rom.value?.platform_slug ?? "",
false,
claimedContainer.value,
claimedAt.value,
);
// The claim only goes when the backend says it went. Left standing, it
// tells the user why the container is still busy and gives the unmount
@@ -950,6 +1032,8 @@ async function performSaveAndExit(): Promise<void> {
rom.value.platform_slug,
capabilities.value.autosaveSlot,
true,
claimedContainer.value,
claimedAt.value,
);
saved = result.saved;
released = result.released;
@@ -957,7 +1041,12 @@ async function performSaveAndExit(): Promise<void> {
// The save-and-exit request failed, so the claim may still be held;
// fall back to a plain release so the container is freed before the
// player is marked exited.
released = await streamingStore.releaseSession(rom.value.platform_slug);
released = await streamingStore.releaseSession(
rom.value.platform_slug,
true,
claimedContainer.value,
claimedAt.value,
);
}
} finally {
isSavingAndExiting.value = false;
@@ -988,7 +1077,12 @@ async function handleSaveState(): Promise<void> {
if (isSavingState.value) return;
isSavingState.value = true;
try {
await streamingApi.saveState(rom.value.platform_slug, streamSlot.value);
await streamingApi.saveState(
rom.value.platform_slug,
streamSlot.value,
claimedContainer.value,
claimedAt.value,
);
} catch (err) {
console.warn("[streaming] Could not save state:", err);
snackbar.error(t("play.stream-save-state-failed"), { timeout: 6000 });
@@ -1002,7 +1096,12 @@ async function handleLoadState(): Promise<void> {
if (isLoadingState.value) return;
isLoadingState.value = true;
try {
await streamingApi.loadState(rom.value.platform_slug, streamSlot.value);
await streamingApi.loadState(
rom.value.platform_slug,
streamSlot.value,
claimedContainer.value,
claimedAt.value,
);
} catch (err) {
console.warn("[streaming] Could not load state:", err);
snackbar.error(t("play.stream-load-state-failed"), { timeout: 6000 });
@@ -1020,7 +1119,12 @@ async function handleSwapDisc(): Promise<void> {
if (!rom.value || selectedDisc.value === null || isSwappingDisc.value) return;
isSwappingDisc.value = true;
try {
await streamingApi.swapDisc(rom.value.platform_slug, selectedDisc.value);
await streamingApi.swapDisc(
rom.value.platform_slug,
selectedDisc.value,
claimedContainer.value,
claimedAt.value,
);
showDiscSwap.value = false;
} catch (err) {
console.warn("[streaming] Could not swap disc:", err);
@@ -1188,11 +1292,17 @@ function onPageHide(): void {
streamingStore.saveAndExitKeepalive(
platform,
capabilities.value.autosaveSlot,
claimedContainer.value,
claimedAt.value,
);
} else {
// Still loading, or exited with a release that failed: nothing to save,
// and this is the last chance to hand the container back.
streamingStore.releaseSessionKeepalive(platform);
streamingStore.releaseSessionKeepalive(
platform,
claimedContainer.value,
claimedAt.value,
);
}
// Guards the in-app unmount path from double-releasing if the page
// comes back from the bfcache and is then navigated normally.
@@ -1247,11 +1357,18 @@ onBeforeUnmount(() => {
rom.value?.platform_slug ?? "",
capabilities.value.autosaveSlot,
false,
claimedContainer.value,
claimedAt.value,
);
} else {
// Nothing is running, so there is nothing worth a state: asking for one
// here would only file whatever the last session left in the slot.
void streamingStore.releaseSession(rom.value?.platform_slug ?? "", false);
void streamingStore.releaseSession(
rom.value?.platform_slug ?? "",
false,
claimedContainer.value,
claimedAt.value,
);
}
});
</script>
@@ -1556,8 +1673,9 @@ onBeforeUnmount(() => {
:aria-label="t('play.stream-volume')"
/>
<!-- States and the save-and-exit belong to the claim holder. -->
<template v-if="capabilities.hasAutosave && !isJoining">
<!-- States and the save-and-exit belong to the claim holder. An
exit-state emulator has an autosave slot but refuses both. -->
<template v-if="container?.supports_live_states && !isJoining">
<RBtn
icon="mdi-content-save-outline"
variant="text"
@@ -1660,12 +1778,11 @@ onBeforeUnmount(() => {
</template>
<template #content>
<p class="r-v2-stream__exit-text">{{ endedMessage }}</p>
<div v-if="endedReason" class="r-v2-stream__ended-reason">
<span class="r-v2-stream__ended-reason-label">
{{ t("play.session-ended-reason-label") }}
</span>
<span>{{ endedReason }}</span>
</div>
<SessionEndedReason
v-if="endedReason"
:reason="endedReason"
class="r-v2-stream__ended-reason"
/>
</template>
<template #footer>
<!-- eslint-disable vuejs-accessibility/no-autofocus -- RDialog reads [autofocus] to place initial focus, and focusing the dialog's action on open is intentional modal UX -->
@@ -2085,9 +2202,6 @@ onBeforeUnmount(() => {
line-height: 1.5;
}
.r-v2-stream__ended-reason {
display: flex;
flex-direction: column;
gap: 3px;
margin-top: 12px;
padding: 10px 12px;
border-radius: var(--r-radius-md);
@@ -2096,14 +2210,6 @@ onBeforeUnmount(() => {
font-size: var(--r-font-size-sm);
color: var(--r-color-fg);
line-height: 1.5;
overflow-wrap: anywhere;
}
.r-v2-stream__ended-reason-label {
font-size: var(--r-font-size-xs);
font-weight: var(--r-font-weight-bold);
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--r-color-fg-muted);
}
.r-v2-stream__exit-actions {