From d8e482034d4fbf7795d83e9fcb39c5543ba4bb38 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 16 Sep 2026 15:05:46 +0000 Subject: [PATCH 001/332] chore(deps): update mariadb docker tag to v13 --- .github/workflows/copilot-setup-steps.yml | 2 +- .github/workflows/e2e.yml | 2 +- .github/workflows/migrations.yml | 4 ++-- .github/workflows/pytest.yml | 2 +- backend/docker-compose.test.yml | 2 +- docker-compose.yml | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml index 8636222a2..ab8f4e2c4 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest services: mariadb: - image: mariadb:12.3.3 + image: mariadb:13.0.2 ports: - 3306:3306 env: diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 82f4f7785..21a7c2f37 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -29,7 +29,7 @@ jobs: runs-on: ubuntu-latest services: mariadb: - image: mariadb:12.3.3 + image: mariadb:13.0.2 ports: - 3306 env: diff --git a/.github/workflows/migrations.yml b/.github/workflows/migrations.yml index 1d603225a..3071d38da 100644 --- a/.github/workflows/migrations.yml +++ b/.github/workflows/migrations.yml @@ -76,11 +76,11 @@ jobs: matrix: include: # renovate: datasource=docker depName=mariadb - - mariadb: "12.3.3" + - mariadb: "13.0.2" charset: utf8mb4 collation: utf8mb4_general_ci # renovate: datasource=docker depName=mariadb - - mariadb: "12.3.3" + - mariadb: "13.0.2" charset: utf8mb3 collation: utf8mb3_unicode_ci # Oldest supported LTS, and the only leg still on the pre-uca1400 diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index c127fc30f..2ff2534a1 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -36,7 +36,7 @@ jobs: db: [mariadb, postgresql] services: mariadb: - image: mariadb:12.3.3 + image: mariadb:13.0.2 ports: - 3306 env: diff --git a/backend/docker-compose.test.yml b/backend/docker-compose.test.yml index 891c61b6d..2e4b50702 100644 --- a/backend/docker-compose.test.yml +++ b/backend/docker-compose.test.yml @@ -3,7 +3,7 @@ # uv run pytest services: mariadb: - image: mariadb:12.3.3 + image: mariadb:13.0.2 ports: - "3306:3306" environment: diff --git a/docker-compose.yml b/docker-compose.yml index b64be6106..98dcf8a55 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -37,7 +37,7 @@ services: tty: true romm-db-dev: - image: mariadb:12.3.3 + image: mariadb:13.0.2 container_name: romm-db-dev restart: unless-stopped env_file: .env From 6f03b6ec87a418468ed5bae5804e64f4aefc05dd Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Wed, 16 Sep 2026 10:19:28 -0500 Subject: [PATCH 002/332] feat(sync): surface save conflicts detected by negotiate The API negotiate path reported `action: "conflict"` in its response but never announced it on the socket, and nothing in the frontend consumed any `sync:*` event, so a save conflict was invisible to the user. Emit `sync:conflict` from negotiate for each conflicting operation, and add the v2 consumer that shows a warning toast naming the game. The emit is fail-open: an unreachable Redis must not block a client's launch. The toast dedupes per page session, because a conflict is re-reported on every negotiation until it is resolved. Co-Authored-By: Claude Sonnet 5 --- backend/endpoints/sync.py | 20 ++- backend/tests/endpoints/test_sync.py | 112 +++++++++++++++++ frontend/src/locales/bg_BG/rom.json | 2 + frontend/src/locales/cs_CZ/rom.json | 2 + frontend/src/locales/de_DE/rom.json | 2 + frontend/src/locales/en_GB/rom.json | 2 + frontend/src/locales/en_US/rom.json | 2 + frontend/src/locales/es_ES/rom.json | 2 + frontend/src/locales/fr_FR/rom.json | 2 + frontend/src/locales/hu_HU/rom.json | 2 + frontend/src/locales/it_IT/rom.json | 2 + frontend/src/locales/ja_JP/rom.json | 2 + frontend/src/locales/ko_KR/rom.json | 2 + frontend/src/locales/pl_PL/rom.json | 2 + frontend/src/locales/pt_BR/rom.json | 2 + frontend/src/locales/ro_RO/rom.json | 2 + frontend/src/locales/ru_RU/rom.json | 2 + frontend/src/locales/tr_TR/rom.json | 2 + frontend/src/locales/zh_CN/rom.json | 2 + frontend/src/locales/zh_TW/rom.json | 2 + .../useSyncConflictToast/index.test.ts | 114 ++++++++++++++++++ .../composables/useSyncConflictToast/index.ts | 48 ++++++++ frontend/src/v2/layouts/AppLayout.vue | 4 + 23 files changed, 333 insertions(+), 1 deletion(-) create mode 100644 frontend/src/v2/composables/useSyncConflictToast/index.test.ts create mode 100644 frontend/src/v2/composables/useSyncConflictToast/index.ts diff --git a/backend/endpoints/sync.py b/backend/endpoints/sync.py index 6616a4757..5aa091143 100644 --- a/backend/endpoints/sync.py +++ b/backend/endpoints/sync.py @@ -16,6 +16,7 @@ from endpoints.responses.sync import ( SyncOperationSchema, SyncSessionSchema, ) +from endpoints.sockets.sync import emit_sync_conflict from handler.auth.constants import Scope from handler.database import ( db_device_handler, @@ -115,7 +116,7 @@ class SyncCompletePayload(BaseModel): @protected_route(router.post, "/negotiate", [Scope.ASSETS_READ, Scope.DEVICES_READ]) -def negotiate_sync( +async def negotiate_sync( request: Request, payload: SyncNegotiatePayload, ) -> SyncNegotiateResponse: @@ -338,6 +339,23 @@ def negotiate_sync( f"{total_conflict} conflicts, {total_no_op} no-ops" ) + # Never fatal: the emitter dials Redis, and a negotiation must not fail + # because the user could not be notified. + for op in operations: + if op.action != "conflict": + continue + try: + await emit_sync_conflict( + user_id=request.user.id, + device_id=device.id, + session_id=sync_session.id, + file_name=op.file_name, + rom_id=op.rom_id, + reason=op.reason, + ) + except Exception as e: # noqa: BLE001 + log.warning(f"Failed to emit sync:conflict for {op.file_name}: {e}") + return SyncNegotiateResponse( session_id=sync_session.id, operations=operations, diff --git a/backend/tests/endpoints/test_sync.py b/backend/tests/endpoints/test_sync.py index d10b80fef..a3fa0fcef 100644 --- a/backend/tests/endpoints/test_sync.py +++ b/backend/tests/endpoints/test_sync.py @@ -1017,3 +1017,115 @@ class TestSyncCompleteWithPlaySessions: data = response.json() assert data["session"]["status"] == "COMPLETED" assert data["play_session_ingest"] is None + + +class TestNegotiateConflictEvents: + """A negotiating client has nowhere to resolve a conflict, so the socket + event is the only surface the user gets.""" + + @staticmethod + def _device_with_history(device_id: str, admin_user: User, save: Save) -> Device: + """A device whose last sync of `save` was an hour ago.""" + device = db_device_handler.add_device( + Device(id=device_id, user_id=admin_user.id, sync_enabled=True) + ) + db_device_save_sync_handler.upsert_sync( + device_id=device.id, + save_id=save.id, + synced_at=datetime.now(timezone.utc) - timedelta(hours=1), + ) + return device + + @staticmethod + def _changed_client_save(save: Save) -> dict: + return { + "rom_id": save.rom_id, + "file_name": save.file_name, + "slot": save.slot, + "content_hash": "hash_the_server_never_saw", + "updated_at": "2099-01-01T00:00:00Z", + "file_size_bytes": 100, + } + + def test_conflict_emits_socket_event( + self, client, access_token: str, admin_user: User, save: Save + ): + device = self._device_with_history("neg-conflict-dev", admin_user, save) + + with mock.patch( + "endpoints.sync.emit_sync_conflict", new_callable=mock.AsyncMock + ) as emit: + response = client.post( + "/api/sync/negotiate", + json={ + "device_id": device.id, + "saves": [self._changed_client_save(save)], + }, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + data = response.json() + assert data["total_conflict"] == 1 + emit.assert_awaited_once() + assert emit.await_args is not None + assert emit.await_args.kwargs == { + "user_id": admin_user.id, + "device_id": device.id, + "session_id": data["session_id"], + "file_name": save.file_name, + "rom_id": save.rom_id, + "reason": "Both sides changed since last sync", + } + + def test_no_conflict_negotiation_emits_nothing( + self, client, access_token: str, admin_user: User, save: Save + ): + """A negotiated no_op is not a conflict, so it must stay silent.""" + device = db_device_handler.add_device( + Device(id="neg-calm-dev", user_id=admin_user.id, sync_enabled=True) + ) + db_device_save_sync_handler.set_untracked( + device_id=device.id, save_id=save.id, untracked=True + ) + + with mock.patch( + "endpoints.sync.emit_sync_conflict", new_callable=mock.AsyncMock + ) as emit: + response = client.post( + "/api/sync/negotiate", + json={ + "device_id": device.id, + "saves": [self._changed_client_save(save)], + }, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + data = response.json() + assert data["total_conflict"] == 0 + assert any(op["action"] == "no_op" for op in data["operations"]) + emit.assert_not_awaited() + + def test_emit_failure_leaves_the_negotiation_intact( + self, client, access_token: str, admin_user: User, save: Save + ): + """An unreachable Redis must not stop a client from syncing.""" + device = self._device_with_history("neg-conflict-down", admin_user, save) + + with mock.patch( + "endpoints.sync.emit_sync_conflict", + new_callable=mock.AsyncMock, + side_effect=RuntimeError("redis is down"), + ): + response = client.post( + "/api/sync/negotiate", + json={ + "device_id": device.id, + "saves": [self._changed_client_save(save)], + }, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["total_conflict"] == 1 diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index f2210488e..4bd24eea9 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -361,6 +361,8 @@ "results-found": "Намерени резултати", "revision": "Revision", "rom-updated-successfully": "ROM-ът е обновен успешно!", + "save-conflict-detected": "Открит е конфликт в записа за {game}.", + "save-conflict-detected-unknown-game": "Открит е конфликт в записа.", "save-data": "Данни от записи", "save-deleted": "Записът е изтрит.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index bdbae7be4..52a6c38d1 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -361,6 +361,8 @@ "results-found": "Nalezené výsledky", "revision": "Revision", "rom-updated-successfully": "ROM úspěšně aktualizována!", + "save-conflict-detected": "Zjištěn konflikt uložené pozice pro {game}.", + "save-conflict-detected-unknown-game": "Zjištěn konflikt uložené pozice.", "save-data": "Uložená data", "save-deleted": "Uložená pozice smazána.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index 8b4a5331c..a746f1711 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -361,6 +361,8 @@ "results-found": "Gefundene Ergebnisse", "revision": "Revision", "rom-updated-successfully": "ROM erfolgreich aktualisiert!", + "save-conflict-detected": "Spielstand-Konflikt für {game} erkannt.", + "save-conflict-detected-unknown-game": "Spielstand-Konflikt erkannt.", "save-data": "Speicherdaten", "save-deleted": "Spielstand gelöscht.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index ecac5c738..d774a2a20 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -361,6 +361,8 @@ "results-found": "Results found", "revision": "Revision", "rom-updated-successfully": "Rom updated successfully!", + "save-conflict-detected": "Save conflict detected for {game}.", + "save-conflict-detected-unknown-game": "Save conflict detected.", "save-data": "Save data", "save-deleted": "Save deleted.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index dc514aeb8..5da494639 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -361,6 +361,8 @@ "results-found": "Results found", "revision": "Revision", "rom-updated-successfully": "Rom updated successfully!", + "save-conflict-detected": "Save conflict detected for {game}.", + "save-conflict-detected-unknown-game": "Save conflict detected.", "save-data": "Save data", "save-deleted": "Save deleted.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index bf3c224eb..bddac099e 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -361,6 +361,8 @@ "results-found": "Resultados encontrados", "revision": "Revision", "rom-updated-successfully": "ROM actualizada correctamente", + "save-conflict-detected": "Conflicto de partida detectado en {game}.", + "save-conflict-detected-unknown-game": "Conflicto de partida detectado.", "save-data": "Datos guardados", "save-deleted": "Partida eliminada", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index 051204882..ee12dcf9d 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -361,6 +361,8 @@ "results-found": "Résultats trouvés", "revision": "Revision", "rom-updated-successfully": "ROM mise à jour avec succès !", + "save-conflict-detected": "Conflit de sauvegarde détecté pour {game}.", + "save-conflict-detected-unknown-game": "Conflit de sauvegarde détecté.", "save-data": "Sauvegardes", "save-deleted": "Sauvegarde supprimée.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index b86b444a7..b97d06293 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -361,6 +361,8 @@ "results-found": "Talált eredmények", "revision": "Revision", "rom-updated-successfully": "A ROM frissítése sikeresen megtörtént!", + "save-conflict-detected": "Mentéskonfliktus észlelve: {game}.", + "save-conflict-detected-unknown-game": "Mentéskonfliktus észlelve.", "save-data": "Mentések", "save-deleted": "Mentés törölve.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index 06253ffc4..43aeaba05 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -361,6 +361,8 @@ "results-found": "Risultati trovati", "revision": "Revision", "rom-updated-successfully": "ROM aggiornata con successo!", + "save-conflict-detected": "Conflitto di salvataggio rilevato per {game}.", + "save-conflict-detected-unknown-game": "Conflitto di salvataggio rilevato.", "save-data": "Dati di salvataggio", "save-deleted": "Salvataggio eliminato.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index 763b5ab08..88cdc97de 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -361,6 +361,8 @@ "results-found": "検索結果", "revision": "Revision", "rom-updated-successfully": "ROMを正常に更新しました!", + "save-conflict-detected": "{game} のセーブで競合が検出されました。", + "save-conflict-detected-unknown-game": "セーブの競合が検出されました。", "save-data": "セーブデータ", "save-deleted": "セーブを削除しました。", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index 96a08f955..a9635465f 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -361,6 +361,8 @@ "results-found": "검색 결과", "revision": "Revision", "rom-updated-successfully": "ROM이 성공적으로 업데이트되었습니다!", + "save-conflict-detected": "{game}의 세이브 충돌이 감지되었습니다.", + "save-conflict-detected-unknown-game": "세이브 충돌이 감지되었습니다.", "save-data": "저장 데이터", "save-deleted": "세이브가 삭제되었습니다.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index 93b15c6d1..4b182e6f1 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -361,6 +361,8 @@ "results-found": "Znalezione wyniki", "revision": "Revision", "rom-updated-successfully": "ROM zaktualizowany pomyślnie!", + "save-conflict-detected": "Wykryto konflikt zapisu dla {game}.", + "save-conflict-detected-unknown-game": "Wykryto konflikt zapisu.", "save-data": "Dane zapisu", "save-deleted": "Zapis usunięty.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index 3a114a473..37cc9961d 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -361,6 +361,8 @@ "results-found": "Resultados encontrados", "revision": "Revisão", "rom-updated-successfully": "ROM atualizada com sucesso!", + "save-conflict-detected": "Conflito de save detectado em {game}.", + "save-conflict-detected-unknown-game": "Conflito de save detectado.", "save-data": "Dados salvos", "save-deleted": "Save excluído.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index fa93dd3c6..76916393b 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -361,6 +361,8 @@ "results-found": "Rezultate găsite", "revision": "Revision", "rom-updated-successfully": "ROM actualizat cu succes!", + "save-conflict-detected": "Conflict de salvare detectat pentru {game}.", + "save-conflict-detected-unknown-game": "Conflict de salvare detectat.", "save-data": "Date salvate", "save-deleted": "Salvare ștearsă.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index 742c9f71c..deff4ef8e 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -361,6 +361,8 @@ "results-found": "Найдено результатов", "revision": "Revision", "rom-updated-successfully": "ROM успешно обновлён!", + "save-conflict-detected": "Обнаружен конфликт сохранения для {game}.", + "save-conflict-detected-unknown-game": "Обнаружен конфликт сохранения.", "save-data": "Сохранения", "save-deleted": "Сохранение удалено.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index 81f205f3b..9231e9353 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -361,6 +361,8 @@ "results-found": "Sonuçlar bulundu", "revision": "Revision", "rom-updated-successfully": "ROM başarıyla güncellendi!", + "save-conflict-detected": "{game} için kayıt çakışması algılandı.", + "save-conflict-detected-unknown-game": "Kayıt çakışması algılandı.", "save-data": "Kayıt verisi", "save-deleted": "Kayıt silindi.", "save-target": "Save File/Folder Target", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index a32f43752..eb0efbbef 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -361,6 +361,8 @@ "results-found": "搜索结果", "revision": "修订版本", "rom-updated-successfully": "ROM 更新成功!", + "save-conflict-detected": "检测到 {game} 的存档冲突。", + "save-conflict-detected-unknown-game": "检测到存档冲突。", "save-data": "存档数据", "save-deleted": "存档已删除。", "save-target": "存档文件/文件夹位置", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index 2ce3e2212..f5c0dc556 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -361,6 +361,8 @@ "results-found": "搜尋结果", "revision": "Revision", "rom-updated-successfully": "ROM 更新成功!", + "save-conflict-detected": "偵測到 {game} 的存檔衝突。", + "save-conflict-detected-unknown-game": "偵測到存檔衝突。", "save-data": "存檔資料", "save-deleted": "存檔已刪除。", "save-target": "Save File/Folder Target", diff --git a/frontend/src/v2/composables/useSyncConflictToast/index.test.ts b/frontend/src/v2/composables/useSyncConflictToast/index.test.ts new file mode 100644 index 000000000..c9770e399 --- /dev/null +++ b/frontend/src/v2/composables/useSyncConflictToast/index.test.ts @@ -0,0 +1,114 @@ +import { mount } from "@vue/test-utils"; +import mitt from "mitt"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { defineComponent } from "vue"; +import { installSyncConflictToast } from "./index"; + +// Minimal socket stand-in: records handlers so tests can fire events, and +// stays "connected" so `useSocketEvent` never tries to dial out. +const handlers = new Map void>(); +vi.mock("@/services/socket", () => ({ + default: { + connected: true, + connect: vi.fn(), + on: (event: string, handler: (payload: unknown) => void) => { + handlers.set(event, handler); + }, + off: vi.fn(), + }, +})); + +// The composable only interpolates, so echoing the key and the name is enough +// to tell "named the game" from "fell back to the generic string". +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ + t: (key: string, params?: { game?: string }) => + params?.game ? `${key}:${params.game}` : key, + }), +})); + +const cachedRom = { + id: 7, + name: "Pokemon Violet", + fs_name: "pokemon_violet.zip", +}; +vi.mock("@/v2/stores/galleryRoms", () => ({ + default: () => ({ + getRomById: (id: number) => (id === cachedRom.id ? cachedRom : null), + }), +})); + +vi.mock("@/stores/roms", () => ({ + default: () => ({ currentRom: null, recentRoms: [] }), +})); + +const emitter = mitt(); + +function install() { + mount( + defineComponent({ + setup() { + installSyncConflictToast(); + return () => null; + }, + }), + { global: { provide: { emitter } } }, + ); +} + +function conflict(overrides: Record = {}) { + return { + device_id: "dev-1", + session_id: 3, + file_name: "pokemon_violet.sav", + rom_id: cachedRom.id, + reason: "Both sides changed since last sync", + ...overrides, + }; +} + +describe("useSyncConflictToast", () => { + let toasts: unknown[] = []; + + beforeEach(() => { + handlers.clear(); + toasts = []; + // The emitter outlives the tests, so stale listeners would each record the + // same emit and inflate the counts. + emitter.all.clear(); + emitter.on("snackbarShow", (payload) => { + toasts.push(payload); + }); + }); + + it("warns with the game name", () => { + install(); + handlers.get("sync:conflict")?.(conflict()); + + expect(toasts).toHaveLength(1); + expect(toasts[0]).toMatchObject({ + color: "warning", + msg: `rom.save-conflict-detected:${cachedRom.name}`, + }); + }); + + it("falls back to the generic string when the ROM is not cached", () => { + install(); + handlers.get("sync:conflict")?.(conflict({ rom_id: 999 })); + + expect(toasts).toHaveLength(1); + expect(toasts[0]).toMatchObject({ + msg: "rom.save-conflict-detected-unknown-game", + }); + }); + + it("toasts once per conflict, however often it is reported", () => { + install(); + const handler = handlers.get("sync:conflict"); + handler?.(conflict()); + handler?.(conflict()); + handler?.(conflict({ file_name: "another_game.sav" })); + + expect(toasts).toHaveLength(2); + }); +}); diff --git a/frontend/src/v2/composables/useSyncConflictToast/index.ts b/frontend/src/v2/composables/useSyncConflictToast/index.ts new file mode 100644 index 000000000..05bd6a408 --- /dev/null +++ b/frontend/src/v2/composables/useSyncConflictToast/index.ts @@ -0,0 +1,48 @@ +// useSyncConflictToast: the dedupe is per page session, because a conflict is +// re-reported on every negotiation until it is resolved. +import { useI18n } from "vue-i18n"; +import storeRoms from "@/stores/roms"; +import { useSnackbar } from "@/v2/composables/useSnackbar"; +import { useSocketEvent } from "@/v2/composables/useSocketEvent"; +import storeGalleryRoms from "@/v2/stores/galleryRoms"; + +/** The backend's `sync:conflict` payload; socket payloads have no generated type. */ +export interface SyncConflictSocketPayload { + device_id: string; + session_id: number; + file_name: string; + rom_id: number; + reason: string; +} + +export function installSyncConflictToast(): void { + const { t } = useI18n(); + const snackbar = useSnackbar(); + const romsStore = storeRoms(); + const galleryRomsStore = storeGalleryRoms(); + + const seen = new Set(); + + /** The ROM's display name, or null when no loaded cache holds the game. */ + function romName(romId: number): string | null { + const rom = + galleryRomsStore.getRomById(romId) ?? + (romsStore.currentRom?.id === romId ? romsStore.currentRom : null) ?? + romsStore.recentRoms.find((recent) => recent.id === romId); + return rom ? (rom.name ?? rom.fs_name) : null; + } + + useSocketEvent("sync:conflict", (payload) => { + const key = `${payload.rom_id}:${payload.file_name}`; + if (seen.has(key)) return; + seen.add(key); + + const name = romName(payload.rom_id); + snackbar.warning( + name + ? t("rom.save-conflict-detected", { game: name }) + : t("rom.save-conflict-detected-unknown-game"), + { icon: "mdi-content-save-alert-outline", timeout: 8000 }, + ); + }); +} diff --git a/frontend/src/v2/layouts/AppLayout.vue b/frontend/src/v2/layouts/AppLayout.vue index 210b7004b..b9c216da5 100644 --- a/frontend/src/v2/layouts/AppLayout.vue +++ b/frontend/src/v2/layouts/AppLayout.vue @@ -41,6 +41,7 @@ import { prefetchPlatformIcons } from "@/v2/composables/usePlatformIconCache"; import { useReducedMotion } from "@/v2/composables/useReducedMotion"; import { installScanLifecycle } from "@/v2/composables/useScanLifecycle"; import { installStageActiveClass } from "@/v2/composables/useStageActive"; +import { installSyncConflictToast } from "@/v2/composables/useSyncConflictToast"; import { installBackMorph } from "@/v2/composables/useViewTransition"; installPermissionsHydration(); @@ -49,6 +50,9 @@ installPermissionsHydration(); // route the user is on (navbar indicator + /scan view consume the same // store state). installScanLifecycle(); +// Global save-sync conflict wiring: a conflict detected by the server is +// re-reported on every negotiation, so the toast dedupes per page session. +installSyncConflictToast(); // Mirror useBreakpoint() refs onto so scoped styles // can branch on viewport via `html[data-bp~="xs"] .foo { … }` instead of // hardcoding `@media (max-width: …)` values across every SFC. From ee0cd1d1bf89b7827ddf309b3fa1217b2a5f8769 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Wed, 16 Sep 2026 10:42:30 -0500 Subject: [PATCH 003/332] fix(sync): bound conflict notification latency, fall back on a blank name Negotiate awaited one socket emit per conflict in sequence, and each emit dials a fresh Redis manager, so a client whose launch reported many conflicts queued behind its own notification infrastructure with no upper bound on how long that took. Run the emits concurrently under a single bounded asyncio.wait_for, so the wait is constant rather than proportional to the conflict count. Each failure is still logged per file, and an unreachable Redis still leaves the negotiation intact. The conflict toast also fell back to the file name only when a ROM's name was null, not when it was blank, which rendered "Save conflict detected for ". Addresses the review on #4552. Co-Authored-By: Claude Sonnet 5 --- backend/endpoints/sync.py | 46 +++++++++++++------ backend/tests/endpoints/test_sync.py | 35 ++++++++++++++ .../useSyncConflictToast/index.test.ts | 14 +++++- .../composables/useSyncConflictToast/index.ts | 3 +- 4 files changed, 83 insertions(+), 15 deletions(-) diff --git a/backend/endpoints/sync.py b/backend/endpoints/sync.py index 5aa091143..b5f25287c 100644 --- a/backend/endpoints/sync.py +++ b/backend/endpoints/sync.py @@ -1,3 +1,4 @@ +import asyncio from datetime import datetime from fastapi import HTTPException, Request, status @@ -40,6 +41,10 @@ router = APIRouter( tags=["sync"], ) +# The emitter dials Redis once per conflict, so this bounds a pathological case: +# a client's launch must not queue behind its own notification infrastructure. +CONFLICT_NOTIFY_TIMEOUT_S = 2.0 + class ClientSaveState(BaseModel): rom_id: int = Field(description="ID of the ROM this save belongs to.") @@ -339,22 +344,37 @@ async def negotiate_sync( f"{total_conflict} conflicts, {total_no_op} no-ops" ) - # Never fatal: the emitter dials Redis, and a negotiation must not fail - # because the user could not be notified. - for op in operations: - if op.action != "conflict": - continue + # Never fatal, and never slow: a negotiation must not fail or stall because + # the user could not be notified. The events go out together so the wait + # stays constant rather than growing with the number of conflicts. + conflict_ops = [op for op in operations if op.action == "conflict"] + if conflict_ops: try: - await emit_sync_conflict( - user_id=request.user.id, - device_id=device.id, - session_id=sync_session.id, - file_name=op.file_name, - rom_id=op.rom_id, - reason=op.reason, + results = await asyncio.wait_for( + asyncio.gather( + *( + emit_sync_conflict( + user_id=request.user.id, + device_id=device.id, + session_id=sync_session.id, + file_name=op.file_name, + rom_id=op.rom_id, + reason=op.reason, + ) + for op in conflict_ops + ), + return_exceptions=True, + ), + timeout=CONFLICT_NOTIFY_TIMEOUT_S, ) + for op, emit_result in zip(conflict_ops, results, strict=True): + if isinstance(emit_result, BaseException): + log.warning( + f"Failed to emit sync:conflict for {op.file_name}: " + f"{emit_result}" + ) except Exception as e: # noqa: BLE001 - log.warning(f"Failed to emit sync:conflict for {op.file_name}: {e}") + log.warning(f"Failed to emit {len(conflict_ops)} sync:conflict events: {e}") return SyncNegotiateResponse( session_id=sync_session.id, diff --git a/backend/tests/endpoints/test_sync.py b/backend/tests/endpoints/test_sync.py index a3fa0fcef..0506be5bd 100644 --- a/backend/tests/endpoints/test_sync.py +++ b/backend/tests/endpoints/test_sync.py @@ -1,8 +1,11 @@ """Tests for sync endpoints.""" +import asyncio import os +import time from datetime import datetime, timedelta, timezone from io import BytesIO +from typing import Any from unittest import mock from fastapi import status @@ -1129,3 +1132,35 @@ class TestNegotiateConflictEvents: assert response.status_code == status.HTTP_200_OK assert response.json()["total_conflict"] == 1 + + def test_slow_notification_does_not_stall_the_negotiation( + self, client, access_token: str, admin_user: User, save: Save + ): + """Notification latency must not scale with the number of conflicts.""" + device = self._device_with_history("neg-conflict-slow", admin_user, save) + + async def hang(**_kwargs: Any) -> None: + await asyncio.sleep(30) + + with ( + mock.patch( + "endpoints.sync.emit_sync_conflict", + new_callable=mock.AsyncMock, + side_effect=hang, + ), + mock.patch("endpoints.sync.CONFLICT_NOTIFY_TIMEOUT_S", 0.01), + ): + started = time.monotonic() + response = client.post( + "/api/sync/negotiate", + json={ + "device_id": device.id, + "saves": [self._changed_client_save(save)], + }, + headers={"Authorization": f"Bearer {access_token}"}, + ) + elapsed = time.monotonic() - started + + assert response.status_code == status.HTTP_200_OK + assert response.json()["total_conflict"] == 1 + assert elapsed < 10 diff --git a/frontend/src/v2/composables/useSyncConflictToast/index.test.ts b/frontend/src/v2/composables/useSyncConflictToast/index.test.ts index c9770e399..1448be8d7 100644 --- a/frontend/src/v2/composables/useSyncConflictToast/index.test.ts +++ b/frontend/src/v2/composables/useSyncConflictToast/index.test.ts @@ -32,9 +32,11 @@ const cachedRom = { name: "Pokemon Violet", fs_name: "pokemon_violet.zip", }; +const blankNameRom = { id: 8, name: "", fs_name: "blank_name.zip" }; vi.mock("@/v2/stores/galleryRoms", () => ({ default: () => ({ - getRomById: (id: number) => (id === cachedRom.id ? cachedRom : null), + getRomById: (id: number) => + [cachedRom, blankNameRom].find((rom) => rom.id === id) ?? null, }), })); @@ -92,6 +94,16 @@ describe("useSyncConflictToast", () => { }); }); + it("falls back to the file name when the ROM's name is blank", () => { + install(); + handlers.get("sync:conflict")?.(conflict({ rom_id: blankNameRom.id })); + + expect(toasts).toHaveLength(1); + expect(toasts[0]).toMatchObject({ + msg: `rom.save-conflict-detected:${blankNameRom.fs_name}`, + }); + }); + it("falls back to the generic string when the ROM is not cached", () => { install(); handlers.get("sync:conflict")?.(conflict({ rom_id: 999 })); diff --git a/frontend/src/v2/composables/useSyncConflictToast/index.ts b/frontend/src/v2/composables/useSyncConflictToast/index.ts index 05bd6a408..6015f3d16 100644 --- a/frontend/src/v2/composables/useSyncConflictToast/index.ts +++ b/frontend/src/v2/composables/useSyncConflictToast/index.ts @@ -29,7 +29,8 @@ export function installSyncConflictToast(): void { galleryRomsStore.getRomById(romId) ?? (romsStore.currentRom?.id === romId ? romsStore.currentRom : null) ?? romsStore.recentRoms.find((recent) => recent.id === romId); - return rom ? (rom.name ?? rom.fs_name) : null; + // `name` is nullable and can be blank, so this is a truthy fallback. + return rom ? rom.name || rom.fs_name : null; } useSocketEvent("sync:conflict", (payload) => { From 1732211337f25824c02d413fef06879a71dad3a4 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Wed, 16 Sep 2026 11:05:14 -0500 Subject: [PATCH 004/332] fix(sync): keep the negotiate route off the event loop `negotiate_sync` became `async def` so the new conflict emit could be awaited, which moved every synchronous handler call in its body (device lookup, save fetch, session writes, last_seen) onto the event loop. A device negotiating a large library blocked unrelated async requests and Socket.IO traffic for the duration. The route goes back to a sync `def`, so FastAPI keeps the negotiation in the threadpool, and only the emit crosses to a loop. The socket manager is built per call in write-only mode, which is what lets it run on a loop of its own; the folder watcher already bridges the same emitter that way. Co-Authored-By: Claude Sonnet 5 --- backend/endpoints/sync.py | 73 +++++++++++++++++++++++---------------- 1 file changed, 44 insertions(+), 29 deletions(-) diff --git a/backend/endpoints/sync.py b/backend/endpoints/sync.py index b5f25287c..b1a4e6f9c 100644 --- a/backend/endpoints/sync.py +++ b/backend/endpoints/sync.py @@ -120,8 +120,42 @@ class SyncCompletePayload(BaseModel): play_sessions: list[SyncPlaySessionEntry] | None = None +async def _notify_conflicts( + user_id: int, + device_id: str, + session_id: int, + conflict_ops: list[SyncOperationSchema], +) -> None: + """Emit one sync:conflict event per operation, batched and bounded.""" + try: + results = await asyncio.wait_for( + asyncio.gather( + *( + emit_sync_conflict( + user_id=user_id, + device_id=device_id, + session_id=session_id, + file_name=op.file_name, + rom_id=op.rom_id, + reason=op.reason, + ) + for op in conflict_ops + ), + return_exceptions=True, + ), + timeout=CONFLICT_NOTIFY_TIMEOUT_S, + ) + for op, emit_result in zip(conflict_ops, results, strict=True): + if isinstance(emit_result, BaseException): + log.warning( + f"Failed to emit sync:conflict for {op.file_name}: {emit_result}" + ) + except Exception as e: # noqa: BLE001 + log.warning(f"Failed to emit {len(conflict_ops)} sync:conflict events: {e}") + + @protected_route(router.post, "/negotiate", [Scope.ASSETS_READ, Scope.DEVICES_READ]) -async def negotiate_sync( +def negotiate_sync( request: Request, payload: SyncNegotiatePayload, ) -> SyncNegotiateResponse: @@ -344,37 +378,18 @@ async def negotiate_sync( f"{total_conflict} conflicts, {total_no_op} no-ops" ) - # Never fatal, and never slow: a negotiation must not fail or stall because - # the user could not be notified. The events go out together so the wait - # stays constant rather than growing with the number of conflicts. + # The route stays sync so the negotiation's DB work keeps running in the + # threadpool; only the emit crosses to a loop, and it is never fatal. conflict_ops = [op for op in operations if op.action == "conflict"] if conflict_ops: - try: - results = await asyncio.wait_for( - asyncio.gather( - *( - emit_sync_conflict( - user_id=request.user.id, - device_id=device.id, - session_id=sync_session.id, - file_name=op.file_name, - rom_id=op.rom_id, - reason=op.reason, - ) - for op in conflict_ops - ), - return_exceptions=True, - ), - timeout=CONFLICT_NOTIFY_TIMEOUT_S, + asyncio.run( + _notify_conflicts( + user_id=request.user.id, + device_id=device.id, + session_id=sync_session.id, + conflict_ops=conflict_ops, ) - for op, emit_result in zip(conflict_ops, results, strict=True): - if isinstance(emit_result, BaseException): - log.warning( - f"Failed to emit sync:conflict for {op.file_name}: " - f"{emit_result}" - ) - except Exception as e: # noqa: BLE001 - log.warning(f"Failed to emit {len(conflict_ops)} sync:conflict events: {e}") + ) return SyncNegotiateResponse( session_id=sync_session.id, From beb4fda927a01ccd0a04e44c4d9120c84f47f8bc Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Wed, 16 Sep 2026 15:52:05 -0500 Subject: [PATCH 005/332] fix(sync): bound conflict emit fan-out and key the toast per device A wide conflict set opened one Redis connection per conflict at once, so a client controlled how many the server dials in a single negotiation. Cap the fan-out with a semaphore alongside the existing deadline. The toast deduped on ROM and file alone, dropping a second device's conflict on the same save. Key it per device too. Co-Authored-By: Claude Sonnet 5 --- backend/endpoints/sync.py | 30 ++++--- backend/tests/endpoints/test_sync.py | 90 +++++++++++++++++-- .../useSyncConflictToast/index.test.ts | 9 ++ .../composables/useSyncConflictToast/index.ts | 2 +- 4 files changed, 110 insertions(+), 21 deletions(-) diff --git a/backend/endpoints/sync.py b/backend/endpoints/sync.py index b1a4e6f9c..d4d3f1f89 100644 --- a/backend/endpoints/sync.py +++ b/backend/endpoints/sync.py @@ -41,9 +41,10 @@ router = APIRouter( tags=["sync"], ) -# The emitter dials Redis once per conflict, so this bounds a pathological case: -# a client's launch must not queue behind its own notification infrastructure. +# The emitter dials Redis once per conflict, so a pathological conflict set is +# bounded two ways: a deadline on the wait, and a cap on live connections. CONFLICT_NOTIFY_TIMEOUT_S = 2.0 +CONFLICT_NOTIFY_MAX_CONCURRENCY = 8 class ClientSaveState(BaseModel): @@ -127,20 +128,23 @@ async def _notify_conflicts( conflict_ops: list[SyncOperationSchema], ) -> None: """Emit one sync:conflict event per operation, batched and bounded.""" + limiter = asyncio.Semaphore(CONFLICT_NOTIFY_MAX_CONCURRENCY) + + async def emit_one(op: SyncOperationSchema) -> None: + async with limiter: + await emit_sync_conflict( + user_id=user_id, + device_id=device_id, + session_id=session_id, + file_name=op.file_name, + rom_id=op.rom_id, + reason=op.reason, + ) + try: results = await asyncio.wait_for( asyncio.gather( - *( - emit_sync_conflict( - user_id=user_id, - device_id=device_id, - session_id=session_id, - file_name=op.file_name, - rom_id=op.rom_id, - reason=op.reason, - ) - for op in conflict_ops - ), + *(emit_one(op) for op in conflict_ops), return_exceptions=True, ), timeout=CONFLICT_NOTIFY_TIMEOUT_S, diff --git a/backend/tests/endpoints/test_sync.py b/backend/tests/endpoints/test_sync.py index 0506be5bd..e4a8284ba 100644 --- a/backend/tests/endpoints/test_sync.py +++ b/backend/tests/endpoints/test_sync.py @@ -19,6 +19,7 @@ from handler.database import ( ) from models.assets import Save from models.device import Device, SyncMode +from models.platform import Platform from models.rom import Rom from models.user import User from utils.validation import MAX_ROM_IDS_PER_QUERY @@ -744,13 +745,19 @@ class TestNegotiateAdvanced: content_hash=content_hash, ) - with mock.patch( - "endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock - ), mock.patch( - "endpoints.saves.fs_asset_handler.remove_file", new_callable=mock.AsyncMock - ), mock.patch( - "endpoints.saves.scan_save", - new=mock.AsyncMock(side_effect=make_scanned), + with ( + mock.patch( + "endpoints.saves.fs_asset_handler.write_file", + new_callable=mock.AsyncMock, + ), + mock.patch( + "endpoints.saves.fs_asset_handler.remove_file", + new_callable=mock.AsyncMock, + ), + mock.patch( + "endpoints.saves.scan_save", + new=mock.AsyncMock(side_effect=make_scanned), + ), ): return client.post( f"/api/saves?rom_id={rom.id}&slot=autosave&emulator=eden" @@ -1164,3 +1171,72 @@ class TestNegotiateConflictEvents: assert response.status_code == status.HTTP_200_OK assert response.json()["total_conflict"] == 1 assert elapsed < 10 + + def test_wide_conflict_set_bounds_concurrent_emits( + self, + client, + access_token: str, + admin_user: User, + rom: Rom, + platform: Platform, + ): + """Each emit opens its own Redis connection, so the fan-out is capped.""" + device = db_device_handler.add_device( + Device(id="neg-conflict-wide", user_id=admin_user.id, sync_enabled=True) + ) + saves = [ + db_save_handler.add_save( + Save( + rom_id=rom.id, + user_id=admin_user.id, + file_name=f"wide_{index}.sav", + file_name_no_tags=f"wide_{index}", + file_name_no_ext=f"wide_{index}", + file_extension="sav", + emulator="test_emulator", + slot=f"slot-{index}", + file_path=f"{platform.slug}/saves/test_emulator", + file_size_bytes=1.0, + ) + ) + for index in range(6) + ] + for save in saves: + db_device_save_sync_handler.upsert_sync( + device_id=device.id, + save_id=save.id, + synced_at=datetime.now(timezone.utc) - timedelta(hours=1), + ) + + live = 0 + peak = 0 + cap = 2 + + async def track(**_kwargs: Any) -> None: + nonlocal live, peak + live += 1 + peak = max(peak, live) + await asyncio.sleep(0.05) + live -= 1 + + with ( + mock.patch( + "endpoints.sync.emit_sync_conflict", + new_callable=mock.AsyncMock, + side_effect=track, + ) as emit, + mock.patch("endpoints.sync.CONFLICT_NOTIFY_MAX_CONCURRENCY", cap), + ): + response = client.post( + "/api/sync/negotiate", + json={ + "device_id": device.id, + "saves": [self._changed_client_save(save) for save in saves], + }, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["total_conflict"] == len(saves) + assert emit.await_count == len(saves) + assert peak == cap diff --git a/frontend/src/v2/composables/useSyncConflictToast/index.test.ts b/frontend/src/v2/composables/useSyncConflictToast/index.test.ts index 1448be8d7..cefd346e8 100644 --- a/frontend/src/v2/composables/useSyncConflictToast/index.test.ts +++ b/frontend/src/v2/composables/useSyncConflictToast/index.test.ts @@ -123,4 +123,13 @@ describe("useSyncConflictToast", () => { expect(toasts).toHaveLength(2); }); + + it("toasts per device, so a second device's conflict is not swallowed", () => { + install(); + const handler = handlers.get("sync:conflict"); + handler?.(conflict()); + handler?.(conflict({ device_id: "dev-2" })); + + expect(toasts).toHaveLength(2); + }); }); diff --git a/frontend/src/v2/composables/useSyncConflictToast/index.ts b/frontend/src/v2/composables/useSyncConflictToast/index.ts index 6015f3d16..40e72266f 100644 --- a/frontend/src/v2/composables/useSyncConflictToast/index.ts +++ b/frontend/src/v2/composables/useSyncConflictToast/index.ts @@ -34,7 +34,7 @@ export function installSyncConflictToast(): void { } useSocketEvent("sync:conflict", (payload) => { - const key = `${payload.rom_id}:${payload.file_name}`; + const key = `${payload.device_id}:${payload.rom_id}:${payload.file_name}`; if (seen.has(key)) return; seen.add(key); From f947da377803104b7f52e3c2f78bd5e87a088d25 Mon Sep 17 00:00:00 2001 From: Stuart Anderson Date: Thu, 17 Sep 2026 10:50:28 -0500 Subject: [PATCH 006/332] chore: typecheck frontend/scripts via tsconfig.node.json --- docs/FRONTEND_ARCHITECTURE.md | 19 ++++++++++--------- frontend/package.json | 2 +- frontend/tsconfig.node.json | 14 ++++++++++++++ 3 files changed, 25 insertions(+), 10 deletions(-) create mode 100644 frontend/tsconfig.node.json diff --git a/docs/FRONTEND_ARCHITECTURE.md b/docs/FRONTEND_ARCHITECTURE.md index 47b2468a0..c3cc246ed 100644 --- a/docs/FRONTEND_ARCHITECTURE.md +++ b/docs/FRONTEND_ARCHITECTURE.md @@ -123,7 +123,8 @@ frontend/ ├── index.html # HTML entry point (
) ├── package.json # Dependencies & scripts ├── vite.config.js # Vite build config with plugins -├── tsconfig.json # TypeScript configuration +├── tsconfig.json # Vue app TypeScript (vue-tsc) +├── tsconfig.node.json # Node/Vite tooling TypeScript (tsc -p) ├── eslint.config.js # ESLint flat config ├── .nvmrc # Node 24 │ @@ -1099,14 +1100,14 @@ Procedural SVG generation for: ### Scripts -| Script | Command | Purpose | -| ----------- | ---------------------------- | ----------------------------------- | -| `dev` | `vite --host` | Development server | -| `build` | `vite build` | Production build | -| `preview` | `vite preview` | Preview production build | -| `typecheck` | `vue-tsc` | TypeScript validation | -| `generate` | `openapi-typescript-codegen` | Generate types from backend OpenAPI | -| `lint` | `eslint` | Lint `.vue`, `.js`, `.ts` files | +| Script | Command | Purpose | +| ----------- | -------------------------------------------------------- | ----------------------------------------------------------------------- | +| `dev` | `vite --host` | Development server | +| `build` | `vite build` | Production build | +| `preview` | `vite preview` | Preview production build | +| `typecheck` | `vue-tsc --noEmit && tsc --noEmit -p tsconfig.node.json` | App SFCs (`tsconfig.json`) and Node/Vite tooling (`tsconfig.node.json`) | +| `generate` | `openapi-typescript-codegen` | Generate types from backend OpenAPI | +| `lint` | `eslint` | Lint `.vue`, `.js`, `.ts` files | ### OpenAPI Code Generation diff --git a/frontend/package.json b/frontend/package.json index 27073b501..feeca9d46 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -26,7 +26,7 @@ "dev": "vite --host", "build": "vite build", "preview": "vite preview", - "typecheck": "vue-tsc --noEmit", + "typecheck": "vue-tsc --noEmit && tsc --noEmit -p tsconfig.node.json", "generate": "openapi --input http://127.0.0.1:3000/openapi.json --output ./src/__generated__ --client axios --useOptions --useUnionTypes --exportServices false --exportSchemas false --exportCore false", "test": "vitest run", "test:watch": "vitest", diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json new file mode 100644 index 000000000..c9a97cfe0 --- /dev/null +++ b/frontend/tsconfig.node.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "moduleResolution": "bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["node"] + }, + // Aids `npm run typecheck` in expanding typechecking + // to Node/Vite tooling that vue-tsc does not cover. + "include": ["scripts/**/*.ts"] +} From 29cad3359d33ac7117fa1864ca58393aa10dd61d Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 18:50:26 +0200 Subject: [PATCH 007/332] fix(v2): drop the stale subtab when switching game details tabs The per-tab cleanup watchers never fired: the tab unmounted before the route replace landed. GameDetails now drops ?subtab= in the same replace that switches tabs, and useSubtabQuery only reads a subtab that belongs to its own tab. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XAReUPhZXnp7LyiP1W4GGQ --- .../GameDetails/FilesTab/FilesTab.test.ts | 2 +- .../GameDetails/FilesTab/FilesTab.vue | 50 ++---------- .../v2/components/GameDetails/MediaTab.vue | 46 ++--------- .../v2/components/GameDetails/SaveDataTab.vue | 44 ++--------- .../src/v2/components/shared/EmptyState.vue | 66 ---------------- .../composables/useSubtabQuery/index.test.ts | 78 +++++++++++++++++++ .../v2/composables/useSubtabQuery/index.ts | 40 ++++++++++ frontend/src/v2/views/GameDetails.vue | 4 +- 8 files changed, 140 insertions(+), 190 deletions(-) delete mode 100644 frontend/src/v2/components/shared/EmptyState.vue create mode 100644 frontend/src/v2/composables/useSubtabQuery/index.test.ts create mode 100644 frontend/src/v2/composables/useSubtabQuery/index.ts diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts index 5b9c3e21b..e99f4eee9 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts @@ -15,7 +15,7 @@ const { uploadRoms, refetchRom, confirmFn, snackbar, routeQuery, grants } = warning: vi.fn(), info: vi.fn(), }, - routeQuery: { subtab: undefined as string | undefined }, + routeQuery: { tab: "files", subtab: undefined as string | undefined }, grants: { upload: true, delete: false }, })); diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue index 1d779780a..527efd2bb 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue @@ -59,6 +59,7 @@ import { useIsAlive } from "@/v2/composables/useIsAlive"; import { useRomFileUpload } from "@/v2/composables/useRomFileUpload"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; +import { useSubtabQuery } from "@/v2/composables/useSubtabQuery"; import { errorMessage } from "@/v2/utils/errorMessage"; import FileRow from "./FileRow.vue"; import FilesSummary from "./FilesSummary.vue"; @@ -298,15 +299,11 @@ const validSubtabIds = computed( ); // ---------- Subtab state (URL-persisted via `?subtab=`) ---------- -function readSubtabFromRoute(): Subtab { - const raw = route.query.subtab; - if (typeof raw === "string" && validSubtabIds.value.has(raw as Subtab)) { - return raw as Subtab; - } - return "all"; -} - -const subTab = ref(readSubtabFromRoute()); +const subTab = useSubtabQuery( + "files", + (value) => validSubtabIds.value.has(value), + "all", +); // If the currently-selected subtab no longer has files (e.g. after a // rom refresh dropped that category), snap back to "all" so the user @@ -319,41 +316,6 @@ watch( { flush: "post" }, ); -watch(subTab, (value) => { - if (route.query.subtab !== value) { - router.replace({ - path: route.path, - query: { ...route.query, subtab: value }, - }); - } -}); - -watch( - () => route.query.subtab, - (value) => { - if ( - typeof value === "string" && - validSubtabIds.value.has(value as Subtab) && - value !== subTab.value - ) { - subTab.value = value as Subtab; - } - }, -); - -// When the user navigates away from the Files tab, drop the subtab -// param so it doesn't leak onto sibling tabs (mirrors MediaTab). -watch( - () => route.query.tab, - (value) => { - if (value !== "files" && route.query.subtab) { - const rest = { ...route.query }; - delete rest.subtab; - router.replace({ path: route.path, query: rest }); - } - }, -); - // ---------- Filtered file list (driven by the active subtab) ---------- // "All files": Root first, then each present folder in alphabetical // order (by label). Inside every bucket, files keep the path-based diff --git a/frontend/src/v2/components/GameDetails/MediaTab.vue b/frontend/src/v2/components/GameDetails/MediaTab.vue index 6112f53cc..20c0e0fcb 100644 --- a/frontend/src/v2/components/GameDetails/MediaTab.vue +++ b/frontend/src/v2/components/GameDetails/MediaTab.vue @@ -12,9 +12,8 @@ // // The soundtrack player is reused from v1 for now. import { RBtn, RDropzone, REmptyState } from "@v2/lib"; -import { computed, defineAsyncComponent, ref, watch } from "vue"; +import { computed, defineAsyncComponent, ref } from "vue"; import { useI18n } from "vue-i18n"; -import { useRoute, useRouter } from "vue-router"; import type { DetailedRom } from "@/stores/roms"; import SubtabNav, { type SubtabNavItem, @@ -28,6 +27,7 @@ import { import { useRomSoundtrack } from "@/v2/composables/useRomSoundtrack"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSoundtrackActions } from "@/v2/composables/useSoundtrackActions"; +import { useSubtabQuery } from "@/v2/composables/useSubtabQuery"; const ManualSubtab = defineAsyncComponent( () => import("@/v2/components/GameDetails/ManualSubtab.vue"), @@ -73,44 +73,10 @@ const validSubtabs = [ ] as const; type Subtab = (typeof validSubtabs)[number]; -const route = useRoute(); -const router = useRouter(); - -const subTab = ref( - validSubtabs.includes(route.query.subtab as Subtab) - ? (route.query.subtab as Subtab) - : "manual", -); - -watch(subTab, (value) => { - if (route.query.subtab !== value) { - router.replace({ - path: route.path, - query: { ...route.query, subtab: value }, - }); - } -}); - -watch( - () => route.query.subtab, - (value) => { - if (typeof value === "string" && validSubtabs.includes(value as Subtab)) { - subTab.value = value as Subtab; - } - }, -); - -// When the user navigates away from the Media tab, drop the subtab query -// param so stale state doesn't leak onto other tabs. -watch( - () => route.query.tab, - (value) => { - if (value !== "media" && route.query.subtab) { - const rest = { ...route.query }; - delete rest.subtab; - router.replace({ path: route.path, query: rest }); - } - }, +const subTab = useSubtabQuery( + "media", + (value) => validSubtabs.includes(value as Subtab), + "manual", ); // ---------- Subtab nav ---------- diff --git a/frontend/src/v2/components/GameDetails/SaveDataTab.vue b/frontend/src/v2/components/GameDetails/SaveDataTab.vue index 27d1cff07..44eb6088a 100644 --- a/frontend/src/v2/components/GameDetails/SaveDataTab.vue +++ b/frontend/src/v2/components/GameDetails/SaveDataTab.vue @@ -14,9 +14,8 @@ // user navigates to a sibling tab. import { RBtn, RDropzone } from "@v2/lib"; import { storeToRefs } from "pinia"; -import { computed, ref, watch } from "vue"; +import { computed, ref } from "vue"; import { useI18n } from "vue-i18n"; -import { useRoute, useRouter } from "vue-router"; import type { DetailedRomSchema, SaveSchema, @@ -42,6 +41,7 @@ import { useBreakpoint } from "@/v2/composables/useBreakpoint"; import { useConfirm } from "@/v2/composables/useConfirm"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; +import { useSubtabQuery } from "@/v2/composables/useSubtabQuery"; import type { AssetType } from "@/v2/utils/assets"; import { errorMessage } from "@/v2/utils/errorMessage"; @@ -61,42 +61,10 @@ const { smAndDown } = useBreakpoint(); const validSubtabs = ["saves", "states"] as const; type Subtab = (typeof validSubtabs)[number]; -const route = useRoute(); -const router = useRouter(); - -const subTab = ref( - validSubtabs.includes(route.query.subtab as Subtab) - ? (route.query.subtab as Subtab) - : "saves", -); - -watch(subTab, (value) => { - if (route.query.subtab !== value) { - router.replace({ - path: route.path, - query: { ...route.query, subtab: value }, - }); - } -}); -watch( - () => route.query.subtab, - (value) => { - if (typeof value === "string" && validSubtabs.includes(value as Subtab)) { - subTab.value = value as Subtab; - } - }, -); -// When the user navigates away from this tab, drop the subtab param -// so it doesn't leak onto sibling tabs. -watch( - () => route.query.tab, - (value) => { - if (value !== "save-data" && route.query.subtab) { - const rest = { ...route.query }; - delete rest.subtab; - router.replace({ path: route.path, query: rest }); - } - }, +const subTab = useSubtabQuery( + "save-data", + (value) => validSubtabs.includes(value as Subtab), + "saves", ); const authStore = storeAuth(); diff --git a/frontend/src/v2/components/shared/EmptyState.vue b/frontend/src/v2/components/shared/EmptyState.vue deleted file mode 100644 index e0c95b5e8..000000000 --- a/frontend/src/v2/components/shared/EmptyState.vue +++ /dev/null @@ -1,66 +0,0 @@ - - - - - diff --git a/frontend/src/v2/composables/useSubtabQuery/index.test.ts b/frontend/src/v2/composables/useSubtabQuery/index.test.ts new file mode 100644 index 000000000..4360ffd94 --- /dev/null +++ b/frontend/src/v2/composables/useSubtabQuery/index.test.ts @@ -0,0 +1,78 @@ +import { flushPromises, mount } from "@vue/test-utils"; +import { describe, expect, it } from "vitest"; +import { defineComponent, type Ref } from "vue"; +import { + createMemoryHistory, + createRouter, + type LocationQueryRaw, +} from "vue-router"; +import { useSubtabQuery } from "./index"; + +type Subtab = "saves" | "states"; +const SUBTABS: readonly string[] = ["saves", "states"]; + +async function mountAt(query: LocationQueryRaw) { + const router = createRouter({ + history: createMemoryHistory(), + routes: [{ path: "/rom/:id", component: { template: "
" } }], + }); + await router.push({ path: "/rom/1", query }); + + let subtab!: Ref; + const Host = defineComponent({ + setup() { + subtab = useSubtabQuery( + "save-data", + (value) => SUBTABS.includes(value), + "saves", + ); + return () => null; + }, + }); + mount(Host, { global: { plugins: [router] } }); + return { router, subtab }; +} + +describe("useSubtabQuery", () => { + it("reads the subtab when the URL is on its tab", async () => { + const { subtab } = await mountAt({ tab: "save-data", subtab: "states" }); + + expect(subtab.value).toBe("states"); + }); + + it("ignores a subtab left over from another tab", async () => { + const { subtab } = await mountAt({ tab: "media", subtab: "states" }); + + expect(subtab.value).toBe("saves"); + }); + + it("falls back on an unknown subtab", async () => { + const { subtab } = await mountAt({ tab: "save-data", subtab: "manual" }); + + expect(subtab.value).toBe("saves"); + }); + + it("writes a change back to the URL", async () => { + const { router, subtab } = await mountAt({ tab: "save-data" }); + + subtab.value = "states"; + await flushPromises(); + + expect(router.currentRoute.value.query).toEqual({ + tab: "save-data", + subtab: "states", + }); + }); + + it("follows an external navigation to another subtab", async () => { + const { router, subtab } = await mountAt({ tab: "save-data" }); + + await router.push({ + path: "/rom/1", + query: { tab: "save-data", subtab: "states" }, + }); + await flushPromises(); + + expect(subtab.value).toBe("states"); + }); +}); diff --git a/frontend/src/v2/composables/useSubtabQuery/index.ts b/frontend/src/v2/composables/useSubtabQuery/index.ts new file mode 100644 index 000000000..c4634405c --- /dev/null +++ b/frontend/src/v2/composables/useSubtabQuery/index.ts @@ -0,0 +1,40 @@ +// Binds a details tab's active subtab to the route's `?subtab=` param. +import { shallowRef, watch, type Ref } from "vue"; +import { useRoute, useRouter } from "vue-router"; + +export function useSubtabQuery( + tabId: string, + isValid: (value: string) => boolean, + fallback: T, +): Ref { + const route = useRoute(); + const router = useRouter(); + + // A tab mounting mid-switch still sees the previous tab's subtab in the URL. + function fromRoute(): T | null { + const raw = route.query.subtab; + if (route.query.tab !== tabId || typeof raw !== "string") return null; + return isValid(raw) ? (raw as T) : null; + } + + // `shallowRef` cannot resolve its unwrap type for a generic `T`. + const subtab = shallowRef(fromRoute() ?? fallback) as Ref; + + watch(subtab, (value) => { + if (route.query.subtab === value) return; + void router.replace({ + path: route.path, + query: { ...route.query, subtab: value }, + }); + }); + + watch( + () => [route.query.tab, route.query.subtab], + () => { + const value = fromRoute(); + if (value !== null && value !== subtab.value) subtab.value = value; + }, + ); + + return subtab; +} diff --git a/frontend/src/v2/views/GameDetails.vue b/frontend/src/v2/views/GameDetails.vue index 67ae1397f..975b953d8 100644 --- a/frontend/src/v2/views/GameDetails.vue +++ b/frontend/src/v2/views/GameDetails.vue @@ -88,9 +88,11 @@ onBeforeRouteUpdate(async (to) => { const tab = ref((route.query.tab as string) || "overview"); watch(tab, (value) => { if (route.query.tab !== value) { + // The subtab belongs to the tab being left. + const { subtab: _subtab, ...query } = route.query; router.replace({ path: route.path, - query: { ...route.query, tab: value }, + query: { ...query, tab: value }, }); } }); From e78b972aef6b7af669fa5400c892aa81badeb8db Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 18:50:40 +0200 Subject: [PATCH 008/332] fix(v2): stop the page scrollbar flickering on route changes The route crossfade snapshot showed through the transparent scrollbar track, blurred background art included, and swallowed the thumb. Give the v2 page scrollbar an opaque track. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XAReUPhZXnp7LyiP1W4GGQ --- frontend/src/v2/styles/global.css | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/frontend/src/v2/styles/global.css b/frontend/src/v2/styles/global.css index ef60c85f7..f2451dfa2 100644 --- a/frontend/src/v2/styles/global.css +++ b/frontend/src/v2/styles/global.css @@ -19,6 +19,17 @@ -moz-osx-font-smoothing: grayscale; } +/* Opaque track: a transparent one lets the route crossfade's snapshot, with the + blurred art bleeding into the gutter, show through and swallow the thumb. */ +html.r-v2 { + scrollbar-color: color-mix( + in srgb, + var(--r-color-brand-primary) 35%, + transparent + ) + var(--r-color-bg); +} + /* Responsive page padding — `--r-row-pad` is consumed everywhere as the horizontal gutter for page rows / toolbars / nav / widgets. Shrinking it here tightens every consumer at once on narrower viewports, so From 5d58f9177ce9f8b4ff4ae7dcbd1bf71be7341db7 Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 18:50:41 +0200 Subject: [PATCH 009/332] fix(v2): match the folder mappings help button to the Scan view Use the same info button (no native tooltip) and center the note icon in the mapping types dialog. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XAReUPhZXnp7LyiP1W4GGQ --- .../Settings/FolderMappingsSection.vue | 29 ++++--------------- 1 file changed, 5 insertions(+), 24 deletions(-) diff --git a/frontend/src/v2/components/Settings/FolderMappingsSection.vue b/frontend/src/v2/components/Settings/FolderMappingsSection.vue index a2242e4cf..3b7cc7cb0 100644 --- a/frontend/src/v2/components/Settings/FolderMappingsSection.vue +++ b/frontend/src/v2/components/Settings/FolderMappingsSection.vue @@ -359,18 +359,14 @@ onMounted(async () => { row-height="44px" @update:sort="onSort" > - + @@ -474,21 +470,6 @@ onMounted(async () => { flex: 1; } -/* Help affordance inside the "Type" column header — a small, muted - icon that tints to fg on hover. Negative inline-end margin keeps it - visually attached to the label without enlarging the header gap. */ -.r-v2-mappings__help-icon { - color: var(--r-color-fg-faint) !important; - width: 22px !important; - height: 22px !important; - min-width: 0 !important; - margin-left: 2px !important; -} -.r-v2-mappings__help-icon:hover { - color: var(--r-color-fg) !important; - background: var(--r-color-surface-hover) !important; -} - .r-v2-mappings__folder { font-weight: var(--r-font-weight-medium); white-space: nowrap; @@ -575,7 +556,7 @@ html[data-bp~="xs"] margin: 4px 0 0; padding: 10px 12px; display: inline-flex; - align-items: flex-start; + align-items: center; gap: 10px; border-radius: 8px; background: color-mix(in srgb, var(--r-color-brand-primary) 8%, transparent); From a90f67bb45677d3c0a274a7737dd176daa0b11d2 Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 18:50:43 +0200 Subject: [PATCH 010/332] fix(v2): keep CRT mode and reduced motion mutually exclusive Reduced motion collapses every animation to one near-instant pass, which breaks the CRT overlay. Turning either on now turns the other off, and a device with both saved on keeps reduced motion. Fixes #4562 Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XAReUPhZXnp7LyiP1W4GGQ --- frontend/src/v2/layouts/AppLayout.vue | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/frontend/src/v2/layouts/AppLayout.vue b/frontend/src/v2/layouts/AppLayout.vue index 93bba99f9..aaed35c16 100644 --- a/frontend/src/v2/layouts/AppLayout.vue +++ b/frontend/src/v2/layouts/AppLayout.vue @@ -31,6 +31,7 @@ import SoundtrackMiniPlayer from "@/v2/components/Soundtrack/MiniPlayer.vue"; import { BACKGROUND_ART_KEY } from "@/v2/composables/useBackgroundArt"; import { installBreakpointAttribute } from "@/v2/composables/useBreakpoint"; import { installPermissionsHydration } from "@/v2/composables/useCan"; +import { useCrtMode } from "@/v2/composables/useCrtMode"; import { useDebugMode } from "@/v2/composables/useDebugMode"; import { installGalleryProvenance } from "@/v2/composables/useGalleryProvenance"; import { useGamepad } from "@/v2/composables/useGamepad"; @@ -61,14 +62,22 @@ installStageActiveClass(); // (not the shell root) for the same reason as the theme classes: Vuetify // teleports overlays outside the app tree, and this keeps the flag reachable // there too. -const { enabled: reducedMotion } = useReducedMotion(); +const { enabled: reducedMotion, toggle: toggleReducedMotion } = + useReducedMotion(); +// The reduced-motion neutralize breaks CRT mode's endless animations, so the +// two exclude each other; with both saved on, reduced motion wins. +const { enabled: crtMode } = useCrtMode(); watch( reducedMotion, (on) => { document.documentElement.classList.toggle("r-v2-reduced-motion", on); + if (on) crtMode.value = false; }, { immediate: true }, ); +watch(crtMode, (on) => { + if (on && reducedMotion.value) toggleReducedMotion(); +}); const collectionsStore = storeCollections(); const platformsStore = storePlatforms(); From c9b0007ff4a85cce7600d7ef8dd08acd3cb02033 Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 18:50:44 +0200 Subject: [PATCH 011/332] feat(v2): unify empty states and smooth loading transitions - REmptyState replaces the duplicate shared EmptyState and the hand-rolled empty blocks; it gains a plain variant for framed surfaces (RTable). - Missing games/firmware render it outside their list frame, matching Excluded, and pair a pill count with the round kebab. - useLoadingPhase only paints a skeleton when a load outlasts 200ms, holds it for 300ms, and keeps the settled view through a quick refetch. Applied to RTable, the Missing sections, Home, the platform/collection indexes, Activity, the Jukebox sidebar and the soundtrack queue. - RBtn's loading debounce moves to the shared useDelayedFlag. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XAReUPhZXnp7LyiP1W4GGQ --- .../Dialogs/ManageCollectionsDialog.vue | 18 ++- .../v2/components/Gallery/GalleryShell.vue | 26 ++-- .../GameDetails/AchievementsTab.vue | 17 +-- .../v2/components/Player/SelectSaveDialog.vue | 25 +--- .../components/Player/SelectStateDialog.vue | 25 +--- .../Settings/MissingFirmwareSection.vue | 112 +++++++++++------- .../Settings/MissingGamesSection.vue | 86 +++++++------- .../Settings/PlatformsStatsSection.test.ts | 2 +- .../Settings/PlatformsStatsSection.vue | 25 ++-- .../components/Settings/StreamingSection.vue | 36 +++--- .../src/v2/components/Soundtrack/Panel.vue | 19 +-- .../src/v2/components/shared/AssetList.vue | 35 ++---- .../src/v2/components/shared/AssetStrip.vue | 35 ++---- .../composables/useDelayedFlag/index.test.ts | 46 +++++++ .../v2/composables/useDelayedFlag/index.ts | 46 +++++++ .../composables/useLoadingPhase/index.test.ts | 86 ++++++++++++++ .../v2/composables/useLoadingPhase/index.ts | 61 ++++++++++ frontend/src/v2/lib/data/RTable/RTable.vue | 45 +++---- frontend/src/v2/lib/primitives/RBtn/RBtn.vue | 34 +----- .../REmptyState/REmptyState.stories.ts | 12 ++ .../primitives/REmptyState/REmptyState.vue | 31 ++++- frontend/src/v2/views/Activity.vue | 23 ++-- .../src/v2/views/CollectionsIndex.test.ts | 11 +- frontend/src/v2/views/CollectionsIndex.vue | 27 +++-- frontend/src/v2/views/Gallery/Search.vue | 19 +-- frontend/src/v2/views/Home.test.ts | 49 ++++++-- frontend/src/v2/views/Home.vue | 65 ++++++---- frontend/src/v2/views/Jukebox/BrowseMode.vue | 25 ++-- frontend/src/v2/views/NotFound.vue | 38 +++--- frontend/src/v2/views/PlatformsIndex.test.ts | 11 +- frontend/src/v2/views/PlatformsIndex.vue | 26 ++-- 31 files changed, 675 insertions(+), 441 deletions(-) create mode 100644 frontend/src/v2/composables/useDelayedFlag/index.test.ts create mode 100644 frontend/src/v2/composables/useDelayedFlag/index.ts create mode 100644 frontend/src/v2/composables/useLoadingPhase/index.test.ts create mode 100644 frontend/src/v2/composables/useLoadingPhase/index.ts diff --git a/frontend/src/v2/components/Dialogs/ManageCollectionsDialog.vue b/frontend/src/v2/components/Dialogs/ManageCollectionsDialog.vue index 69c75ca88..c71691753 100644 --- a/frontend/src/v2/components/Dialogs/ManageCollectionsDialog.vue +++ b/frontend/src/v2/components/Dialogs/ManageCollectionsDialog.vue @@ -18,7 +18,7 @@ // circular tick when on. Clicking toggles INSTANTLY (optimistic // update + API call; reverts on failure). // * Empty state if no collections exist. -import { RDialog, RDivider } from "@v2/lib"; +import { RDialog, RDivider, REmptyState } from "@v2/lib"; import type { Emitter } from "mitt"; import { computed, inject, onBeforeUnmount, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; @@ -283,9 +283,12 @@ function closeDialog() { -
- {{ t("collection.no-collections-yet-hint") }} -
+ @@ -338,13 +341,6 @@ function closeDialog() { max-height: 360px; overflow-y: auto; } - -.r-v2-mng-coll__empty { - padding: 24px 16px; - color: var(--r-color-fg-muted); - font-size: 13px; - text-align: center; -} -
- +
diff --git a/frontend/src/v2/components/shared/AssetList.vue b/frontend/src/v2/components/shared/AssetList.vue index 3a39a93e3..4a9a9fd5e 100644 --- a/frontend/src/v2/components/shared/AssetList.vue +++ b/frontend/src/v2/components/shared/AssetList.vue @@ -11,7 +11,7 @@ // * manage (selectable=false) — Save data subtab. Rows are static; the // trailing area renders the `#actions` slot (download/delete/toggle), // and `showOwner` adds an author chip for community items. -import { RBtn, RIcon, RTooltip } from "@v2/lib"; +import { RBtn, REmptyState, RIcon, RTooltip } from "@v2/lib"; import { computed } from "vue"; import { useI18n } from "vue-i18n"; import { AUTOSAVE_SLOT } from "@/services/api/save"; @@ -287,15 +287,13 @@ const fadeIndex = computed(() => -
- -

