126 Commits

Author SHA1 Message Date
Terri
a420c7da31 fix(saves): stop Pokemon scratch RAM writes from flooding save sync (#5758)
* fix(play): show the automatic Save synced toast at most once every 5 minutes

* fix(saves): let sigil decide when a Pokemon save is the same, ignoring scratch RAM

* pr-ready: code-review

* pr-ready: review-polish

* pr-ready: prose

* fix(play): hold SRAM changes in the browser and upload them once the game goes quiet

* fix(play): upload a held save before a state replaces it, and report only new snapshots

* 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: review-polish

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

* pr-ready: prose

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

* pr-ready: prose (code-review fixes)

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

* fix(play): leave a save a running session holds out of other tabs' sync passes

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

* build(sigil): pin ef9b51e

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 07:41:09 -05:00
Georges-Antoine Assi
c413c066c6 refactor(docker): supervise the container with s6-overlay (#4019)
* refactor(docker): supervise the container with s6-overlay

The init script was a hand-rolled supervisor: PID files, /proc polling, a
5s watchdog loop and a trap-based shutdown. Its shutdown wait was unbounded,
so a process that refused to exit stranded PID 1 and left the container up
and serving nothing, which no restart policy can detect.

s6-rc replaces it with a declared service graph. Ordering and readiness
gates that were sequential bash become dependencies, and the failure modes
become configuration:

- timeout-kill bounds SIGTERM before SIGKILL, and flag-timeout-killpg
  escalates to the whole process group.
- S6_BEHAVIOUR_IF_STAGE2_FAILS=2 exits the container when a startup step
  fails, so the restart policy retries instead of the container wedging.
- valkey gets --shutdown-on-sigterm force, so it stops refusing to exit
  when the snapshot it writes on shutdown cannot be written.

A crashed service is now restarted on its own instead of taking the whole
container down. Its leftover children are swept first, because children
reparented from a hard-killed master keep holding its listening sockets and
would make every replacement fail to bind.

Optional services have no conditional mechanism in s6-rc, so they start,
check their environment variable, and take themselves down with s6-svc -O.

Running with a read-only root filesystem now needs /run mounted exec, since
s6 executes its generated stage scripts from there.

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

* fix(docker): always start the RQ scheduler under s6

The s6 service carried over the four-flag ENABLE_SCHEDULED_* gate from the
init script, which #4033 has since removed on master. Since this branch
deletes that script, the fix would be lost on rebase.

Nothing else respects the condition: startup.py registers the netplay,
upload-tmp and zip-cache cleanups unconditionally, three more flags gate
periodic tasks absent from the list, and the watcher defers its rescans
through the scheduler. Any of those leaves jobs in the scheduler registry
with no process to run them, and a stuck delayed scan_platforms entry reads
to the concurrent scan guard as a scan already queued, refusing every
manual scan.

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

* fix(docker): port master's init changes to the s6 services

Master reworked docker/init_scripts/init while this branch replaced it,
so carry those changes into the s6-rc services:

- Replace rq-scheduler with `rq cron` (romm-rq-cron) on tasks.cron_config.
- Add romm-rq-scan-worker (scans queue) and romm-rq-streaming-worker
  (streaming queue, down unless config.yml enables streaming).
- Run every worker with --with-scheduler and the RomMRedis connection
  class, passing the Redis URL through RQ_REDIS_URL so the password stays
  off the command line, and read REDIS_SSL as a boolean.
- Bring gunicorn's flags in line: --no-control-socket, a private-range
  FORWARDED_ALLOW_IPS default, 4 workers and a 65s keep-alive.
- Check the sync folder and SSH keys path in romm-init, and switch the
  features off through the container environment when they're unusable.
- Accept the backend's truthy values for the watcher flags.
- Point the serving-layer guard tests at the gunicorn run script and
  drop the PID-file tests, which guarded the bash watchdog.

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

* test(docker): guard the s6-overlay service tree

Check that every service is in the user bundle, depends on something
that exists, and that every longrun has its finish sweep, kill timeout
and process-group flag. Also check that the dev entrypoint starts the
same RQ workers and cron scheduler as the image, since it keeps its own
launcher.

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

* fix(dev): pass the image's RQ flags in the dev entrypoint

The dev image's RQ cron scheduler and workers ran without the RomMRedis
connection class, and the workers without --results-ttl, so they kept
redis-py's maintenance notification probe and RQ's default result TTL.
The s6 guard test now compares each rq command's flags with the image's.

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

* fix(docker): address Greptile review on the s6 service tree

- Cut the s6 script comments to two lines, keeping the reason each
  helper exists.
- Compare the values of the dev entrypoint's RQ options with the
  image's, not only their names, allowing for the dev image's path,
  PID files and LOGLEVEL default.

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

* ci(docker): check every s6 service stays up after boot

The heartbeat only proves gunicorn and nginx came up. Enable both watchers
and require each longrun in the s6 tree to report up for 15s straight, so a
crashing or restart-looping worker, cron, valkey or watcher fails the job.

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

* ci(docker): enable streaming so its worker is checked too

The streaming worker turns itself off when streaming.enabled is false in
config.yml, which the services check read as a failure.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-11-24 08:29:06 -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
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
Georges-Antoine Assi
8aa975af99 docs(architecture): keep design in the architecture docs, point to code for listings (#5586)
* docs(architecture): keep design in the architecture docs, point to code for listings

BACKEND_ARCHITECTURE.md had grown to 2,223 lines, most of it listings
copied from the code: every route, every model column, the migration
list, the env var tables, the cache keys and a file-by-file tree. Those
change with most pull requests and had drifted (151 documented routes
against 287 registered, a viewer/editor/admin role model that is now two
roles plus permission groups, the middleware order reversed).

Keep what changes slowly and the code doesn't explain: layers, request
flow, the auth, permission and visibility model, scanning, RetroArch
sync, sockets, device installs, tasks and notification channels. Replace
each listing with a pointer to where the fact lives (OpenAPI, models/,
env.template, examples/config.example.yml, tasks/registry.py). Fix the
roles, middleware order and visibility rules while there.

FRONTEND_ARCHITECTURE.md loses its route, store, namespace and script
lists the same way. AGENTS.md and the backend-development skill no
longer promise "every endpoint".

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

* docs(architecture): address Greptile review on access-control wording

- Permission groups also carry hidden entities and age settings; users
  add their own hidden entities and override the group's age settings.
- owned_rom_asset_or_404 is owner-only; public downloads check
  owner-or-public themselves, then assert_rom_visible.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 10:11:14 -05:00
Sam Dornan
104e34d700 perf(streaming): start the streaming worker only when streaming is enabled (#5570) 2026-11-12 07:38:48 -06: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
Georges-Antoine Assi
fe11afefe3 feat(oidc): add OIDC_AUTH_PARAMS for extra authorization request parameters (#5431)
* feat(oidc): add OIDC_AUTH_PARAMS for extra authorization request parameters

Lets admins send provider options such as prompt=select_account on the
OIDC login redirect. Authlib's authorize_params override its generated
state, nonce and PKCE values, so the parameters RomM manages are
rejected at startup.

Closes #5406

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

* refactor(oidc): trim parse_oidc_auth_params docstring

Addresses Greptile review on #5431.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:04:00 -05:00
Sam Dornan
1642a323c0 fix(sort): strip only configured articles, and keep custom sort keys as typed (#5429) 2026-10-31 19:17:00 -05: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
Sam Dornan
7eae2b8ffb chore(frontend): remove the v1 UI and console mode (#5309) 2026-10-23 19:37:45 -05:00
Zach Clendenen
1f6b4d11ca feat(permissions): gate emulator streaming and in-browser play behind group permissions (#5185)
* feat(permissions): gate emulator streaming behind a group permission

Add a streaming permission entity. Read shows streaming and allows joining
a session; write allows starting one. Users without read get a disabled
streaming config, so every streaming surface hides.

Migration 0152 grants read and write to every existing group, so nobody
loses access on upgrade. Groups created afterwards start without it.
Owner-scoped session controls (save, exit, release) stay ungated so a
revoked user can still leave a running game without losing saves.

* fix(streaming): pr-ready code-review fixes for the streaming grant

Own-only read no longer joins other users' sessions, the config refetches on permissions:changed, the store skips the joinable request when streaming is off, and tests clean up the groups they create.

* refactor(streaming): pr-ready simplify pass on the streaming grant

Collapse the streaming permission helpers onto assert_can/can_access, return an empty joinable list instead of 403, skip the permission resolve when streaming is off, and add a stream.start action key so the UI hides Stream (but keeps Join) for users without the write grant.

* docs(streaming): pr-ready review-polish pass on the streaming grant

Trim the 0152 migration docstring to a single summary line, matching 0150 and 0151.

* docs(streaming): pr-ready humanizer pass on the streaming grant

Plainer wording for the stream.start action key comment and the Permission Groups paragraph, which now says an own-only read shows streaming without the join.

* feat(permissions): gate in-browser emulation behind a group permission

Adds an emulation entity next to streaming. Read plays in the browser
(EmulatorJS, Ruffle, js-dos, PICO-8, EasyRPG) and joins netplay rooms,
write hosts them. Migration 0152 now backfills both entities onto every
existing group.

* fix(streaming): address Greptile review on PR 5185

- Pin the claimed container in the stream player, so a permission refresh
  that turns streaming off mid-game keeps save, load and disc swap until
  the session ends.
- Empty the Join list when a refreshed config turns streaming off, and
  discard any joinable request still in flight.
- Update the installPermissionsHydration doc to name every layout that
  calls it.

* fix(migrations): renumber play permissions migration to 0153 after master's 0152

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

* chore(permissions): drop redundant PermEntity comments

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

* refactor(streaming): drop the live config refresh on permission changes

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-09 14:47:11 -04:00
Georges-Antoine Assi
de62fa3815 fix(oidc): match any of the comma-separated groups in OIDC_ROLE_* (#5203)
* fix(oidc): match any of the comma-separated groups in OIDC_ROLE_*

OIDC_ROLE_ADMIN/EDITOR/VIEWER were read as one raw string and checked
for membership in the roles claim, so a value like
"romm-admin,platform-admins" never matched and the login was rejected
with 403. Parse each variable into a set of stripped, non-empty values
and grant the role when it intersects the claim. A single-valued string
claim is matched whole rather than by substring.

Fixes #4302

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

* test(oidc): reject a string role claim that only contains a mapped group

Addresses Greptile's review on #5203: the string-claim case only covered a
match, which the old substring check would also have passed.

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-09 13:56:00 -04:00
Georges-Antoine Assi
be6ad905b1 fix(sync): serve the newest on-disk RetroArch state in a slot (#5193)
* fix(sync): resolve RetroArch paths across emulators sharing a core folder

Several RomM emulator ids map to one RetroArch folder (mednafen_psx_hw,
beetle_psx_hw and the raw "Beetle PSX HW" all sync through
saves/Beetle PSX HW/). The manifest built paths from whichever id an
asset carried, but GET parsed the folder back to the canonical id and
matched it exactly, so an asset filed under another alias was advertised
and then 404'd. Uploads also started a second autosave history beside
the alias's.

The manifest now lists the newest asset per folder, and GET, PUT and
DELETE resolve a path across every alias. Rewrites of an existing
unslotted save or state stay under that row's own emulator.

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

* fix(sync): prefer on-disk alias saves and share newest-per-key grouping

pr-ready step 2 (code-review --fix).

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

* refactor(sync): one alias helper and a lineage computed once

pr-ready step 3 (simplify).

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

* test(sync): type the alias fixture's asset kind

pr-ready step 4 (review-polish).

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

* test(sync): isolate the asset dir per RetroArch sync test

The alias tests write different bytes to the same asset paths, and
user and ROM ids repeat across xdist worker databases, so parallel
runs raced on those files.

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

* fix(sync): serve the newest on-disk RetroArch state in a slot

Missing states are dropped before slot grouping for the manifest and reads, so a newer missing state (or alias) no longer hides an older one still on disk. A PUT still matches the missing row and revives it in place.

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

* fix(sync): fall back past a RetroArch file that vanished unflagged

Addresses Greptile's review on #5193: a state whose file was deleted before
`missing_from_fs` was set still won its slot. The manifest now rebuilds when
hashing flags an asset, and GET flags a missing file and resolves again, so an
older asset at the path is listed and served.

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 19:12:12 -04:00
Georges-Antoine Assi
79d1feba6c fix(sync): resolve RetroArch paths across emulators sharing a core folder (#5191)
* fix(sync): resolve RetroArch paths across emulators sharing a core folder

Several RomM emulator ids map to one RetroArch folder (mednafen_psx_hw,
beetle_psx_hw and the raw "Beetle PSX HW" all sync through
saves/Beetle PSX HW/). The manifest built paths from whichever id an
asset carried, but GET parsed the folder back to the canonical id and
matched it exactly, so an asset filed under another alias was advertised
and then 404'd. Uploads also started a second autosave history beside
the alias's.

The manifest now lists the newest asset per folder, and GET, PUT and
DELETE resolve a path across every alias. Rewrites of an existing
unslotted save or state stay under that row's own emulator.

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

* fix(sync): prefer on-disk alias saves and share newest-per-key grouping

pr-ready step 2 (code-review --fix).

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

* refactor(sync): one alias helper and a lineage computed once

pr-ready step 3 (simplify).

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

* test(sync): type the alias fixture's asset kind

pr-ready step 4 (review-polish).

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

* test(sync): isolate the asset dir per RetroArch sync test

The alias tests write different bytes to the same asset paths, and
user and ROM ids repeat across xdist worker databases, so parallel
runs raced on those files.

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

* fix(sync): delete every aliased state in a slot and prefer one on disk

Addresses Greptile review on #5191: a slot's state is picked live-first
across aliases, so a newer missing alias no longer hides an older one on
disk, and DELETE removes every state in the slot so an older alias can't
resurface at the same path.

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 17:00:52 -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
Georges-Antoine Assi
1060afc1af fix(devices): count a device that polls claim as online (#5190)
A client that drains installs by polling claim (Argosy) never holds the
/devices socket, so the install dialog showed it offline while awake.
Each claim now sets a presence key that lapses after the same 90 seconds
as a socket's.

Also add TZ to env.template, since save version names and log
timestamps follow the container's time zone.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 13:31:20 -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
6f2a361481 Play RPG Maker 2000/2003 games in the browser with EasyRPG (#5077)
* feat(player): play RPG Maker 2000/2003 games in the browser with EasyRPG

Embed the EasyRPG web player for extracted game folders on the rpg-maker
platform. The backend generates the player's index.json from the scanned
files and merges in the free EasyRPG RTP under every name the official
and fan RTPs give its assets, so games that lean on the RTP find them.
In-game saves sync with the user's RomM saves through the player's
IndexedDB storage.

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

* refactor(easyrpg): read the free RTP from a fixed path instead of an env var

The full image always keeps the RTP at /var/www/html/assets/easyrpg/rtp,
so the path is a constant beside the web path nginx serves it under. The
dev container links its copy there at startup.

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

* fix(easyrpg): code-review fixes for the save sync and asset endpoint

- Wait for an in-flight push before the quit push, so the newest save uploads
- Keep Play disabled until the fresh rom (and its saves) is fetched
- Stop onPlay and the rom fetch from acting after the view unmounts
- Leave through usePlayerExit like the other players
- Handle a rejected IDB commit when the run itself fails
- Track uploads by the browser's file name
- Load only visibility and files per asset request, not the full rom
- Serve DEV_MODE files as octet-stream, matching nginx
- Make the traversal test actually reach the endpoint

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

* refactor(easyrpg): simplify pass over the player and asset endpoint

- Load only file paths per asset request, and look up RTP folders in O(1)
- Reuse RomFile.file_name_for_download and usePlayerFullscreen
- Share one dev/prod serve helper for game and RTP files
- Derive the save sync's game key from the rom
- Have the RTP table tool reuse normalize_name
- Make save-module internals private and tidy the prepare/read loops

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

* feat(easyrpg): flag RPG Maker game folders on the rom schemas

Gallery lists carry no files, so the frontend guessed that every multi-file
rom on the rpg-maker platform was playable, including RPG Maker XP/VX/MV
folders. Rom now has a deferred `is_easyrpg_game` subquery (an RPG_RT.ldb at
the folder root), loaded with the other gallery file stats and derived from
loaded files on the with_files path, and the frontend reads it.

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

* refactor(easyrpg): drop server save sync, keep saves per user in the browser

Server sync moves to a follow-up that puts the web players on device sync.
Saves now stay in the player's IndexedDB, as js-dos does, with the same note
on the start page. The player is launched as `<rom id>-<user id>` so each
RomM account sharing a browser profile keeps its own saves; nginx and Vite
drop the user id when routing to the backend.

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

* fix(easyrpg): address Greptile review

- Start timing the play session once the player page loads
- Use object-form props in the view test's button mock
- Keep the RTP table tool's docstring to one sentence

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

* refactor(easyrpg): keep the RTP table in a fixtures folder

Matches handler/metadata/fixtures, where the other bundled data files live.

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-03 17:51:38 -04:00
Ilyas Hallak
27ddb88967 feat(api): Add a REST endpoint to start a library scan (#5014)
* Add a REST endpoint to start a library scan

POST /api/tasks/scan queues a scan with the options of the `scan` socket
event, so clients authenticating with a bearer or client token can
start one without a Socket.IO session. It answers 202 with the queued job,
409 while a library scan is queued or running, and 503 when no worker
listens on the scan queue.

The enqueue path moves into queue_scan, shared with the socket handler.
A short Redis lock now covers the in-flight check and the enqueue, so two
requests landing on different web workers cannot both queue a library
scan. The socket handler also answers scan:done_ko for an unknown scan
type instead of raising.

* Default a scan without apis to the enabled sources, lease the request lock

A scan request that leaves out `apis` now uses every enabled metadata
source, on the REST endpoint and the socket alike, as the scheduled scan
and the watcher do. An explicit empty list still means no sources. The
web UI always sends `apis`, so its scans are unchanged.

redis_lock takes an optional lease_seconds, and the library scan request
lock holds its key for 30s while waiters give up after 5s, so a slow
holder cannot lose the lock to a waiter that then queues a second scan.

* Narrow optional mock call args in the new scan tests

* pr-ready step 2 (code-review): narrow the scan lock timeout handling to acquiring the lock

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

* pr-ready step 3 (simplify): share the held-lock stub, read the task name off the queued job

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

* pr-ready step 4 (review-polish): drop a test comment that recorded old behaviour

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

* Validate socket scan options with ScanPayload and list workers once per scan request

The socket handler now parses its options with the same ScanPayload the REST
endpoint uses, so an unknown key, scan type or metadata source answers
scan:done_ko instead of falling back to a scan of everything. v1 callers that
could send a null platform id now send a real one or none.

queue_scan checks for a live scan worker itself, so the socket also refuses a
scan no worker would pick up, and it lists the workers once for that check and
the in-flight check. The blocking RQ calls run in a thread, off the event loop.

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

* Rename useScanProviders' ScanPayload to ScanSourceOptions

It shared its name with the generated ScanPayload request type while holding
only the metadata source options.

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-02 18:46:28 -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
Georges-Antoine Assi
819811b155 feat(converto): library format settings and "Download as" on the game page (#5000)
* feat(converto): integrate rom-converto for title id extraction and download conversion

* feat(converto): add conversion settings UI with per-platform format policies

* fix(converto): read conversion targets from the backend and translate the settings page

* fix(docker): ship rom-converto in the production image

Only the dev Dockerfile installed the binary, so the integration could
never enable on a released image. Fetch the same pinned, checksummed
musl build in a dedicated stage and copy it next to RAHasher.

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

* fix(converto): skip the update check and batch info calls

The CLI asks api.github.com for a newer release on every run unless
told not to, so pass --no-update-check on each invocation. Inspect a
rom's files in one `info --paths-file` run instead of one subprocess
per file, and read the inspectable extensions from the capabilities
manifest so scans skip files info cannot recognize.

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

* fix(scan): keep sigil authoritative for title ids

rom-converto ran first and overrode the ids sigil read. Sigil now runs
first and records its per-file ids; rom-converto only fills files sigil
left unset, on new or changed files, in one batch. Restore the base-id
selection for sigil extractions on every platform, as on master.

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

* fix(downloads): make conversion opt-in and bound the cache

The download endpoint returned a converted file to every client once a
platform had a target, including the browser player and apps that check
hashes against RomFile. Conversion now needs ?converted=true.

A pre-warmed copy is served whatever its size; the in-request size cap
only gates starting a conversion. ROM_CONVERTO_CACHE_MAX_SIZE_GB
(default 20, 0 unbounded) caps the cache: conversions and the pre-warm
task stop when it is full, and cleanup evicts the least recently served
copies.

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

* chore(types): regenerate frontend types for the converto schema

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

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

- Fall back to rom-converto's stored ids only when it ran this pass, in
  disc order, so a rescan that skipped extraction keeps sigil's save target
- Persist per-file title ids that extraction writes onto reused rows
- Only authenticated callers may start an in-request conversion; past a
  240s deadline serve the original and let the conversion finish into the
  cache instead of nginx returning 504
- Treat a probe OSError or timeout as a failed probe; kill the subprocess
  when the caller is cancelled
- Give the pre-warm task the scan timeout and report progress in the
  ConversionStats shape the task UI reads
- Reuse zip_cache constants, walk the cache off the event loop, tolerate
  files vanishing mid-cleanup, and trim long comments

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

* refactor(converto): simplify conversion code (pr-ready step 3)

- Move the converted-download policy (target lookup, cached-first, sync
  size cap, deadline) from the endpoint into utils/conversion_cache and
  share conversion_target with the pre-warm task
- Share one path lookup between get_cached_converted and get_or_convert;
  the pre-warm walks the cache once and tracks a running byte budget
  instead of walking it twice per rom
- One normalize_platform_formats beside TARGETS_BY_PLATFORM for the
  config loader (via _validated_platform_map) and the settings endpoint;
  update_converto_settings takes a ConvertoConfig and is written back
  with dataclasses.asdict
- read_infos owns its never-raise contract, so the scan drops its blanket
  except; drop the unused RomConvertoInfo.kind and error attributes
- Sort files for the rom-converto identity only when it is used; stat
  each cached file once during cleanup

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

* chore(converto): trim comments (pr-ready step 4)

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

* refactor(converto): convert on first download instead of pre-warming

A library pre-warm fought the TTL: cleanup dropped every copy nobody
downloaded within a day. Remove the Convert library task and convert on
demand only. Files over ROM_CONVERTO_MAX_SYNC_SIZE_MB now start their
conversion in the background while the original is served, so the next
download within the TTL gets the converted copy at any size.

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

* refactor(converto): drop decrypt and encrypt download targets

Downloads now only change a rom's container or compression (CHD, RVZ,
CSO, NSZ, ...); serving decrypted files is left for a separate decision.
NDS and PS3 have no remaining targets. Also note that the conversion
concurrency limit applies per process.

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

* refactor(converto): move the cache limits into converto.*

cache_max_size_gb and max_sync_size_mb join cache_ttl_hours in
config.yml and PUT /api/config/converto_settings, replacing the
ROM_CONVERTO_CACHE_MAX_SIZE_GB and ROM_CONVERTO_MAX_SYNC_SIZE_MB env
vars, so every eviction knob is edited in one place at runtime. The
loader takes its defaults from ConvertoConfig and one table holds each
integer's minimum for both the loader and the payload.

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

* refactor(converto): lock conversions with flock instead of a sentinel

A conversion now holds a non-blocking flock on its key dir, which the
kernel releases if the worker dies. That replaces the .partial sentinel,
its 6-hour staleness guess (which a long ROM_CONVERTO_TIMEOUT could
outlive), and the rename-aside takeover. Cleanup skips locked dirs, and
partial output gets a hidden name so it never counts as a served copy.

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

* test(converto): parametrize repeated test cases

Collapse the per-platform info parsing, operation resolution and
converto_active cases into parametrized tests, so a new platform or
target is one row.

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

* refactor(scan): run rom-converto first with sigil as the fallback

rom-converto reads each rom's new or changed files first, in one batch,
and its title ids win. sigil still reads what it can, since it alone
provides save targets and Switch content types, and fills the ids
rom-converto left unset.

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

* fix(converto): edit the cache size limits on the settings page

* feat(converto): store per-file metadata read by rom-converto during scans

* fix(converto): show the labels of the cache settings fields

* fix(scan): keep the stored save target when sigil reads nothing

* fix(converto): read Xbox 360 disc ids and Wii title versions, store content type as text

* feat(converto): save file icons, banners and backgrounds read by rom-converto

* chore(converto): bump rom-converto to v0.23.0

* fix(converto): address review findings in the conversion cache, scan metadata and settings

* refactor(converto): move per-file metadata out of the conversion PR

Scan-time metadata (title ids, the 17 rom_files columns, artwork and
converto.scan_metadata) moves to its own PR so its columns land with the
UI that reads them. This PR keeps conversion only.

The conversion cache no longer has uncompressed_size_bytes to budget
with, so a conversion to an uncompressed target reserves a fixed
multiple of its input and the cleanup pass after it evicts any overshoot.

Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ

* feat(converto): let the client pick the download format with ?format=

`?format=zso,iso` lists the formats a client can read. The stored file is
served whenever its format is listed, even with conversion off, so most
emulator clients never trigger a conversion. Otherwise the first listed
format with a cached copy is served, then the first one rom-converto can
produce.

A conversion that outlasts a short wait answers 202 with Retry-After
instead of falling back to the original, so a URL never serves two
different files and a client never gets bytes it can't read. 406 means
no listed format can be served. HEAD reports the same without starting
a conversion. This replaces `?converted=true`, the per-platform download
target and `max_sync_size_mb`; `cache_ttl_hours` stays config.yml-only.

Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ

* feat(converto): convert the library in place with a manual task

`converto.platform_formats` now names the format a platform's library is
stored in, and the new "Convert library" task brings every matched rom
to it. Each output is staged in a `.romm_tmp_` directory beside the
original, moved into place, and only then are the originals (and a cue's
tracks) deleted. Single-file roms take the new name, folder roms keep
theirs and get their .m3u entries rewritten, and the file rows refresh,
so a rom keeps its id, saves and collections.

Only lossless conversions qualify, so xbox (xiso trims the dump) has no
library format. Unmatched roms are skipped because a converted file no
longer hash-matches a DAT. `/api/config` now carries the library targets
and, per input extension, the formats a download can be converted to.

Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ

* feat(converto): library format settings and "Download as" on the game page

The settings page follows the reworked backend: per-platform formats are
now the library format the "Convert library" task stores matched games
in ("Leave as is" keeps a platform untouched), the scan metadata, cache
TTL and max-sync fields are gone, and a "Convert library now" button
starts the task behind a typed confirmation, since it deletes the
originals.

The game's More menu offers "Download as <format>" for a single-file rom
when download conversion is on, from the per-extension table
`/api/config` exposes. A one-byte ranged GET asks for the format, the UI
polls through 202s while it converts, then downloads it; a 406 shows an
error.

Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ

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

Guard the conversion settings route, add it to the user menu, ignore a
non-positive Retry-After, drop duplicate Download as clicks, name the game
in the persisted error, and tidy the settings page (display-name sort,
useUnloadGuard, decimal cache sizes, save snapshot).

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

* refactor(settings): share the config alerts and save bar (pr-ready step 3)

Extract ConfigFileAlerts and SettingsSaveBar from the three settings
views that copied them, move ScanSettings onto useUnloadGuard, align the
retry slot, and flatten downloadFormats, getDownloadFormats and the
format poll loop.

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

* chore(converto): trim comments (pr-ready step 4)

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

* feat(converto): guard destructive tasks and serve download formats per rom

- TaskSpec gains destructive and single_instance. The Tasks list asks for a
  typed confirmation before a destructive task, and POST /tasks/run answers
  409 while a single-instance task is queued or running.
- convert_library is both, and only runnable with ROM_CONVERTO_ENABLED.
- The heartbeat reports CONVERTO.ENABLED, which hides Conversion settings
  from the sidebar and user menu and warns on the page.
- DetailedRomSchema.download_formats lists what the caller can convert the
  rom's single file to, resolved by the backend's own operation table and
  empty for visitors who can't start a conversion. It replaces
  CONVERTO_DOWNLOAD_FORMATS in /api/config and the frontend's copy of the
  extension matching.

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

---------

Co-authored-by: Yukine <devyukine@gmx.de>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: DevYukine <20647088+DevYukine@users.noreply.github.com>
2026-10-01 21:46:29 -04:00
Sam Dornan
3b4e230b7c Upgrade SQLAlchemy to 2.1 (#5007) 2026-10-01 19:17:30 -04:00
Georges-Antoine Assi
640a783f3f feat(converto): convert the library in place and serve downloads in a requested format (#4999)
* feat(converto): integrate rom-converto for title id extraction and download conversion

* fix(docker): ship rom-converto in the production image

Only the dev Dockerfile installed the binary, so the integration could
never enable on a released image. Fetch the same pinned, checksummed
musl build in a dedicated stage and copy it next to RAHasher.

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

* fix(converto): skip the update check and batch info calls

The CLI asks api.github.com for a newer release on every run unless
told not to, so pass --no-update-check on each invocation. Inspect a
rom's files in one `info --paths-file` run instead of one subprocess
per file, and read the inspectable extensions from the capabilities
manifest so scans skip files info cannot recognize.

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

* fix(scan): keep sigil authoritative for title ids

rom-converto ran first and overrode the ids sigil read. Sigil now runs
first and records its per-file ids; rom-converto only fills files sigil
left unset, on new or changed files, in one batch. Restore the base-id
selection for sigil extractions on every platform, as on master.

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

* fix(downloads): make conversion opt-in and bound the cache

The download endpoint returned a converted file to every client once a
platform had a target, including the browser player and apps that check
hashes against RomFile. Conversion now needs ?converted=true.

A pre-warmed copy is served whatever its size; the in-request size cap
only gates starting a conversion. ROM_CONVERTO_CACHE_MAX_SIZE_GB
(default 20, 0 unbounded) caps the cache: conversions and the pre-warm
task stop when it is full, and cleanup evicts the least recently served
copies.

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

* chore(types): regenerate frontend types for the converto schema

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

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

- Fall back to rom-converto's stored ids only when it ran this pass, in
  disc order, so a rescan that skipped extraction keeps sigil's save target
- Persist per-file title ids that extraction writes onto reused rows
- Only authenticated callers may start an in-request conversion; past a
  240s deadline serve the original and let the conversion finish into the
  cache instead of nginx returning 504
- Treat a probe OSError or timeout as a failed probe; kill the subprocess
  when the caller is cancelled
- Give the pre-warm task the scan timeout and report progress in the
  ConversionStats shape the task UI reads
- Reuse zip_cache constants, walk the cache off the event loop, tolerate
  files vanishing mid-cleanup, and trim long comments

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

* refactor(converto): simplify conversion code (pr-ready step 3)

- Move the converted-download policy (target lookup, cached-first, sync
  size cap, deadline) from the endpoint into utils/conversion_cache and
  share conversion_target with the pre-warm task
- Share one path lookup between get_cached_converted and get_or_convert;
  the pre-warm walks the cache once and tracks a running byte budget
  instead of walking it twice per rom
- One normalize_platform_formats beside TARGETS_BY_PLATFORM for the
  config loader (via _validated_platform_map) and the settings endpoint;
  update_converto_settings takes a ConvertoConfig and is written back
  with dataclasses.asdict
- read_infos owns its never-raise contract, so the scan drops its blanket
  except; drop the unused RomConvertoInfo.kind and error attributes
- Sort files for the rom-converto identity only when it is used; stat
  each cached file once during cleanup

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

* chore(converto): trim comments (pr-ready step 4)

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

* refactor(converto): convert on first download instead of pre-warming

A library pre-warm fought the TTL: cleanup dropped every copy nobody
downloaded within a day. Remove the Convert library task and convert on
demand only. Files over ROM_CONVERTO_MAX_SYNC_SIZE_MB now start their
conversion in the background while the original is served, so the next
download within the TTL gets the converted copy at any size.

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

* refactor(converto): drop decrypt and encrypt download targets

Downloads now only change a rom's container or compression (CHD, RVZ,
CSO, NSZ, ...); serving decrypted files is left for a separate decision.
NDS and PS3 have no remaining targets. Also note that the conversion
concurrency limit applies per process.

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

* refactor(converto): move the cache limits into converto.*

cache_max_size_gb and max_sync_size_mb join cache_ttl_hours in
config.yml and PUT /api/config/converto_settings, replacing the
ROM_CONVERTO_CACHE_MAX_SIZE_GB and ROM_CONVERTO_MAX_SYNC_SIZE_MB env
vars, so every eviction knob is edited in one place at runtime. The
loader takes its defaults from ConvertoConfig and one table holds each
integer's minimum for both the loader and the payload.

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

* refactor(converto): lock conversions with flock instead of a sentinel

A conversion now holds a non-blocking flock on its key dir, which the
kernel releases if the worker dies. That replaces the .partial sentinel,
its 6-hour staleness guess (which a long ROM_CONVERTO_TIMEOUT could
outlive), and the rename-aside takeover. Cleanup skips locked dirs, and
partial output gets a hidden name so it never counts as a served copy.

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

* test(converto): parametrize repeated test cases

Collapse the per-platform info parsing, operation resolution and
converto_active cases into parametrized tests, so a new platform or
target is one row.

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

* refactor(scan): run rom-converto first with sigil as the fallback

rom-converto reads each rom's new or changed files first, in one batch,
and its title ids win. sigil still reads what it can, since it alone
provides save targets and Switch content types, and fills the ids
rom-converto left unset.

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

* feat(converto): store per-file metadata read by rom-converto during scans

* fix(scan): keep the stored save target when sigil reads nothing

* fix(converto): read Xbox 360 disc ids and Wii title versions, store content type as text

* feat(converto): save file icons, banners and backgrounds read by rom-converto

* chore(converto): bump rom-converto to v0.23.0

* fix(converto): address review findings in the conversion cache, scan metadata and settings

* refactor(converto): move per-file metadata out of the conversion PR

Scan-time metadata (title ids, the 17 rom_files columns, artwork and
converto.scan_metadata) moves to its own PR so its columns land with the
UI that reads them. This PR keeps conversion only.

The conversion cache no longer has uncompressed_size_bytes to budget
with, so a conversion to an uncompressed target reserves a fixed
multiple of its input and the cleanup pass after it evicts any overshoot.

Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ

* feat(converto): let the client pick the download format with ?format=

`?format=zso,iso` lists the formats a client can read. The stored file is
served whenever its format is listed, even with conversion off, so most
emulator clients never trigger a conversion. Otherwise the first listed
format with a cached copy is served, then the first one rom-converto can
produce.

A conversion that outlasts a short wait answers 202 with Retry-After
instead of falling back to the original, so a URL never serves two
different files and a client never gets bytes it can't read. 406 means
no listed format can be served. HEAD reports the same without starting
a conversion. This replaces `?converted=true`, the per-platform download
target and `max_sync_size_mb`; `cache_ttl_hours` stays config.yml-only.

Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ

* feat(converto): convert the library in place with a manual task

`converto.platform_formats` now names the format a platform's library is
stored in, and the new "Convert library" task brings every matched rom
to it. Each output is staged in a `.romm_tmp_` directory beside the
original, moved into place, and only then are the originals (and a cue's
tracks) deleted. Single-file roms take the new name, folder roms keep
theirs and get their .m3u entries rewritten, and the file rows refresh,
so a rom keeps its id, saves and collections.

Only lossless conversions qualify, so xbox (xiso trims the dump) has no
library format. Unmatched roms are skipped because a converted file no
longer hash-matches a DAT. `/api/config` now carries the library targets
and, per input extension, the formats a download can be converted to.

Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ

* fix(converto): address Greptile and Copilot review findings

- Publish a converted library file with a no-replace link, so a file that
  appears during conversion is never overwritten.
- Delete originals only after the rom row or its playlists point at the new
  file, and keep them if that update fails. Playlists are rewritten atomically.
- Refuse a cue conversion whose tracks another rom or another cue holds.
- Remove stage dirs a killed conversion left behind.
- Try later ?format= targets when a conversion fails, treat any locked key dir
  as converting, and cap how many conversions downloads can start.
- Drop the unsupported iso target for CD platforms from the example config and
  list the ROM_CONVERTO_* variables in env.template.

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

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

Serve converted outputs at 0644, read cue sheets and playlists with a BOM,
stage folder rom conversions outside the rom folder, keep one rom's failure
from stopping the convert library task, accept alias extensions as the stored
format, probe running conversions with a shared lock, and bound the timeout.

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

* refactor(converto): simplify conversion code (pr-ready step 3)

Check and chmod rom-converto output once in the adapter, canonicalize
requested format aliases, reuse LINK_FALLBACK_ERRNOS and the handler's atomic
write, make the download format table a constant, skip the probe lock once
cached, and fold duplicated name checks and cache stat passes.

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

* chore(converto): trim comments (pr-ready step 4)

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

* refactor(converto): find rom-converto on PATH instead of ROM_CONVERTO_PATH

Both images install the binary on PATH, the variable was undocumented,
and RAHasher is already resolved the same way.

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

---------

Co-authored-by: Yukine <devyukine@gmx.de>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: DevYukine <20647088+DevYukine@users.noreply.github.com>
2026-10-01 19:02:37 -04:00
Georges-Antoine Assi
54e377ca9d Merge pull request #4982 from rommapp/claude/rq-slim-imports-7m0jrn
perf: keep task code out of the cron scheduler and idle RQ workers
2026-10-01 12:16:26 -04:00
Georges-Antoine Assi
17765df6b2 fix(tasks): keep failure reports and queue choice on the task spec
report_task_failure can run in the worker parent when a work horse is
killed, so it now enqueues notify_task_failure on the default queue
instead of loading the notification stack there.

enqueue_task defaults to the queue its spec names. The streaming worker
runs as PreloadingWorker, which imports the enabled scheduled tasks of
its queues, so the reaper's per-minute horse inherits its stack. Spec
tests now read config in a fresh interpreter instead of comparing a
value with itself.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 11:29:52 -04:00
Sam Dornan
a31136cd21 Keep the FULLTEXT index on searches with short words or stopwords (#4970) 2026-09-30 22:45:44 -04:00
Claude
1e6dd1a2ac perf: keep task code out of the cron scheduler and idle RQ workers
The registry imported every task module to read each task's title,
schedule, queue and timeout, so `rq cron` and every RQ worker parent
loaded the whole app. Task metadata now lives in the registry as
`TaskSpec`s with a dotted path to the implementation, which `get_task`
imports only when a job runs. Cron, the tasks API, enqueueing and the
worker's failure reporting read specs only.

Every log line also imported handler.metadata.base_handler, and with
it every metadata provider, for the redaction regex. The sensitive keys
and their regex now live in logger.formatter.

A test pins that importing the cron config or the worker class loads
neither handler.database, the auth handlers nor fastapi.

Measured RSS at LOGLEVEL=INFO, master -> this branch:
- rq cron: 164 MB -> 72 MB
- idle RQ worker (x3): 133 MB -> 68 MB
- gunicorn web worker: 214 MB -> 206 MB

Each job's work horse now imports its task module itself, 0.1-0.5s
more per job on an x86 host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gh1SRMfuK7BZmf6YxMqSyT
2026-10-01 01:32:21 +00:00
Sam Dornan
6941de13db Remove unused code and deduplicate copied helpers (#4975) 2026-09-30 18:51:36 -04:00
Georges-Antoine Assi
ce980b677f Merge pull request #4957 from beemines/feat/configurable-cleanup-schedules
feat: make netplay and upload cleanup schedules configurable
2026-09-30 16:48:05 -04:00
Georges-Antoine Assi
8be4802e26 Make ZIP cache and sync session cleanup schedules configurable
Adds ENABLE_SCHEDULED_CLEANUP_ZIP_CACHE, SCHEDULED_CLEANUP_ZIP_CACHE_CRON,
ENABLE_SCHEDULED_CLEANUP_SYNC_SESSIONS and SCHEDULED_CLEANUP_SYNC_SESSIONS_CRON,
defaulting to the previous hardcoded behavior.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 16:32:50 -04:00
Georges-Antoine Assi
7fc4722c23 pr-ready: code-review fixes
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 16:18:19 -04:00
Sam Dornan
79fbce6beb test(backend): build test rows through shared factories and enforce them with ruff (#4972)
* test(backend): build test ROMs through one make_rom factory

Tests created Rom rows by hand in dozens of places, each spelling out the
same slug and filename fields and deriving the slug inline. Production never
computes a slug from a name, so this was test-only filler duplicated across
files.

tests/factories.py adds make_rom(platform, name, *, fs_stem, fs_extension,
**overrides), which fills the slug and filename columns and persists through
db_rom_handler.add_rom. The shared conftest fixtures, scan_stubs.add_rom and
the local helpers and inline constructors across 35 test files now use it.
Each test keeps its filename shape (underscored stems in the FULLTEXT search
tests, spaced "Name (USA)" stems in the sibling tests), and fixtures shared
across files keep their exact slugs.

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

* test(backend): keep extensionless filenames intact in scan_stubs.add_rom

rpartition(".") on a name with no dot returned an empty stem and the whole
name as the extension, so make_rom stored ".README" for "README".
os.path.splitext leaves such names whole.

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

* test(backend): build test saves, states and screenshots through factories

Tests built Save, State and Screenshot rows by hand across about 20 files,
each spelling out file_name_no_tags, file_name_no_ext and file_extension
although BaseAsset already derives them from file_name.

tests/factories.py adds make_save, make_state and make_screenshot. Each sets
the rom and user ids, the file name, and a default file_path under the rom's
platform, applies overrides last, and persists through the matching db
handler. The conftest asset fixtures and the persisted constructors and local
helpers now use them. Rows a test observes keep their file_path, emulator,
slot, size and hash, and a filename part stays an override wherever it
differs from what the model derives.

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

* test(backend): ban direct add_* persistence in tests via ruff TID251

The factories only stay the one home for test rows if nothing routes
around them. Ruff's banned-api rule now flags db_rom_handler.add_rom,
db_save_handler.add_save, db_state_handler.add_state and
db_screenshot_handler.add_screenshot anywhere under tests/ except
tests/factories.py. Production code is unaffected.

The remaining add_rom calls move onto make_rom: the unique-path, soundtrack
and id-index tests in test_roms_handler.py, the scan tests in
test_fastapi.py, physical and missing rows in the feed, download and model
tests, and the name=None exporter rows. Scan tests keep a filename-derived
placeholder as the name, which scan_rom treats the same as no name. Three
calls keep a noqa: the tests of how add_rom merges a partial scanned row,
and the rescan test that persists scan_rom's output as a scan does.

The backend skill and the architecture doc now point at tests/factories.py.

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

* test(backend): move the firmware and client-token factories into tests/factories.py

The add_firmware and add_device_token conftest fixtures returned a builder,
unlike the importable make_* functions. They become make_firmware and
make_device_token alongside them, with the same defaults, and their callers
import them rather than requesting a fixture. make_device_token now draws the
raw credential from auth_handler.generate_client_token, so it carries the
real rmm_ prefix instead of restating it, and the hand-built client tokens in
the auth tests use it too.

The ruff TID251 ban now also covers db_firmware_handler.add_firmware and
db_client_token_handler.add_token under tests/.

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

* docs: point at every test factory, not just the ROM and asset ones

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:01:56 -05:00
Georges-Antoine Assi
8b7a6464fb fix(auth): address Greptile review on OIDC identity matching
- Match on (issuer, sub) with exact collation, so subjects from another
  provider or differing only in case never match.
- Refuse a login whose email is linked to another subject at the same
  issuer instead of rebinding the account; relink only across issuers.
- Check the account is enabled before saving identity changes.
- Keep the old email when it is claimed between the check and the write.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 17:34:14 -04:00
Georges-Antoine Assi
9d4bb40a6d fix(auth): match OIDC users by their sub claim so an email change still logs in
Store the provider's `sub` on a new nullable users.oidc_sub column, look users
up by it first and fall back to email, backfilling the sub on the next login. A
user matched by sub gets their stored email updated, unless another account
already holds it.

Fixes #1690

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 17:34:14 -04:00
Georges-Antoine Assi
1027cc3832 Merge pull request #4852 from rommapp/fix/7z-hash-timeout-scales-with-size
fix(scan): raise the 7-Zip timeout default and keep partial bytes out of the fallback hash
2026-09-28 08:08:07 -04:00
Georges-Antoine Assi
d6530463f6 fix(scan): raise the default SEVEN_ZIP_TIMEOUT to 180 seconds
Sixty seconds cut off extraction of mid-sized disc images, so their scan
fell back to hashing the archive itself.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 07:55:49 -04:00
Georges-Antoine Assi
e7e3b4b2b6 refactor(device): move device auth and tests into the device packages
- endpoints/device_auth.py -> endpoints/device/auth.py (and its response module)
- Device and install handler tests mirror the new package layout
- The install router is included by the device router, so main.py mounts one
  /devices router plus the /auth/device one
- GET /api/devices/online moves to the install routes and 404s while
  DEVICE_INSTALL_ENABLED is off, like the rest of them

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 16:06:45 -04:00
Georges-Antoine Assi
673c1b1052 refactor(device): nest device endpoints, responses and install handler in packages
- endpoints/device.py, device_install.py -> endpoints/device/__init__.py, install.py
- endpoints/responses/device.py, device_install.py -> endpoints/responses/device/__init__.py, install.py
- handler/device_install_handler.py, device_install_policy.py -> handler/device_install/__init__.py, policy.py

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 15:55:42 -04:00
nendo
f0c49b6a38 feat(devices): push downloads from the web UI to a device's download queue 2026-09-28 02:08:03 +09:00
Sam Dornan
3206bc541f chore(deps): move from httpx to httpx2 (#4830) 2026-09-26 21:17:13 -04:00
Sam Dornan
9c1e6b2d86 refactor(backend): move engine-specific query SQL out of handlers into utils/sql_dialect.py (#4793) 2026-09-26 13:48:33 -04:00
Georges-Antoine Assi
4bcc9da844 refactor(netplay): apply simplify pass
- Move connect-time user resolution and login-session binding into
  SocketHandler.authenticate, shared by the /ws and netplay servers.
- Add SocketHandler.get_session and drop the per-module copies.
- Fold disconnect into leave-room, and the user load into the ROM gate.
- Read the room password only from the field EmulatorJS sends.
- Close both servers' sockets for a revoked session concurrently.
- Correct the join-room password rule in the architecture doc.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:03:08 -04:00
Georges-Antoine Assi
2af79c1486 fix(netplay): apply code-review xhigh findings
- Bind netplay sockets to their login session, keying the socket set per
  channel so revoking a session closes sockets on both servers.
- Read the room password from the top-level field EmulatorJS sends, and
  compare it in constant time.
- Namespace Socket.IO room names so a room id cannot collide with a sid.
- Refuse a duplicate player id on join, and leave the current room before
  opening or joining another.
- Coerce client-supplied maxPlayers and names, and store the resolved ROM id.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 12:50:37 -04:00
Georges-Antoine Assi
00cfeeac77 Merge remote-tracking branch 'origin/master' into claude/netplay-auth
# Conflicts:
#	backend/endpoints/sockets/netplay.py
2026-09-25 12:30:17 -04:00
Georges-Antoine Assi
aa80073d34 feat(streaming): run exit save pulls on the streaming worker
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:34:05 -04:00
Georges-Antoine Assi
9131ac9f43 Merge remote-tracking branch 'origin/master' into streaming-reaper
# Conflicts:
#	backend/tasks/registry.py
2026-09-25 10:45:52 -04:00
Georges-Antoine Assi
e1052665c1 feat(streaming): run the session reaper on a streaming queue with a worker of its own
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 09:46:35 -04:00
Georges-Antoine Assi
22aa445d27 fix(streaming): hold the reaper off for a stale window after a restart, schedule it only with streaming on, and warn about later pools once across processes
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 09:29:48 -04:00
Georges-Antoine Assi
29e6b8c1e9 fix(streaming): keep a claim fresh through its setup, log what spawned work raised, and notify a task's success only after that work ends (code-review)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 08:40:50 -04:00