492 Commits

Author SHA1 Message Date
Matt Kaatman
d8d9fa7884 fix(igdb): let region_mode decide the localized title (#5785)
* fix(igdb): let region_mode decide the localized title

get_igdb_preferred_locale ignored scan.priority.region_mode, so a rom
tagged (Japan) always got IGDB's ja-JP localized title, even with
prefer_config and us first in scan.priority.region. Under prefer_config
the configured regions now come first and the rom's own tags are the
fallback, matching the ScreenScraper handler since #4413. The default
prefer_rom_tags ordering is unchanged.

Fixes #5784

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

* docs(igdb): fold the region_mode note into one docstring sentence

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

* pr-ready: code-review

Log a missing IGDB locale at debug: under prefer_config every ROM asks
for the first config locale, so a missing one is routine, not a warning.
Pin SCAN_REGION_MODE in the multi-region locale test instead of relying
on MagicMock's auto attribute.

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

* pr-ready: simplify

Drop the IGDB-locale filter on the ROM's region codes; the final
lookup loop already skips codes IGDB has no locale for.

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

* pr-ready: prose

Spell out the USA region in the prefer_config test docstring so it
does not read as the pronoun, untangle the fallback test docstring, and
finish the clipped Returns line.

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

* fix(metadata): share one region order across IGDB, ScreenScraper and LaunchBox

IGDB now tries every preferred locale in order, up to the first region
that uses the default title, instead of only the first. Under
prefer_config with [eu, jp], a (Japan) ROM whose game has no EU
localization gets the Japanese title again rather than the default.

preferred_region_codes in the filesystem base handler builds the region
order once. ScreenScraper, IGDB and LaunchBox all read it, so LaunchBox
artwork follows region_mode too, and uppercase config codes match the
ROM's tags for every provider.

European country codes map to IGDB's EU locale and ScreenScraper's ss
to the default title, so a (France) ROM no longer falls through to the
next configured region.

An unquoted no (Norway, Norwegian) in scan.priority.region or
scan.priority.language loads as false from YAML and crashed every IGDB
match. The config loader now turns it back into "no" and drops other
non-string entries with a warning.

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

* refactor(igdb): drop _string_codes and spell out the EU region codes

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-26 20:11:48 -05:00
MMagTech
ea8aac7d5d fix(ra): hash an arcade set by its archive, not the CHD beside it (#5747)
* fix(ra): hash an arcade set by its archive, not the CHD beside it

RetroAchievements identifies an arcade game by its set's name. A folder
holding a set and its disc was hashed by the CHD, which is named after the
disc (gdl-0018.chd beside azumanga.zip).

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

* pr-ready: code-review

Pass the arcade set's archive to RAHasher directly. RAHasher on Linux
does not expand a /* wildcard, so the arcade hash of <folder>/* is the
MD5 of an empty name. Prefer the archive named after the folder so a
larger BIOS or parent zip beside it does not win.

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

* pr-ready: plain-prose

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-23 11:13:09 -05:00
Georges-Antoine Assi
1ab3a3625a feat(auth): use the OIDC picture claim as the user's avatar (#5730)
* feat(auth): use the OIDC picture claim as the user's avatar

On each OIDC sign-in, a user with no avatar, or one synced from the
provider earlier, gets the picture claim stored as their avatar. An
uploaded avatar is never replaced. The download goes through the
SSRF-guarded client (the configured provider's origin may reach a LAN
address), is capped at 5 MB, must sniff as a supported image, and any
failure is logged without blocking the sign-in.

Closes #4297

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

* fix(auth): address review on the OIDC avatar sync

Addresses Greptile's review on #5730:
- ask the UserInfo endpoint when the ID token has no picture claim
- keep an avatar uploaded while the picture downloaded
- allow only the OIDC provider's origins to reach private addresses
- trim docstrings and narrow await_args in the callback test

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

* test(auth): type the OIDC avatar test helpers for mypy

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

* pr-ready: code-review

Bound the OIDC picture download with an overall deadline, trust the
OIDC CA bundle, catch hostname encoding errors so sign-in never 500s,
and set the synced avatar with a conditional update so a concurrent
upload wins.

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

* pr-ready: simplify

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

* pr-ready: review-polish

Type the pytest fixtures and helpers in the OIDC avatar tests.

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

* pr-ready: prose

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

* fix(auth): remove the synced OIDC avatar when the user uploads one

Once avatar_path points at the uploaded avatar.<ext>, the sync never
touches the user's avatar again, so the old oidc-avatar.<ext> file
would otherwise stay on disk for good.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:23:21 -05:00
MMagTech
ac9f5ab505 fix(saves): hash bytes that only end like a zip as one file (#5719)
* fix(saves): hash bytes that only end like a zip as one file

zipfile.is_zipfile is true for any file whose last 64 KB hold a zip's end
record. An emulator state can: Power Stone's Flycast (Naomi) state holds
the tail of the game's own TorrentZip archive. Reading such a file as a
zip fails, so compute_content_hash returned None, and a snapshot push
carrying the state was refused whole with "does not hash to the
manifest's value".

When the bytes cannot be read as a zip (BadZipFile), compute_content_hash,
hash_save_content and the memory card hash now hash them as one file, as
the web player's saveContentHash and the snapshot identity hash already
do. A real zip they cannot read within the limits stays unknown.

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

* pr-ready: code-review

Hash bytes as one file when the copied central directory points an entry
before the bytes start, as the tail of an archive longer than the state does.

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

* pr-ready: plain-prose

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

* fix(saves): decide what is a zip archive by one rule

Bytes are a zip archive only when their entries start at the first byte.
A state or save holding another archive, whole or only its tail, after
data of its own is hashed, shaped, uploaded and unpacked as one raw file
everywhere: the content hashers, the identity hash, save_shape_of,
check_upload and unpack_save_unit. A real archive with a corrupt entry
stays unknown to the content hashers, and the identity hash falls back to
the bytes for one past the limits too.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-22 10:00:16 -05:00
MMagTech
c925728cab fix(converto): move save channels to the converted files (#5681)
* fix(converto): move save channels to the converted files

Convert library pointed the game at its new file and refreshed its files,
but a channel names its file by SHA-1, name and size, and those still named
the original. Afterwards GET /api/channels?rom_file_id=<new file> found
nothing and a push into the channel with the new file was refused 422
("the ROM file does not match the channel's").

After the refresh, every user's channels on the game move: one on a
replaced file (an iso, a cue, its tracks, a rewritten m3u) to the file that
replaced it, and one on the game's sync file (channel_file_id) to its new
sync file, since name order picks that once no cue is left. The move keeps
updated_at, which orders a user's channels.

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

* pr-ready: code-review

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

* pr-ready: simplify

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

* pr-ready: prose

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

* fix(converto): move channels before deleting the originals

Convert library now refreshes a ROM's files while the originals are still
on disk, moves what keys to them onto the outputs in one transaction, and
only then deletes the originals. A failure before the deletion removes the
outputs, puts rewritten playlists back and keeps the channels on the
originals, so no failure leaves a channel on a file that is gone.

The sync-file redirect follows only to a file this run wrote, so a disc
that failed to convert no longer takes a converted disc's channels, and it
yields to the channel's own replacement when the user already has a channel
of that label on the new sync file.

The same transaction moves the ROM's snapshot hashes, so archival snapshots
still reattach after a rescan, and its states' capture disc, so a resume
mounts the right disc.

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

* perf(converto): skip the ROM-level hash in the early file refresh

The refresh that runs while a folder ROM's originals and outputs are both
on disk rereads every top-level file for the ROM-level hashes and RAHasher,
and the refresh after the originals go does it again. A new rom_hashes flag
on refresh_rom_files keeps the stored ROM-level hashes in the early
refresh, which then reads only the new and changed files, so the originals
are never reread and the ROM-level hashes are computed once.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-21 08:38:19 -05:00
MMagTech
f2986597d5 fix(scan): read title ids from zipped games (#5694)
A scan skipped every archive before asking sigil for a title id, but sigil
reads a .zip in place: a Vita dump through its sce_sys/param.sfo, any other
platform through the largest member. So a zipped game got no title id and
no cart facts, which left its saves nothing to convert between emulators by.
PS Vita is the common case, since a zip is the usual Vita dump.

Let .zip through both checks and keep skipping every other archive, which
sigil doesn't open. A hashed single-file archive also never queued its file
for extraction, so that branch now does, as the others do.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:19:11 -05:00
Henrique Reis Neves
a936e661dd fix(resources): inflate gzip-encoded metadata media downloads (#5670)
store_media_file streamed the raw response body without decode_gzip, so
media served with Content-Encoding: gzip (the LaunchBox image CDN does
this whenever the client accepts gzip) was written to disk still
compressed. Covers, screenshots and manuals already inflated it.

Fixes #5669

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:24:27 -05:00
Struchkov Mark
2bc4b8d0e5 fix(sync): support safe RetroArch WebDAV backups (#5648)
* fix(sync): preserve RetroArch saves before WebDAV overwrites

* fix(sync): lock RetroArch backups across workers and honor zero retention

Address Greptile review on #5648: publish backups under an flock on the
backup folder so workers cannot prune each other's copies, replace the
os.link publish with an exists check and os.replace under that lock (no
hardlink support needed), and skip pruning when MAX_SAVES_PER_SLOT is 0.

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

* fix(sync): harden RetroArch COPY backups (code-review)

pr-ready step 2. Lock through a regular file so NFS grants the flock,
answer 404 for PSP bundle paths so RetroArch still uploads, back up the
state the upload overwrites rather than a served stream capture, compare
the Destination authority without default ports, accept a lowercase
Overwrite value, prune backups by age, and share the stamp regex.

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

* refactor(sync): simplify RetroArch COPY backups (simplify)

pr-ready step 3. Check the source once before copying, publish backups
with the served file mode, drop the redundant deleted/ segment from the
backup storage path, and fold the two retention tests into one.

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

* fix(sync): back up RetroArch deletes and share upload targets

Back up the file a MOVE into deleted/ drops before dropping it, and read
only the Destination tail so a reverse proxy may rewrite the host and
prefix. COPY resolves its source first, answering 404 whenever an upload
writes over nothing (versioned saves, PSP members), from the same upload
target helpers PUT uses. Backups are hardlinked when the filesystem
allows, and the stamp grammar and retention policy move to the sync
handler.

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

* test(sync): list the RetroArch COPY route with the other WebDAV verbs

COPY authenticates through _authorize like the rest of the WebDAV
routes, so the route guard test lists it as handled in its module.

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

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:09:39 -05:00
alexcastgonz
631a1a3763 fix(roms): parse TOSEC compound region and language tags (#5582)
* fix(roms): parse TOSEC compound region and language tags

* test(roms): use unrecognized compound tag components

* fix(roms): limit TOSEC compounds to two-letter codes (pr-ready: code-review)

Single-letter GoodTools codes made (SW-R) read as Sweden and Russia,
and old-style [T-Br] translation tags read as Taiwan and Brazil.

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

* test(roms): drop prefix test the compound branch never reaches (pr-ready: simplify)

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

* docs(roms): clarify _resolve_every docstring (pr-ready: humanizer)

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

* fix(roms): give exact-case codes precedence in compound tags

Addresses Greptile: "Nl-No" read as Netherlands and Norway instead of
Dutch and Norwegian.

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

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:33:31 -05:00
Georges-Antoine Assi
e813e4d666 chore(coherence): adopt Coherence with specs, invariants and a PR report (#5584)
* chore(coherence): adopt Coherence with specs, invariants and a PR report

Install @posthog/coherence as a frontend dev dependency and wire its
Claude Code hooks into the committed .claude/settings.json, so every
agent session in the repo gets the vocabulary, specs, journal and checks.
The hooks call the binary under frontend/ through $CLAUDE_PROJECT_DIR.

Declare 23 components and the entrances that carry outside trust, and
six invariants, each refuted with a deliberate break before it counted:

- every /api route requires auth and its scopes, except a named public
  list (new route sweep in tests/endpoints/test_route_guards.py)
- a hidden rom, platform or firmware answers every id route exactly as
  a missing id would (new sweep over every method of every id route)
- the unscoped save, state and screenshot fetches by id are reached only
  from their own routers (chokepoints)
- validate_path never resolves outside its base folder

The PR workflow runs in comment mode: one report comment, failing only
when Coherence itself breaks. Trunk skips Prettier and markdownlint on
*.spec.md and *.practice.md, since Prettier escapes their globs.

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

* test(routes): satisfy mypy in the route guard sweep

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

* chore(coherence): record the worktree test database enactment

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

* fix(roms): answer a hidden rom like a missing one on file routes; tighten route sweeps

Addresses Greptile's review on #5584.

The rom file delete and reading-progress routes answered "File not found"
for a hidden rom but "Rom with id N not found" for a missing one, so a
caller could tell them apart. They now raise the same not-found.

The route sweeps now reach the checks they claim to test: a protected
route with no scopes counts as public (its guard admits anyone), write
requests carry a body and upload name so validation can't answer first,
RomFile-keyed routes get a real file id, error bodies are compared with
the id normalized, and the rom routes are swept with the rom hidden
directly, through its platform, and by the unrated filter.

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

* fix(coherence): tighten route guard sweeps and isolate oracle test databases (code-review)

- Count a route as protected only when its endpoint is the scope-checking
  wrapper with non-empty scopes, not just when it declares the bearer scopes.
- Treat 401 and 403 like 422 as never reaching the visibility check, and
  sweep /api/streaming/states/{rom_id}.
- Run pytest oracles with a per-run ROMM_TEST_DB_TAG unless one is set.
- Use the shared setup-frontend action and ubuntu-24.04 in the workflow.

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

* refactor(tests): simplify route guard sweeps and path tests (simplify)

- Mark scope-guard wrappers with required_scopes so the auth sweep reads a
  public attribute instead of the private closure.
- Derive the entity regex from one segment list, ask each missing id once,
  and run the three hide scenarios through one sweep helper.
- Fold the new validate_path inputs into the existing valid, traversal and
  absolute path tests.

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

* chore(coherence): trim workflow comments (review-polish)

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

* test(filesystem): restore the validate_path property test the paths invariant cites

Filesystem.spec.md names test_validate_path_never_escapes_its_base as the
invariant's evidence, and Coherence selects it by name.

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

* chore(coherence): run hooks from the local binary instead of npx

Each hook calls frontend/node_modules/.bin/coherence directly and exits 0
when it isn't installed, so sessions without frontend deps (fresh
worktrees, backend-only setups, cloud setup still installing) don't report
a hook error on every tool call, and no hook pays npx's startup.

Also commits the journal and run records left by earlier sessions, which
.coherence/.gitignore keeps as durable records.

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

* refactor(tests): share the bearer, user token and hide helpers

Tests built the same Authorization headers and HiddenEntity rows in about
40 local copies, and two modules imported private helpers from other test
files. They now use bearer, user_headers and hide from tests/auth_helpers.py.

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

* refactor(endpoints): one 404 for a missing or hidden rom, platform or firmware

Each route wrote the missing-row 404 and the hidden-row 404 separately and
had to keep them identical by hand. visible_rom_or_404,
visible_platform_or_404 and visible_firmware_or_404 take the lookup result
and raise one answer for both, either the standard not-found or a bespoke
detail. Re-reads after a write keep a plain not-found check, so an edit that
hides the row doesn't turn into a 404 after it succeeded.

The RomFile-keyed routes (/roms/{file_id}/files, .../files/content/{name},
/roms/{file_id}/patch) name their path parameter file_id instead of id, so
the route sweep reads which id a route takes from its path and drops its
hand-kept list. URLs are unchanged.

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

* docs(setup): develop inside WSL on Windows

@posthog/coherence installs only on Linux and macOS, so npm install in
frontend/ fails on native Windows.

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

* chore(coherence): record the whole-repo chokepoint run

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

* chore(types): regenerate API types for the file_id patch route

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:53:46 -05:00
alexcastgonz
c56d27be7b fix(roms): read full country names in filenames as regions (#5578)
* fix(roms): read full country names in filenames as regions

No-Intro writes full country names, e.g. (Poland) or (Czech Republic).
parse_tags only resolved the names listed in REGIONS, so the regions added
from the provider vocabulary were stored as other tags. Add those names to
the filename region aliases, skipping any that a language vocabulary claims.

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

* chore(roms): shorten region alias comment per Greptile review

Addresses Greptile's comment-length finding on #5578.

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

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-14 10:29:59 -05:00
Terri
8a1e6280b1 feat(saves): add save channels and snapshots (#5198)
* feat(saves): add save channels and snapshots

* feat(saves): close spec gaps in save channels and hash with sigil

* feat(saves): play snapshots in the v2 player, which pushes snapshots

* fix(saves): code review: authorization, retention losses, held-save sync, batched responses

* refactor(saves): simplify pass

* refactor(saves): review-polish pass

* docs(saves): humanizer pass

* feat(saves): run every EmulatorJS page on the v2 player

* feat(saves): per-user snapshot pins

* feat(sigil): store the identity a save restore needs and pin sigil 0f05f25

* fix(saves): meet type-aware lint in the v2 player

* feat(sigil): store N64 header and playlist title ids, pin sigil 0847fda

* feat(saves): convert saves for a core on download and list save layouts

* feat(saves): prune unreachable archival snapshots and empty detached channels on delete

* feat(saves): device sync from the token, held snapshots and shared-card pushes

* feat(saves): arc restores past abandoned snapshots and color channels by age

* fix(saves): code-review and security-audit fixes

* refactor(saves): simplify pass

* chore(saves): review-polish pass

* docs(saves): humanizer pass

* fix(sync): file RetroArch autosave versions as their channel's next snapshot

* fix(saves): address review findings and trim docstrings

* fix(saves): share-lock planned rows by id so PostgreSQL accepts the lock

* test(saves): stub the detached-channels fetch in SaveDataTab stories

* feat(saves): carry the full current snapshot in a 409, pin sigil 2071dff

* chore(sigil): pin 5d4ddb4, which reads .cue and .gdi sheets

* docs(saves): drop v2 wording now that one UI remains

* chore(sigil): pin 0190443, which reads PS2 raw BIN images and cue sheets

* fix(sigil): treat a file too short for its format as routine during scans

* chore(migrations): renumber save channel migrations after upstream's 0154

* fix(snapshots): a hardcore switch on unchanged content makes a new current

* fix(sync): decide a channel's slot from its history and the device's snapshot

* chore(docker): pin sigil at 794d99f for PSP Store release save prefixes

* refactor(db): squash the save channel migrations into 0161

Fold the slot linking (0162) and the rom_files sigil identity columns (0163)
into 0161_save_channels, so the feature ships as one revision.

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

* fix(saves): close visibility and input gaps found in review (pr-ready step 2)

code-review --fix:
- negotiate_sync drops channel slots on ROMs hidden from the caller
- channel PATCH/attach/DELETE answer 404 when the channel's ROM is hidden
- a push copying a save from a hidden ROM answers 404
- _own_device applies require_token_device to bound client tokens
- adopting a legacy save syncs its sharing with the channel it joins

security-audit follow-ups:
- another user's detached public save or state is no longer downloadable
- profile and option values must be a single path segment
- companions are de-duplicated and capped at 8

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

* refactor(saves): share channel and asset lookups, drop duplicates (pr-ready step 3)

simplify:
- readable_channel_or_404 and channels_on_files replace four copies of the
  channel 404 check and two copies of the file-fed channel listing
- readable_rom_asset_or_404 serves both public save and state downloads
- _own_device resolves through require_device; _clone_origin takes the source
- reuse _unprocessable, DESCRIPTOR_EXTENSIONS, SAVE_SLOT_MAX_LENGTH, uniqueBy
  and uuidv7; neutral forms default their required pattern to the allowed one
- RetroArch delete checks held rows in one query, a guarded upload lists the
  slot only without a channel head, and uploads are read off the event loop
- snapshotSession builds push requests once; player comment cleanups

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

* docs(saves): trim two docstrings to two lines (pr-ready step 4)

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

* fix(saves): answer held RetroArch paths with 423, mirror slot labels

- RetroArch Cloud Sync answers 423 Locked for a PUT over a held unslotted save
  and for a DELETE where only held rows sit at the path, instead of 409 and 404
- channelLabelForSlot returns null for blank and state_ slots, as the backend's
  channel_label does, so the player files them under no channel either
- document that sharing a channel lets every user read and push into it

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

* chore(docker): pin sigil at 85f88a8 for Switch .nup containers

* fix(snapshots): a save pushed in another shape or format makes a new current

* refactor(saves): drop the always-true SAVE_SYNC.SNAPSHOTS heartbeat flag

Nothing reads it, and the SAVE_SYNC block's presence already tells a
client the server speaks the snapshot API. Also trim the rom detail
channel field comments to one line each.

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

* refactor(frontend): use uuidv7 for every client-generated id

Drop the randomToken wrapper and the notification inbox's Math.random tab
id, so uuidv7 is the one helper that works outside a secure context.

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

* refactor(saves): trim redundant snapshot API surface, dead code and duplicate logic

API:
- Drop PUT /snapshots/{id}/devices/{device_id}; GET /snapshots/{id}?hold=true holds.
- GET /snapshots is history only (channel_id required); GET /channels serves currents.
- A snapshot carries channel_id instead of an embedded channel.
- POST /saves/{id}/content takes the same query parameters as the GET, plus container_path.

Backend:
- Remove the archival write path, clone.py, DBStatesHandler.get_state, the sigil
  identity-hash path, unused relationships and composite snapshot indexes.
- One held/frozen lookup, one bulk-delete guard, SQLAlchemy dialect upserts, and
  the shared reserve_version_name in the writer.
- The writer takes a visibility filter and checks the channel and parent itself.
- The restore handler picks per-game or merge; fewer wrapper types and tables.

Frontend:
- Channel delete uses the shared typed confirm; DeleteChannelDialog is gone.
- Held offline pushes go through a per-channel SnapshotSession.
- Remove the slot-based pending upload path.
- The timeline shares the fan's badge logic.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(saves): release archival backups through module functions

The saves and states handlers each built a private DBSnapshotsHandler to
call release_backup and refresh_backup_digests, since they can't import
the shared instance. Both only ever ran inside the caller's session, so
they are now module functions taking it, like channel_for_slot.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(saves): share one deleted-assets handler instance

The saves handler built its own DBDeletedAssetsHandler because it can't
import the package's instance. The instance is now built in
deleted_assets_handler.py and re-exported by the package, so both use it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 21:59:19 -05:00
Henrique Reis Neves
34117694ac fix(scan): read revision tags written without a separator (#5559)
GoodTools sets name a revision with no space or dash after "Rev", as in
"Sonic The Hedgehog (W) (REV01) [!].gen". REVISION_TAG_REGEX required a
separator, so "(REV01)" and "(Rev1)" left the revision empty and landed
in the free-form tags instead.

The regex now also takes "Rev" followed directly by a digit. A letter
right after "Rev" still does not count, so tags such as "(Revenge)" and
"(RevB)" stay plain tags.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:25:52 -05:00
Georges-Antoine Assi
03636ec156 fix(player): boot the base game, not a patch or translation (#5538)
* fix(player): boot the base game, not a patch or translation

Files in a game's translations/ or hacks/ folder were mixed in with the
base game: a .ups or .bps there counted as a bootable translation, a
tagged variant sorting first became the default, and "All discs" zipped
every file so EmulatorJS booted a translation's playlist.

Patch files are now recognised by extension wherever they sit, the
default and the selector's order favour the top-level (base) files, and
"All discs" requests only the base set through file_ids. The content
endpoint generates its playlist when the served files carry none, rather
than when the rom has one anywhere.

Fixes #5462

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

* fix(player): apply code-review fixes

Share the m3u check through has_playlist, memoise the boot file ids, and
correct the playerDisc comments.

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

* refactor(player): simplify the base-set helpers

One allDiscFiles helper backs offersAllDiscs, defaultDisc and bootFileIds,
and isPatchFile alone owns the patch rule.

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

* fix(player): keep variants and media out of playlists; classify patches on the backend

The backend's disc rule now leaves out patches, media and cheats, and a
playlist covers only the base game's discs, so whole-rom downloads, the
native shell and the streaming disc swap stop listing translations, hacks
or a selected manual. A selection with no disc gets no generated .m3u.

The scanner files any patch format as a patch, and the file schema does
the same for rows scanned before, so the frontend trusts the category.
The heartbeat now carries the supported patch extensions, which replaces
the frontend copy, and one fileExtension helper replaces three.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:56:17 -05:00
Georges-Antoine Assi
903ed64d94 fix(scan): hash compressed ROMs by their content in every format (#5537)
* fix(scan): hash compressed ROMs by their content in every format

Files inside a game folder and standalone single-stream files picked a
reader from a hand-written extension/MIME chain that treated plain .gz as
tar, missed .tgz/.txz/.xz and the application/gzip MIME spelling, and
called max() on empty archives. One suffix-then-MIME lookup in
utils/archives now picks the reader, plain gzip/bz2/xz streams are
decompressed (or read as a tarball when they hold one), and an empty or
unreadable archive falls back to hashing its raw bytes.

Fixes #5328

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

* fix(scan): don't read a zero-prefixed compressed stream as an empty tar

Addresses Greptile review on #5537: tarfile.is_tarfile accepts a
zero-filled opening, so a plain .iso.bz2 or .iso.gz starting with zeros
fell back to its compressed bytes. A tarball now needs a first member.
Also moves hash_largest_member's failure contract into Returns:.

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

* fix(scan): fall back to raw bytes on more unreadable archives (code-review)

Catch ValueError from corrupt Deflate64 members and undecodable zip
names, treat an archive with empty content as unreadable, route zips
with methods zipfile can't decode through 7zz, and drop the zlib.error
handlers no reader raises any more.

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

* refactor(scan): route 7z and undecodable zips through one largest-member reader (simplify)

Replace hash_largest_7z_member with a read_7z_file iterator built on the
shared 7zz listing and streaming helpers, probe zips with
_undecodable_zip_method instead of inspecting the exception cause, share
one decompression error tuple, snapshot only the ROM-level accumulators,
and reuse the archive-writing test helpers.

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

* fix(scan): bound, single-pass and RAR-aware largest-member hashing

- Every Python-side archive read (zip, tar, gzip, bz2, xz, and the
  composite zip/tar readers) now shares the SEVEN_ZIP_TIMEOUT budget the
  7zz and bsdtar paths already had, so a decompression bomb falls back to
  the raw bytes instead of tying up a scan thread.
- Compressed tarballs are read in one streaming pass: each member larger
  than every one before it is hashed into a copy of the hashers as it
  passes, instead of listing the whole archive and then decompressing it
  again to reach the largest member.
- gzip is decompressed member by member and ignores trailing bytes the
  way gunzip does, instead of discarding the content when padding follows
  the last member.
- RAR members inside game folders hash by their largest member through
  bsdtar.
- ARCHIVE_FORMAT_BY_SUFFIX moves to utils.filesystem and is the single
  suffix list: COMPRESSED_FILE_EXTENSIONS, RAR_FILE_EXTENSIONS and the
  handler's ARCHIVE_READERS are built from it.
- _calculate_rom_hashes detects the MIME type once per file and reads the
  embedded CHD hash in the same thread, so libmagic no longer runs twice
  per file or on the event loop.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:58:59 -05:00
Nathan Alcantara
e8fa1d5f20 chore(scan): recognize Brazilian Portuguese as a language (#5499)
* feat(scan): recognize Brazilian Portuguese as a language

Add "Pt-BR" (Brazilian Portuguese) to the filename language table, so
"(Pt-BR)" and "(T-Pt-BR)" no longer fall back to an unrecognized tag or
to European Portuguese, and show the Brazilian flag for it in the UI.

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

* fix(scan): read the regional variant ahead of a translation's version

"[T+Pt-BR1.1_Grp]" kept the version in the lookup and fell back to
Portuguese. Match only the two-letter variant that opens the patch, and
cover the Brazilian flag in the frontend tests.

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

* style(scan): apply black formatting

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 07:42:56 -05:00
Tyler Vigario
bbb7d98f53 fix(scan): look a file named by several titles up by each of them (#5478)
* fix(scan): look a file named by several titles up by each of them

No-Intro and Redump name a game released under several titles by all of
them, joined by " ~ ". Each file-name lookup now tries the full name
first and then each title, tags and extension kept, until one matches;
SteamGridDB searches the titles too. Only the title is split, never a
tag group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Eky1CPt1rz6BWLAqWVNmU9

* fix(scan): search each SteamGridDB name once

From Greptile's review: a title can repeat a name a provider already
gave, so SteamGridDB's candidate names are deduplicated, first position
kept, with a test. The new test module's docstring is one sentence, as
AGENTS.md asks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Eky1CPt1rz6BWLAqWVNmU9

* fix(scan): keep the full-name answer on a miss and cap title lookups

pr-ready step 2 (code-review xhigh --fix): return the full name's result when
every title misses, dedupe and cap titles at 4, and stop wrapping CSDb, whose
lookup only reads a (csdb-N) tag.

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

* refactor(scan): give SteamGridDB the bare titles and inline lookup args

pr-ready step 3 (simplify): add compute_titles so SteamGridDB stops re-attaching
and re-stripping tags, inline the Moby and SS platform ids, and merge the two
all-miss tests.

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

* fix(scan): keep the narrowed Moby and SS platform ids for mypy

pr-ready step 4 (review-polish): the locals inlined in step 3 narrow the
optional platform ids, which a lambda body cannot do; restore them.

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

* docs(scan): reword the title cap comment

pr-ready step 5 (humanizer).

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-08 16:40:43 -05:00
Sam Dornan
48c1e8a311 perf(scan): stop quick scan re-reading unchanged ROMs (#5516) 2026-11-08 11:12:28 -06:00
Georges-Antoine Assi
37e4ca304d fix: permission, validation and resource-limit hardening (#5496)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

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

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

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

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

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

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

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

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

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

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

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

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

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

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

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

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

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

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

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

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

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

* test: fix mypy errors in the new tests

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

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

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

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

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

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

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

* style: apply review-polish pass on permission hardening

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

* fix(play-sessions): filter rom_id and device_id on PlaySession after the visibility join

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 11:39:30 -05:00
Sam Dornan
4393b70973 feat(media): JPEG XL library images and cover uploads (#5438)
* feat(media): serve JPEG XL library images inline

Add .jxl to the image extensions the download endpoint serves inline,
with an explicit image/jxl type since mimetypes doesn't know it, and to
the frontend lists that pick artwork and folder screenshots out of
rom.files. AVIF was already covered; the new test pins both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs

* feat(media): accept JPEG XL cover uploads through a Pillow plugin

Pillow 13 reads AVIF but not JPEG XL. pillow-jxl-plugin registers a
JXL codec with Pillow (imported once in utils/images, which the cover
and WebP-conversion code already load). It ships musllinux wheels for
the image's amd64 and arm64 builds.

ROM and collection artwork uploads now accept image/jxl and store it
re-encoded as PNG, since covers are served in their stored format and
not every browser renders JPEG XL. Avatars, stored as uploaded, keep
the PNG/JPEG/WebP/GIF allowlist.

The plugin is GPL-3.0, which is compatible with RomM's AGPL-3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs

* test(roms): expect JPEG XL in the artwork rejection message

Artwork uploads now also accept JPEG XL, so the rejection message lists
it. The collection tests were updated with the change; this ROM one was
missed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs

* fix(media): list library JPEG XL images only where the browser renders them

Library files are served as stored, and Chrome and Firefox render no
JPEG XL, so .jxl artwork and folder screenshots showed as broken tiles
there. A one-time probe decodes a 22-byte JPEG XL image and the artwork
and screenshot lists only include .jxl files once it succeeds (Safari),
updating reactively when the answer arrives. Chromium 153 fails the
probe, so the files stay hidden there as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs

* fix(media): size-check JPEG XL before decoding and keep it out of screenshot uploads

pillow-jxl decodes every pixel in _open(), before Pillow's
decompression-bomb check sees the size, so a small, highly compressed
JXL declaring a huge canvas could exhaust memory. utils/jxl reads the
width and height from the codestream SizeHeader (bare or inside a
container) and runs Pillow's own bomb check on them first, then
registers this guarded decoder in place of the plugin's.

The decoder raises RuntimeError on a corrupt file, which escaped
store_artwork as a 500. The guard turns it into SyntaxError, so Pillow
reports UnidentifiedImageError and the upload takes the same path as a
corrupt PNG.

POST /api/screenshots validated against the library inline list, so it
started accepting .jxl, but the asset endpoint serves those as
attachments. Screenshot uploads now use their own list without JPEG XL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs

* style(media): one-sentence jxl docstring and a narrowed mock call in the JXL test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs

* style(media): one-sentence canRenderJxl doc comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:14:06 -06:00
Sam Dornan
b62a81b968 fix(scan): strip .p8 from PICO-8 cart titles so LaunchBox can match them (#5427) 2026-10-31 18:29:41 -05:00
Sam Dornan
d2f90ebba3 fix(scan): hash game folders in sorted file order (#5421) 2026-10-31 15:32:25 -05:00
Stu Anderson
3ae27a67a1 chore(seed): realistic, fast, debuggable seeded images (#5253)
* feat(seed): realistic, fast, debuggable seeded images

generate_test_data.py can now seed a library whose images look like a real
one, quickly, so gallery, sizing and image-conversion work can be tested
without anyone's private cover art. The default (--image-fidelity 1) is
unchanged: same seed, byte-identical files.

- --image-fidelity 2: covers drawn at the real-world size mix (measured
  aggregates from one 8,396-cover library), the small cover made by RomM's
  own resize rule, and debug art on every image: the game's title, system
  and region; a box with rom id, size, kind and format; the original path;
  pure-colour corner pixels, named corners, percent ticks, crop boxes, a
  circle that shows stretching and a transparency ring.
- --image-fidelity 3: the same over texture calibrated to real bytes per
  pixel, with 22% of big.png holding JPEG bytes as in real libraries.
- --image-weighted-every N (default 10): at level 2, every Nth rom id is
  drawn at level 3, so one library serves layout and file-size work.
- --image-media: also write ScreenScraper media (sizes provisional).
- --image-workers / --image-limit: images are drawn in a process pool
  from a per-rom random stream (seed, rom id), identical to one process.
  2,000 roms with images seed in about 18 s instead of about 10 minutes.
- After a real run the seeder rotates the gallery's Redis cache, so a
  fresh seed never serves the previous library's lists.

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

* fix(seed): keep rows independent of image flags; survive a cache failure

- The screenshot count is drawn for every rom, whatever --images or
  --image-limit say, so those flags no longer shift the rows that follow
  (--no-images rows were already off in the previous seeder). With the
  defaults the draws are unchanged: level 1 output is still byte-identical.
- A Redis error while rotating the gallery cache prints a warning instead
  of aborting after the rows are committed, so the report still prints.
- Comments in seed_images.py trimmed to the repository's one-or-two-line rule.
- tests/tools/test_generate_test_data.py runs the seeder with inserts
  recorded instead of written: rows match with --image-limit and
  --no-images, and a cache failure still reports the saved seed.

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

* docs(seed): document seeding a test library in DEVELOPER_SETUP

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

* fix(seed): code-review fixes for seeded images

pr-ready step 2 (code-review xhigh --fix):
- level-3 noise is drawn per channel and retuned, so PNG output reaches
  the measured 0.9 / 1.5 / 2.0 bytes per pixel spread
- --image-media is rejected at --image-fidelity 1, where it did nothing
- paths come from rom_fs_resources_path, get_media_resources_path,
  CoverSize and MetadataMediaType instead of being rebuilt
- drop the unused path_column parameter and a no-op ImageChops call
- draw a batch's images while the next batch is built and inserted
- the cache-failure test checks the rows of the failing run
- drop a duplicate media-off test

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

* refactor(seed): simplify pass over seeded images

pr-ready step 3 (simplify):
- extract small_cover_size from resize_cover_to_small, so the seeder
  draws the small cover at RomM's size instead of writing, reopening
  and overwriting it
- draw_rom_images returns nothing and follows plan_rom_images, and
  files_written is derived from the plan
- _fitted_size measures from a proportional guess instead of stepping
  down one point at a time (about a quarter of level-2 draw time)
- one draw path for the pool and inline cases
- drop the ink parameter, the CORNER_RING alias, the _fade_ring wrapper
  and the RomImageJob caption default; tighten comments
- trim media from the two slowest tests and use dataclasses.replace

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

* docs(seed): humanizer pass over the seeding docs

pr-ready step 5 (humanizer).

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

* refactor(seed): one image pipeline, dry runs write nothing, main owns its cleanup

- level 1 mosaics go through plan_rom_images/draw_rom_images like the
  other levels, so they get media, workers and RomM's small-cover size
- --dry-run plans image paths but writes no files
- main() is a thin wrapper: it registers the UTC connect listener and
  removes it (disposing the pool) in a finally, and the image pool
  cancels queued draws on error; the test no longer patches SQLAlchemy
- the recommendation feed cache is rotated with the gallery cache

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-10-31 10:27:02 -04:00
Georges-Antoine Assi
638601f480 fix(webp): raise the cover WebP quality to 95 (#5410)
* fix(webp): raise the cover WebP quality to 95

Quality 90 left visible artifacts on box art with small text. On a
sample of real covers, 95 adds about 3 dB of luma PSNR for about 25%
more bytes (small covers go from 20% to 25% of the PNG size, big ones
from 27% to 36%); 100 costs another third for little gain.

Small animated covers now use the same quality instead of Pillow's
default of 80, and the ignored optimize flag is dropped from the static
WebP save.

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

* Apply suggestion from @greptile-apps[bot]

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-10-30 18:09:56 -04:00
Georges-Antoine Assi
b35eb4d07c fix(scan): clean up unreferenced rescan media, split scan_rom and move its parts into handler/scan (#5408)
* fix(scan): delete screenshots and media a rescan leaves unreferenced

A complete rescan keeps the stored artwork, so two kinds of file stayed on
disk with nothing pointing at them:

- screenshots indexed past a shorter new list, since files are named by
  position and only the indexes in range were rewritten
- media of a type removed from the preferences, since providers record no
  path for it and stale media was compared over the preferred types only

get_rom_screenshots now deletes the indexes past the new list, and
remove_stale_media compares every media type.

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

* refactor(scan): split scan_rom's merge into named steps

scan_rom held seeding the row, following Demozoo links, splicing scene
summaries, resetting rematched sources, the scene lock, rehash cleanup,
priority merges for fields, tags and artwork, and the SteamGridDB pass in one
body. Each step is now its own helper, the SteamGridDB lookup a _RomLookups
method, and the providers' answers a dict keyed by source instead of fourteen
locals. The Pouet and CSDb link follows share one helper. Behaviour is
unchanged.

McCabe complexity of scan_rom goes from 68 to 13, and the function from 664
to 215 lines.

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

* fix(scan): trim remove_stale_media's docstring per Greptile review

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

* refactor(scan): move the scan vocabulary, lookups and merge into handler/scan

scan_handler.py held the scan types and metadata sources, the per-source
lookups, the merge of their answers and the orchestration in one 2,000-line
module. It now builds on a handler/scan package:

- sources.py: ScanType, MetadataSource, the tag constants, RESCAN_RULES,
  should_consult, stored_match_id and the priority ordering
- lookups.py: RomLookups, the LaunchBox and Steam resolvers and
  get_main_platform_igdb_id
- merge.py: the pure steps that merge the sources' answers into a rom's
  columns

scan_handler.py keeps scan_platform, scan_rom, the asset scans and the media
downloads. Importers point at the module that now defines each name, and the
helpers that crossed a module boundary lost their leading underscore.
clear_rehash_misses takes the attempted sources instead of the lookups, so
merge does not depend on lookups. Behaviour is unchanged.

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

* fix(ci): import ScanType from handler.scan.sources in the e2e seed script

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

* fix(scan): harden leftover screenshot cleanup (pr-ready: code-review)

List the screenshots folder once, use isdecimal() for the index test, and
log rather than raise when a leftover can't be removed. Point three
comments at handler/scan instead of scan_handler.

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

* refactor(scan): tidy the merge helpers and patch paths (pr-ready: simplify)

- fetch_sgdb_rom refetches by stored_id and builds the SGDB name list
  itself, so the name sources stay private to lookups.
- follow_demozoo_link checks the source is enabled; scan_rom loops over
  Pouët and CSDb.
- order_merge_sources holds the one ordering pass, and
  build_metadata_handlers adds the empty SGDB entry.
- Leftover screenshots go through the quiet-delete helper, renamed
  _discard_file.
- Tests patch rom lookups through handler.scan.lookups.

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

* fix(scan): never leave a recorded media or screenshot path without its file

- remove_stale_media only deletes a file whose owner or source changed
  when that new owner stores the type again in this pass. A file nothing
  records is still deleted.
- Screenshots past a shorter list are pruned by remove_screenshots_past
  once the new paths are saved, in both download_rom_resources and
  update_rom, so a failed cover or manual leaves them in place.
- The release-notes schema diff watches scan_handler.py beside
  scan/sources.py, for ranges that span the move.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:23:13 -04:00
Georges-Antoine Assi
63faff8883 fix(misc): Rename paths, rescan artwork, scan lookups and streaming teardown fixes (#5396)
* fix(roms): rewrite only the moved part of a renamed rom's file paths

Renaming a rom rewrote each of its files with
`str.replace(old fs_name, new fs_name)` on both the name and the path. On
disk, rename_fs_rom moves only `fs_path/old` to `fs_path/new`, so:

- a folder rom's inner file named after the folder (`Game (Disc 1).bin`
  in `Game/`) was renamed in the database but not on disk;
- an fs_name that also appears in the platform path (a rom named `n64`
  under `n64/roms`) rewrote the platform path too.

_moved_file_location mirrors the move instead: a single-file rom's name
changes, a folder rom's files keep their names under the renamed folder,
and anything else is left alone.

_refetch_changed_matches now returns the ids it refetched, so the
RetroAchievements badge download keys off that rather than repeating the
comparison, and the shared-media rematch uses the same _match_changed
check as the refetch loop.

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

* fix(scan): keep artwork a complete rescan has nothing to replace with

A complete rescan deleted the rom's cover, manual, screenshots and every
provider media folder before asking any provider, then reset the stored
paths. A provider that was down, rate limited or no longer had the art
left the rom with none.

The wipe is gone, and scan_rom no longer resets the path columns on a
complete rescan. The download step already replaces what changed:
covers, manuals and screenshots refetch when their URL differs, and
remove_stale_media drops provider media whose owner or URL changed. The
URLs and locks are still cleared, so whatever answers now can replace a
file; a file nothing replaces stays where it was.

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

* refactor(scan): move scan_rom's provider lookups onto a _RomLookups class

scan_rom defined 16 provider lookups as closures over its own locals
(scan type, platform, rom, rom_attrs, enabled sources, the attempted and
inconclusive sets), so none of them could be read or tested apart from
the 1,000-line function around them.

They are now methods of _RomLookups, a dataclass holding exactly what
they used to capture, along with the helpers they share (consults,
note_inconclusive, resolve_fetch and the cached match files). scan_rom
builds one instance and keeps its local names for the shared sets, so its
body is unchanged apart from the calls. SteamGridDB's lookup stays nested
because it reads the other providers' results.

scan_rom drops from 977 to 664 lines. Its own complexity is unchanged:
that comes from the merge after the lookups, not the lookups themselves.

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

* refactor(streaming): one teardown order for every way a session ends

A session could be torn down three ways, each spelling out its steps:

- teardown_released_session (owner release and single admin release)
- teardown_abandoned_session (stale takeover and the reaper)
- force_release_all's inline _teardown

The first two ran the same stop/playtime/activity/state/saves sequence
in two copies. The sweep differed in ways that mattered: it held no drain
marker while it worked, recorded the termination after the stop (so a
polling tab could miss it), marked the exit save pull pending only after
the stop, and deleted the key unconditionally, even if a newer claim had
replaced the one it read.

_stop_and_collect now holds the shared sequence, and both lifecycle
teardowns call it after their own opening (a drain marker for a release,
a staleness-checked marker for an abandoned session). The sweep runs
teardown_released_session for each session, like a single admin release.
With no container config left, it still records the termination, then
frees the key through the guarded release_own_session.

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

* fix: apply code-review findings (pr-ready step 2)

Record playtime and clear the activity entry when force-release-all frees
a session whose container config is gone, and let the PICO-8 cartridge
fallback see a cover a complete rescan keeps.

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

* refactor: apply simplify findings (pr-ready step 3)

Let _RomLookups.attempts() record the attempt it gates, drop scan_rom's
local aliases for the lookups' state, read the platform slug off the
lookups in fetch_launchbox_rom, seed the kept artwork paths into
rom_attrs for every rescan so the PICO-8 fallback reads them directly,
return None from _moved_file_location when a file did not move, and
share the playtime and activity steps through close_session_record.

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

* fix: address Greptile review on #5396

Drop a cover's other formats once a new one is stored, so a kept upload
in another extension can't shadow it, and move the rename path rule onto
FSRomsHandler next to rename_fs_rom.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:06:52 -04:00
Alessandro Digilio
88e3c016f9 fix(sigil): classify routine extraction failures by type (#5304)
* fix(sigil): 🔇 classify routine extraction failures by type

* fix(sigil): log sigil's error message and correct test error codes

pr-ready step 2 (code-review): log the exception text instead of the bare
numeric code, restore the comment on why these failures are routine, use
NEEDS_KEY's real code (-6) in the fixture, and give parametrized cases ids.

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

* refactor(sigil): split routine and unexpected failures into separate except clauses

pr-ready step 3 (simplify).

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

* fix(sigil): keep sidecar files away from sigil

Disc sheets, subchannel data and text files beside a ROM never hold a title
id, and sigil fails short ones with the same IO error it raises for real
read failures, so they kept logging at ERROR on every scan.

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

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:44:55 -04:00
Georges-Antoine Assi
e232a52656 fix(docker): boot when the container runs as a non-default UID (#5189)
* fix(docker): boot when the container runs as a non-default UID

Unraid runs the container as 99:100, which can't write to the image's
/romm (owned by 1000, mode 755), only to the mounted subfolders. The
PSP pending dir at /romm/cache/retroarch_sync was created at import
time, so every gunicorn worker failed to boot.

- Buffer pending PSP save files under the user's assets folder
  (assets/users/<user>/retroarch/psp_pending/), beside the other
  RetroArch Cloud Sync files and outside the client-reachable blob
  categories.
- Move the zip and rom-converto download caches to /tmp/romm/cache,
  and point nginx's internal /cache/ alias there.
- Put gunicorn's control socket in /tmp/gunicorn instead of
  $HOME/.gunicorn, since HOME is / for that UID.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(docker): honor ROMM_TMP_PATH for caches, explain an unwritable sync folder

- The download caches live under $ROMM_TMP_PATH/cache when it's set,
  so installs with a small Docker disk (Unraid's docker.img) can point
  them at a share. The entrypoint exports the same path for nginx's
  /cache/ alias.
- With ENABLE_SYNC_FOLDER_WATCHER on and /romm/sync not writable, /init
  warns and skips the watcher instead of dying on mkdir under errexit.
- The compose example lists the /romm/sync mount the sync features need.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): cover reading back and clearing buffered PSP files

Addresses Greptile's review on #5189.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): apply code-review findings to PSP pending buffer

Remove the emptied psp_pending folder after a merge, define the sync
folder path once in init, update the architecture doc's PSP and blob
locations, and drop a stale .gitignore entry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(sync): apply simplify findings to PSP pending cleanup

Clear the buffered folder with remove_directory, let the startup check
own creating the sync folder, and reword the test fixture docstring.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): cap buffered PSP files and drop them on delete

Buffered files for an unresolved save folder now count against the
bundle limits, so a folder can't fill the assets share and then fail
every merge once it resolves. A DELETE also removes the buffered copy,
so a deleted file isn't merged back when the folder resolves.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(docker): check the sync folder for push-pull sync too

ENABLE_SYNC_PUSH_PULL keeps SSH keys and device saves under /romm/sync
as well, so an unwritable folder now disables it with the watcher and
warns at boot instead of failing when the task runs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(docker): strip whitespace from env vars like the backend does

The backend strips every variable it reads, while the init script and
nginx templates used raw values, so a padded ROMM_TMP_PATH sent nginx's
/cache/ alias somewhere the backend never writes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(config): drop the CACHE_BASE_PATH comment

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(docker): say which backend config strips env whitespace

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* revert(docker): drop the entrypoint env whitespace trimming

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): apply pr-ready code-review findings

Gate push-pull on its SSH keys path rather than a writable sync folder,
accept the same truthy values as the backend, and clear only the merged
PSP pending files so another worker's buffered file survives.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor: apply pr-ready simplify findings

Share one truthy pattern across init's flag checks (the watcher gates
now accept the same values as the backend), disable gunicorn's unused
control socket instead of placing it, derive the converts redirect from
its own cache path, and factor the unknown PSP folder in tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(docker): apply pr-ready humanizer pass to the sync mount note

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(fs): create handler base folders on first write, skip leftover temp files

FSHandler no longer mkdirs its base path when constructed, so a module-level
handler rooted at an unmounted or unwritable folder can't take down boot;
every write path already creates its parent folders. Blob listings skip
.romm_tmp_ files a crashed write left behind, so they are never merged into
a PSP bundle or advertised in the sync manifest. The prefix now lives in one
TEMP_FILE_PREFIX constant.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 16:48:50 -04:00
Zach Clendenen
38dfb208f0 fix(streaming): file RetroArch streaming exits as raw saves (#5174)
* fix(streaming): keep foreign saves offered when the import-spec check fails

A broker that misses the 5 s import-spec deadline used to read as "imports
nothing": the Saves tab vanished and foreign picks were refused with
"Save is not a restorable archive". Keep the last good answer in Redis so
every worker can fall back on it, cache 404s for five minutes instead of
forever, answer a pick that can't be checked with a retryable 503, and
refetch the streaming config whenever the Stream page mounts.

* fix(streaming): code-review fixes for the import-spec fallback

Hold a fallback answer for 10 s so one claim's checks don't each wait out
the broker timeout, read the stored answer back through the broker
response parser, and warn about a pre-import broker once per worker
instead of at every cache expiry.

* refactor(streaming): simplify pass on the import-spec fallback

Make ImportSpecUnavailable the 503 itself so the save and state pickers
no longer convert it by hand, and store the broker's own response body
as the last answer instead of rebuilding its shape.

* chore(streaming): review-polish on the import-spec fallback

Trim the cache comments and the exception docstring, fit the 503 detail
within the line limit, and annotate the fresh-worker test dict for mypy.

* docs(streaming): humanizer pass on import-spec comments and test docstrings

* fix(streaming): tell lasting import-spec failures from passing ones

Only timeouts, connection errors, 5xx and 429 fall back to the broker's
last answer. A refused request (401, other 4xx) or a reply RomM can't read
caches no imports for 30 s and logs an error, so a pick gets a refusal
instead of an endless retry. A 404 from a broker that answered before
uses that answer, since it is likelier a restart behind a proxy than a
downgrade.

* fix(streaming): ask for a retry when a picked state can't be checked

An older save with the newest state resumes the pick only through an
import, so an unanswered import-spec check now returns the 503 instead of
launching from the older archive's own state.

* fix(streaming): share an in-flight config request

App load and the Stream page both fetch the config; two requests could land
out of order and leave the older answer in place. (Stability item 5.)

* fix(streaming): hold the resume picker until the fresh config lands

What the broker imports decides which saves and states are on offer, and the
app-load config can predate its answer. The panel shows a spinner until the
Stream page's own refetch settles, so a pick can't vanish under the player.
(Stability item 4.)

* fix(streaming): ask every platform's broker at once on /config

The checks ran on the default thread pool (cpu+4 threads), so a broker
serving more platforms than that cost one timeout per wave: 10.7 s for 14
platforms on a 6-CPU dev box with a silent broker. The Stream page's picker
now waits on /config, so the checks get a pool of their own.

* fix(streaming): address Greptile review on the import-spec fallback

- Play waits on the fresh config with the resume picker, so it can't send a
  preselected state the player can't see yet.
- The streaming store gets a reset() for logout, and a config reply asked for
  as the previous account is dropped instead of landing in the next one.
- The configFresh write after the refetch checks useIsAlive().
- Trimmed the require_import_spec docstring, the configFresh comment and the
  /config pool comment to the house length.
- Declined: a worker-wide pool for the /config checks. Each request's threads
  end within the broker timeout, and a shared bounded pool would bring back
  timeout waves under concurrent loads.

* fix(streaming): share /config broker checks across requests

Addresses Greptile's re-raised finding on #5174 that each /config request
opened its own pool of up to 64 threads, so overlapping page loads during
a silent broker multiplied the worker's threads.

- The checks run in one worker-wide pool, and a check already in flight
  for the same container and platform is joined rather than asked again,
  so concurrent page loads hold no more threads than one does, with no
  queued-timeout waves.
- Callers await the shared run through asyncio.shield, so a request that
  disconnects doesn't cancel the check others are waiting on.

* fix(streaming): file a RetroArch exit's save raw and boot the newest save

A RetroArch exit holding one .srm and its states is no longer stored as a
.saves.zip: the .srm is filed bare under the core's emulator name with a
timestamped name, and each state goes through the state store. Exits with
more than one save, a memory card, or unlabelled members still keep the zip.

A launch with no pick now boots the newest save, raw or zip. A newer bare
.srm goes through the broker's save import when the broker accepts one,
and the launch screen defaults to the same save.

* fix(streaming): keep the exit zip when a raw save can't be filed safely

pr-ready step 2 (code review).

- Keep the zip for a core that isn't one plain folder name, a malformed
  manifest kind, a member that fails to unpack, or a broker that doesn't
  import saves.
- Fall back to the newest archive when the default raw save fails to import.
- File exit states oldest first; one unreadable stored state no longer
  drops the rest.
- Rename locals that shadowed the archive module; fix a test return type
  and a stale comment.

* refactor(streaming): simplify the default save comparison

pr-ready step 3 (simplify): default_save reuses _newest's ordering, and newestSave takes the first match in the newest-first list.

* docs(streaming): trim the raw-save docstrings

pr-ready step 4 (review-polish).

* fix(streaming): rank saves by their last write and read .ZIP as an archive

The web player writes into its existing save row, which only moves
updated_at, so ranking by created_at let a stream with no pick boot an
older streaming zip over newer web-player progress. The backend default
and the launch screen now rank by updated_at, and the picker dates rows
by it. Upper-case .ZIP saves are now read as archives on both sides, to
match the web player's case-insensitive guard.

* feat(states): hash states so duplicate checks skip reading files

Adds states.content_hash (migration 0149), filled on every state write:
streaming capture, the states upload and update endpoints, the scan and
the RetroArch sync push. The streaming duplicate check compares hashes
and falls back to reading the file for rows stored before this, which
are not backfilled.

* fix(streaming): leave an untouched default off the claim and skip missing saves

Review items 1 and 2: a default sent as a pick bypassed the zip fallback, and a save marked missing could become the newest.

* fix(streaming): code-review fixes for raw exit filing and state hashing

pr-ready step 2: keep the zip when a state can't be filed, don't treat a missing state file as a duplicate, fall back to the native archive when a defaulted save fails, hash off the event loop, count filed states as new.

* docs(streaming): review-polish, trim the newest-save comment

* fix(streaming): bind the background exit pull's states to the swapped disc

Decision 1: the exit save job filed states without the session's disc id, so on a multi-disc game its copy could lose the disc binding. The second copy is still dropped by the hash dedupe.

* fix(streaming): keep the exit zip when one of its states fails to store

Decision 2: a state that threw on store was logged and lost, since the zip holding it was dropped. The zip holds the same .srm, so booting it as the default loses nothing.

* fix(sync): keep updated_at when RetroArch sync flags a vanished save or state

* fix(streaming): record a legacy state's hash when dedupe reads its bytes

* fix(streaming): file a RetroArch exit's auto state raw instead of keeping the zip

The auto state now goes into the state history under its own capture
stamp, so an exit carrying one files its .srm raw like any other. It is
never hydrated, and a resume pick of it is refused, since the broker
would file it into its numbered working slot.

* fix(streaming): hydrate the newest state still on disk

A newer row sync flagged as gone from disk made hydrate push nothing.
It now skips such rows the way the save picks already do.

* docs(streaming): note the auto-state refusal in resolve_resume_state

* fix(streaming): resume a RetroArch auto state like any other state

The broker files any pushed state into its working slot, so .state.auto
reads as slot 0 like a bare .state. Hydrate and the resume pick now push
it instead of skipping or refusing it.

* fix(streaming): address Greptile review on raw RetroArch exits

- A default .srm the broker refuses at activate now boots the newest
  native archive instead of failing the launch. Only a default save
  that rode the import alone falls back; a hand pick still fails.
- Exit states the history hasn't seen are filed just under the next
  state it already holds, so an older slot no longer heads the history
  over the exit capture teardown filed first.
- A raw exit save is skipped only when it matches the newest usable
  save, so returning to an older save records the play, and a match on
  a row whose file is gone no longer deletes the new copy.
- Stream.test.ts clicks the rendered play button instead of casting
  the view model to call onPlay.
- Trim the raw-exit docstrings to one sentence.

* fix(streaming): reserve a free version name for a raw RetroArch exit save

Addresses Greptile: the exit's .srm took a second-resolution tag without
checking whether another save held that name, so it could overwrite one.
Also compares updated_at naively in the mark-missing test, which failed on
PostgreSQL's UTC-aware column.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(streaming): file each RetroArch exit state on the disc it was saved on

Addresses Greptile: every state in the exit archive took the session's
final disc, so a hotkey slot saved before a swap resumed on the wrong one.
The session now keeps each swap with its time, and a session that ran more
than one disc files each state by its archive timestamp.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 20:44:14 -04:00
Georges-Antoine Assi
3b8eabdb77 feat(sync): sync RetroArch Cloud Sync saves through save slots (#5170)
* feat(sync): sync RetroArch Cloud Sync saves through save slots

RetroArch saves were unslotted and overwritten in place, so they never
reached the slot-based sync the native clients use, and a bad upload
replaced the only copy.

A save path now serves the newest slotted version for its ROM, core and
extension, from any slot, under RetroArch's own file name. An upload adds
a version to that slot (or autosave), skips unchanged bytes, and prunes to
MAX_SAVES_PER_SLOT. A delete removes every save the path covers, so none
resurfaces on the next sync. Unslotted saves keep serving until the first
slotted upload; PSP bundles and states are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): lock RetroArch save uploads and prune per core and extension

Addresses Greptile's review on #5170:
- Move the RetroArch save upload into sync_handler.store_save_version,
  leaving the endpoint to validate and map the result to a status.
- Hold a Redis lock per (user, rom, core, extension) across the lookup,
  write, scan and row update, so concurrent same-second uploads never file
  two rows over one tagged file. A lock timeout answers 503.
- Prune only the uploaded path's core and extension in the slot, so
  another core's or a .rtc's current save is never dropped.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): pr-ready code-review fixes for RetroArch save slots

- Scope an extensionless prune to dotless file names, since every name
  ends in an empty extension.
- Treat only NULL slots as unslotted in the manifest, matching the query
  it replaced and the PSP bundle lookup.
- Share one helper for the slot versions a RetroArch path covers.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(sync): pr-ready simplify pass for RetroArch save slots

- Scope a slot prune by save ids, so the versions a RetroArch path covers
  are decided once in Python instead of again in SQL.
- One newest-per-key helper for states and save versions, and
  resolve_save_by_slot reuses it.
- A canonical_save_file_name helper next to the state one.
- The upload builds its tagged name once, checks its length in the
  handler, and finds a same-second version in the list it already loaded.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(sync): pr-ready review-polish pass

Drop a comment the canonical_save_file_name helper now says.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): map RetroArch saves onto autosave lineages with unique version names

- Only RetroArch's .srm goes through slots, as the autosave versions of
  its ROM and core. Companion files such as .rtc stay single unslotted
  saves, so a slot never offers a clock file as the save.
- RetroArch reads, writes and deletes in autosave only, leaving named
  slots alone.
- Every slot prune, web uploads included, is scoped to the uploaded save's
  lineage (emulator and extension), so one core's uploads never drop
  another's only save.
- The manifest lists the newest version under the client's spelling of
  the game when it still names the ROM.
- reserve_version_name moves a taken tag on a second and claims it in
  Redis, so same-second, concurrent or repeated-hour uploads from either
  endpoint never share a file. The RetroArch lock and its 503 go.
- The manifest reads only the newest version per lineage, through one
  window query.
- An upload is hashed before it is written, so an unchanged re-send
  writes nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): seed the client-spelled save instead of uploading it

Uploading TEST_ROM.srm only resolves to the test_rom ROM under MariaDB's
case-insensitive collation, so the test 409'd on PostgreSQL. Seeding the
version directly still checks that the manifest keeps the client's
spelling of the game.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): resolve RetroArch saves to ROMs case-insensitively on PostgreSQL

Cloud Sync matches a save's game name to a ROM's fs_name_no_ext. MariaDB's
collation ignores case, but PostgreSQL compared exactly, so TEST_ROM.srm
never reached the test_rom ROM. PostgreSQL now compares lowercased names,
served by a new expression index (0150), and the endpoint test uploads the
differently-cased name again.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): address Greptile review on RetroArch save slots

- add_save derives the prune lineage from the tagged name it stores, so a
  dotted upload such as game.rev.srm is counted against its own versions.
- Deleting a RetroArch .srm path also removes unslotted saves in that
  lineage spelled in another case, which the manifest hid behind the
  autosave head and PostgreSQL's exact match left behind.
- reserve_version_name looks up existing versions off the event loop.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 18:30:57 -04:00
Georges-Antoine Assi
3f13d1e752 fix(sync): store RetroArch Cloud Sync blobs under the assets volume (#5155)
The config/, thumbnails/ and system/ blobs lived at /romm/retroarch_sync,
which no documented mount covers, so they sat in the image's anonymous
/romm volume and were lost on `compose down`/`up`, `-V`, or a
docker rm/run upgrade. RetroArch can then treat the missing files as
deleted on the server and drop its local copies.

They now live at assets/users/<user>/retroarch/<category>/, beside the
user's saves and states. The old path never shipped in a release, so
no data migration is needed.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-05 19:31:21 -04:00
Sam Dornan
655976faa9 feat(soundtrack): play SPC, VGM, VGZ and GYM soundtracks in the browser (#5079) 2026-10-03 13:12:28 -04:00
Georges-Antoine Assi
746df798c0 fix(scan): refresh screenshots when only their order changes (#5029)
* fix(scan): refresh screenshots when only their order changes

Stored screenshots are named by position (0.jpg, 1.jpg, ...), but the
re-download check compared the provider's urls as an unordered set, so a
reorder was never picked up. Compare the lists directly, in both the scan
download step and update_rom.

Fixes #4103

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(scan): cover the screenshot reorder in update_rom

Address Greptile review on #5029: add an endpoint test for update_rom's
own reorder check, and narrow await_args before reading its kwargs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(scan): drop the old screenshot when its replacement fails

With overwrite on, a failed download left the previous image at that
index. The next scan saw matching urls and a file on disk, so it kept
the stale image for good. Remove it instead, so the next scan refetches.

Addresses Greptile review on #5029.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 18:58:37 -04:00
Georges-Antoine Assi
05bf29fe09 feat(converto): read per-file title ids with rom-converto during scans (#5031)
* feat(converto): read per-file title ids with rom-converto during scans

The title-id half of #5002: rom-converto's info runs fill rom_files.title_id
and title_version, sigil fills what rom-converto can't read and keeps owning
save targets, and roms in a scan batch share info runs of up to 64 files.
A converto_read_at marker lets quick scans backfill files rom-converto has
not read yet. converto.scan_metadata (config.yml only) turns it off.

The other per-file fields and embedded images stay out until a UI reads them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): name the same-content check that keeps unread title ids

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): queue unread files in one pass over the built rows

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(converto): address Greptile review on #5031

- A file refresh now persists converto_read_at when rom-converto's read
  confirms a reused row's stored title id, so the file isn't re-read on
  every refresh.
- RomConvertoService.read_infos splits its paths into info runs of at
  most INFO_BATCH_SIZE, so a rom with many files can't send them all
  through one run.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(converto): apply code-review fixes

- A stored file title id counts as rom-converto's only once rom-converto
  has read the row, so a stale sigil id can't override a fresh extraction.
- Fresh hashes decide whether unread title ids still describe a file,
  ahead of a size and mtime a copy can preserve.
- One rom's failed candidate listing no longer aborts its scan batch.
- The info paths file's cleanup can't raise out of read_infos.
- _rom_file_order sorts by Path like _TitleIdSource.order.
- Restored the in-place reconcile test for _identify_rom.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): apply simplify pass

- sync_rom_files reads 'rom-converto read this pass' off converto_read_at
  instead of an inspected set threaded through ParsedRomFiles, FSRom, the
  scan socket and the refresh.
- One _converto_may_read check serves the scan and the batch candidates.
- converto_candidates reuses _list_rom_dir, validates paths off the event
  loop and is best-effort itself, so the scan socket gathers it plainly.
- get_rom_files builds rom-converto paths from the validated rom dir
  instead of validating each file again.
- _rom_level_identity returns early on sigil's extraction.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(converto): apply review-polish pass

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): drop the shared info batch

Sharing rom-converto info runs across a scan batch saved about 2 ms per
rom (one process start) in exchange for a second directory walk per
rebuilt rom, the RomConvertoInfoBatch bookkeeping and the scan socket
wiring. Each rom now reads its own files; read_infos still caps a run
at INFO_RUN_MAX_FILES.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): name the rom-converto columns inline

Drops ROM_FILE_CONVERTO_COLUMNS and ROM_FILE_CONVERTO_KEPT_COLUMNS, so
_copy_scanned_columns keeps master's frozenset keep_when_unset.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 13:49:40 -04:00
Zach Clendenen
b8bb383ccd chore(uploads): apply review-polish pass
pr-ready step 4 (review-polish): trim comments that restate the code.
2026-10-01 10:45:24 -05:00
Zach Clendenen
0742f133e0 fix(api): apply code-review fixes for overlong names
pr-ready step 2 (code-review xhigh --fix): byte-check screenshot, rename
and ROM fs_name paths, fit streaming save archive names, cap email and
collection names, log duplicate collections at warning.
2026-10-01 10:34:16 -05:00
Zach Clendenen
a62996d2d2 fix(uploads): reject file names over the 255-byte filesystem limit
Upload names were held to FILE_NAME_MAX_LENGTH, 450 characters, but
ext4, XFS, Btrfs and ZFS cap a name at 255 bytes. A longer name passed
validation and the write failed with ENAMETOOLONG, a 500. Non-ASCII
names hit it early: a Japanese title reaches 255 bytes at about 85
characters.

Check the encoded length in the shared write path and in the save and
state uploads, so those return 400. Saves are checked after the slot's
datetime tag is added, since the tag adds 22 bytes. Memory card version
files trim the card name to fit, because a 255-character card name
leaves no room for the timestamp.
2026-09-30 22:30:34 -05:00
Sam Dornan
54bec6ed48 fix(scan): reuse unchanged empty files on quick scan (#4949)
* fix(scan): reuse unchanged empty files on quick scan

An empty file hashes to the default digest, which _make_file_hash stores
as a blank md5. rom_file_unchanged required a non-blank md5 on hashable
platforms, so an empty top-level file in a folder ROM (for example an
MSU-1 .msu) never counted as unchanged. The whole folder was re-hashed
and the ROM re-emitted on every quick scan, pushing it to the front of
Recently added.

Treat a zero-byte file as already hashed. Stored hashes stay blank so the
empty-input digest never feeds hash-based metadata matching.

Fixes #4933

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Mre6qcBuXvGJzBJjJfkDvy

* docs(scan): name _make_file_hash as the source of blank empty-file hashes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Mre6qcBuXvGJzBJjJfkDvy

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:56:01 -05:00
Sam Dornan
4cbf43acab perf(gamelist): validate media tag paths once per directory (#4943)
* perf(gamelist): validate media tag paths once per directory

A full-platform gamelist parse ran validate_path on every media tag,
about a dozen lstat calls each, which added up to tens of seconds per
platform on NFS/SMB mounts.

FSHandler.cached_path_validator returns a validate_path equivalent that
runs the lexical checks per call but hits the disk once per distinct
parent directory. The leaf needs no syscall: validate_path accepts a
symlinked leaf, and a plain one resolves inside its checked directory.
The gamelist parse builds one per pass and threads it to the media tag
and directory-entry checks.

On a 1,500-entry gamelist with six media tags per entry, lstat calls
drop from 108,140 to 200.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U5CmSdodtG5s2MiH9y65LE

* test(gamelist): pin one validate_path call per media folder

Condense cached_path_validator's docstring to one sentence, and assert
the exact per-folder call counts in the gamelist parse test, with the
media index stubbed so only the parse's own validation is counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U5CmSdodtG5s2MiH9y65LE

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:15:14 -05:00
Sam Dornan
33c10f5d6c Run the chroma-key placeholder check off the event loop (#4899)
* Run the chroma-key placeholder check off the event loop

_discard_if_chroma_key decoded every stored media image synchronously
inside an async method, so each check (about 15 to 35 ms for a 1024px
screenshot or box face) stalled the event loop and every other request or
scan task running on it. The decode now runs through asyncio.to_thread,
like the cover and logo work in the same handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Hold the file lock across the chroma-key check and delete

With the check awaited on a worker thread, a concurrent writer could
replace the file between the verdict and the delete, and the replacement
was then removed on the old file's verdict. The existence check, the
decode and the unlink now run under the path's lock, and a test replaces
the file mid-check to prove the new artwork survives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Make the chroma-key replacement test independent of timing

The test slept 0.2s and hoped the writer had run by then; a slow writer
would let unlocked code pass. It now asserts the path lock is held during
the check before the writer starts, and that the writer cannot finish
while the check runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 15:36:14 -05:00
Sam Dornan
6d9438b456 Add an opt-in setting to show the game logo in place of the title on the v2 game page (#4888)
* Show the scraped game logo in place of the title on the v2 game page

When a ROM has a ScreenScraper wheel (ss_metadata.logo_path), the details
header renders it inside the h1, with the game name as alt text, and falls
back to the text title when there is no logo or it fails to load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Trim the transparent border off stored game logos

ScreenScraper wheels often sit on a padded 1024x512 canvas, so a logo shown
in place of the game title looked indented and smaller than its neighbours.
store_metadata_media now crops each logo to its visible pixels, including
logos already on disk, so a rescan fixes existing libraries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Put the logo-as-title display behind a UI setting, off by default

Adds a showLogoTitle entry to useUISettings (synced to the user's
ui_settings like the other display preferences) and a 'Show logo as
title' toggle in the Gallery section of the User Interface settings, with
the new strings translated in every locale. GameHeader shows the logo only
when the setting is on. Also clears the existing em-dashes from
UserInterface.vue comments, which the lint rule flags once the file changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Outline the title logo so dark or light lettering stays readable

Some ScreenScraper wheels carry thin black text (A Link to the Past's
subtitle) that vanished on the dark theme, and white lettering has the same
problem on the light one. The logo now gets a 1px rim in the theme's text
colour, replacing the soft drop shadow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Size the title logo by area so square logos match wide ones

A shared 128px height cap left near-square wheels (A Link to the Past,
Aria of Sorrow) with about half the area of wide ones. Once the logo loads,
GameHeader now sets its width so every logo covers roughly the same area
(40,000 px, 22,000 on phones), within a 176px (120px) height cap and the
existing 420px width cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* pr-ready step 2 (code-review): harden logo trimming and logo retry

- Share one IMAGE_DECODE_ERRORS tuple (adds SyntaxError and
  DecompressionBombError) across the image helpers, so a broken or
  oversized logo no longer aborts store_metadata_media.
- Trim under the per-file lock and replace the file atomically, so a failed
  save keeps the original and a hardlinked source is never cropped.
- Skip every multi-frame image, and crop in the image's own mode so palette
  logos stay compact.
- Reset the header's logo failure and ratio whenever the logo URL changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* pr-ready step 3 (simplify): share the resource URL helper, trim dead code

- Add versionedResourceUrl to v2/utils/romFiles and use it from GameHeader,
  romArtwork and ManualSubtab, so the scraped-media cache-bust rule has one
  home.
- Key the header's logo load state on the URL (failedSrc, loadedLogo)
  instead of resetting two refs from a watch; hoist the shared 420px cap.
- Drop logo CSS the inline sizing made dead (display, height, object-fit,
  object-position).
- Read the alpha bbox with getbbox instead of a full RGBA copy, and check
  transparency before counting frames.
- Use a handler fixture in TestTrimTransparentBorder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* pr-ready step 4 (review-polish): drop a filler comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* pr-ready step 5 (humanizer): state three comments directly

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Bound logo trimming by pixel count and test phone logo sizing

- Skip trimming a logo above MAX_TRIM_PIXELS (16M), checked from the image
  header before any pixel is decoded, so a large download under Pillow's
  decompression-bomb threshold can't exhaust worker memory mid-scan.
- Cover the xs area and height cap in GameHeader's sizing tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 15:01:30 -05:00
Sam Dornan
d344662eac Keep ScreenScraper disc art for every disc of a multi-disc game (#4885)
* Keep ScreenScraper disc art for every disc of a multi-disc game

ScreenScraper tags each disc's support-2D art with a "support" number,
but the extractor kept only the first support-2D it met, so discs 2 and
up were never downloaded or shown.

The first disc still fills physical_url/physical_path, which the cover
art, disc-spin animation and exporters read. Every later disc goes to a
new ss_metadata.physical_extra_discs list, is downloaded next to it as
physical/physical_disc<N>.png, and gets its own entry on the v2 Artwork
subtab.

Existing ROMs pick up the extra discs on their next metadata refresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22

* Type the extra-disc test metadata so mypy can index it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22

* Label the first disc's art on multi-disc games

ss_metadata now records which disc physical_url shows, so the Artwork
subtab can label it "Physical media (disc N)" alongside the later discs.
It stays plain "Physical media" for single-disc games, gamelist art, or
when no later disc's art is on disk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22

* pr-ready step 2 (code-review): harden disc numbers and rematch cleanup

- Read ScreenScraper's disc number with safe_int and clamp it to 1, so
  a zero, negative or non-string "support" value counts as the first disc.
- Remove the physical folder on an ss_id change when only later discs
  had art, so a rematch doesn't keep the old game's disc images.
- Collapse store_metadata_media's two result lists into one target list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22

* pr-ready step 3 (simplify): one home for the media a provider dict records

- Add FSResourcesHandler.recorded_media, which lists every recorded file
  including a <type>_extra_discs list, so store_metadata_media and the
  update_rom cleanup share one rule and neither special-cases physical.
- Skip stripping a disc's URL once a better region already supplied it.
- Share the ScreenScraper disc tests' patch setup in an _extract helper
  and spell out each test's discs instead of slicing a fixture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22

* Refetch media whose source changed and keep shared art on rematch

- A scan now deletes each stored media file whose recorded URL changed,
  or a later disc's file the new metadata dropped, before storing, so a
  physical.png saved from another disc's art is fetched again instead of
  showing under a "(disc 1)" label.
- A rematch deletes a later disc's own file instead of the whole physical
  folder, so gamelist art sharing that folder survives.

Addresses the Greptile review on this PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22

* Keep a shared media file a higher-priority provider still records

The stale-media check could delete a shared file such as physical.png
because a lower-priority provider's URL for it changed, even though the
file held a higher-priority provider's unchanged art. Each provider now
leaves alone the paths the providers before it still record.

Addresses the second Greptile review on this PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22

* Decide stale shared media by which provider owns the path

The previous rule kept any path a higher-priority provider recorded, so
when ScreenScraper newly claimed a physical.png that still held older
gamelist art, neither provider refetched it. A shared path's file now
belongs to the first provider, in priority order, that records it, and
the file is refetched when that owner or its URL differs between the
previous and current metadata. Every provider is compared in one pass,
including ones outside this scan's sources.

Addresses the third Greptile review on this PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22

* Name the fields of recorded media instead of using bare tuples

RecordedMedia was a four-item tuple alias that callers unpacked by
position, with a comment spelling out what each slot held. It is now a
NamedTuple with explicit fields and a path property, and the per-path
ownership claim in remove_stale_media gets the same treatment.

Addresses review feedback on this PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 13:59:07 -05:00
Claude
42e5b5d119 Remove the no-emdash Trunk linter after a one-time sweep
The linter ran over every Markdown file and Python comment, so full-repo
trunk runs on master kept failing on em-dashes that predate it. Replace
the existing ones once and drop the check. The AGENTS.md rule stays, the
v2 ESLint rule stays, and pr-ready's humanizer pass catches new ones in
prose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RyamrxVw5BzEidVzm68LY7
2026-09-28 16:59:56 +00:00
Georges-Antoine Assi
d5301ac8fd Merge pull request #4854 from rommapp/fix/rom-file-category-anchor
fix(scan): anchor rom file category to the folder below the rom root
2026-09-28 08:12:17 -04:00
Georges-Antoine Assi
847b222b3f fix(scan): keep partial 7z member bytes out of the raw-archive hash
When extracting the largest member of a .7z failed partway, the bytes already
streamed stayed in the file and ROM-level hashers, and the raw-archive
fallback was appended on top, giving a hash that matched neither. The hashers
are now restored to their pre-extraction state before the fallback runs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 07:53:39 -04:00
Georges-Antoine Assi
0e35dc8d17 fix(scan): address Greptile review on the rom file category anchor
Recompute the folder category for rows a Quick scan reuses, so files
categorized before the anchor fix are corrected without a Complete scan,
and annotate the new tests' parameters.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 20:23:51 -04:00
Georges-Antoine Assi
a1fa09b6c8 fix(scan): anchor rom file category to the folder below the rom root
category_for_path_parts matched every segment of the library-relative
path and returned the first hit in enum order, so inner dump folders
(content/Game, content/CMCmn/demo), the rom folder itself, or even the
platform folder could set a file's category, and a bare `game` segment
outranked an `update` or `dlc` folder above it.

The scanner now passes the path relative to the ROM root, and only the
top folder there decides the category; deeper files inherit it.

Fixes #4581

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 14:48:11 -04:00
Sam Dornan
146464551b perf(scan): download a rom's media files concurrently (#4842)
* perf(scan): download a rom's media files concurrently

download_rom_resources fetched the cover, manual, each screenshot, each
provider media type and every RetroAchievements badge one after another,
so a single ROM never used more than one of the ScreenScraper account's
request slots.

They now download together. ScreenScraper media still goes through its
existing thread and rate limiters, and badges share a new cap of 8 in
flight across all scans. The path columns and changed provider media
dicts are written back in one update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf

* style(tests): sort imports with the Trunk isort config

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf

* fix(scan): code-review fixes for concurrent media downloads

- Run provider media dicts one after another, since they share paths
- Await every download before raising the first failure (gather_all)
- Fetch each duplicate media or badge path once (store_ra_badges)
- Reuse store_ra_badges in update_rom
- Share the in-flight test helper and trim comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf

* refactor(scan): simplify pass on concurrent media downloads

- Move gather_all to utils/concurrency and unpack its results directly
- Let write_file_streamed create the badge directory instead of every badge
- Share the in-flight test helper through tests/concurrency_stubs
- Stub downloads with AsyncMock through one fixture, drop a redundant test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf

* fix(scan): save the paths that landed when a provider download fails

Cover, manual and screenshot paths are written before a provider media or
badge failure is re-raised, so a failure there no longer loses them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf

* fix(scan): save each download group's results independently

Paths, provider media and badges each keep their own outcome, and every
change that landed is written before the first failure is re-raised. The
test builds a real Rom instead of a namespace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 13:35:21 -05:00
Sam Dornan
3206bc541f chore(deps): move from httpx to httpx2 (#4830) 2026-09-26 21:17:13 -04:00
Sam Dornan
5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* chore(mypy): switch to strict mode with listed exceptions

Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.

That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
  sites patched a dependency through the module that imported it
  (`scan_module.fs_rom_handler`); they now import the same object from
  its source, so every patch targets what it did before. Tests that
  replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
  explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
  dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
  NotRequired dump_* keys spelled out, and the media dict never has them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): give every generic its type arguments

Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.

- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
  JSON and endpoint bodies map string keys to mixed values, so the Any is
  real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
  _exclude_hidden are generic over the Select they're given, and
  _build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
  Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
  QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.

Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
  shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
  annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
  async_cache, so it is cast to Redis[bytes] rather than changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* test(upload): assert cleanup against the patched upload directory

The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): keep the row type through the ROM filter helpers

filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 16:32:29 -05:00