* 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>
22 KiB
RomM Frontend Architecture
A map of the RomM frontend (frontend/): a Vue 3 single-page app that talks to the backend over /api/* (REST) and /ws (Socket.IO). This document says where things live and how they fit together. The detailed rules for writing UI code live in the skills under .claude/skills/ (frontend-components, frontend-theming, frontend-input, frontend-patterns, frontend-i18n), and commands are in frontend/AGENTS.md.
Contents
- Stack
- Layers and directories
- Startup
- Routing
- State: Pinia stores
- API, caching and real time
- Components
- Styling and theming
- Input and responsive layout
- Players
- Internationalization
- Types
- Build, test and tooling
1. Stack
| Concern | Choice |
|---|---|
| Framework | Vue 3 (<script setup>, TypeScript) |
| Build | Vite, with Lightning CSS as the CSS transformer |
| State | Pinia |
| Routing | Vue Router (history mode, lazy route components) |
| HTTP | Axios against /api, CSRF header on every request |
| Real time | socket.io-client at /ws/socket.io/ |
| i18n | vue-i18n, one lazy-loaded JSON file per locale and namespace |
| Styling | Generated design tokens plus per-component scoped CSS. No component library, no utility framework |
| Icons | @mdi/font, trimmed at build time to the icons the source uses |
| Tests | Vitest (happy-dom unit tests, plus Storybook play() tests in Chromium), Playwright for e2e |
There is no Vuetify and no Tailwind. A small hand-written base reset lives in src/styles/reset.css.
2. Layers and directories
flowchart TD
Views["views/ + layouts/<br/>(route-level pages)"] --> Components["components/<br/>(feature composites)"]
Components --> Lib["lib/<br/>(R* primitives)"]
Views --> Composables["composables/"]
Components --> Composables
Composables --> Stores["stores/ (Pinia)"]
Stores --> Services["services/<br/>(api, cache, socket)"]
Services --> Backend[("backend<br/>/api and /ws")]
Lib --> Tokens["tokens/ → styles/tokens.css"]
Everything lives under frontend/src/ and is imported through the @/ alias (scripts/aliases.ts, shared by the app build, Vitest and Storybook).
| Directory | What it holds |
|---|---|
RomM.vue, main.ts |
Root component (theme classes, backend status banner, <router-view>) and the bootstrap. |
views/ |
One component per route: Home, Gallery/{Platform,Collection,Search}, GameDetails, Jukebox/, Player/*, Auth/*, Settings pages, pairing. |
layouts/ |
AppLayout (main shell: nav, mini player, global composables), AuthLayout, SettingsLayout. |
components/ |
Feature composites, grouped by feature (Gallery, GameDetails, Settings, Player, Scan, Dialogs, ...) plus shared/ for cross-feature ones. |
lib/ |
The design-system primitives, R* components, in tiers: primitives, structural, forms, menus, overlays, data, media, plus a11y. |
composables/ |
Reusable logic: input (useGamepad, useSpatialNav, useGridNav, useInputModality), responsive (useBreakpoint), gallery URL state, player, socket. |
stores/ |
Pinia stores (section 5). |
services/ |
api/ (one module per backend area), cache/ (response cache), socket.ts, plus native-app helpers. |
plugins/ |
index.ts (Pinia, i18n and the event emitter), router.ts (routes and guards), routeNames.ts, view-transition helpers, md-editor wrapper. |
router/routes.ts |
Lazy route-component registry and the layout loaders. |
tokens/, styles/ |
Design tokens in TypeScript and the generated styles/tokens.css, plus fonts.css, global.css, reset.css, scrollbar.css. |
locales/ |
One folder per locale, one JSON file per namespace, plus the loader and two CI check scripts. |
types/ |
Hand-written shared types, including the typed event map (emitter.d.ts). |
__generated__/ |
Types generated from the backend's OpenAPI schema. Never edited by hand. |
utils/ |
Pure helpers (covers, formatting, player runtimes, storage, validation). |
Outside src/: e2e/ (Playwright), .storybook/, scripts/ (build plugins and the token generator), eslint-plugin-romm/ (repo-specific lint rules), public/ and assets/ (static files and emulator payloads).
3. Startup
main.ts does the following, in order:
- Imports the icon font and the global stylesheets (
fonts,global,reset,scrollbar). - Creates the app and registers plugins: Pinia, i18n, and a typed
mittevent emitter provided asemitter. - Starts syncing the per-user localStorage namespace with the signed-in user (
setStorageUser), synchronously, so stored preferences switch user before anything renders. - Provides the accessible-name labels the
R*primitives use for their own controls (ChromeLabelsKey). - Awaits, together, the initial data (
heartbeat, current user, config) and the locale messages. The router waits for both because the first guard resolves the page title. - Installs the router and mounts
#app.
Stale chunks after a redeploy are handled once, by a guarded reload on vite:preloadError and on router import errors.
RomM.vue puts r-app and r-dark or r-light on <html>, driven by the settings.theme preference (auto, dark, light) and prefers-color-scheme. The classes live on <html> so overlays that teleport to <body> resolve the same tokens.
4. Routing
Routes are declared in plugins/router.ts, named in plugins/routeNames.ts (ROUTES), and bound to lazy components in router/routes.ts; read those for the current list. Three layouts:
auth: setup, login, registration and password reset.main(AppLayout): home, search, music, the platform and collection galleries, and the ROM routes:/rom/:romplus one player route per engine (section 10).settings(SettingsLayout, nested inmain, the sidebar and content-panel shell): scan, upload, activity, notifications, profiles and the settings pages.- Device pairing sits outside the layouts, under
/pair.
The global beforeEach guard:
- If the backend is unreachable, lets navigation through on cached state (a banner explains it and re-routes once the backend answers).
- Sends everyone to
/setupwhile the setup wizard is pending, and away from it afterwards. - Sends unauthenticated users to
/login?next=...unless the route is auth-exempt (login,setup,reset-password,register,pair). - Checks
ROUTE_SCOPES(for examplescanneedsplatforms.write,administrationneedsusers.write) against the user's OAuth scopes and sends a user without them to the 404 view. - Applies the route title (
meta.titleis a locale key; views that own their title callusePageTitle).
beforeResolve runs a View Transition for real view changes (not for query-only changes). Scroll and focus restoration across navigations live in stores/scrollRestoration and stores/focusRestoration.
5. State: Pinia stores
One store per concern lives in stores/: session and server state (auth, heartbeat, config, permissions), the library (platforms, collections, the gallery stores, roms), playing, background work (scanning, upload, tasks), notifications and navigation.
Two worth knowing:
galleryRomsis the gallery list. It is windowed: a sparsebyPositionmap filled by random-access window fetches as rows enter the virtualiser's viewport, plus a total count and a per-letter offset table from the backend. The gallery context (current platform or collection) lives here.galleryFilterholds filters;gallerySelectionholds multi-select.romsholds what the gallery doesn't: a small LRU cache of detailed ROM records (detailedRoms, read throughgetDetailedRomanduseRouteRom),currentRom, and Home's recent and continue-playing rows.
Logout calls reset() on every store that defines one. Per-user preferences are not in Pinia: they are useUserLocalStorage keys, namespaced by user id (an ESLint rule forbids unscoped localStorage access).
6. API, caching and real time
REST. services/api/index.ts creates the Axios instance (baseURL: "/api", repeated-key array params, 120 s timeout) and interceptors: the x-csrftoken header from the romm_csrftoken cookie, in-flight tracking that emits a network-quiesced DOM event, reachability events (backend-online, backend-offline, backend-suspect) that useServerConnection turns into the status banner, a CSRF-token refetch when the backend rejects the token, and 401 handling that clears the session cookie and sends the user to the login page. Each backend area has its own module (rom.ts, platform.ts, collection.ts, save.ts, state.ts, sync.ts, ...) returning typed responses. Large uploads go through chunked upload helpers in rom.ts.
Types. Request and response shapes come from __generated__/, regenerated from the backend OpenAPI schema (npm run generate). The backend is the source of truth for the API contract.
Response cache. services/cache/ is an optional stale-while-revalidate cache on top of the browser Cache API, behind the user setting settings.enableExperimentalCache. Home's recent and continue-playing requests use it. The roms store's add and remove helpers for those rows clear the matching cached responses; other writes, such as metadata edits through applyRomWrite, do not.
Socket.IO. services/socket.ts exports one client (autoConnect: false). It connects on demand (scanning, uploads and activity presence call socket.connect() when they need it), and AppLayout reconnects it on mount. Views and composables subscribe through useSocketEvent or socket.on and emit directly. Events in use:
- scanning: emit
scanandscan:stop; receivescan:scanning_platform,scan:scanning_rom,scan:update_stats,scan:done,scan:done_ko(consumed byuseScanLifecycle, which batches per-ROM updates); - presence and play activity:
activity:heartbeat,activity:start,activity:stop, andactivity:update/activity:refresh/activity:clear; permissions:changed:installPermissionsHydration()(inuseCan, called from each layout) re-fetches/permissions/meinto the permissions store, and the activity store re-lists the sessions the user may see. Route-guard scopes (auth.user.oauth_scopes) come with the user record, not from this event.
useSocketTransportHealth and useServerConnection feed the backend-status banner.
Cross-store consistency. The same ROM can sit in the gallery window map, Home's rows and the detail cache. useRomSync is the single place that writes a changed ROM into all of them, so callers don't update each store by hand.
7. Components
Three tiers, each importing only from the tiers below it:
lib/primitives (RBtn,RTextField,RSelect,RDialog,RTable, ...). Presentation plus accessible behaviour only: no stores, no API calls. Each has a Storybook story, and an interactive one has aplay()test that runs axe.components/shared/composites: reusable combinations of primitives that know about app concepts (a platform picker, a language selector).- Feature composites under
components/<feature>/and theviews/that compose them. These own data fetching and store access.
Conventions that matter day to day: the lib/ barrel (@/lib) exports the primitives; dialogs mount once, in GlobalDialogs inside AppLayout, and open through emitter events (emitter.emit("showXDialog", ...), typed in types/emitter.d.ts); overlays push themselves on the escape stack (lib/overlays/RDialog/escapeStack). See the frontend-components and frontend-patterns skills for the SFC structure, import order, loading and error patterns, and the "no duplicated coverage between Vitest and Storybook" testing rule.
8. Styling and theming
- Tokens are defined once in
src/tokens/index.tsand compiled tosrc/styles/tokens.cssbyscripts/build-tokens.ts(npm run build:tokens, run automatically beforedevandbuild). Components readvar(--r-...); hex colour literals are lint errors (romm/no-color-literal). - Themes are the
r-darkandr-lightclasses on<html>(section 3). Each themed colour is onelight-dark(<light>, <dark>)declaration resolved bycolor-scheme:html.r-appsetslight dark(the OS preference), and the two classes pin it. The generator pairs the palettes by name and fails the build if a token exists in only one. - Stylesheets loaded globally:
fonts.css(self-hosted fonts),global.css(the.r-appbase, backdrop layers),reset.css(the base reset, in@layer base, plus the full-height app shell),scrollbar.css. - Component styles are scoped SFC
<style>blocks. Layout switches use thehtml[data-bp~="..."]attribute selectors rather than@media(section 9). - Boot splash.
index.htmlcarries a tiny inline style so the first paint matches the theme before the app mounts. - Icons.
@mdi/fontis imported once inmain.ts; thetrimMdiIconsbuild plugin drops every icon the source never names.
The frontend-theming skill covers the token vocabulary, state colours and the zero-literal policy.
9. Input and responsive layout
Every interactive surface works with mouse, touch, keyboard and gamepad. There is one model: the gamepad is translated into keyboard events, so components handle keys and a pad works for free.
useGamepadpolls the pad and emits synthetic arrow, Escape and click events.useSpatialNavmoves focus to the nearest control for arrows nobody claimed.useGridNavadds per-view 2D grid behaviour.useGlobalHotkeyshandles/,?and theg h/g p/g csequences, and ignores keys a widget already claimed withpreventDefault.- The claim rule: a handler that uses a key calls
preventDefault; one that doesn't leaves the key alone. Escape closes the topmost entry on the escape stack, and an unclaimed pad B navigates back. useInputModalitysetsdata-input="mouse|touch|key|pad"on<html>; focus rings show only forkeyandpad.- Breakpoints come from one place,
useBreakpoint, using the Material thresholds (xsunder 600 px up toxlfrom 1920 px).installBreakpointAttribute()mirrors the active set onto<html data-bp="...">, and CSS selects on it. Conditional mounting uses the composable's refs.
While a game runs (playing store), the pad and keyboard belong to the emulator and the above is suspended. The frontend-input skill has the details.
10. Players
Each engine has a view under views/Player/ and its own route:
| Route suffix | Engine / view | Notes |
|---|---|---|
ejs |
EmulatorJS (EmulatorJS.vue) |
Most consoles, and plain DOS through the dosbox_pure core. Cores are served from frontend/assets/emulatorjs under /assets/emulatorjs. |
jsdos |
js-dos (JsDos.vue) |
Windows 3.x and 9x (win3x, win9x), and only .jsdos bundles. |
pico8 |
PICO-8 (Pico8.vue) |
Own runtime and audio worklet under utils/. |
easyrpg |
EasyRPG (EasyRpg.vue) |
Game files are fetched per ROM; nginx (and the Vite dev proxy) rewrite /assets/easyrpg/games/<rom id>-<user id>/... to /api/roms/<rom id>/easyrpg/.... |
ruffle |
Ruffle (Ruffle.vue) |
Flash. |
stream |
Streaming (Stream.vue, Desktop.vue) |
Remote play. |
useCanPlay decides whether a ROM is playable in this browser (admin toggles, platform support, a file to boot, a streaming container, or a local emulator in the desktop shell); usePlatformPlayable answers the same for a whole platform. ejs and jsdos run cross-origin isolated (COOP and COEP headers, set by nginx in production and by scripts/playerIsolationHeaders.ts in dev and preview; a test fails if the two drift). Headers apply only to a document load, so a route change into a player is not enough when the engine needs SharedArrayBuffer (js-dos always does; EmulatorJS only for threaded cores): the view relaunches into an isolated document with useIsolatedLaunch (the pre-play selection crosses as a per-tab intent). On the way out, usePlayerExit replaces the document instead of navigating, because isolation outlives SPA navigations and blocks the third-party images the rest of the app embeds. Save states, saves and play sessions go through services/api/{state,save,play-session}.ts, with useDeviceSaveSync and usePendingAssetSync reconciling device saves.
EmulatorJS is a snapshot client (utils/saveSync/snapshotSession.ts). sessionTarget picks the channel: the booted snapshot's, else the booted save's, else the one the slot names (autosave files into default), created by the first push. Every SRAM write and state capture pushes onto the snapshot the last push made. A session that booted an older snapshot rewinds the channel on its first push, and once another device moves the channel on, the server keeps the session's pushes as a branch. A push the server can't take yet waits in pendingAssetStore and replays as recorded. "Play from here" in the snapshot drawer opens /rom/:id/ejs?snapshot=<id>[&state=<id>], and snapshotId rides the launch intent across the isolation reload.
11. Internationalization
All user-visible text is a message key, written t("namespace.key"). Locale files are src/locales/<locale>/<namespace>.json, one namespace per feature area. en_US is the source and the fallback; every key must exist in every locale in the same change, and keys stay sorted. src/locales/index.ts loads one locale's namespaces lazily with import.meta.glob, and the browser language picks the default (exact region first, then language). Two CI scripts enforce parity and ordering: check_i18n_locales.py and check_i18n_sorted.py. See the frontend-i18n skill.
12. Types
__generated__/: OpenAPI-derived models. Regenerate, never edit.- Store files re-export the domain aliases the app uses (
SimpleRom,DetailedRominstores/roms.ts). types/: shared hand-written types, the typed emitter event map, and ambient declarations for the player libraries.
13. Build, test and tooling
Scripts live in frontend/package.json, and frontend/AGENTS.md explains the common ones. typecheck (vue-tsc --build) covers the app, the Node tooling and the e2e suite.
Vite (vite.config.js): the Vue plugin, PWA, and project plugins from scripts/ (precompress for static assets, playerIsolationHeaders, previewAssets, platformIconManifest, trimMdiIcons). The dev server proxies /api, /ws, /netplay and /openapi.json to the backend (DEV_PORT or DEV_PROXY_TARGET).
Tests (vitest.config.ts, three projects):
app: unit and component tests (src/**/*.test.ts).storybook: every story in headless Chromium, withplay()interactions and an axe pass (layout enabled, so colour contrast is checked) on each.eslint-plugin-romm: the repo's custom lint rules, one file each undereslint-plugin-romm/rules/.
e2e/ holds the Playwright suite (smoke loads, auth, ROM actions, an axe check per page); see e2e/README.md.
Lint and format run through Trunk (trunk fmt && trunk check), which wraps ESLint, Prettier and the rest. CI (.github/workflows/) runs typecheck, tests, build, the boot check, e2e, i18n parity, and the API-types check that fails when the committed __generated__/ drifts from the backend schema.