Commit Graph

2188 Commits

Author SHA1 Message Date
Georges-Antoine Assi
08f294d0fa Merge pull request #3571 from rommapp/claude/kind-goodall-0b77y7
feat: Per-platform custom library structure with non-destructive identity
2026-09-08 16:46:44 -04:00
Georges-Antoine Assi
892657465f fix: stage the config fixture for e2e and address review findings
The e2e job copied only the fixture library, not the config.yml declaring its
platform-folder-first layout, so the seeder scanned an empty library.

Reject `.` and `..` template sections: no directory listing yields either, so a
template carrying one discovered nothing and marked the platform's roms missing.

Drop the cached `full_path` when either half is set. A scan reads it and then
renames the file in place, which left the cached pair stale.

Point `build_physical_fs_name` at the index 0126 actually creates.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 09:11:16 -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
30212cdf66 Merge pull request #4393 from rommapp/fix/quiet-rq-scheduler-heartbeat-logs
Quiet RQ's per-tick scheduler heartbeat log line
2026-09-07 21:57:00 -04:00
Georges-Antoine Assi
b62dbb5d9c Trim the noise-filter comments and cover the worker wiring
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 21:43:11 -04:00
Georges-Antoine Assi
ade76effbb Quiet RQ's per-tick scheduler heartbeat log line
Each worker started with --with-scheduler forks a scheduler that logs
"Scheduler sending heartbeat to <queues>" on every 1s tick. With
LOGLEVEL=DEBUG that is two lines per second, which drowns out the rest of
the log.

Generalize the existing registry-cleanup filter to cover RQ's periodic
noise and install it on the rq.scheduler logger before the worker forks
the scheduler off.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 21:38:38 -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
a73667a5ca refactor: rename the parsed template type to StructureTemplate
`LibraryStructure` named two unrelated things: the A/B enum for which of
RomM's two folder layouts a library uses, and this branch's parsed
per-platform template. Both were imported into handler/filesystem.

The parsed template is now `StructureTemplate`, with `parse_library_structure`
and `parse_platform_structures` following it to `parse_structure_template` and
`parse_platform_templates`. `LibraryStructure` again refers only to the enum.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 17:50:08 -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
eef3e55d29 fix(gallery): join roms_metadata before the grouped dedup window
The genre/franchise/company/publisher/developer/collection/age-rating/
player-count filters read from `roms_metadata`, but the join was added at the
end of `filter_roms`, after the "Group ROMs" block had already derived its
dedup window from the query. The window therefore filtered on a table it never
joined: the database cross-joined `roms` against `roms_metadata` (a view over
`roms`), which SQLAlchemy reports as a cartesian product.

Besides the cost, the window then ranked every ROM in the library rather than
the matching ones, so a game whose matching version was not the group's primary
one disappeared from the gallery entirely.

Fixes #4389

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 16:22:18 -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
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
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
00bf206b46 chore(backend): cut a log nobody reads and a comment that ran long
The sigil import-time debug line never printed at the default INFO level,
and the binding's absence already reaches the UI through
SigilService.is_enabled() on /heartbeat.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 18:00:25 -04:00
Georges-Antoine Assi
714c99693b fix(recommendations): weight a co-occurrence by the evidence behind it
Co-play and co-collection were a bare cosine, which saturates at 1.0 the
moment two games are always seen together. On a single-user server, the
common case, that is every pair of games the owner has played: the signal
became a flat +0.15 on all of them rather than something that discriminates
between them, and a genuinely similar unplayed game needed a content score of
0.273 just to draw level. Tetris and Madden were neighbours.

The cosine is now damped by the number of sightings behind it, the way
`get_fallback_rom_ids` shrinks a rating toward the mean by its vote count. A
lone sighting keeps a quarter of its weight, which leaves it under
MIN_EDGE_SCORE on its own, while a pair a whole server agrees on is untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 17:04:32 -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
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
1393f4196e Merge remote-tracking branch 'origin/master' into claude/pr-4367-status-sql1q9
# Conflicts:
#	backend/tests/utils/test_gamelist_exporter.py
#	backend/tests/utils/test_pegasus_exporter.py
#	backend/utils/pegasus_exporter.py
2026-09-06 11:08:58 -04:00
Sam Dornan
ac2f468875 refactor(export): rename GAMELIST_MEDIA_DIRS to PLATFORM_MEDIA_DIRS
The map now serves the gamelist import, the gamelist export, and the
Pegasus export, so a name tied to one of them misleads.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Dye15Zspts7hBruKYsPuT
2026-09-06 12:26:56 +00:00
Sam Dornan
08c9d1862b fix(export): merge gamelist.xml and metadata.pegasus.txt instead of overwriting
Both exporters rebuilt their file from the database on every run, so a
scan with `scan.gamelist.export: true` threw away everything the frontend
or the user had written into it: favorites, play counts, per-game
emulator and core overrides, hashes, `<folder>` entries, ES-DE's
`<alternativeEmulator>` block, and Pegasus launch commands.