{{ emptyLabel }}

-
+
@@ -465,23 +463,6 @@ const fadeIndex = computed(() => align-self: flex-start; } -.r-asset-list__empty { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 8px; - padding: 24px 12px; - color: var(--r-color-fg-muted); - text-align: center; - border: 1px dashed var(--r-color-border); - border-radius: var(--r-radius-md); -} -.r-asset-list__empty p { - margin: 0; - font-size: 12px; -} - .r-asset-list__tip { display: flex; flex-direction: column; diff --git a/frontend/src/v2/components/shared/AssetStrip.vue b/frontend/src/v2/components/shared/AssetStrip.vue index 96dacb7da..09fefdf03 100644 --- a/frontend/src/v2/components/shared/AssetStrip.vue +++ b/frontend/src/v2/components/shared/AssetStrip.vue @@ -1,7 +1,7 @@
-
+
- -
diff --git a/frontend/src/v2/views/Gallery/Search.vue b/frontend/src/v2/views/Gallery/Search.vue index 0b8ee6c52..0388ccdee 100644 --- a/frontend/src/v2/views/Gallery/Search.vue +++ b/frontend/src/v2/views/Gallery/Search.vue @@ -9,7 +9,6 @@ import { computed, nextTick, onMounted, ref } from "vue"; import { useI18n } from "vue-i18n"; import storeGalleryFilter from "@/stores/galleryFilter"; import GalleryShell from "@/v2/components/Gallery/GalleryShell.vue"; -import EmptyState from "@/v2/components/shared/EmptyState.vue"; import PageHeader from "@/v2/components/shared/PageHeader.vue"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; @@ -22,10 +21,6 @@ const { total, initialFetching } = storeToRefs(galleryRoms); const initialSearch = ref(false); const shellRef = ref | null>(null); -const showStandaloneEmpty = computed( - () => !initialFetching.value && total.value === 0 && !!searchTerm.value, -); - const emptyMessage = computed(() => searchTerm.value ? t("rom.no-games-match-query", { query: searchTerm.value }) @@ -58,6 +53,7 @@ onMounted(async () => { :search-placeholder="t('rom.search-placeholder')" autofocus-search :empty-message="emptyMessage" + empty-icon="mdi-magnify-close" :skeleton-row-count="4" > - diff --git a/frontend/src/v2/views/Home.test.ts b/frontend/src/v2/views/Home.test.ts index a10b5307d..96639e2c5 100644 --- a/frontend/src/v2/views/Home.test.ts +++ b/frontend/src/v2/views/Home.test.ts @@ -2,7 +2,7 @@ import { flushPromises, mount } from "@vue/test-utils"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { defineComponent, nextTick, ref } from "vue"; +import { defineComponent, ref } from "vue"; import { RECENT_PLAYED_ROMS_LIMIT, RECENT_ROMS_LIMIT, @@ -12,6 +12,7 @@ import storeCollections, { type Collection } from "@/stores/collections"; import storePlatforms, { type Platform } from "@/stores/platforms"; import storeRoms, { type SimpleRom } from "@/stores/roms"; import { useStreamingStore, type JoinableSession } from "@/stores/streaming"; +import { SKELETON_DELAY_MS } from "@/v2/composables/useLoadingPhase"; import Home from "./Home.vue"; vi.mock("vue-i18n", () => ({ @@ -226,6 +227,19 @@ function mountHome() { }); } +/** Mounts with every row still loading, past the delay before skeletons show. */ +async function mountLoadingHome() { + holdRowsLoading(); + vi.useFakeTimers(); + try { + const wrapper = mountHome(); + await vi.advanceTimersByTimeAsync(SKELETON_DELAY_MS); + return wrapper; + } finally { + vi.useRealTimers(); + } +} + /** The section a card row renders into, located by its heading. */ function findRow(wrapper: ReturnType, title: string) { return wrapper.findAll("section").find((s) => s.text().startsWith(title)); @@ -267,6 +281,24 @@ describe("Home", () => { expect(wrapper.text()).toContain("home.empty-headline"); }); + it("paints neither the sections nor the empty library while a load is still quick", async () => { + holdRowsLoading(); + vi.useFakeTimers(); + try { + const wrapper = mountHome(); + await vi.advanceTimersByTimeAsync(SKELETON_DELAY_MS - 1); + + expect(findRow(wrapper, "home.recently-added")).toBeUndefined(); + expect(wrapper.text()).not.toContain("home.empty-headline"); + + await vi.advanceTimersByTimeAsync(1); + + expect(findRow(wrapper, "home.recently-added")).toBeDefined(); + } finally { + vi.useRealTimers(); + } + }); + it("renders the recommendations row with its per-card reason", async () => { stubHomeFetches(true); getRecommendedRoms.mockResolvedValue({ @@ -313,10 +345,7 @@ describe("Home", () => { ["recommendations.for-you", RECOMMENDED_ROMS_LIMIT], ["home.recently-added", RECENT_ROMS_LIMIT], ])("paints one skeleton per requested slot in %s", async (title, limit) => { - holdRowsLoading(); - - const wrapper = mountHome(); - await nextTick(); + const wrapper = await mountLoadingHome(); const row = findRow(wrapper, title); @@ -330,10 +359,7 @@ describe("Home", () => { "common.platforms", "common.collections", ])("withholds %s's count until its list lands", async (title) => { - holdRowsLoading(); - - const wrapper = mountHome(); - await nextTick(); + const wrapper = await mountLoadingHome(); // The list has not resolved, so the count is unknown: a 0 here would be a // number the row is about to replace. @@ -343,10 +369,7 @@ describe("Home", () => { }); it("reserves the reason caption under every recommended placeholder", async () => { - holdRowsLoading(); - - const wrapper = mountHome(); - await nextTick(); + const wrapper = await mountLoadingHome(); const units = findRow(wrapper, "recommendations.for-you")?.findAll( ".r-v2-home__rec", diff --git a/frontend/src/v2/views/Home.vue b/frontend/src/v2/views/Home.vue index b63747ee0..a351992d8 100644 --- a/frontend/src/v2/views/Home.vue +++ b/frontend/src/v2/views/Home.vue @@ -33,6 +33,7 @@ import PlatformTile from "@/v2/components/Platforms/PlatformTile.vue"; import CardRow from "@/v2/components/shared/CardRow.vue"; import RecommendationReason from "@/v2/components/shared/RecommendationReason.vue"; import { useGridNav } from "@/v2/composables/useGridNav"; +import { useLoadingPhase } from "@/v2/composables/useLoadingPhase"; import { useWebpSupport } from "@/v2/composables/useWebpSupport"; import { collectionCoverList } from "@/v2/utils/collectionCovers"; @@ -145,8 +146,8 @@ const gridRoot = ref(null); useGridNav(gridRoot); // Flips once every initial request has settled. Until then the store -// `fetching*` flags are still false and the stores are still empty, so -// `isEmpty` reads true for a library that simply hasn't loaded yet. +// `fetching*` flags are still false and the stores are still empty, so an +// empty store can't tell an empty library from one that hasn't loaded yet. const initialLoadDone = ref(false); onMounted(async () => { @@ -180,36 +181,32 @@ onMounted(async () => { .finally(() => (fetchingContinue.value = false)), ); } + // Not an emptiness signal, so the empty-library decision doesn't wait on it. if (showRecommendations.value) { - initialLoads.push(loadRecommendations()); + void loadRecommendations(); } await Promise.allSettled(initialLoads); initialLoadDone.value = true; }); -// True when nothing has been added yet AND we're no longer fetching — -// mirrors v1's EmptyHome check so we don't flash the placeholder while -// the initial loads are still in-flight. -const isEmpty = computed( +const hasContent = computed( () => - !fetchingPlatforms.value && - !fetchingCollections.value && - !fetchingSmartCollections.value && - !fetchingVirtualCollections.value && - !fetchingRecent.value && - !fetchingContinue.value && - recentRoms.value.length === 0 && - continuePlayingRoms.value.length === 0 && - filledPlatforms.value.length === 0 && - allCollections.value.length === 0 && - (!showSmartCollections.value || smartCollections.value.length === 0) && - (!showVirtualCollections.value || virtualCollections.value.length === 0), + recentRoms.value.length > 0 || + continuePlayingRoms.value.length > 0 || + filledPlatforms.value.length > 0 || + allCollections.value.length > 0 || + (showSmartCollections.value && smartCollections.value.length > 0) || + (showVirtualCollections.value && virtualCollections.value.length > 0), ); -// Gate on the load having actually happened: `isEmpty` alone is true -// during setup, before any request has been made. -const showEmptyState = computed(() => initialLoadDone.value && isEmpty.value); +// The first list to land with items settles on the sections; only once every +// load has come back empty does the empty library take over. In between the +// page stays blank, and shows the section skeletons only if that runs long. +const phase = useLoadingPhase( + () => !initialLoadDone.value && !hasContent.value, + () => !hasContent.value, +); // Filesystem snapshot for the empty state — shows the user what RomM // can already see on disk so the "run a scan" CTA isn't a leap of @@ -243,8 +240,8 @@ async function loadLibraryInfo() { } } -watch(showEmptyState, (empty) => { - if (empty) void loadLibraryInfo(); +watch(phase, (value) => { + if (value === "empty") void loadLibraryInfo(); }); // Favorite ROMs — derived from the Favorites collection's rom_ids. @@ -277,7 +274,7 @@ function collectionCovers(c: { -
+
- From c5900dcaa62d19b21c6fcc87c778968a038703b2 Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 19:29:51 +0200 Subject: [PATCH 021/332] fix(v2): keep select menus from outgrowing their field over long descriptions Option subtitles no longer size the menu: they take the width set by the field and the titles and wrap, so the scan type menu in refresh metadata matches its field on phones. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XAReUPhZXnp7LyiP1W4GGQ --- frontend/src/v2/lib/forms/RSelect/RSelect.vue | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/frontend/src/v2/lib/forms/RSelect/RSelect.vue b/frontend/src/v2/lib/forms/RSelect/RSelect.vue index 6dd58f429..258422075 100644 --- a/frontend/src/v2/lib/forms/RSelect/RSelect.vue +++ b/frontend/src/v2/lib/forms/RSelect/RSelect.vue @@ -1777,9 +1777,8 @@ html[data-input="pad"] .r-select__field:focus { white-space: nowrap; } /* Column wrapper for two-row items (title + subtitle). Pair with the - single-line `.r-select__item-title` and `.r-select__item-subtitle` - classes inside it — the wrapper takes the flex slot the bare title - would have used. */ + `.r-select__item-title` and `.r-select__item-subtitle` classes inside + it — the wrapper takes the flex slot the bare title would have used. */ .r-select__item-stack { flex: 1; min-width: 0; @@ -1792,13 +1791,12 @@ html[data-input="pad"] .r-select__field:focus { `flex: 1` — let it size to its line height. */ flex: 0 0 auto; } +/* A description never widens the menu past the activator; it wraps instead. */ .r-select__item-subtitle { + contain: inline-size; font-size: 11px; font-weight: var(--r-font-weight-medium); color: var(--r-color-fg-muted); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; } .r-select__item-check { color: var(--r-color-brand-primary); From 9bc1d58069cb4e179f92d62e7124a5e453e6257a Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 19:59:20 +0200 Subject: [PATCH 022/332] fix(v2): keep a tap from flipping the input modality back to mouse A tap is followed by compatibility mouse events, so every touch flipped the modality and resized touch-sized controls under the finger. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XAReUPhZXnp7LyiP1W4GGQ --- .../useInputModality/index.test.ts | 59 +++++++++++++++++++ .../v2/composables/useInputModality/index.ts | 20 +++++-- 2 files changed, 75 insertions(+), 4 deletions(-) create mode 100644 frontend/src/v2/composables/useInputModality/index.test.ts diff --git a/frontend/src/v2/composables/useInputModality/index.test.ts b/frontend/src/v2/composables/useInputModality/index.test.ts new file mode 100644 index 000000000..d879a36fd --- /dev/null +++ b/frontend/src/v2/composables/useInputModality/index.test.ts @@ -0,0 +1,59 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// The listeners and the modality ref are module-level singletons, so each test +// re-imports the module to install onto a clean window. +async function loadFresh() { + vi.resetModules(); + const { useInputModality } = await import("./index"); + const hook = useInputModality(); + hook.install(); + return hook; +} + +function tap() { + window.dispatchEvent(new Event("touchstart")); +} + +describe("useInputModality", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(0); + }); + + it("tracks the last input device", async () => { + const { modality } = await loadFresh(); + + tap(); + expect(modality.value).toBe("touch"); + expect(document.documentElement.dataset.input).toBe("touch"); + }); + + it("ignores the compatibility mouse events a tap fires", async () => { + const { modality } = await loadFresh(); + + tap(); + window.dispatchEvent(new Event("mousedown")); + window.dispatchEvent(new Event("mousemove")); + + expect(modality.value).toBe("touch"); + }); + + it("follows a real mouse once the tap window has passed", async () => { + const { modality } = await loadFresh(); + + tap(); + vi.advanceTimersByTime(1000); + window.dispatchEvent(new Event("mousedown")); + + expect(modality.value).toBe("mouse"); + }); + + it("keeps a gamepad from being nudged out by mouse movement", async () => { + const { modality, setModality } = await loadFresh(); + + setModality("pad"); + window.dispatchEvent(new Event("mousemove")); + + expect(modality.value).toBe("pad"); + }); +}); diff --git a/frontend/src/v2/composables/useInputModality/index.ts b/frontend/src/v2/composables/useInputModality/index.ts index a2c889943..92bcdb1e3 100644 --- a/frontend/src/v2/composables/useInputModality/index.ts +++ b/frontend/src/v2/composables/useInputModality/index.ts @@ -9,6 +9,10 @@ import { readonly, ref } from "vue"; export type InputModality = "mouse" | "touch" | "key" | "pad"; const modality = ref("mouse"); +// A tap is followed by compatibility mouse events, which would flip the +// modality straight back to mouse and resize every touch-sized control. +const MOUSE_AFTER_TOUCH_MS = 700; +let lastTouchAt = 0; let installed = false; let teardown: (() => void) | null = null; @@ -36,16 +40,24 @@ export function useInputModality() { // focused tile. Only a deliberate click (mousedown) flips the // modality back to mouse; mousemove / wheel are ignored while // in pad mode. + const fromTouch = () => + performance.now() - lastTouchAt < MOUSE_AFTER_TOUCH_MS; const onMouseMove = () => { - if (modality.value === "pad") return; + if (modality.value === "pad" || fromTouch()) return; + setModality("mouse"); + }; + const onMouseDown = () => { + if (fromTouch()) return; setModality("mouse"); }; - const onMouseDown = () => setModality("mouse"); const onWheel = () => { - if (modality.value === "pad") return; + if (modality.value === "pad" || fromTouch()) return; setModality("mouse"); }; - const onTouch = () => setModality("touch"); + const onTouch = () => { + lastTouchAt = performance.now(); + setModality("touch"); + }; const onKey = (e: KeyboardEvent) => { // Ignore modifier-only presses and clicks that happen to be keyboard- // triggered — what we care about is real navigational keys. From e95b27bf1c0d9e79c4b593c453198ca2739a0baf Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 19:59:24 +0200 Subject: [PATCH 023/332] fix(v2): rework the match rom dialog header for phones The layout switcher moves up to the header, the one row that doesn't reflow as the filters or the search state change. The filter label is gone and the provider chips are one scrolling row, smaller on phones so all of them fit; the search button keeps its own full-width row. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XAReUPhZXnp7LyiP1W4GGQ --- .../v2/components/Dialogs/MatchRomDialog.vue | 59 ++++++++----------- .../MatchRom/MatchRomProviderFilter.vue | 6 ++ 2 files changed, 29 insertions(+), 36 deletions(-) diff --git a/frontend/src/v2/components/Dialogs/MatchRomDialog.vue b/frontend/src/v2/components/Dialogs/MatchRomDialog.vue index a81b8fa25..48805af87 100644 --- a/frontend/src/v2/components/Dialogs/MatchRomDialog.vue +++ b/frontend/src/v2/components/Dialogs/MatchRomDialog.vue @@ -313,15 +313,23 @@ function closeDialog() { {{ rom.fs_name }} + +