Add v2 browser playback for .p8 and .p8.png cartridges, backed by the
FAKE-08 WebAssembly runtime, with canvas rendering, audio, fullscreen and
keyboard, gamepad, mouse and touch input. Wires up platform detection,
play actions, routing, localization, gallery navigation, play-session
tracking and lifecycle cleanup.
The runtime is fetched in the emulator stage of docker/Dockerfile, pinned
by source commit and verified with sha256, so it is provisioned the same
way as EmulatorJS, Ruffle and js-dos rather than committed to the repo.
DISABLE_PICO8 gates the player, matching the existing DISABLE_EMULATOR_JS,
DISABLE_RUFFLE_RS and DISABLE_JSDOS toggles.
Based on #4383.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Rename `FirmwareTemplate.platform_path` to `firmware_dir`: it returns the
firmware folder, while the same name on `StructureTemplate` returns the platform
folder. Name the watcher's index for the segment it points at.
Fold the two reads of a raw structure key into `_raw_template`, and drop the
docstrings that only restated a one-line delegation or a signature.
Remove `footer-create-summary-default`, which no component references and whose
copy still named Structure A.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`filesystem.structure` now spells out the whole layout rather than only the part
below a platform folder. A template is relative to the library root, `{platform}`
marks the platform folder, and `{game}` marks where a game begins.
Merge `{gameFile}` and `{gameDir}` into one `{game}` terminal. The information a
terminal carried was the depth, not the kind: at a declared level a file is a
game of its own and a folder is one multi-file game, which a stat answers. That
drops the two-template idiom for a level holding both, and `_discover_default_roms`
with it, since the default scan is now just `roms/{platform}/{game}`.
Retire the auto-detected `{platform}/roms` layout, along with
`filesystem.roms_folder` and `filesystem.firmware_folder`, which named one path
segment each that a template now contains. Both are refused at startup with the
template that reproduces the layout, so an instance that relied on either says so
instead of scanning an empty library and marking every rom missing. Firmware gets
its own `structure.firmware` key rather than following the rom layout implicitly.
`get_roms_fs_structure` keeps meaning the folder a platform's games start in, so
the `.physical` sentinel paths already in the database still resolve. Per-platform
overrides have to agree with `default` on where the platform folder sits;
relocating one platform needs platform discovery and the watcher to union several
roots, which is left out.
The setup wizard reports `library_ready` plus the configured template instead of
a `struct_a`/`struct_b` discriminator, so the banner shows the layout in force
rather than guessing it client-side.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Testing the custom library structure against a live library turned up four
defects, all of them a path being reduced to a bare file name.
Both exporters wrote a rom's `fs_name` alone, so every game a template nests
was exported as if it sat in the platform folder: ES-DE and Pegasus could not
find any of them. They now write the rom's path relative to the platform
folder, the folder the metadata files themselves live in, and copy exported
media into the matching subfolder so two identically named roms keep their own
artwork.
Merging into an existing gamelist.xml / metadata.pegasus.txt keyed entries by
file name too, so identically named roms in different folders both merged into
the first entry and produced duplicates. Entries are now keyed by path, with a
Pegasus block matched by the folder its listed files sit in.
Reading a gamelist.xml had the same collision: two roms sharing a file name
both took the metadata of whichever entry was parsed last. A rom's own path now
wins, and a bare file name stays a fallback key for the tools that write those,
dropped when two entries share it.
Default discovery surfaced hidden folders as multi-file games, unlike
structured discovery which skips them. exclude_multi_roms now owns that rule
for both.
Also validate `exclude`'s exclusion_type: an unknown value reached
`Config.__getattribute__` and returned a 500 rather than a 422.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Key the unique roms index on a sha256 digest of the full path. Indexing
(platform_id, fs_path, fs_name) directly is 5804 bytes of utf8mb4, which MySQL
rejects with ER_TOO_LONG_KEY and MariaDB silently demotes to a hash index; the
digest column keeps it a 260-byte BTREE on every supported driver. It is derived
by the same @validates hook that maintains the other fs_name columns, and
resynced explicitly in update_rom and convert_rom_to_folder.
Migration 0126 backfills the digest in one dialect-branched UPDATE. A Python
executemany right after the ADD COLUMN silently applies only its first parameter
set on mariadb-connector, leaving the rest NULL. test_migrations pins the SQL
expression to compute_full_path_hash so the two cannot drift.
Drop the relocation pre-pass. mark_missing_roms already runs before the identify
loop, so a moved file reaches get_matching_missing_rom, which requires all three
hashes to agree (or a title_id, covering non-hashable platforms), refuses
ambiguous matches, re-parses filename tags and emits over the socket. The
pre-pass duplicated it with a weaker CRC-only check, hashed every candidate
twice, compared folder sizes against a total that excludes filtered files, and
ran on QUICK scans.
Send uploads to a folder the platform's structure will actually discover, so the
next scan does not flag a fresh upload as missing, and refuse with a 400 when
only the user can pick the folder.
Make 0126's downgrade refuse when duplicate file names exist instead of deleting
the roms (and their saves, notes and collection membership) that carry them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A grouping folder is no longer also a game. With `{gameDir}` and
`{category}/{gameFile}` declared together, the category folder was surfaced
as a multi-file game *and* descended into, listing its contents twice. A
folder any template descends into is now treated as a grouping level.
Relocation runs for every platform, not only those with a custom structure.
Dropping a platform's template moves every game back to the platform root,
which previously read as a library of new games and orphaned all the saves,
play history, favorites and collection membership. A library whose paths are
unchanged still costs one query and no hashing. This also removes the need
for a manual "apply relocation" toggle.
Physical games are excluded from relocation candidates: they have no file, so
they read as having disappeared from their path on every scan.
A near-miss on the terminal macro (`{gameFolder}` for `{gameDir}`) now names
the offending section instead of only reporting a missing terminal.
Documents two limits the QA pass asked about: a move that also compresses or
extracts the game changes its size and is not detected (the size pre-filter
runs before hashing), and how reverting to the default layout behaves.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Conflict resolution notes:
- Locale rom.json: master sorted and reworked every file; took master's and
re-inserted `location` / `location-copied` in sorted position. Added them to
the new tr_TR locale.
- FSRom gained a required `fs_path`, so `build_hashless_fs_rom` now takes one
and both call sites pass the rom's own path.
- `get_roms` keeps this branch's `_collect_fs_roms` discovery while adopting
master's one-pass build and in-place sort.
- `mark_missing_roms` takes full paths and now also excludes physical games
(master), and the scan loop keeps master's early missing-sync plus its
restored-rom emit alongside this branch's relocation pass. The relocation
filter now applies only to the identify loop, so a relocated rom is no longer
re-flagged missing at the end of the scan.
- Relocation writes rom files through master's `sync_rom_files` (which replaced
`purge_rom_files` / `add_rom_file`), so row ids and track metadata survive.
- Master's unique index on (platform_id, fs_name) contradicts this branch's
premise that same-named files in different folders are distinct games.
Migration 0126 widens it to (platform_id, fs_path, fs_name); physical games
all share one folder, so a duplicate title is still rejected.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The resolver took the provider names as a second tuple that had to stay in the
same order as the gather, which a reordered lookup would silently break. Pairing
the name with its coroutine follows the shape scan_handler already uses for
provider_fetches, and folds the gather into the resolver.
Also trims the comments and docstrings the review pass flagged as over-long.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The metadata search gathers every provider without return_exceptions, so an
unreachable IGDB took ScreenScraper's, MobyGames', Flashpoint's, LaunchBox's
and Demozoo's matches down with it and the user got a 500 instead of the
matches that had already come back.
Both gathers now collect exceptions and resolve them per provider, mirroring
the resolve_fetch pattern the scan already uses. int(search_term) is evaluated
before the gather, so an invalid ID still reports as a client error.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A game added today had no edges until the 5:30 AM rebuild, so its "Similar
games" section was empty and nothing could reach it from a feed.
`build_for` scores a handful of ROMs against the current library instead of
sweeping every pair, and folds them into the stored neighbour lists of the
games they matched so the new game is reachable from both directions. The
full build is the same sweep with every ROM as a target, so the two paths
share one implementation rather than drifting.
The scan hands over the ids it wrote. Past MAX_TOP_UP_ROMS the incremental
path saves nothing, so that case queues a rebuild rather than blocking the
scan on work a rebuild would redo.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Three tests reached the public internet on every CI run. `test_update_rom`
posts an igdb cover url and never mocked `get_cover`, so the fetch went out;
the two lock tests do the same with a manual url. The fix for the manual is
not just a decorator: `test_manual.py` patched `get_manual` on the
`fs_resource_handler` singleton with `monkeypatch.setattr`, and monkeypatch
restores by *setting* the bound method back as an instance attribute, which
then shadows a later class-level `patch.object` for the rest of the worker's
run. `mock.patch.object` deletes instead, so the patch in test_rom.py now
takes effect. Same change for the other singleton patches in that file, which
leak the same way.
The placeholder host moves to www.screenscraper.fr. `ss.fr` is a live
domain-parking host, unrelated to ScreenScraper, and the update path appends
`ssid` and `sspassword` to the url before fetching it.
The suite now makes no outbound request at all, bar the two ssrf tests that
exercise the rejection hook.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Both routes passed every caller-supplied platform_id straight to the
exporter. A permission group can grant platforms.write while hiding
individual platforms, so such a caller could export a platform hidden
from them -- reading its metadata and rewriting its gamelist.xml or
metadata.pegasus.txt.
Resolve and check every platform up front, the way update_platform and
delete_platform already do, so a rejected request writes nothing at all
rather than failing part way through a batch. A missing platform 404s
like a hidden one, so the response is not an oracle for whether the
platform exists.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Both export endpoints write into the library -- gamelist.xml and
metadata.pegasus.txt in the platform directory, plus media copied into
the per-type folders -- but were gated on roms.read, so any Viewer or
any roms.read client token could trigger a library write. Since #4368
those writes also merge the file already on disk, which makes a read
scope an even poorer fit.
platforms.write is the scope that already gates the sibling library
configuration writes in endpoints/configs.py, including the PUT /config/scan
that toggles the auto-export these endpoints mirror.
No UI change: nothing calls exportGamelistXml/exportPegasus, and the
generated frontend types carry no paths or scopes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The pytest job went from ~5 to ~21 minutes. Nineteen streaming tests take
60-66s each on a runner because they connect to a fake broker for real: a
workstation answers "unreachable" at once, a runner drops the packets and
the test burns the whole socket timeout (60s for a transfer, 120s for a
disc swap). One rom test fetches a manual from ss.fr the same way. Reading
the -vv timestamps out of the CI log, test_streaming.py alone accounted for
1250s of 1997s, and the job sat on a single worker for 1236s while the
other three finished in four minutes.
Refuse connections outside loopback, so a missed mock fails instantly with
the OSError the code already handles. Alongside that, three costs the fix
exposed: bcrypt runs 1670 times per suite for three constant fixture
passwords, the save-pull tests sleep out a retry backoff they don't assert
on, and the chunking test opens a thousand transactions to reach an id
count.
Under CI settings locally: 264.6s -> 61.8s, same 3977 passed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Resolve conflicts in the v2 Home view and its test: keep both the
recommendations row from this branch and the live multiplayer sessions
row from master.
Master added migrations 0119 through 0121 that forked the Alembic chain
against this branch's 0119 through 0122. Renumber this branch's
migrations to 0122 through 0125 so they chain after 0121_state_disc_file.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D9EiQ8VWDJfzhEViDdj84d
endpoints/streaming.py had grown to 3778 lines, but only about a third of
that was routes. The rest was a second copy of the layer handler/streaming
already exists to hold: broker verbs, webstation protocol translation,
state and save and memory-card transfer, session teardown.
Split it along those seams rather than by route, and give claim_session
the same treatment: its 406 lines are now four named phases.
Cross-module calls go through the module (states.pull_state_to_library,
commands.stop) instead of imported names, so one definition site is what
tests patch and what every caller reads.
No route path, scope or response model changed, so the OpenAPI schema is
untouched.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A broker's launch, join and desktop replies name the URL the browser loads
in an iframe, and urljoin keeps an absolute (or `javascript:`) URL verbatim,
so a container that answered with one could run script in RomM's origin
instead of its own. The three sites now share one resolver that drops a room
URL leaving the configured host, the stage refuses a source that is not
http(s), and the frame is sandboxed without allow-top-navigation so a
container page cannot steer the tab it sits in.
Also drop the shared secret from the config entry a resolution warning
prints, which named the misconfigured container by dumping it whole.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Session ownership and lifecycle, mostly around who a teardown belongs to:
- file the exit state, save states and state frames under the session's
owner rather than the caller, so an admin driving someone else's session
no longer collects their saves
- beat the heartbeat from the admin desktop view, which the stale sweep was
tearing down three minutes in
- take the claim through release_own_session when a launch aborts, instead
of deleting a key another player may already hold
- require the same claim to stamp a launch, so a late activate cannot revive
a drain marker with a six hour TTL
- pull the in-game save archive on every teardown path, not just the two
that remembered to
- skip draining keys in the admin force-release sweep
Plus: pool members must share a protocol, since the head's capabilities are
what the frontend renders; a claim clears terminations across the whole pool;
multiplayer is only recorded where the broker can actually seat a joiner; and
an unserializable config no longer caches forever on a repr() that repeats.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- The five new modules each defined `log = logging.getLogger("romm")`, which is
what `logger.logger` already exports; they import it now.
- `ACK_TIMEOUT` had two homes. It is a protocol fact, so `protocol.py` owns it
and the endpoint imports it from there; the unused
`BROKER_LOAD_STATE_TIMEOUT` copy goes.
- Module and function docstrings trimmed to what the code cannot say: the
change history and the justifications belong in the commit messages they came
from.
- `asset_store` takes the union `write_file` accepts rather than `Any`.
- Four hand-rolled `setInterval` pairs (presence beat, session poll, exit
chord, live sessions, activity tick) become `useIntervalFn`, which also
cleared a real gap: the presence composable's timer had no scope teardown.
- The launch pushes are matched on the container the claim's 202 named, not on
the platform: a pool serves one platform from more than one container, so a
second tab could otherwise act on the first's launch.
- Test helpers typed: the push capture and the resume-claim tuple carry real
types, and an unused `_claim_ready` helper goes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`POST /streaming/sessions` blocked for up to STREAMING_LAUNCH_TIMEOUT (10
minutes) while a broker unpacked a pkg or archive, and four mechanisms existed
to keep that survivable: a 3s status poll the client ran alongside it purely
for progress, `launch_timeout` shipped through /config so the client could size
its own axios ceiling, and a cancel-then-undo branch that re-released a session
the player had already abandoned, because a blocking POST cannot be cancelled.
The claim now answers 202 as soon as the container is reserved and everything
that can fail synchronously has (404, 409, 428 are all still the claim's own
status). The launch runs detached and pushes to the user room the
force-release notice already used:
- `streaming:launch-ready` carries the room URL and the resume outcome
- `streaming:launch-failed` carries the reason; the claim is already freed
- `streaming:launch-phase` carries the broker's extraction phase
The backend polls the broker for that phase itself, once, however many tabs are
watching, and only pushes changes. `GET /sessions/{platform}/status` stays as
the fallback for a tab that missed a push.
That retires the client's launch poll, the `launch_timeout` plumbing and the
cancel-then-undo branch. Leaving during a launch is now just a release, and the
launch-ready handler hands the container back if the player has already gone.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Every streaming route returned a bare `JSONResponse`, so none of their shapes
reached the OpenAPI schema and `services/api/streaming.ts` hand-maintained a
parallel copy of all eleven of them. A response-shape change was a silent
frontend break with nothing to catch it.
`endpoints/responses/streaming.py` declares the shapes and the routes return
them, so they generate like every other endpoint. The 428 a claim raises when a
container still holds an undecided memory card is declared too, through
`responses=`, rather than staying an undocumented `detail` dict.
The frontend types are regenerated and the hand-written interfaces become
aliases onto them. The typecheck immediately found two places they had already
drifted: the hand-written `PlatformCapabilities` was missing `has_memory_card`,
and `LiveSessionCard` passed a possibly-undefined host username where a
nullable string was expected. The termination notice had drifted on the backend
side too: it records `ended_at`, `rom_id` and `rom_name`, which the first draft
of the schema did not carry.
Releasing a session now hands its teardown to FastAPI's `BackgroundTasks`
rather than attaching it to a hand-built response, which is what lets the route
return a model.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`endpoints/streaming.py` held a general-purpose Redis session store and an HTTP
client alongside its routes, so both were reachable only through the ASGI test
client and neither could serve a second caller. They now sit in
`handler/streaming/` next to the container and protocol modules, matching how
`handler/netplay_handler.py` already owns its Redis room state.
- `session_store.py`: the keys, TTLs, compare-and-set helpers, drain markers,
staleness rule and termination notices. Its names are public now, because the
module boundary is the privacy boundary.
- `broker.py`: the urllib transport, its bounded reads and byte caps, and the
translation of a transport failure into the 502/503 the frontend parses.
The endpoint module drops from 5157 lines to 3616 and keeps the routes, the
claim and teardown flows, and the asset sync.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`endpoints/states.py` wrote the same write-scan-upsert sequence twice for
screenshots and once for states, and the streaming sync had written its own
third copy of each. The sequence now lives in `handler/asset_store.py`, which
both callers use.
What differs between them stays with the caller: the upload route still owns
its filename validation and last-played bump, and the streaming sync still owns
its byte-identical dedup and its retention limit. `store_state_file` takes a
`fields` map for columns only one caller owns, so the upload path can never
clear the disc the streaming path recorded.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Two shapes of streaming broker were branched on at 19 call sites, and every
consumer re-derived a container's host, key, emulator, capabilities and card
sync from the raw YAML on each call. `_containers_for_platform` re-ran host
parsing and the operator's misconfiguration warnings on every request, and
`_container_label` re-read config.yml once per listed row.
`handler/streaming/`:
- `protocol.py` gives each broker shape a class owning its route prefixes,
timeouts, response dialect, stream-URL assembly and capability flags. A call
site now asks `protocol.supports_disc_swap` or `protocol.save_state_accepted`
instead of re-testing `protocol: webstation`. Instances are interned per
subfolder so identical configs share one object.
- `capabilities.py` holds the per-platform and per-emulator slot tables and the
state transfer limits, keyed purely by platform and emulator.
- `config.py` turns the raw list into frozen `ResolvedContainer` records with
every question already answered, memoized until the config changes, so the
warnings fire once per config rather than once per lookup. A container RomM
cannot dial still resolves, with an empty key: unclaimable, but visible in
the admin fleet view where the operator can see why.
`endpoints/streaming.py` drops ~700 lines and takes records rather than dicts
throughout; `container.emulator` and `container.protocol.session_route(...)`
replace the derivations that used to run per call.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Backend:
- One session-scan iterator (`_iter_session_keys` / `_iter_live_sessions`)
replaces three copies of the Redis scan-and-decode loop, and
`_get_live_session` replaces five independent "a drain marker is nobody's
session" checks.
- `_abort_claim` replaces seven inlined claim-abort cleanups, so a new failure
branch can no longer wedge a container and orphan a blank card.
- `_quiesce_container` and `_collect_exit_state` replace the stop-evacuate-wipe
and guarded state-pull blocks written out in all three teardown paths. The
`_record_termination` calls stay at the call sites: the three order it
differently and each has its own reason.
- `_hold_reservation` / `_drop_reservation` collapse the two
release-after-state-pull helpers into one, and absorb the third copy of that
branch inlined in the released-session teardown.
- `_load_state_broker`'s two protocol branches were byte-identical, so it now
takes its route from `_transfer_route`; `_raise_broker_http_error` and
`_raise_broker_unreachable` replace the error translation copied into
`_call_broker` and `_webstation_activate`.
- `_container_labels` builds the label map once per request rather than
re-reading and re-parsing config.yml for every listed row.
- The joinable listing fetches each ROM once, through `get_rom_simple` rather
than the `@with_details` query, for five columns.
- `store_memory_card_version` hands the hash it computed in memory to the scan,
which was reading the archive back off disk to recompute it.
- `_prune_state_history` takes the history its caller already fetched.
- `playlist_files` in utils/m3u.py is now the one home for "which files are
discs", shared by the download endpoint, the m3u generator and the swapper.
Frontend:
- `useActivityPresence` replaces the presence block copied verbatim from
EmulatorJS.vue into Stream.vue.
- `MemoryCardNameDialog` replaces three copies of the same name-entry dialog.
- The two private axios error extractors give way to the `errorMessage` util,
three hand-rolled spinners to `RSpinner`, six manual listener pairs to
`useEventListener`, and five copy-on-write Set/Map trackers to `reactive`.
- `keepaliveHeaders` moves next to the interceptor that owns the CSRF header.
- The exit chord polls at 10Hz instead of every frame, the stage measures its
offset once instead of per mousemove, `postToStream` reuses the frame list
the attach pass walked, and the admin/home polls skip a hidden tab.
- `containerLabelForPlatform` on the store replaces the two `streamLabel`
definitions that answered differently, and the stream/join action labels move
onto useGameActions so the button and the menu cannot word them differently.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Conflicts and how they were resolved:
- `useGameActions`: master renamed `useCanPlay`'s `canPlay` to `canPlayLocal`
and kept a local `canPlayStream`, while this branch moved `canPlayStream`
into `useCanPlay` and folded it into `canPlay`. Kept this branch's shape and
took master's `useScanTrigger()` call.
- `Player/Stream.vue`: kept this branch's force-release and session-poll block,
and re-placed master's `useUnloadGuard(sessionActive)` next to the
`sessionActive` watch.
- `locales/*/play.json`: kept both sides' keys, re-sorted.
- `__generated__/index.ts`: kept both sides' model exports, re-sorted.
- `test_config_loader.py`: kept both sides' tests.
Master took 0114 through 0118 while this branch was open, so its three
migrations are renumbered 0119-0121 and rechained after
`0118_rom_category_cheat_pg`, leaving alembic with a single head.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
DEFAULT_EXCLUDED_DIRS only ever seeded EXCLUDED_PLATFORMS, but its name
implied it was the general directory list, which is how the media folders
came to be added to it in the first place. Rename it and its superset to
DEFAULT_EXCLUDED_PLATFORM_DIRS and DEFAULT_EXCLUDED_MULTI_FILE_DIRS, and
spell out what a multi-file ROM is.
DEFAULT_EXCLUDED_FILES and DEFAULT_EXCLUDED_EXTENSIONS keep their generic
names: each still feeds both a single-file and a multi-file-parts exclusion.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Fold the exporter's folder map and the importer's ESDE_MEDIA_MAP into a
single GAMELIST_MEDIA_DIRS, so writing, reading and skipping a media type
is one edit. This also picks up thumbnails/, which the scan exclusions were
missing, and drops the hand-appended "images" literal.
Serve the multi-file defaults pre-unioned as DEFAULT_EXCLUDED_MULTI_DIRS so
neither UI has to re-join two lists; v1 was still mapping EXCLUDED_MULTI_FILES
to DEFAULT_EXCLUDED_DIRS and rendering the media dirs as deletable.
Collapse the per-tag asset loop and the bespoke <mix> block into one table
keyed by tag, and skip fnmatch for the exclusion patterns that hold no glob
characters, now that the multi-file list is more than twice as long.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`scan_platforms` ends in four places, and three of them had to remember to
flush the counters a coalesced increment held back. The fourth, the early
return on a folder structure it cannot read, did not, and was correct only
because it sits above the first report. `finish` pairs the flush with the
emit so every exit gets both, including that one.
The failure path's guard around the flush goes with it. It was protecting
against an emit that fails, one line above an emit that would fail the same
way and is not protected, and `update_job_meta` already swallows its own
errors, so it bought nothing.
Also: `refetchCurrentRom` wrote `currentRom` twice, once directly and again
through `syncCachedRom`, which owns that write and applies the same identity
guard. `useRomScanRefresh` kept an `alive` check that `useSocketEvent`'s
unsubscribe already covers; its test was passing on the check rather than the
unsubscribe, so the socket mock now actually unsubscribes. DeleteManualDialog
was the tenth surface still spelling out the refetch by hand, and seven
components kept a rom store binding nothing reads any more.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Two gaps the coalesced reporting left open.
A scan that fails between a held-back increment and its end never
published the counters that increment held, so the task meta and the
progress view kept a stale snapshot of a scan that had gone further. The
failure path now flushes before it says the scan failed, and a flush
that cannot be delivered is logged rather than raised in place of the
error the scan is reporting.
`_published_at` also started at `0.0`, which reads as a report that has
already happened. A monotonic clock counting from boot can sit under the
interval, and the first increment would be coalesced away against a scan
that had never reported at all. It starts at `None` instead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Both CI failures came from one import cycle. RQ could no longer resolve
`endpoints.sockets.scan.scan_platforms`, and the e2e seed script failed the
same way, because `sigil` imports the platform slug enum, importing anything
under `handler.metadata` runs its `__init__`, that reaches `gamelist_handler`
which imports `handler.filesystem`, and `roms_handler` there imports `sigil`
back while it is still half-initialised.
The cycle predates this branch. It stayed hidden because `scan.py` reached
the enum through `utils.switch`, imported late enough that
`handler.filesystem` was already loaded; naming the adapter directly moved
that import to the top of the module and the ordering luck ran out.
So the enum moves to `utils/platform_slugs.py`, which imports nothing but
`enum`. Naming a platform no longer drags in httpx, redis and the titledb
task, and the 29 call sites point at the module that owns it rather than
picking it up from a 1000-line metadata handler that happens to re-export
it. `import adapters.services.sigil` now also works on its own, which it
did not before.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feat(streaming): forward the rom and interface language to the broker
The webstation activate payload already carries the platform, which is
how RetroArch picks its core; the language travels the same way. Two
values, because they answer different questions. `rom.language` is the
game's own, reduced from rom.languages, which stores names ("French")
from filename parsing and shortcodes ("fr") from metadata providers.
`gui_language` is the player's, from their UI locale, and sits beside
`rom` rather than inside it: it describes the player, so it is sent for
a launch with no rom at all.
A launcher whose games ship several languages in one folder needs both.
ScummVM detects one target per language and the target is what boots, so
without a language a multilingual game starts in whichever variant sorts
first. RomM rarely knows a game's own language and a multilingual folder
is exactly where it usually does not, which is what makes the interface
locale worth sending as the broker's fallback.
A locale keeps its region as a subtag ("pt_BR" becomes "pt-br"): that is
the whole difference between Brazilian and European Portuguese to an
emulator shipping both, and a broker that makes nothing of the region
drops it. Values RomM cannot reduce are omitted so a broker falls back
to its own default rather than failing the launch.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feat(streaming): add ScummVM to the platform capabilities table
Without an entry the frontend offers no save controls at all for a
ScummVM session. ScummVM's saves are its states, so the broker's single
working slot is both what a save-state writes and what a resume loads,
and there is no memory card. Its own slot 0 autosave rides the save
archive rather than the state routes, which is why this mirrors the
RetroArch shape: no slot grid, one autosave slot.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* style(streaming): satisfy black on the new language tests
Trunk's black wants the signature on one line; it fit all along.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Three problems the review pass turned up, all in the title id path.
A HASHES rescan re-reads every byte but `_should_extract_title_ids` only
exempted COMPLETE, so replacing a file in place left the previous binary's
title id and save target beside the new hashes. That row is
self-inconsistent, and the stale save target points saves at the wrong
game's folder. A scan that re-reads the bytes now re-reads the id too.
`refresh_rom_files` extracted title ids and then dropped `parsed.identity`
on the floor. Since only Switch populates `content_type`, the parse of every
changed file on PSP, PS2, PSX, Wii and the rest had no observable effect at
all, and a rom with no stored id never gained one from a quick scan or an
upload. The identity it reads is now persisted, guarded so a parse that read
nothing leaves the stored triple alone.
The Tinfoil feed keyed its titledb index on `str(index_entry.get("nsuId"))`
and then tested that for `None`, which `str()` had already turned into the
string "None". Entries without an nsuId were stored under that literal key,
each one overwriting the last, instead of being skipped.
Also revert the heartbeat to `cm.get_config()`. Reading the last-parsed
config avoided a YAML re-parse, but the same request already triggers
several through `get_platforms()`, so it bought nothing and left the
endpoint reporting a stale flag after a config edit.
`tests/endpoints/feeds.py` is renamed to `test_feeds.py`. It never matched
pytest's `test_*.py`, so all 15 feed tests, `test_tinfoil_feed` among them,
have been dormant since they were written.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
DEFAULT_EXCLUDED_DIRS feeds both EXCLUDED_PLATFORMS and
EXCLUDED_MULTI_FILES, so listing the gamelist media folders there also
hid any platform directory that happened to share a name. The media
folders now live in DEFAULT_EXCLUDED_MEDIA_DIRS and only join the
multi-file exclusions.
The config response exposes the new list so the settings UI keeps
treating those entries as read-only defaults instead of offering a
remove action that the next config load would undo.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Callers that arrived while a probe was still running all read an empty cache
and started a probe of their own, so the cache only bounded outbound traffic
once a result had landed. Serialise the miss path on a per-source lock.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Trim the constant comments down to the non-obvious facts, and relax the two
exact-TTL assertions that would flake if a second elapsed mid-test.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Two review findings on the heartbeat rate limit.
The client IP comes from a forwarded header the caller controls, since the
container runs uvicorn with --forwarded-allow-ips="*", so rotating that header
defeated the per-IP cap outright; a distributed flood has no single IP to key
on either. Caching each source's result for the length of the window bounds
outbound provider probes at one per source, whatever the inbound rate. The
per-IP cap stays as the cheap first gate.
The window's INCR and EXPIRE were separate round trips, so a call interrupted
between them left a counter with no TTL that later calls never repaired,
locking that key out for good. Both now run in one transaction, with EXPIRE NX
so a live window is never extended and a counter can never lack a TTL.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Every counter change wrote the rq job meta (a synchronous redis call on
the event loop) and published a socket event. That was two round trips
per rom, and since quick scans stopped skipping the roms they already
know, every rom in the library pays them: 40k round trips on a 20k
library where 200 used to do, all serialized behind the stats lock.
Counters stay exact on every increment; only the reporting is coalesced,
to one report per 250ms. Totals and platform counts still report as they
happen, being rare, and a scan flushes anything held back before it says
it is done.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The platform sync clears `missing_from_fs` before the batch loop runs, so
a rom being scanned can no longer tell that it was missing, and the fold
left the skip path (which could tell) unreachable for a quick scan. A rom
whose file came back byte for byte therefore emitted nothing and kept its
stale badge. Collect the restored roms from the snapshot the loop already
takes, for the ones it visits as well as the ones it skips.
Cleanups on the same paths:
- hoist the quick reconcile above the metadata prelude it never reads,
which was a config file parse and a tag parse per rom
- drop the unreachable quick clause from `_should_hash_incrementally`:
`refresh_rom_files` owns that policy
- drop `RomFilesRefresh.files`, which nothing reads
- take the refresh lock without a guard that had nothing to protect
- fold the single-caller upload destination helpers into one
- give "a quick scan needs no metadata source" one home, and read the
refresh title from the key rom.json already owns
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A quick scan skipped every rom it already knew, so a file dropped into a
game folder went unnoticed until a complete or hashes rescan. This branch
answered that with a seventh scan type; letting quick reconcile the files
of the roms it knows says the same thing with less to learn.
Quick now visits every rom. New ones take the metadata pipeline as
before; existing ones only have their files reconciled against disk,
keeping the stored hashes of files whose size and mtime are unchanged. No
provider is contacted for an existing rom, so quick no longer needs a
metadata source picked, in the scan view, the platform dialog and the per
rom refresh alike.
The watcher schedules a quick scan again, and the per rom "Refresh files"
action sends quick scoped to that rom.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The refresh lists a rom folder and then deletes every row the listing
missed, so two uploads completing at once could let the slower listing
drop the file the faster one had just registered. Hold a per rom lock
across the listing and the sync.
Three smaller fixes on the same paths:
- honour SKIP_TITLE_ID_EXTRACTION, which the refresh read the hash flag
but not this one for
- emit a rom that just stopped being missing even when its files did not
change, so an open gallery drops the stale badge
- unlink the empty destination claim when the rename meant to replace it
fails, rather than leave a zero byte file for the next scan to ingest
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Backend:
- Drop the HashPolicy enum: FULL had no caller and INCREMENTAL was the
default, so refresh_rom_files uses the existing_files knob directly.
- Narrow RomFilesRefresh to the counters callers read.
- Build ParsedRomFiles once so the incremental return stops dropping the
title id fields.
- Give the assembling suffix one home in config, read by both the
assembler and the scanner's excluded extensions.
- Fold the duplicated destination collision check into one helper, and
branch /start on the upload target itself.
- Load the lighter rom for the refresh emit and the upload endpoints,
keep the flat file stat off the event loop, and reuse the directory
listing for the RA hash lookup.
Frontend:
- Route the platform scan dialog and the scan view through
useScanTrigger, so a scan started while one runs is refused rather
than emitted and rejected by the backend.
- Rename the socket payload type to ScanRequest, away from the
useScanProviders type of the same name.
- Drop the dead uploading prop and folder icon, reuse singleRomTitle,
and resolve each file's relative path once per listing.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>