The exporters now read the existing file first and merge into it. For a
ROM RomM knows, the tags and keys RomM emits replace the old ones and
everything else is carried over. Entries with no matching ROM, folders,
scraper provider blocks and later Pegasus collections are written back
untouched. A file that cannot be parsed or decoded is left alone and the
export for that platform fails instead of replacing it.

Fixes #4158

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XjH6MYLVFVoY92JdBFgKXw
2026-09-06 01:17:38 +00: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
7546ebafda docs(streaming): move the migration guide to the docs site
The webstation migration guide belongs in rommapp/docs, where users reading
about emulator streaming will find it (rommapp/docs#128). The deprecation
warning and the protocol module now link to the published page.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-05 19:10:28 -04: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
Spinnich
0d7ce16d16 fix(screenscraper): let the daily-quota breaker recover
HTTP 431 means a ROM did not match and the daily cap on proposing unknown
ROMs for review is reached; scraping is unaffected, so it becomes a
not-found with one informational line per scan instead of a refusal that
takes the provider out.

HTTP 431 is really two answers at once and only one of them concerns the
scan. The scrape allowance (430) still trips a breaker, since every
remaining ROM would otherwise cost a round trip to be told the same thing,
but it now arms only after repeated refusals, ignores the ones already in
flight when a refusal was counted, and re-checks the free account endpoint
so it recovers without a scan to reset it. The account check can no longer
arm it at all.

A recoverable breaker can clear itself while a rom is still gathering its
other providers, so a complete rescan read it as having answered and wiped
the rom's id. It is now sampled where ScreenScraper is consulted.

The manual-match search gathers every provider without return_exceptions,
so it now swallows an exhausted ScreenScraper the way the scan lookups do.

Fixes #4123

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 15:08:18 +00: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
Georges-Antoine Assi
8b2931a56d fix(scan): don't let a Hasheous outage read as a conclusive miss
`_request` swallowed a non-404 HTTP error and a timeout into an empty dict,
which `lookup_rom` then reported as conclusive: Hasheous answered and knows
nothing about these hashes. A 500 or a timeout therefore de-verified a rom on
a rehash and cleared its id on a complete rescan.

Both paths now raise, so the conclusive flag already carried by `lookup_rom`
tells the two empty matches apart on its own.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 20:58:18 -04:00
Georges-Antoine Assi
4db67ff039 Merge pull request #4352 from Spinnich/fix/ra-skip-games-without-achievements
fix(retroachievements): don't match ROMs against games with no achievement set
2026-09-04 20:25:58 -04:00
Georges-Antoine Assi
09f0001aa1 Merge pull request #4345 from sdornan/feat/platform-folder-aliases
feat(scan): resolve Batocera, RetroBat and ES-DE folder names to platforms
2026-09-04 20:24:43 -04:00
Georges-Antoine Assi
996d12adea feat(metadata): add RPG Maker platform and resolve easyrpg folders
Batocera, RetroBat and ES-DE all ship an `easyrpg` folder for RPG Maker
2000/2003 games, but RomM had no platform for them, so the folder fell
through as an unmatched platform that matched no metadata.

Add UniversalPlatformSlug.RPG_MAKER and wire it to the two providers that
carry the platform: ScreenScraper (system 231, "EasyRPG") for metadata and
libretro (system "RPG Maker") for thumbnails. IGDB, MobyGames and TheGamesDB
have no RPG Maker platform, so they stay unmapped, the same way DOOM is
wired.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 19:09:21 -04:00
Georges-Antoine Assi
80185b225c refactor(scan): resolve platform folder names in both directions
Fold the folder name resolution into one home and make it case-insensitive
end to end.

Config folder names are lowercased as the config is parsed, so bindings,
versions and the built-in alias table are all matched the same way. A SNES/
folder now resolves, and a binding written GameCube: matches a gamecube/
folder.

Add resolve_fs_slug(), the inverse used to recover a renamed folder, which
replaces the two swapped dicts in scan_platform. Only slugs reached by
exactly one folder name are reversible, so recovery never guesses between
amiga500, amiga600 and amiga1200.

Validate system.platforms and system.versions through one helper that
rejects empty and non-string values, and treat a null block as empty rather
than exiting.

Restore the atari800 override in the example configs: its folder name is
itself a RomM slug, so it can never be an alias. A new test derives the
needed overrides from the alias table to keep the examples honest.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 17:32:07 -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
8cc1e8bd15 style(gamelist): trim the media map comments to the non-obvious why
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 16:29:56 -04:00