fix(streaming): let multi-disc games pick a starting disc (#5446)

* fix(streaming): let multi-disc games pick a starting disc

The streaming launch screen had no disc selector, so a multi-disc game
always started on its first disc. The claim now takes an optional
disc_file_id. Containers with a tray route mount the playlist as before
and swap to the pick once the game is up (a resumed state's own disc
still wins); anything else boots the picked disc file directly.

Fixes #5271

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(streaming): boot a resumed state's disc and record a directly booted disc

Addresses Greptile review on #5446.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-11-03 20:40:09 -05:00
committed by GitHub
parent 4b01bebfb8
commit 58e2fdbadb
9 changed files with 353 additions and 12 deletions

View File

@@ -150,6 +150,8 @@ class ClaimStreamingSessionRequest(BaseModel):
# card has never been adopted. "adopt" keeps it, "discard" wipes it, and
# "discard" doubles as the override for a card that could not be read.
card_import: Literal["adopt", "discard"] | None = None
# Optional disc of a multi-disc set to start on, one of its playlist entries.
disc_file_id: Annotated[int, Field(ge=1)] | None = None
# Decided on the launch screen and fixed for the session. True advertises
# the session on GET /sessions/joinable and tells the room to show its
# comms surface while the host is still alone.
@@ -902,6 +904,16 @@ async def claim_session(
req.memory_card_id,
)
start_disc = None
if req.disc_file_id is not None:
start_disc = next(
(f for f in playlist_files(rom.files) if f.id == req.disc_file_id), None
)
if start_disc is None:
raise HTTPException(
status_code=400, detail="File is not a disc of this ROM"
)
# A broker with no join route cannot seat a second viewer, so recording
# the flag there would advertise a session every Join would 409 on.
multiplayer = req.multiplayer and reference.protocol.supports_join
@@ -1018,6 +1030,27 @@ async def claim_session(
# that is valid inside that container.
library_base = container.library_path
rom_path = f"{library_base}/{rom.full_path}"
# The tray can only step through a playlist the emulator loaded, so a
# container without one boots the picked disc on its own.
start_disc_id = None
booted_disc_id = None
if start_disc is not None:
if container.capabilities["supports_disc_swap"] and rom.has_m3u_file():
start_disc_id = start_disc.id
else:
# No swap can follow, so a resumed state's own disc boots instead.
state_disc = next(
(
f
for f in playlist_files(rom.files)
if resume_state is not None
and f.id == resume_state.disc_file_id
),
None,
)
boot_disc = state_disc or start_disc
rom_path = f"{library_base}/{boot_disc.full_path}"
booted_disc_id = boot_disc.id
# Nothing beats for the player until the stream is up, and on a slow
# container these steps can outlast the window after which a claim is stale.
@@ -1095,6 +1128,8 @@ async def claim_session(
memory_card_synced=memory_card is not None,
multiplayer=multiplayer,
blank_card_id=undo.blank_card_id,
start_disc_id=start_disc_id,
booted_disc_id=booted_disc_id,
)
return LaunchingSessionSchema(

View File

@@ -29,6 +29,7 @@ from handler.streaming.session_store import (
StreamingSession,
hold_session_claim,
push_to_user,
set_session_disc,
stamp_launched,
)
from logger.logger import log
@@ -62,6 +63,8 @@ async def run_launch(
multiplayer: bool,
blank_card_id: int | None,
native_fallback: bool = False,
start_disc_id: int | None = None,
booted_disc_id: int | None = None,
) -> None:
"""Start the game, then tell the player's tabs where to find it.
@@ -71,6 +74,9 @@ async def run_launch(
Args:
native_fallback: `archive_path` holds only a default save, so a refusal
of it boots the newest native archive instead.
start_disc_id: the disc the player picked to start on, if any.
booted_disc_id: the disc `rom_path` boots directly, recorded so states
saved on it remember their disc.
"""
# Nothing beats for the player until the stream is up, so without this the
# next claimant reads the record as abandoned and tears the container down
@@ -222,18 +228,25 @@ async def run_launch(
)
)
# A resumed state remembers which disc it was captured on. The launch
# always starts on the playlist's first disc, so put the right one back.
if booted_disc_id is not None:
await set_session_disc(
session_key, booted_disc_id, session["broker_session_id"]
)
return
# The launch always starts on the playlist's first disc. A resumed state
# needs the disc it was captured on, which outranks the player's pick.
resume_disc_id = (
resume_state.disc_file_id if resume_pushed and resume_state else None
)
if isinstance(resume_disc_id, int):
disc_id = resume_disc_id if isinstance(resume_disc_id, int) else start_disc_id
if disc_id is not None:
background.spawn_sync_task(
states.restore_session_disc(
rom.id,
container,
session_key,
file_id=resume_disc_id,
file_id=disc_id,
broker_session_id=session["broker_session_id"],
)
)

View File

@@ -831,7 +831,7 @@ async def restore_session_disc(
file_id: int,
broker_session_id: str | None = None,
) -> bool:
"""Background task: put back the disc a resumed state was captured on.
"""Background task: switch to the disc a resumed state or the player names.
The launch always mounts the ROM folder so the emulator loads the playlist
and starts on the first disc; anything else would boot a bare image the

View File

@@ -13617,6 +13617,223 @@ def test_resuming_a_state_with_no_disc_swaps_nothing(
restore.assert_not_called()
# ── claim: starting disc ────────────────────────────────────────────────────
def _claim_disc(client, token, rom_id, disc_file_id):
return client.post(
"/api/streaming/sessions",
json={"rom_id": rom_id, "disc_file_id": disc_file_id},
headers=_auth(token),
)
def test_claim_starts_on_the_picked_disc_through_the_tray(client, access_token):
rom = _rom_on("dc")
_add_rom_file(rom, "Game.m3u")
_add_rom_file(rom, "Game (Disc 1).chd")
disc = _add_rom_file(rom, "Game (Disc 2).chd")
run_launch_mock = AsyncMock()
with (
_streaming(_tray_container(rom)),
patch("handler.streaming.launch.run_launch", run_launch_mock),
):
r = _claim_disc(client, access_token, rom.id, disc.id)
assert r.status_code == 202
kwargs = run_launch_mock.call_args.kwargs
assert kwargs["start_disc_id"] == disc.id
assert kwargs["rom_path"] == f"{LIBRARY_BASE_PATH}/{rom.full_path}"
def test_claim_boots_the_picked_disc_where_no_tray_can_reach_it(client, access_token):
rom = _rom_on("dc")
_add_rom_file(rom, "Game.m3u")
_add_rom_file(rom, "Game (Disc 1).chd")
disc = _add_rom_file(rom, "Game (Disc 2).chd")
run_launch_mock = AsyncMock()
with (
_streaming(_container_for(rom)),
patch("handler.streaming.launch.run_launch", run_launch_mock),
):
r = _claim_disc(client, access_token, rom.id, disc.id)
assert r.status_code == 202
kwargs = run_launch_mock.call_args.kwargs
assert kwargs["start_disc_id"] is None
assert kwargs["rom_path"] == f"{LIBRARY_BASE_PATH}/{disc.full_path}"
def test_claim_boots_the_picked_disc_of_a_set_without_a_playlist(client, access_token):
"""The tray steps through a loaded playlist, which a set with no .m3u never
gives the emulator."""
rom = _rom_on("dc")
_add_rom_file(rom, "Game (Disc 1).chd")
disc = _add_rom_file(rom, "Game (Disc 2).chd")
run_launch_mock = AsyncMock()
with (
_streaming(_tray_container(rom)),
patch("handler.streaming.launch.run_launch", run_launch_mock),
):
r = _claim_disc(client, access_token, rom.id, disc.id)
assert r.status_code == 202
kwargs = run_launch_mock.call_args.kwargs
assert kwargs["start_disc_id"] is None
assert kwargs["rom_path"] == f"{LIBRARY_BASE_PATH}/{disc.full_path}"
@pytest.mark.parametrize("own_file", [True, False])
def test_claim_refuses_a_disc_that_is_not_one_of_the_roms(
client, access_token, rom: Rom, own_file: bool
):
streamed = _rom_on("dc")
playlist = _add_rom_file(streamed, "Game.m3u")
_add_rom_file(streamed, "Game (Disc 1).chd")
stranger = _add_rom_file(rom, "Other.chd")
container = _tray_container(streamed)
run_launch_mock = AsyncMock()
with (
_streaming(container),
patch("handler.streaming.launch.run_launch", run_launch_mock),
):
r = _claim_disc(
client, access_token, streamed.id, (playlist if own_file else stranger).id
)
assert r.status_code == 400
run_launch_mock.assert_not_called()
assert not asyncio.run(
async_cache.exists(session_store.session_redis_key(_key_of(container)))
)
def _run_launch_restoring(
rom: Rom,
user: User,
*,
start_disc_id: int | None,
resume_disc_id: int | None = None,
booted_disc_id: int | None = None,
set_disc: AsyncMock | None = None,
) -> MagicMock:
"""Run a launch and return the stand-in for the disc restore it spawns."""
resume_state = (
cast(State, MagicMock(disc_file_id=resume_disc_id))
if resume_disc_id is not None
else None
)
session: StreamingSession = {
"broker_session_id": "s1",
"claimed_at": "t1",
"user_id": user.id,
}
restore = MagicMock()
with (
patch(
"handler.streaming.launch.webstation.activate",
MagicMock(return_value={"url": "/room/x"}),
),
patch("handler.streaming.launch.lifecycle.hold_session_claim", new=AsyncMock()),
patch(
"handler.streaming.launch.lifecycle.publish_session_activity",
new=AsyncMock(),
),
patch("handler.streaming.launch.stamp_launched", new=AsyncMock()),
patch("handler.streaming.launch.push_to_user", new=AsyncMock()),
patch("handler.streaming.launch.background.spawn_sync_task"),
patch(
"handler.streaming.launch.states.hydrate_states_to_broker", new=MagicMock()
),
patch("handler.streaming.launch.states.restore_session_disc", restore),
patch("handler.streaming.launch.set_session_disc", set_disc or AsyncMock()),
):
asyncio.run(
launch.run_launch(
container=_resolved(_tray_container(rom)),
session_key="k1",
session=session,
user=user,
rom=rom,
platform=rom.platform_slug,
rom_name=rom.name or rom.fs_name_no_ext,
rom_path="rom/path",
rom_language=None,
gui_language=None,
archive_path=None,
resume_state=resume_state,
resume_slot=None,
resume_pushed=resume_state is not None,
resume_after_launch=False,
resume_import="none",
memory_card_synced=False,
multiplayer=False,
blank_card_id=None,
start_disc_id=start_disc_id,
booted_disc_id=booted_disc_id,
)
)
return restore
def test_run_launch_swaps_to_the_picked_disc(admin_user: User):
rom = _rom_on("dc")
restore = _run_launch_restoring(rom, admin_user, start_disc_id=42)
restore.assert_called_once()
assert restore.call_args.kwargs["file_id"] == 42
def test_run_launch_resumes_on_the_states_disc_over_the_pick(admin_user: User):
"""A state only loads on the disc it was captured on."""
rom = _rom_on("dc")
restore = _run_launch_restoring(
rom, admin_user, start_disc_id=42, resume_disc_id=43
)
restore.assert_called_once()
assert restore.call_args.kwargs["file_id"] == 43
def test_run_launch_leaves_the_first_disc_without_a_pick(admin_user: User):
rom = _rom_on("dc")
restore = _run_launch_restoring(rom, admin_user, start_disc_id=None)
restore.assert_not_called()
def test_claim_boots_the_resumed_states_disc_where_no_tray_can_reach_it(
client, access_token, admin_user: User
):
"""No swap can follow a direct boot, so the state's disc wins up front."""
rom = _rom_on("dc")
_add_rom_file(rom, "Game.m3u")
state_disc = _add_rom_file(rom, "Game (Disc 1).chd")
picked = _add_rom_file(rom, "Game (Disc 2).chd")
state = _add_state(rom, admin_user, "Game.state", "retroarch")
db_state_handler.update_state(state.id, {"disc_file_id": state_disc.id})
run_launch_mock = AsyncMock()
with (
_streaming({**_container_for(rom), "emulator": "retroarch"}),
patch("handler.streaming.states.push_resume_state", return_value=True),
patch("handler.streaming.launch.run_launch", run_launch_mock),
):
r = client.post(
"/api/streaming/sessions",
json={"rom_id": rom.id, "disc_file_id": picked.id, "state_id": state.id},
headers=_auth(access_token),
)
assert r.status_code == 202
kwargs = run_launch_mock.call_args.kwargs
assert kwargs["rom_path"] == f"{LIBRARY_BASE_PATH}/{state_disc.full_path}"
assert kwargs["booted_disc_id"] == state_disc.id
def test_run_launch_records_a_directly_booted_disc_without_a_swap(
admin_user: User,
):
rom = _rom_on("dc")
set_disc = AsyncMock()
restore = _run_launch_restoring(
rom, admin_user, start_disc_id=None, booted_disc_id=42, set_disc=set_disc
)
restore.assert_not_called()
set_disc.assert_awaited_once_with("k1", 42, "s1")
# ── _restore_session_disc (direct) ──────────────────────────────────────────

View File

@@ -8,6 +8,7 @@ export type ClaimStreamingSessionRequest = {
save_id?: (number | null);
memory_card_id?: (number | null);
card_import?: ('adopt' | 'discard' | null);
disc_file_id?: (number | null);
multiplayer?: boolean;
};

View File

@@ -115,6 +115,7 @@ async function claimSession(
memoryCardId?: number,
cardImport?: MemoryCardImport,
multiplayer?: boolean,
discFileId?: number,
) {
return api.post<LaunchingSession>("/streaming/sessions", {
rom_id: romId,
@@ -123,6 +124,7 @@ async function claimSession(
...(memoryCardId !== undefined ? { memory_card_id: memoryCardId } : {}),
...(cardImport !== undefined ? { card_import: cardImport } : {}),
...(multiplayer !== undefined ? { multiplayer } : {}),
...(discFileId !== undefined ? { disc_file_id: discFileId } : {}),
});
}

View File

@@ -189,6 +189,7 @@ export const useStreamingStore = defineStore("streaming", () => {
memoryCardId?: number,
cardImport?: MemoryCardImport,
multiplayer?: boolean,
discFileId?: number,
): Promise<LaunchingSession> {
const { data } = await streamingApi.claimSession(
romId,
@@ -197,6 +198,7 @@ export const useStreamingStore = defineStore("streaming", () => {
memoryCardId,
cardImport,
multiplayer,
discFileId,
);
return data;
}

View File

@@ -2,6 +2,7 @@ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent, nextTick, type Slots, type VNodeChild } from "vue";
import type {
RomFileSchema,
SaveSchema,
StateSchema,
StreamStatePicksSchema,
@@ -9,10 +10,11 @@ import type {
import AssetPreview from "@/components/Player/AssetPreview.vue";
import SaveDataPanel from "@/components/Player/SaveDataPanel.vue";
import AssetList from "@/components/shared/AssetList.vue";
import { RBtn, RSlider } from "@/lib";
import { RBtn, RSelect, RSlider } from "@/lib";
import type { DetailedRom } from "@/stores/roms";
import { propOf } from "@/test-utils/propOf";
import { saveFixture, stateFixture } from "@/utils/assets.fixtures";
import { detailedRomFixture } from "@/utils/rom.fixtures";
import { detailedRomFixture, romFileFixture } from "@/utils/rom.fixtures";
import Stream from "./Stream.vue";
const mocks = vi.hoisted(() => ({
@@ -234,14 +236,18 @@ const ARCHIVES = [
save(1, "Pool [retroarch 2026-09-14 00-20-28].saves.zip"),
];
function romWith(saves: SaveSchema[], states: StateSchema[] = []): DetailedRom {
function romWith(
saves: SaveSchema[],
states: StateSchema[] = [],
files: RomFileSchema[] = [],
): DetailedRom {
return detailedRomFixture({
id: 3,
name: "Archer Maclean's 3D Pool (USA)",
platform_slug: "gba",
platform_display_name: "Game Boy Advance",
fs_name: "Archer Maclean's 3D Pool (USA).gba",
files: [],
files,
user_saves: saves,
all_user_states: states.map((state) => ({ ...state, username: "admin" })),
user_screenshots: [],
@@ -256,6 +262,7 @@ async function launch(opts: {
imports?: ("save" | "state")[];
// The backend's answer; every state is native unless a test says otherwise.
picks?: StreamStatePicksSchema | Error | Promise<StreamStatePicksSchema>;
files?: RomFileSchema[];
}): Promise<VueWrapper> {
mocks.container = {
name: "WEBSTATION-DEV",
@@ -268,7 +275,7 @@ async function launch(opts: {
supports_multiplayer: false,
};
mocks.getRom.mockResolvedValue({
data: romWith(opts.saves ?? ARCHIVES, opts.states),
data: romWith(opts.saves ?? ARCHIVES, opts.states, opts.files),
});
const ids = (opts.states ?? []).map((state) => state.id);
const picks = opts.picks ?? { native: ids, pickable: ids };
@@ -672,6 +679,45 @@ async function launchFailed(
});
}
const DISCS = [
romFileFixture({ id: 101, file_name: "Pool (Disc 1).chd" }),
romFileFixture({ id: 102, file_name: "Pool (Disc 2).chd" }),
];
function discSelect(wrapper: VueWrapper) {
return wrapper
.findAllComponents(RSelect)
.find((s) => propOf(s, "prependInnerIcon") === "mdi-disc");
}
describe("Stream starting disc", () => {
beforeEach(() => {
mocks.claimSession.mockResolvedValue(CLAIM);
});
it("offers no disc pick for a single-file game", async () => {
const wrapper = await launch({ picker: false });
expect(discSelect(wrapper)).toBeUndefined();
});
it("leaves the disc to the backend until one is picked", async () => {
const wrapper = await launch({ picker: false, files: DISCS });
expect(discSelect(wrapper)).toBeDefined();
await (wrapper.vm as unknown as { onPlay: () => Promise<void> }).onPlay();
expect(mocks.claimSession.mock.calls[0]![6]).toBeUndefined();
});
it("sends the picked disc on the claim", async () => {
const wrapper = await launch({ picker: false, files: DISCS });
await discSelect(wrapper)!.vm.$emit("update:modelValue", 102);
await (wrapper.vm as unknown as { onPlay: () => Promise<void> }).onPlay();
expect(mocks.claimSession.mock.calls[0]![6]).toBe(102);
});
});
describe("Stream session-ended notices", () => {
beforeEach(() => {
mocks.claimSession.mockResolvedValue(CLAIM);

View File

@@ -10,7 +10,7 @@
// the emulator carries both.
// 3. Session: where the game runs and any claim errors (occupied /
// not configured / server).
// 4. Aside: memory card picker + fullscreen-on-play.
// 4. Aside: memory card picker, starting disc + fullscreen-on-play.
//
// The running state is a fixed stage hosting the Selkies iframe with an
// auto-hiding control bar (volume, save/load state, fullscreen, exit).
@@ -91,7 +91,12 @@ import {
useStreamingStore,
} from "@/stores/streaming";
import { emulatorKey } from "@/utils/assets";
import { bootableFiles } from "@/utils/playerDisc";
import {
ALL_DISCS,
bootableFiles,
bootDiscId,
type DiscSelection,
} from "@/utils/playerDisc";
type PlayerState = "idle" | "loading" | "playing" | "error" | "exited";
type ErrorType =
@@ -133,6 +138,8 @@ const showCardImport = ref(false);
const showDiscSwap = ref(false);
const selectedDisc = ref<number | null>(null);
const isSwappingDisc = ref(false);
// ALL_DISCS leaves the backend to mount the whole set on its first disc.
const startDisc = ref<DiscSelection>(ALL_DISCS);
const gameRunning = computed(() => playerState.value === "playing");
useStageActive(gameRunning);
@@ -286,6 +293,13 @@ const discOptions = computed(() => {
return listed.map((f) => ({ title: f.file_name, value: f.id }));
});
const startDiscItems = computed<{ title: string; value: DiscSelection }[]>(
() => [
{ title: t("play.all-discs"), value: ALL_DISCS },
...discOptions.value,
],
);
// A rom with a single swappable disc has nothing to swap to, whatever the
// platform can do.
const canSwapDisc = computed(
@@ -985,6 +999,7 @@ async function onPlay(cardImport?: MemoryCardImport): Promise<void> {
: undefined,
cardImport,
multiplayerOnPlay.value,
bootDiscId(startDisc.value) ?? undefined,
);
claimedContainer.value = launching.container;
heldContainer.value = container.value;
@@ -1687,6 +1702,16 @@ onBeforeUnmount(() => {
<span>{{ t("common.settings") }}</span>
</div>
<div class="r-stream__setup-body">
<RSelect
v-if="discOptions.length > 1 && !isJoining"
v-model="startDisc"
variant="outlined"
density="comfortable"
prepend-inner-icon="mdi-disc"
hide-details
:label="t('rom.file')"
:items="startDiscItems"
/>
<RSwitch
v-model="fullscreenOnPlay"
:label="t('play.full-screen')"