Commit Graph

2097 Commits

Author SHA1 Message Date
Bee
f50eacfcbd feat: add browser PICO-8 player
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>
2026-09-08 17:59:52 -04:00
Georges-Antoine Assi
568aa818de refactor: tighten the library structure naming and docstrings
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>
2026-09-08 08:53:55 -04:00
Georges-Antoine Assi
a7ecfd96a9 feat!: make filesystem.structure the single library layout
`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>
2026-09-08 08:39:21 -04:00
Georges-Antoine Assi
dd7f46b52c fix: make metadata exports and matching follow the library structure
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>
2026-09-08 07:31:05 -04:00
Georges-Antoine Assi
6b01e9943e refactor: trim review-pass comments and cover LocationChip
Cut the comments that explain rather than note: the migration's four-paragraph
docstring, the upload-path and digest-SQL docstrings, and the mark-missing note
in the scan loop. Drop an em-dash from LocationChip's header per CLAUDE.md.

Reword 0126's downgrade error so it no longer embeds a SELECT, which bandit
reads as string-built SQL, and mark the dialect-selected backfill nosec B608 the
way the other migrations do.

Add the LocationChip test its HashChip sibling already had, covering the copy
going through useClipboard (the composable is what applies the secure-context
guard).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 20:17:28 -04:00
Georges-Antoine Assi
f105622513 fix: address code review on the library structure unique index and relocation
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>
2026-09-07 19:14:58 -04:00
Georges-Antoine Assi
9dcaf89890 fix: address PR review feedback on library structure and relocation
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>
2026-09-07 17:01:33 -04:00
Georges-Antoine Assi
4219f56f10 Merge branch 'master' into claude/kind-goodall-0b77y7
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>
2026-09-07 16:24:59 -04:00
Georges-Antoine Assi
7b2baaa545 refactor(config): rename EJS_AUTO_SAVE_SYNC to EJS_ENABLE_AUTO_SAVE_SYNC
The config.yml key (emulatorjs.auto_save_sync) is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 11:08:02 -04:00
Georges-Antoine Assi
1443f66cf5 Merge branch 'master' into feat/auto-save-sync 2026-09-07 10:24:48 -04:00
Georges-Antoine Assi
b930a37448 Merge remote-tracking branch 'origin/master' into fix/ss-quota-breaker-recovery
# Conflicts:
#	backend/endpoints/roms/__init__.py
2026-09-06 22:54:48 -04:00
Georges-Antoine Assi
345dddd98b revert(search): keep the compact gather
The paired (name, coroutine) form cost 20 lines of vertical space to buy a
correct provider name in one error log, which zip's strict=True already guards
the length of. The comment and docstring trims from the same pass stay.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 21:44:10 -04:00
Georges-Antoine Assi
424b9cb75d refactor(search): pair each provider lookup with its name
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>
2026-09-06 21:40:26 -04:00
Georges-Antoine Assi
ebfc8c7966 fix(search): stop one provider's failure from emptying the dialog
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>
2026-09-06 21:35:32 -04:00
Georges-Antoine Assi
6161f8057d refactor(screenscraper): report a short-circuited lookup per rom
A tripped breaker answers in ScreenScraper's place, so the empty match it
produces is not a miss and must not clear the rom's stored ss_id. The scan
learned that by sampling the module-wide is_breaker_tripped() at three points,
which reads another rom's trip as this rom's evidence.

SSHandler now raises ScreenScraperExhaustedError instead of swallowing the
breaker's error, carrying the match it would have returned so the name the
filename lookup derives locally (Switch title database, MAME, PS2 OPL) still
reaches the scan. fetch_ss_rom catches it the way it already catches
ScreenScraperRateLimitError, and drops ScreenScraper from attempted_sources
from a plain local, so the signal is exactly this rom's own lookups.

Also folds in a cleanup pass over the branch: the dead default_factory arm in
_ScanState.reset(), one home for the ssuserInfos.php path, asyncio.wait_for
around the quota probe so it cannot block behind a media download holding the
concurrency slot, and shared fixtures for the ScreenScraper tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 21:35:25 -04:00
Georges-Antoine Assi
17bd4207a0 Merge remote-tracking branch 'origin/master' into claude/igdb-keywords-themes-perspectives 2026-09-06 18:48:46 -04:00
Georges-Antoine Assi
0b1f6f7c80 feat(recommendations): index a scanned rom before the nightly build
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>
2026-09-06 18:38:32 -04:00
Georges-Antoine Assi
d84fa1101e fix(recommendations): guard the vote count and the similar-games auth
The rating-count column cast whatever `total_rating_count` held straight to
a number, without the digit guard every other numeric branch in the
migration carries. The metadata blobs are writable verbatim through the raw
metadata form, so a library holding a non-numeric value could not migrate at
all: PostgreSQL aborts the ALTER TABLE on `invalid input syntax for type
numeric`. The MariaDB branch also reached for JSON_VALUE, which MySQL only
gained in 8.0.21, below the 8.0 the docs advertise.

`/roms/{id}/similar` was gated behind DISABLE_DOWNLOAD_ENDPOINT_AUTH while
resolving permissions unconditionally, so with that flag set an anonymous
request hit `UnauthenticatedUser.role` and 500'd. It is not a download
endpoint; it now requires ROMS_READ, as /api/recommendations does.

The details page also fetched similar games with the feature switched off,
and OverviewTab took a `webp` prop for state it already reads from
useWebpSupport.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 16:40:12 -04:00
Georges-Antoine Assi
e78a4aa1b9 chore(recommendations): cut the comments back to what the code cannot say
The engine carried its tuning history in its comments: measurement logs for
PIVOT_B, the weight a facet held before the company split, the shape of the
cold-start feed before the Bayesian average. None of that describes what the
code does now, and it belongs in the history rather than beside the values.

Also folds serving's ROM loader into feed's, which differed only by the
visibility filter applied afterwards.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 14:35:15 -04:00
f0rthelulz
e1e4663521 feat(player): optional periodic upload of changed save files
Behind a new config flag, emulatorjs.auto_save_sync (default false), the
EmulatorJS player uploads the in-game save (.srm) to the server on
EmulatorJS' own "System Save interval" tick, without Save & Quit.

EmulatorJS already runs that timer (default 300 s) and its
gameManager.saveSaveFiles() fires a "saveSaveFiles" event carrying the
SRAM bytes, but nothing listens to it, so today an in-game save reaches
the server only from Save & Quit or the Export Save File button (#4201).
This subscribes to that event from Player.vue and uploads through the
existing saveSave() when the SRAM hash is unchanged since the previous
tick (a save the core is still writing is never uploaded — the corruption
the earlier automatic upload was removed for, #2349) and differs from the
last upload (an idle session uploads nothing). The tracker is seeded from
the SRAM the core holds after the server save is applied, so a launch
never uploads the server's own file back, and the subscription is turned
off before Save & Quit, Quit and unmount.

The bytes EmulatorJS hands out are views onto the emulator heap, a
SharedArrayBuffer on threaded cores; they are copied into a plain
ArrayBuffer before hashing or uploading.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 11:37:33 -05:00
Georges-Antoine Assi
5bce1215ce refactor(recommendations): deepen four fixes to their root cause
Merge 0123/0124/0125 into one migration. Each added STORED generated
columns to `roms`, and 0125 already dropped and re-added several, so
upgrading rewrote the widest table three times and restated the
`roms_metadata` view three times. One ALTER TABLE now carries the Steam
rebuild, the three IGDB tag columns and the rating count, and the view is
recreated once. Verified upgrade/downgrade/upgrade on MariaDB and Postgres.

Score each unordered pair once. Candidate generation is symmetric, so
every pair had its dot product computed twice. The sweep now runs in
ascending id order and scores only from the lower id, which also makes a
ROM's edges final the moment the sweep passes it, so the incremental
flush survives. Only the target's quality bonus differs by direction, so
one content score is blended twice. The per-ROM candidate ceiling moves
into `candidate_ids`, taking the rarest posting lists first, where it
bounds work instead of being applied after the cost was already paid.

Read identity off one list. `sibling_roms` decides "same title" from
seven provider ids; the suppression here used two, so a pair matched only
by MobyGames was a sibling everywhere else in RomM and a recommendation
for itself here. `IDENTITY_ID_FIELDS` on the model is now the one home,
consumed unscoped by the builder since a reissue on other hardware is no
more a suggestion than a second copy on the same platform.

Make the facet vocabulary a StrEnum. It was spelled out in five places,
two of them already stale, and `facet: str` kept it out of the API
contract, so an unmapped facet silently rendered a raw value. It reaches
OpenAPI as a closed union and the frontend maps are keyed by it, so
adding a facet now fails the typecheck until the UI handles it.

Give each surface one serving entry point. `similar_roms` and
`recommended_roms` own the over-fetch, hydration, visibility filter,
series cap and cache that the two endpoints and the inspection tool each
re-implemented with three different over-fetch constants; the cache moves
in with them so no caller can rank a feed without populating it.
Endpoints now do ORM-to-schema only.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 12:12:52 -04:00
Georges-Antoine Assi
1ff9944224 refactor(recommendations): reuse, simplification and efficiency pass
Backend, wasted work:
- `_score_one` computed `content_similarity` twice per candidate on the
  trim path and built `shared_reasons` for every candidate clearing the
  score floor, discarding almost all of them. Compute content once and
  build reasons only for the edges actually stored.
- `get_feature_rows` outer-joined `RomMetadata`, a view over the wide
  `roms` table, defeating the point of reading the narrow facet mirror.
  Read the generated columns off the `Rom` join already present.
- Feed cache invalidation ran a keyspace SCAN on every `rom_user` write.
  Put graph and per-user version counters in the key so it is one INCR,
  matching `invalidate_filter_values_cache`.

Backend, reuse:
- Route the five name comprehensions beside `_expanded_names` through it.
- `_recency_factor` reimplemented `to_utc`.
- `replace_similarity_edges` hand-rolled `itertools.batched`.
- Derive `TASTE_FACETS` from `FACET_WEIGHTS` instead of restating its keys.

Backend, dead code:
- `ScoredNeighbour`, `BuildStats.to_dict`, `delete_all_similarity_edges`,
  the unread `difficulty`/`completion`/`backlogged` affinity fields,
  `FACET_ORDER` and `RomInfo.rom_id`, and a no-op `column_type` ternary.

Frontend:
- Extract `RecommendationReason` from the two byte-identical copies in
  `Home.vue` and `SimilarGamesGrid.vue`, dropping the repeated
  `primaryReason` calls and their non-null assertions.
- Cap the caption with `--r-card-art-w` rather than a `158px` literal that
  does not track the per-breakpoint card width.
- Key the similar-games fetch on the ROM id: `watchEffect` refetched on
  every optimistic mutation of `currentRom`.
- One home for the similar-games limit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 11:44:00 -04:00
Georges-Antoine Assi
cca9f500f1 fix(auth): mask hidden platforms from the export endpoints
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>
2026-09-06 11:40:00 -04:00
Georges-Antoine Assi
11f6b89dd0 fix(auth): gate the export endpoints on platforms.write
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>
2026-09-06 11:28:05 -04:00
Sam Dornan
8494744ee7 Merge branch 'master' into claude/igdb-keywords-themes-perspectives
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
2026-09-06 00:24:13 +00:00
Georges-Antoine Assi
f78348da0f refactor(streaming): move the endpoint's domain layer into handler/streaming
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>
2026-09-05 18:47:18 -04:00
Georges-Antoine Assi
7443b690be fix(streaming): keep the container's answers inside its own origin
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>
2026-09-05 14:53:43 -04:00
Georges-Antoine Assi
e85fce8e80 fix(streaming): close the holes a review pass found
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>
2026-09-05 14:33:44 -04:00
Georges-Antoine Assi
eccafd13d1 refactor(streaming): polish pass over the new modules
- 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>
2026-09-05 13:13:02 -04:00
Georges-Antoine Assi
74c77d0bb2 feat(streaming): answer the claim before the launch, and push what happens
`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>
2026-09-05 12:04:58 -04:00
Georges-Antoine Assi
1e716b381d feat(streaming): give the streaming routes typed responses
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>
2026-09-05 11:15:36 -04:00
Georges-Antoine Assi
f6b842fe62 refactor(streaming): move the session store and broker transport into handlers
`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>
2026-09-05 10:55:45 -04:00
Georges-Antoine Assi
1da0212b7f refactor(assets): one home for filing a state or a screenshot
`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>
2026-09-05 10:24:56 -04:00
Georges-Antoine Assi
1246d18fe3 refactor(streaming): resolve containers once, behind a broker protocol
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>
2026-09-05 10:13:46 -04:00
Georges-Antoine Assi
3cacb59ee4 refactor(streaming): give the duplicated rules one home each
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>
2026-09-05 08:54:32 -04:00
Georges-Antoine Assi
15233afcb1 Merge branch 'master' into feat/streaming-webstation
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>
2026-09-05 07:49:12 -04:00
Georges-Antoine Assi
e57c5e471c Merge pull request #4353 from Spinnich/fix/complete-rescan-clears-attempted-ids
fix(scan): let a complete rescan clear the ids it rematched
2026-09-04 21:59:48 -04:00
Georges-Antoine Assi
6dd3353855 refactor(metadata): give the unreachable-provider error one home
The same 503 was built inline at seven sites across the metadata handlers, and
the previous commits added two more copies of it as per-handler `_unavailable`
helpers. `base_handler.unavailable(provider)` now builds it for all of them.

Also renames the search endpoint's cover filter to say what it does and types
the scan test's lookup factory.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 21:16:07 -04:00
Georges-Antoine Assi
3b2a9e3043 refactor(scan): share one failure path across the provider lookups
Every gathered provider already resolved through a single loop that logs the
failure, drops the source from the attempted set and falls back to an empty
match. SteamGridDB, which searches on the names the other providers produce and
so cannot join that gather, hand-wrote the same three steps again, and the
search endpoint hand-wrote a third copy. Extract the loop body into
`resolve_fetch` and route SteamGridDB through it.

In the search endpoint the cover gathers now tolerate exceptions instead, so a
failed lookup costs a thumbnail rather than the whole result set. That also
covers Libretro, whose lookup had no guard at all and could fail the request.

On the test side, the platform, rom and `fs_rom` scaffolding was written out
three times across the two scan tests; it now lives in `tests/handler/scan_stubs.py`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 20:58:27 -04:00
Spinnich
24bc4c221b fix(scan): don't let a failed lookup clear the id it couldn't check
A complete rescan clears the id of every source it consulted that came back
empty. That reads an outage as a conclusive miss for the providers that report
a failure as an empty match, so a rescan run while one was down wiped the id it
would otherwise have confirmed, hand-set ones included.

Each of those now reports the failure and leaves the tolerance to the caller,
which is what the gather loop's discard already assumed:

- Pouët, CSDb and Demozoo stop swallowing the 503 their own `_request` raises,
  and Pouët's title search raises it rather than answering "no unique title".
- SteamGridDB and Flashpoint stop catching `Exception` around a whole lookup;
  HLTB stops catching it around its search.
- ScreenScraper answers empty for every remaining ROM once its daily-quota or
  credentials breaker trips, so the scan reads that state off the service and
  drops it from the sources the rescan may clear.

SteamGridDB resolves outside the gather and so needs the discard at its call
site. Search keeps degrading to no thumbnail, since its cover art sits on top
of matches the other providers already produced.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 20:49:51 +00:00
Georges-Antoine Assi
5837ac3df9 refactor(config): name the two default dir lists for what they exclude
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>
2026-09-04 16:42:43 -04:00
Georges-Antoine Assi
65b2a050c1 refactor(gamelist): give the ES-DE media folder names one home
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>
2026-09-04 16:19:55 -04:00
Georges-Antoine Assi
aff25e5013 Merge branch 'master' into claude/github-issue-4226-eab53e 2026-09-04 16:06:33 -04:00
Georges-Antoine Assi
5cc6a98c1b refactor(v2): name the rom refetch for what it touches
`refetchCurrentRom` no longer reads or writes `currentRom`: `syncCachedRom`
owns that write and applies the identity guard. The name promised a function
that acts on the open rom; it fetches the rom it is given and applies it
wherever it is cached, so `refetchRom` is what it does.

Also trims the two comments that had grown past what they explain.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 15:54:44 -04:00
Georges-Antoine Assi
ccc950f72e refactor(scan): let the terminal event own the progress flush
`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>
2026-09-04 15:42:20 -04:00
Georges-Antoine Assi
534033773e fix(scan): report a scan's progress on the paths that skipped it
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>
2026-09-04 15:27:55 -04:00
Georges-Antoine Assi
51e0f0fc2e Merge remote-tracking branch 'origin/master' into perf/scan-progress-coalesce
# Conflicts:
#	backend/endpoints/sockets/scan.py
2026-09-04 15:23:43 -04:00
Georges-Antoine Assi
eec574b49b fix(metadata): give UniversalPlatformSlug a leaf home
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>
2026-09-04 14:28:49 -04:00
jfrag
000c8dd0a9 feat(streaming): forward the game and interface language, and add ScummVM capabilities
* 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>
2026-09-04 12:55:43 -05:00
Georges-Antoine Assi
c4ff894741 fix(scan): keep a rom's title id consistent with the bytes just read
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>
2026-09-04 11:38:57 -04:00