From e9a518458ef105431369a7224e8bbc3c9048f49c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 21 Jul 2026 07:55:03 -0400 Subject: [PATCH 1/9] feat(v2): auto-mark games now-playing on launch + confirm launching shelved games Launching a game now advances its per-user status: it is marked "now playing" and an empty or "finished" status rewinds to "incomplete", while statuses the user set on purpose (completed 100% / retired / never playing) are left untouched. This is applied at the authoritative launch write of all three v2 players (EmulatorJS, Ruffle, Stream); Ruffle and Stream previously persisted nothing on launch, so they now also refresh last_played. Launching a game marked Retired or Never Playing now asks for confirmation first, so an accidental Play does not silently reactivate a game the user deliberately shelved. Gated by a new per-user preference (confirmProtectedLaunch, on by default) exposed as a Gameplay toggle in Settings > User Interface. Adds the shared applyLaunchStatus helper and 5 i18n keys across all 18 locales. Part of #3721. Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/src/composables/useUISettings.ts | 9 ++++++ frontend/src/locales/bg_BG/rom.json | 2 ++ frontend/src/locales/bg_BG/settings.json | 3 ++ frontend/src/locales/cs_CZ/rom.json | 2 ++ frontend/src/locales/cs_CZ/settings.json | 3 ++ frontend/src/locales/de_DE/rom.json | 2 ++ frontend/src/locales/de_DE/settings.json | 3 ++ frontend/src/locales/en_GB/rom.json | 2 ++ frontend/src/locales/en_GB/settings.json | 3 ++ frontend/src/locales/en_US/rom.json | 2 ++ frontend/src/locales/en_US/settings.json | 3 ++ frontend/src/locales/es_ES/rom.json | 2 ++ frontend/src/locales/es_ES/settings.json | 3 ++ frontend/src/locales/fr_FR/rom.json | 2 ++ frontend/src/locales/fr_FR/settings.json | 3 ++ frontend/src/locales/hu_HU/rom.json | 2 ++ frontend/src/locales/hu_HU/settings.json | 3 ++ frontend/src/locales/it_IT/rom.json | 2 ++ frontend/src/locales/it_IT/settings.json | 3 ++ frontend/src/locales/ja_JP/rom.json | 2 ++ frontend/src/locales/ja_JP/settings.json | 3 ++ frontend/src/locales/ko_KR/rom.json | 2 ++ frontend/src/locales/ko_KR/settings.json | 3 ++ frontend/src/locales/pl_PL/rom.json | 2 ++ frontend/src/locales/pl_PL/settings.json | 3 ++ frontend/src/locales/pt_BR/rom.json | 2 ++ frontend/src/locales/pt_BR/settings.json | 3 ++ frontend/src/locales/ro_RO/rom.json | 2 ++ frontend/src/locales/ro_RO/settings.json | 3 ++ frontend/src/locales/ru_RU/rom.json | 2 ++ frontend/src/locales/ru_RU/settings.json | 3 ++ frontend/src/locales/tr_TR/rom.json | 2 ++ frontend/src/locales/tr_TR/settings.json | 3 ++ frontend/src/locales/zh_CN/rom.json | 2 ++ frontend/src/locales/zh_CN/settings.json | 3 ++ frontend/src/locales/zh_TW/rom.json | 2 ++ frontend/src/locales/zh_TW/settings.json | 3 ++ .../v2/composables/useGameActions/index.ts | 31 ++++++++++++++++++- frontend/src/v2/utils/romStatus.ts | 14 ++++++++- frontend/src/v2/views/Player/EmulatorJS.vue | 6 +++- frontend/src/v2/views/Player/Ruffle.vue | 14 +++++++++ frontend/src/v2/views/Player/Stream.vue | 14 +++++++++ .../src/v2/views/Settings/UserInterface.vue | 16 ++++++++++ 43 files changed, 191 insertions(+), 3 deletions(-) diff --git a/frontend/src/composables/useUISettings.ts b/frontend/src/composables/useUISettings.ts index fd82fdf66..cd0cabf42 100644 --- a/frontend/src/composables/useUISettings.ts +++ b/frontend/src/composables/useUISettings.ts @@ -69,6 +69,15 @@ export const UI_SETTINGS_KEYS = { }, boxartStyle: { key: "settings.boxartStyle", default: "cover_path" }, + // Gameplay + // Ask for confirmation before launching a game the user deliberately + // shelved (Retired / Never Playing) so an accidental Play doesn't + // silently reactivate it. + confirmProtectedLaunch: { + key: "settings.confirmProtectedLaunch", + default: true, + }, + // Virtual collections showVirtualCollections: { key: "settings.showVirtualCollections", diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index eba52515a..b8d8775f0 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -59,6 +59,8 @@ "completion": "Завършеност", "completionist": "Перфекционист", "confirm-delete-note": "Сигурен ли си, че искаш да изтриеш бележката \"{title}\"?", + "confirm-launch-protected-body": "Отбелязахте „{name}“ като {status}. Искате ли все пак да я играете?", + "confirm-launch-protected-title": "Стартиране на тази игра?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Копирай линк за сваляне", diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index 5341b8c74..07cfa52f0 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Конфигурация", "confirm-delete-mapping": "Потвърди?", + "confirm-protected-launch": "Потвърждаване при стартиране на архивирани игри", + "confirm-protected-launch-desc": "Питане преди стартиране на игра, отбелязана като „Изоставена“ или „Неиграна никога“.", "continue-playing-as-grid": "Продължи игра като решетка", "continue-playing-as-grid-desc": "Показвай кориците за продължаване на игра като решетка на началната страница", "controller-debug": "Диагностика на контролера", @@ -161,6 +163,7 @@ "folder-name": "Име на папка", "folder-name-header": "Име на папка", "gallery": "Галерия", + "gameplay": "Геймплей", "games-label": "Игри", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index 43c3327b2..9c96f8615 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -59,6 +59,8 @@ "completion": "Dokončení", "completionist": "Kompletista", "confirm-delete-note": "Opravdu chcete smazat poznámku \"{title}\"?", + "confirm-launch-protected-body": "Označili jste „{name}“ jako {status}. Přesto ji chcete hrát?", + "confirm-launch-protected-title": "Spustit tuto hru?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Kopírovat odkaz ke stažení", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index a782c97f8..becc6ccde 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Konfigurace", "confirm-delete-mapping": "Potvrzujete?", + "confirm-protected-launch": "Potvrzovat spuštění odložených her", + "confirm-protected-launch-desc": "Zeptat se před spuštěním hry označené jako Opuštěno nebo Nikdy nebudu hrát.", "continue-playing-as-grid": "Pokračovat ve hraní jako mřížka", "continue-playing-as-grid-desc": "Zobrazit karty pokračovaného hraní na hlavní stránce jako mřížku", "controller-debug": "Ladění ovladače", @@ -161,6 +163,7 @@ "folder-name": "Název složky", "folder-name-header": "Název složky", "gallery": "Galerie", + "gameplay": "Hraní", "games-label": "Hry", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index b11b1017a..48c6d6efa 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -59,6 +59,8 @@ "completion": "Durchgespielt", "completionist": "Vollendung", "confirm-delete-note": "Sind Sie sicher, dass Sie die Notiz \"{title}\" löschen möchten?", + "confirm-launch-protected-body": "Du hast „{name}“ als {status} markiert. Möchtest du es trotzdem spielen?", + "confirm-launch-protected-title": "Dieses Spiel starten?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Download-Link kopieren", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index dfbf83187..f4a5a8cd7 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Konfiguration", "confirm-delete-mapping": "Bestätigen Sie?", + "confirm-protected-launch": "Starten zurückgestellter Spiele bestätigen", + "confirm-protected-launch-desc": "Vor dem Starten eines Spiels nachfragen, das als Aufgegeben oder Nie spielen markiert ist.", "continue-playing-as-grid": "Weiterspielen als Raster", "continue-playing-as-grid-desc": "Zeige die Weiterspielen-Karten als Raster auf der Startseite", "controller-debug": "Controller-Debug", @@ -161,6 +163,7 @@ "folder-name": "Verzeichnisname", "folder-name-header": "Ordnername", "gallery": "Galerie", + "gameplay": "Gameplay", "games-label": "Spiele", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index 6784a9079..947156ea9 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -59,6 +59,8 @@ "completion": "Completion", "completionist": "Completionist", "confirm-delete-note": "Are you sure you want to delete the note \"{title}\"?", + "confirm-launch-protected-body": "You marked \"{name}\" as {status}. Do you want to play it anyway?", + "confirm-launch-protected-title": "Launch this game?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copy download link", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index 025c6dd56..333993e17 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Config", "confirm-delete-mapping": "Do you confirm?", + "confirm-protected-launch": "Confirm launching shelved games", + "confirm-protected-launch-desc": "Ask before launching a game you marked as Retired or Never Playing.", "continue-playing-as-grid": "Continue playing as grid", "continue-playing-as-grid-desc": "View continue playing ROM cards as a grid at the home page", "controller-debug": "Controller debug", @@ -161,6 +163,7 @@ "folder-name": "Folder name", "folder-name-header": "Folder name", "gallery": "Gallery", + "gameplay": "Gameplay", "games-label": "Games", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index c2a374838..1f86d9e45 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -59,6 +59,8 @@ "completion": "Completion", "completionist": "Completionist", "confirm-delete-note": "Are you sure you want to delete the note \"{title}\"?", + "confirm-launch-protected-body": "You marked \"{name}\" as {status}. Do you want to play it anyway?", + "confirm-launch-protected-title": "Launch this game?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copy download link", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index d90e4b629..114393dd9 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Config", "confirm-delete-mapping": "Do you confirm?", + "confirm-protected-launch": "Confirm launching shelved games", + "confirm-protected-launch-desc": "Ask before launching a game you marked as Retired or Never Playing.", "continue-playing-as-grid": "Continue playing as grid", "continue-playing-as-grid-desc": "View continue playing ROM cards as a grid at the home page", "controller-debug": "Controller debug", @@ -161,6 +163,7 @@ "folder-name": "Folder name", "folder-name-header": "Folder name", "gallery": "Gallery", + "gameplay": "Gameplay", "games-label": "Games", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index 5c7d70f37..720a8f04a 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -59,6 +59,8 @@ "completion": "Completado", "completionist": "Completista", "confirm-delete-note": "¿Estás seguro de que quieres eliminar la nota \"{title}\"?", + "confirm-launch-protected-body": "Marcaste «{name}» como {status}. ¿Quieres jugarlo de todos modos?", + "confirm-launch-protected-title": "¿Iniciar este juego?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copiar enlace de descarga", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index c458f2bbe..e174cb68f 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configuración", "confirm-delete-mapping": "¿Confirmas?", + "confirm-protected-launch": "Confirmar el inicio de juegos archivados", + "confirm-protected-launch-desc": "Preguntar antes de iniciar un juego marcado como Abandonado o Nunca jugar.", "continue-playing-as-grid": "Continuar jugando como cuadrícula", "continue-playing-as-grid-desc": "Ver tarjetas de continuar jugando como cuadrícula en la página principal", "controller-debug": "Depuración del mando", @@ -161,6 +163,7 @@ "folder-name": "Nombre de la carpeta", "folder-name-header": "Nombre de carpeta", "gallery": "Galería", + "gameplay": "Juego", "games-label": "Juegos", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index 4f7de4709..bb61b287d 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -59,6 +59,8 @@ "completion": "Complétion", "completionist": "Complétionniste", "confirm-delete-note": "Êtes-vous sûr de vouloir supprimer la note \"{title}\" ?", + "confirm-launch-protected-body": "Vous avez marqué « {name} » comme {status}. Voulez-vous quand même y jouer ?", + "confirm-launch-protected-title": "Lancer ce jeu ?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copier le lien de téléchargement", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index b2c6e2f87..2a4228312 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configuration", "confirm-delete-mapping": "Confirmez-vous ?", + "confirm-protected-launch": "Confirmer le lancement des jeux mis de côté", + "confirm-protected-launch-desc": "Demander avant de lancer un jeu marqué comme Abandonné ou Jamais joué.", "continue-playing-as-grid": "Continuer à jouer en grille", "continue-playing-as-grid-desc": "Voir les cartes de continuer à jouer en grille sur la page d'accueil", "controller-debug": "Débogage manette", @@ -161,6 +163,7 @@ "folder-name": "Nom du dossier", "folder-name-header": "Nom du dossier", "gallery": "Galerie", + "gameplay": "Jeu", "games-label": "Jeux", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index 2de4897b7..90e2ed4ce 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -59,6 +59,8 @@ "completion": "Befejezve", "completionist": "Completionista", "confirm-delete-note": "Biztos hogy törölni akarod ezt a jegyzetet \"{title}\"?", + "confirm-launch-protected-body": "A(z) „{name}“ játékot {status} állapotúnak jelölted. Mindenképp játszani szeretnél vele?", + "confirm-launch-protected-title": "Elindítod ezt a játékot?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Letöltési link másolása", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index dfdb50b3a..afc837b9e 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Konfigurálás", "confirm-delete-mapping": "Megerősíted?", + "confirm-protected-launch": "Félretett játékok indításának megerősítése", + "confirm-protected-launch-desc": "Rákérdezés a Félretett vagy Soha nem játszom jelölésű játék indítása előtt.", "continue-playing-as-grid": "Folytatás rácsnézetben", "continue-playing-as-grid-desc": "A Rom kártyák továbbjátszását rácsnézetben megtekintheted a kezdőlapon", "controller-debug": "Kontroller hibakeresés", @@ -161,6 +163,7 @@ "folder-name": "Mappanév", "folder-name-header": "Mappa név", "gallery": "Galléria", + "gameplay": "Játékmenet", "games-label": "Játékok", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index 0491c39cb..77bb00c54 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -59,6 +59,8 @@ "completion": "Completamento", "completionist": "Completista", "confirm-delete-note": "Sei sicuro di voler eliminare la nota \"{title}\"?", + "confirm-launch-protected-body": "Hai contrassegnato «{name}» come {status}. Vuoi comunque giocarci?", + "confirm-launch-protected-title": "Avviare questo gioco?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copia link per il download", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index 4377ca1f7..2e6ad545d 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configurazione", "confirm-delete-mapping": "Confermi?", + "confirm-protected-launch": "Conferma l'avvio dei giochi accantonati", + "confirm-protected-launch-desc": "Chiedi conferma prima di avviare un gioco contrassegnato come Abbandonato o Mai giocare.", "continue-playing-as-grid": "\"Continua a giocare\" come griglia", "continue-playing-as-grid-desc": "Visualizza le ROM di \"Continua a giocare\" come una griglia nella home", "controller-debug": "Debug controller", @@ -161,6 +163,7 @@ "folder-name": "Nome cartella", "folder-name-header": "Nome cartella", "gallery": "Galleria", + "gameplay": "Gameplay", "games-label": "Giochi", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index 1da82f21b..45794e646 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -59,6 +59,8 @@ "completion": "完了度", "completionist": "コンプリート", "confirm-delete-note": "ノート\"{title}\"を削除してもよろしいですか?", + "confirm-launch-protected-body": "「{name}」を{status}に設定しています。それでもプレイしますか?", + "confirm-launch-protected-title": "このゲームを起動しますか?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "ダウンロードリンクをコピー", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 35efbc7e5..60f083842 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "設定", "confirm-delete-mapping": "確認しますか?", + "confirm-protected-launch": "棚上げしたゲームの起動を確認する", + "confirm-protected-launch-desc": "「中断」または「プレイしない」に設定したゲームを起動する前に確認します。", "continue-playing-as-grid": "プレイを継続をグリッドで表示", "continue-playing-as-grid-desc": "ホームのプレイを継続をグリッドで表示", "controller-debug": "コントローラーデバッグ", @@ -161,6 +163,7 @@ "folder-name": "フォルダ名", "folder-name-header": "フォルダ名", "gallery": "ギャラリー", + "gameplay": "ゲームプレイ", "games-label": "ゲーム", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index 9aee1b00e..ba7bf8ff8 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -59,6 +59,8 @@ "completion": "완료율", "completionist": "완주주의자", "confirm-delete-note": "노트 \"{title}\"을(를) 삭제하시겠습니까?", + "confirm-launch-protected-body": "\"{name}\"을(를) {status}(으)로 표시했습니다. 그래도 플레이하시겠습니까?", + "confirm-launch-protected-title": "이 게임을 실행할까요?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "다운로드 링크 복사", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 5067dfc14..16022f5f8 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "구성", "confirm-delete-mapping": "확인하시겠습니까?", + "confirm-protected-launch": "보류한 게임 실행 확인", + "confirm-protected-launch-desc": "중단 또는 플레이 안 함으로 표시한 게임을 실행하기 전에 확인합니다.", "continue-playing-as-grid": "계속 플레이하기 그리드 뷰", "continue-playing-as-grid-desc": "홈페이지에 계속 플레이하기를 그리드 뷰로 보여줍니다", "controller-debug": "컨트롤러 디버그", @@ -161,6 +163,7 @@ "folder-name": "폴더 이름", "folder-name-header": "폴더 이름", "gallery": "갤러리", + "gameplay": "게임플레이", "games-label": "게임", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index 9a7e68f43..343d3731b 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -59,6 +59,8 @@ "completion": "Ukończenie", "completionist": "Kompletista", "confirm-delete-note": "Czy na pewno chcesz usunąć notatkę \"{title}\"?", + "confirm-launch-protected-body": "Oznaczono „{name}“ jako {status}. Czy mimo to chcesz w nią zagrać?", + "confirm-launch-protected-title": "Uruchomić tę grę?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Kopiuj link do pobrania", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 20e09ff0e..834360a84 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Konfiguracja", "confirm-delete-mapping": "Potwierdzasz?", + "confirm-protected-launch": "Potwierdzaj uruchamianie odłożonych gier", + "confirm-protected-launch-desc": "Pytaj przed uruchomieniem gry oznaczonej jako Porzucone lub Nigdy nie gram.", "continue-playing-as-grid": "Kontynuuj grę w widoku siatki", "continue-playing-as-grid-desc": "Wyświetl karty „kontynuuj grę” w formie siatki na stronie głównej", "controller-debug": "Debugowanie kontrolera", @@ -161,6 +163,7 @@ "folder-name": "Nazwa folderu", "folder-name-header": "Nazwa folderu", "gallery": "Galeria", + "gameplay": "Rozgrywka", "games-label": "Gry", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index 804393325..263647944 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -59,6 +59,8 @@ "completion": "Conclusão", "completionist": "Completista", "confirm-delete-note": "Tem certeza de que deseja excluir a nota \"{title}\"?", + "confirm-launch-protected-body": "Você marcou \"{name}\" como {status}. Deseja jogá-lo mesmo assim?", + "confirm-launch-protected-title": "Iniciar este jogo?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copiar link de download", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index 8dc6abb12..dc9918953 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configuração", "confirm-delete-mapping": "Você confirma?", + "confirm-protected-launch": "Confirmar a inicialização de jogos arquivados", + "confirm-protected-launch-desc": "Perguntar antes de iniciar um jogo marcado como Abandonado ou Nunca jogar.", "continue-playing-as-grid": "Continuar jogando como grade", "continue-playing-as-grid-desc": "Ver cartões de continuar jogando como uma grade na página inicial", "controller-debug": "Depuração do controle", @@ -161,6 +163,7 @@ "folder-name": "Nome da pasta", "folder-name-header": "Nome da pasta", "gallery": "Galeria", + "gameplay": "Jogabilidade", "games-label": "Jogos", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index a9aa2a05c..fdc4c864a 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -59,6 +59,8 @@ "completion": "Finalizare", "completionist": "Completist", "confirm-delete-note": "Sunteți sigur că vreți să ștergeți notația \"{title}\"?", + "confirm-launch-protected-body": "Ai marcat „{name}“ ca {status}. Vrei să îl joci oricum?", + "confirm-launch-protected-title": "Pornești acest joc?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copiază linkul de descărcare", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index 961a071ff..946b590c0 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configurare", "confirm-delete-mapping": "Confirmați?", + "confirm-protected-launch": "Confirmă pornirea jocurilor puse deoparte", + "confirm-protected-launch-desc": "Întreabă înainte de a porni un joc marcat ca Abandonat sau Nu voi juca niciodată.", "continue-playing-as-grid": "Continuă jocul în grilă", "continue-playing-as-grid-desc": "Vezi cardurile „Continuă jocul” în grilă pe pagina principală", "controller-debug": "Depanare controller", @@ -161,6 +163,7 @@ "folder-name": "Nume folder", "folder-name-header": "Nume folder", "gallery": "Galerie", + "gameplay": "Joc", "games-label": "Jocuri", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index b133302b0..f2740cb7b 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -59,6 +59,8 @@ "completion": "Завершение", "completionist": "Перфекционист", "confirm-delete-note": "Вы уверены, что хотите удалить заметку \"{title}\"?", + "confirm-launch-protected-body": "Вы отметили «{name}» как {status}. Всё равно хотите поиграть?", + "confirm-launch-protected-title": "Запустить эту игру?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Копировать ссылку для скачивания", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index 124de29fe..e7e1f6ef7 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Конфигурация", "confirm-delete-mapping": "Вы подтверждаете?", + "confirm-protected-launch": "Подтверждать запуск отложенных игр", + "confirm-protected-launch-desc": "Спрашивать перед запуском игры, отмеченной как «Заброшено» или «Никогда не играть».", "continue-playing-as-grid": "Продолжение игры в виде сетки", "continue-playing-as-grid-desc": "Просмотр карточек продолжения игры в виде сетки на главной странице", "controller-debug": "Отладка контроллера", @@ -161,6 +163,7 @@ "folder-name": "Имя папки", "folder-name-header": "Имя папки", "gallery": "Галерея", + "gameplay": "Игровой процесс", "games-label": "Игры", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index 1f837390b..e8c0b64b0 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -59,6 +59,8 @@ "completion": "Tamamlama", "completionist": "Yüzde yüz tamamlayıcı", "confirm-delete-note": "\"{title}\" notunu silmek istediğinizden emin misiniz?", + "confirm-launch-protected-body": "\"{name}\" oyununu {status} olarak işaretlediniz. Yine de oynamak istiyor musunuz?", + "confirm-launch-protected-title": "Bu oyun başlatılsın mı?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "İndirme bağlantısını kopyala", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index 87509a741..a0e0cffb1 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Yapılandırma", "confirm-delete-mapping": "Onaylıyor musunuz?", + "confirm-protected-launch": "Ertelenen oyunların başlatılmasını onayla", + "confirm-protected-launch-desc": "Bırakıldı veya Hiç Oynanmayacak olarak işaretlediğiniz bir oyunu başlatmadan önce sorun.", "continue-playing-as-grid": "Devam edilen oyunları ızgara olarak göster", "continue-playing-as-grid-desc": "Ana sayfada devam edilen oyunları ızgara görünümünde göster", "controller-debug": "Oyun kumandası hata ayıklama", @@ -161,6 +163,7 @@ "folder-name": "Klasör adı", "folder-name-header": "Klasör adı", "gallery": "Galeri", + "gameplay": "Oynanış", "games-label": "Oyunlar", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index d3c198c47..299338d37 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -59,6 +59,8 @@ "completion": "完成度", "completionist": "完美主义者", "confirm-delete-note": "确定要删除笔记\"{title}\"吗?", + "confirm-launch-protected-body": "您已将“{name}”标记为{status}。仍要玩吗?", + "confirm-launch-protected-title": "启动这个游戏吗?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "复制下载链接", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 05d558d2b..451e7378b 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "配置", "confirm-delete-mapping": "确认吗?", + "confirm-protected-launch": "确认启动已搁置的游戏", + "confirm-protected-launch-desc": "在启动标记为“已搁置”或“不玩”的游戏前进行确认。", "continue-playing-as-grid": "继续游玩(网格)", "continue-playing-as-grid-desc": "以网格形式在主页上显示继续游玩(卡片)部分", "controller-debug": "手柄调试", @@ -161,6 +163,7 @@ "folder-name": "文件夹名称", "folder-name-header": "文件夹名称", "gallery": "游戏库", + "gameplay": "游戏玩法", "games-label": "游戏", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index 77883b216..33f6e1a37 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -59,6 +59,8 @@ "completion": "完成度", "completionist": "完美主義者", "confirm-delete-note": "確定要刪除筆記\"{title}\"嗎?", + "confirm-launch-protected-body": "您已將「{name}」標記為{status}。仍要玩嗎?", + "confirm-launch-protected-title": "啟動這個遊戲嗎?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "複製下載連結", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 9a995cbe5..94cdfde13 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "組態", "confirm-delete-mapping": "確認嗎?", + "confirm-protected-launch": "確認啟動已擱置的遊戲", + "confirm-protected-launch-desc": "在啟動標記為「已擱置」或「不玩」的遊戲前進行確認。", "continue-playing-as-grid": "顯示繼續遊玩卡片", "continue-playing-as-grid-desc": "在首頁上以卡片方式顯示繼續遊玩", "controller-debug": "控制器除錯", @@ -161,6 +163,7 @@ "folder-name": "資料夾名稱", "folder-name-header": "資料夾名稱", "gallery": "遊戲庫", + "gameplay": "遊戲玩法", "games-label": "遊戲", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/v2/composables/useGameActions/index.ts b/frontend/src/v2/composables/useGameActions/index.ts index baeb57714..55be3e261 100644 --- a/frontend/src/v2/composables/useGameActions/index.ts +++ b/frontend/src/v2/composables/useGameActions/index.ts @@ -15,6 +15,7 @@ import { useI18n } from "vue-i18n"; import { useRouter } from "vue-router"; import type { RomUserData, RomUserStatus } from "@/__generated__"; import { useFavoriteToggle } from "@/composables/useFavoriteToggle"; +import { useUISettings } from "@/composables/useUISettings"; import romApi from "@/services/api/rom"; import storeAuth from "@/stores/auth"; import storeRoms from "@/stores/roms"; @@ -26,6 +27,7 @@ import { getDownloadLink, getDownloadPath, isNintendoDSRom } from "@/utils"; import { useCan } from "@/v2/composables/useCan"; import { useCanPlay } from "@/v2/composables/useCanPlay"; import { useClipboard } from "@/v2/composables/useClipboard"; +import { useConfirm } from "@/v2/composables/useConfirm"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useViewTransition } from "@/v2/composables/useViewTransition"; @@ -52,6 +54,8 @@ export function useGameActions( const { morphTransition } = useViewTransition(); const emitter = inject>("emitter"); const snackbar = useSnackbar(); + const confirm = useConfirm(); + const { confirmProtectedLaunch } = useUISettings(); const clipboard = useClipboard(); const romsStore = storeRoms(); const auth = storeAuth(); @@ -199,9 +203,34 @@ export function useGameActions( ); }); - function play() { + async function play() { const rom = getRom(); if (!rom) return; + + // Guard launching a game the user deliberately shelved. `retired` / + // `never_playing` encode an opt-in "don't play" intent, so confirm + // before booting one. Gated by a per-user preference (on by default). + const status = rom.rom_user?.status; + if ( + confirmProtectedLaunch.value && + (status === "retired" || status === "never_playing") + ) { + const ok = await confirm({ + title: t("rom.confirm-launch-protected-title"), + body: t("rom.confirm-launch-protected-body", { + name: rom.name ?? rom.fs_name_no_ext ?? "", + status: t( + status === "retired" + ? "rom.status-retired" + : "rom.status-never-playing", + ), + }), + confirmText: t("play.play"), + tone: "warning", + }); + if (!ok) return; + } + // The launch "load" flourish (disc/cartridge insert) lives on the // player view itself — see EmulatorJS's onPlay — so navigation is // immediate here. diff --git a/frontend/src/v2/utils/romStatus.ts b/frontend/src/v2/utils/romStatus.ts index c8dff8cad..df015a123 100644 --- a/frontend/src/v2/utils/romStatus.ts +++ b/frontend/src/v2/utils/romStatus.ts @@ -4,9 +4,21 @@ // surfaces present the same options, in the same order, with the same // icons. v2-only: v1 still reads `romStatusMap`'s emoji from // `@/utils`, so that map stays untouched. -import type { RomUserStatus } from "@/__generated__"; +import type { RomUserSchema, RomUserStatus } from "@/__generated__"; import type { PlayingStatus } from "@/utils"; +// Advance a ROM's per-user status for a launch. Mutates in place so the +// caller can persist the same object it already sends to the props endpoint. +// The game becomes "now playing"; an empty or "finished" status rewinds to +// "incomplete" (they're playing again). Statuses the user set on purpose +// (completed 100% / retired / never playing) are left untouched. +export function applyLaunchStatus(romUser: RomUserSchema): void { + romUser.now_playing = true; + if (romUser.status === null || romUser.status === "finished") { + romUser.status = "incomplete"; + } +} + // Icon map covering both the enum statuses and the orthogonal boolean // flags (now_playing / backlogged / hidden) so a single menu can present // them together. diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index b49f68642..7b538f64b 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -50,6 +50,7 @@ import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; import { useInputModality } from "@/v2/composables/useInputModality"; import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; +import { applyLaunchStatus } from "@/v2/utils/romStatus"; import { installIOSFullscreenShim } from "@/views/Player/EmulatorJS/utils"; // Reuse v1's heavy emulator integration — do NOT rewrite this. Lazy so the @@ -225,7 +226,10 @@ async function onPlay() { removeIOSFullscreenShim.value?.(); removeIOSFullscreenShim.value = installIOSFullscreenShim(); - if (rom.value && auth.scopes.includes("roms.user.write")) { + if (rom.value?.rom_user && auth.scopes.includes("roms.user.write")) { + // Launching marks the game "now playing" and rewinds an empty/finished + // status to "incomplete"; protected statuses are left untouched. + applyLaunchStatus(rom.value.rom_user); romApi.updateUserRomProps({ romId: rom.value.id, data: rom.value.rom_user, diff --git a/frontend/src/v2/views/Player/Ruffle.vue b/frontend/src/v2/views/Player/Ruffle.vue index f8512e5ef..ecfcf04a4 100644 --- a/frontend/src/v2/views/Player/Ruffle.vue +++ b/frontend/src/v2/views/Player/Ruffle.vue @@ -16,6 +16,7 @@ import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; import { ROUTES } from "@/plugins/router"; import romApi from "@/services/api/rom"; +import storeAuth from "@/stores/auth"; import storePlaying from "@/stores/playing"; import storeRoms, { type DetailedRom, type SimpleRom } from "@/stores/roms"; import type { RuffleSourceAPI } from "@/types/ruffle"; @@ -25,6 +26,7 @@ import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; import { colorCanvas } from "@/v2/tokens"; +import { applyLaunchStatus } from "@/v2/utils/romStatus"; const RUFFLE_VERSION = "0.2.0-nightly.2025.8.14"; const DEFAULT_BACKGROUND_COLOR = colorCanvas.bgDeep; @@ -34,6 +36,7 @@ const route = useRoute(); const router = useRouter(); const { fullscreenOnPlay } = useFullscreenPref(); const playingStore = storePlaying(); +const auth = storeAuth(); const rom = ref(null); const gameRunning = ref(false); @@ -119,6 +122,17 @@ function onPlay() { // and pad-to-UI translation stay muted while the game owns input. playingStore.setPlaying(true); + // Mark the game "now playing" and refresh last_played on launch (protected + // statuses are left untouched by applyLaunchStatus). + if (rom.value?.rom_user && auth.scopes.includes("roms.user.write")) { + applyLaunchStatus(rom.value.rom_user); + romApi.updateUserRomProps({ + romId: rom.value.id, + data: rom.value.rom_user, + updateLastPlayed: true, + }); + } + nextTick(() => { if (!rom.value) return; diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index 6380bdc00..5a3967875 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -22,6 +22,7 @@ import { useRoute, useRouter } from "vue-router"; import { ROUTES } from "@/plugins/router"; import romApi from "@/services/api/rom"; import streamingApi from "@/services/api/streaming"; +import storeAuth from "@/stores/auth"; import storePlaying from "@/stores/playing"; import storeRoms, { type DetailedRom, type SimpleRom } from "@/stores/roms"; import { useStreamingStore } from "@/stores/streaming"; @@ -29,6 +30,7 @@ import GameCover from "@/v2/components/shared/GameCover.vue"; import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; +import { applyLaunchStatus } from "@/v2/utils/romStatus"; type PlayerState = "idle" | "loading" | "playing" | "error" | "exited"; type ErrorType = @@ -44,6 +46,7 @@ const setBgArt = useBackgroundArt(); const romsStore = storeRoms(); const galleryRoms = storeGalleryRoms(); const playingStore = storePlaying(); +const auth = storeAuth(); const rom = ref(null); const playerState = ref("idle"); @@ -284,6 +287,17 @@ async function handlePlay(): Promise { containerHost.value = session.host; playerState.value = "playing"; + // Mark the game "now playing" and refresh last_played on launch (protected + // statuses are left untouched by applyLaunchStatus). + if (rom.value.rom_user && auth.scopes.includes("roms.user.write")) { + applyLaunchStatus(rom.value.rom_user); + romApi.updateUserRomProps({ + romId: rom.value.id, + data: rom.value.rom_user, + updateLastPlayed: true, + }); + } + // Wait for the DOM to update and the iframe to exist. attachTimeouts.forEach((id) => clearTimeout(id)); attachTimeouts = []; diff --git a/frontend/src/v2/views/Settings/UserInterface.vue b/frontend/src/v2/views/Settings/UserInterface.vue index da16faada..53a74e45c 100644 --- a/frontend/src/v2/views/Settings/UserInterface.vue +++ b/frontend/src/v2/views/Settings/UserInterface.vue @@ -54,6 +54,8 @@ const { disableAnimations, enableExperimentalCache, boxartStyle, + // Gameplay + confirmProtectedLaunch, // Virtual collections showVirtualCollections, virtualCollectionType, @@ -331,6 +333,20 @@ function onVirtualCollectionTypeChange(value: unknown) { + + +
+ +
+
+ Date: Tue, 21 Jul 2026 08:02:44 -0400 Subject: [PATCH 2/9] test(v2): cover applyLaunchStatus and the play() launch confirmation Adds unit tests for the shared applyLaunchStatus helper (now-playing flag, empty/finished -> incomplete rewind, and protection of completed/retired/ never-playing) and for useGameActions.play()'s confirmation gate (normal launch skips the prompt, retired/never-playing launches prompt and abort on cancel or proceed on confirm, and the per-user preference disables it). Co-Authored-By: Claude Opus 4.8 (1M context) --- .../composables/useGameActions/index.test.ts | 117 ++++++++++++++++++ frontend/src/v2/utils/romStatus.test.ts | 63 ++++++++++ 2 files changed, 180 insertions(+) create mode 100644 frontend/src/v2/composables/useGameActions/index.test.ts create mode 100644 frontend/src/v2/utils/romStatus.test.ts diff --git a/frontend/src/v2/composables/useGameActions/index.test.ts b/frontend/src/v2/composables/useGameActions/index.test.ts new file mode 100644 index 000000000..0fd174f8e --- /dev/null +++ b/frontend/src/v2/composables/useGameActions/index.test.ts @@ -0,0 +1,117 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { SimpleRom } from "@/stores/roms"; +import { useGameActions } from "./index"; + +// Controllable stubs shared with the mocked modules below. +const push = vi.fn(); +const confirmFn = vi.fn(); +const confirmProtectedLaunch = { value: true }; + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); +vi.mock("vue-router", () => ({ + useRouter: () => ({ push }), +})); +vi.mock("@/composables/useFavoriteToggle", () => ({ + useFavoriteToggle: () => ({ + isFavorite: () => false, + toggleFavorite: vi.fn(), + }), +})); +vi.mock("@/composables/useUISettings", () => ({ + useUISettings: () => ({ confirmProtectedLaunch }), +})); +vi.mock("@/services/api/rom", () => ({ + default: { updateUserRomProps: vi.fn() }, +})); +vi.mock("@/stores/auth", () => ({ + default: () => ({ scopes: [] as string[] }), +})); +vi.mock("@/stores/roms", () => ({ + default: () => ({ update: vi.fn(), removeFromContinuePlaying: vi.fn() }), +})); +vi.mock("@/stores/streaming", () => ({ + useStreamingStore: () => ({ containerForPlatform: () => null }), +})); +vi.mock("@/utils", () => ({ + getDownloadLink: vi.fn(), + getDownloadPath: vi.fn(), + isNintendoDSRom: () => false, +})); +vi.mock("@/v2/composables/useCan", () => ({ + useCan: () => ({ value: true }), +})); +// EJS is the only playable core in these tests, so play() routes to /ejs. +vi.mock("@/v2/composables/useCanPlay", () => ({ + useCanPlay: () => ({ + canPlayEJS: { value: true }, + canPlayRuffle: { value: false }, + }), +})); +vi.mock("@/v2/composables/useClipboard", () => ({ + useClipboard: () => ({ copy: vi.fn() }), +})); +vi.mock("@/v2/composables/useConfirm", () => ({ + useConfirm: () => confirmFn, +})); +vi.mock("@/v2/composables/useSnackbar", () => ({ + useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), +})); +vi.mock("@/v2/composables/useViewTransition", () => ({ + useViewTransition: () => ({ + morphTransition: (_opts: unknown, cb: () => void) => cb(), + }), +})); + +function makeRom(status: SimpleRom["rom_user"]["status"] = null): SimpleRom { + return { + id: 1, + name: "Chrono Trigger", + fs_name_no_ext: "Chrono Trigger", + platform_slug: "snes", + rom_user: { status }, + } as unknown as SimpleRom; +} + +beforeEach(() => { + push.mockClear(); + confirmFn.mockClear(); + confirmProtectedLaunch.value = true; +}); + +describe("useGameActions.play — launch confirmation", () => { + it("launches a normal game without confirming", async () => { + const actions = useGameActions(() => makeRom(null)); + await actions.play(); + expect(confirmFn).not.toHaveBeenCalled(); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); + }); + + it.each(["retired", "never_playing"] as const)( + "asks before launching a %s game and aborts on cancel", + async (status) => { + confirmFn.mockResolvedValue(false); + const actions = useGameActions(() => makeRom(status)); + await actions.play(); + expect(confirmFn).toHaveBeenCalledTimes(1); + expect(push).not.toHaveBeenCalled(); + }, + ); + + it("launches a shelved game once the user confirms", async () => { + confirmFn.mockResolvedValue(true); + const actions = useGameActions(() => makeRom("retired")); + await actions.play(); + expect(confirmFn).toHaveBeenCalledTimes(1); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); + }); + + it("skips the prompt when the preference is disabled", async () => { + confirmProtectedLaunch.value = false; + const actions = useGameActions(() => makeRom("never_playing")); + await actions.play(); + expect(confirmFn).not.toHaveBeenCalled(); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); + }); +}); diff --git a/frontend/src/v2/utils/romStatus.test.ts b/frontend/src/v2/utils/romStatus.test.ts new file mode 100644 index 000000000..2f673f100 --- /dev/null +++ b/frontend/src/v2/utils/romStatus.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import type { RomUserSchema } from "@/__generated__"; +import { applyLaunchStatus } from "./romStatus"; + +// Minimal RomUserSchema factory — only the fields applyLaunchStatus reads +// matter, the rest are filled with representative defaults. +function makeRomUser(overrides: Partial = {}): RomUserSchema { + return { + id: 1, + user_id: 1, + rom_id: 1, + created_at: "", + updated_at: "", + last_played: null, + is_main_sibling: false, + backlogged: false, + now_playing: false, + hidden: false, + rating: 0, + difficulty: 0, + completion: 0, + status: null, + ...overrides, + }; +} + +describe("applyLaunchStatus", () => { + it("marks the game now playing", () => { + const ru = makeRomUser({ now_playing: false }); + applyLaunchStatus(ru); + expect(ru.now_playing).toBe(true); + }); + + it("fills an empty status with incomplete", () => { + const ru = makeRomUser({ status: null }); + applyLaunchStatus(ru); + expect(ru.status).toBe("incomplete"); + }); + + it("rewinds a finished game to incomplete", () => { + const ru = makeRomUser({ status: "finished" }); + applyLaunchStatus(ru); + expect(ru.status).toBe("incomplete"); + }); + + it("leaves an in-progress status untouched", () => { + const ru = makeRomUser({ status: "incomplete" }); + applyLaunchStatus(ru); + expect(ru.status).toBe("incomplete"); + }); + + it.each(["completed_100", "retired", "never_playing"] as const)( + "protects the %s status the user set on purpose", + (status) => { + const ru = makeRomUser({ status }); + applyLaunchStatus(ru); + // now_playing is a separate orthogonal flag, so it still flips on, + // but the deliberate enum status is preserved. + expect(ru.now_playing).toBe(true); + expect(ru.status).toBe(status); + }, + ); +}); From bad4f92702a770a0b7f76dd7547f814ec9395a97 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 21 Jul 2026 08:48:20 -0400 Subject: [PATCH 3/9] fix(v2): record Ruffle launch only after playback starts Move the now-playing / last_played write into the nextTick after the Ruffle player is created and the SWF load is issued, so a failed player creation or load no longer leaves the game marked playing (or rewinds its status). Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/src/v2/views/Player/Ruffle.vue | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/frontend/src/v2/views/Player/Ruffle.vue b/frontend/src/v2/views/Player/Ruffle.vue index ecfcf04a4..f1a1ed0e2 100644 --- a/frontend/src/v2/views/Player/Ruffle.vue +++ b/frontend/src/v2/views/Player/Ruffle.vue @@ -122,17 +122,6 @@ function onPlay() { // and pad-to-UI translation stay muted while the game owns input. playingStore.setPlaying(true); - // Mark the game "now playing" and refresh last_played on launch (protected - // statuses are left untouched by applyLaunchStatus). - if (rom.value?.rom_user && auth.scopes.includes("roms.user.write")) { - applyLaunchStatus(rom.value.rom_user); - romApi.updateUserRomProps({ - romId: rom.value.id, - data: rom.value.rom_user, - updateLastPlayed: true, - }); - } - nextTick(() => { if (!rom.value) return; @@ -156,6 +145,17 @@ function onPlay() { player.style.width = "100%"; player.style.height = "100%"; + // Record the launch only once playback is actually under way, so a + // failed player creation / load doesn't leave the game marked playing. + if (rom.value.rom_user && auth.scopes.includes("roms.user.write")) { + applyLaunchStatus(rom.value.rom_user); + romApi.updateUserRomProps({ + romId: rom.value.id, + data: rom.value.rom_user, + updateLastPlayed: true, + }); + } + if (player.fullscreenEnabled && fullscreenOnPlay.value) { player.enterFullscreen(); } From 44c467524e56a67f024fe7932806e78965152fd7 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 21 Jul 2026 09:00:13 -0400 Subject: [PATCH 4/9] fix(v2): revert local status and handle rejection when a launch write fails The launch write optimistically mutated the shared rom_user but was fire-and-forget, so a network/authorization/server failure produced an unhandled rejection while the client kept status values that were never persisted. Introduce a shared recordLaunch() helper that snapshots the fields, applies the optimistic update, and on failure reverts them and logs instead of leaving the rejection unhandled. Use it in all three v2 players (EmulatorJS, Ruffle, Stream) so the behavior is consistent. Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/src/v2/utils/romStatus.test.ts | 54 +++++++++++++++++++-- frontend/src/v2/utils/romStatus.ts | 23 +++++++++ frontend/src/v2/views/Player/EmulatorJS.vue | 15 ++---- frontend/src/v2/views/Player/Ruffle.vue | 11 ++--- frontend/src/v2/views/Player/Stream.vue | 15 ++---- 5 files changed, 87 insertions(+), 31 deletions(-) diff --git a/frontend/src/v2/utils/romStatus.test.ts b/frontend/src/v2/utils/romStatus.test.ts index 2f673f100..2f96c393f 100644 --- a/frontend/src/v2/utils/romStatus.test.ts +++ b/frontend/src/v2/utils/romStatus.test.ts @@ -1,8 +1,16 @@ -import { describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import type { RomUserSchema } from "@/__generated__"; -import { applyLaunchStatus } from "./romStatus"; +import romApi from "@/services/api/rom"; +import type { SimpleRom } from "@/stores/roms"; +import { applyLaunchStatus, recordLaunch } from "./romStatus"; -// Minimal RomUserSchema factory — only the fields applyLaunchStatus reads +vi.mock("@/services/api/rom", () => ({ + default: { updateUserRomProps: vi.fn() }, +})); + +const updateUserRomProps = vi.mocked(romApi.updateUserRomProps); + +// Minimal RomUserSchema factory — only the fields the launch helpers read // matter, the rest are filled with representative defaults. function makeRomUser(overrides: Partial = {}): RomUserSchema { return { @@ -61,3 +69,43 @@ describe("applyLaunchStatus", () => { }, ); }); + +function makeRom(romUser: RomUserSchema): SimpleRom { + return { id: 1, rom_user: romUser } as unknown as SimpleRom; +} + +describe("recordLaunch", () => { + beforeEach(() => { + updateUserRomProps.mockReset(); + }); + + it("applies the launch status and persists it with last_played", () => { + updateUserRomProps.mockResolvedValue({} as never); + const ru = makeRomUser({ status: null }); + recordLaunch(makeRom(ru)); + + expect(ru.now_playing).toBe(true); + expect(ru.status).toBe("incomplete"); + expect(updateUserRomProps).toHaveBeenCalledWith({ + romId: 1, + data: ru, + updateLastPlayed: true, + }); + }); + + it("reverts the local mutation when the write fails", async () => { + updateUserRomProps.mockRejectedValue(new Error("boom")); + const ru = makeRomUser({ status: "finished", now_playing: false }); + recordLaunch(makeRom(ru)); + + // Optimistic update is visible synchronously... + expect(ru.now_playing).toBe(true); + expect(ru.status).toBe("incomplete"); + + // ...then reverted once the rejected write settles. + await vi.waitFor(() => { + expect(ru.now_playing).toBe(false); + expect(ru.status).toBe("finished"); + }); + }); +}); diff --git a/frontend/src/v2/utils/romStatus.ts b/frontend/src/v2/utils/romStatus.ts index df015a123..9113bcb78 100644 --- a/frontend/src/v2/utils/romStatus.ts +++ b/frontend/src/v2/utils/romStatus.ts @@ -5,6 +5,8 @@ // icons. v2-only: v1 still reads `romStatusMap`'s emoji from // `@/utils`, so that map stays untouched. import type { RomUserSchema, RomUserStatus } from "@/__generated__"; +import romApi from "@/services/api/rom"; +import type { SimpleRom } from "@/stores/roms"; import type { PlayingStatus } from "@/utils"; // Advance a ROM's per-user status for a launch. Mutates in place so the @@ -19,6 +21,27 @@ export function applyLaunchStatus(romUser: RomUserSchema): void { } } +// Persist a launch: optimistically apply the launch status and bump +// last_played, reverting the local mutation if the write fails so client +// state never drifts from the server. Fire-and-forget by design (the caller +// is entering gameplay), but the rejection is handled rather than left to +// surface as an unhandled promise. +export function recordLaunch(rom: SimpleRom): void { + const romUser = rom.rom_user; + const before = { now_playing: romUser.now_playing, status: romUser.status }; + applyLaunchStatus(romUser); + romApi + .updateUserRomProps({ + romId: rom.id, + data: romUser, + updateLastPlayed: true, + }) + .catch((err) => { + Object.assign(romUser, before); + console.error("Failed to record play status:", err); + }); +} + // Icon map covering both the enum statuses and the orthogonal boolean // flags (now_playing / backlogged / hidden) so a single menu can present // them together. diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index 7b538f64b..ed9cf33b6 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -50,7 +50,7 @@ import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; import { useInputModality } from "@/v2/composables/useInputModality"; import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; -import { applyLaunchStatus } from "@/v2/utils/romStatus"; +import { recordLaunch } from "@/v2/utils/romStatus"; import { installIOSFullscreenShim } from "@/views/Player/EmulatorJS/utils"; // Reuse v1's heavy emulator integration — do NOT rewrite this. Lazy so the @@ -226,15 +226,10 @@ async function onPlay() { removeIOSFullscreenShim.value?.(); removeIOSFullscreenShim.value = installIOSFullscreenShim(); - if (rom.value?.rom_user && auth.scopes.includes("roms.user.write")) { - // Launching marks the game "now playing" and rewinds an empty/finished - // status to "incomplete"; protected statuses are left untouched. - applyLaunchStatus(rom.value.rom_user); - romApi.updateUserRomProps({ - romId: rom.value.id, - data: rom.value.rom_user, - updateLastPlayed: true, - }); + if (rom.value && auth.scopes.includes("roms.user.write")) { + // Marks the game "now playing" and bumps last_played on launch; protected + // statuses are left untouched and a failed write reverts locally. + recordLaunch(rom.value); } gameRunning.value = true; diff --git a/frontend/src/v2/views/Player/Ruffle.vue b/frontend/src/v2/views/Player/Ruffle.vue index f1a1ed0e2..5905fe466 100644 --- a/frontend/src/v2/views/Player/Ruffle.vue +++ b/frontend/src/v2/views/Player/Ruffle.vue @@ -26,7 +26,7 @@ import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; import { colorCanvas } from "@/v2/tokens"; -import { applyLaunchStatus } from "@/v2/utils/romStatus"; +import { recordLaunch } from "@/v2/utils/romStatus"; const RUFFLE_VERSION = "0.2.0-nightly.2025.8.14"; const DEFAULT_BACKGROUND_COLOR = colorCanvas.bgDeep; @@ -147,13 +147,8 @@ function onPlay() { // Record the launch only once playback is actually under way, so a // failed player creation / load doesn't leave the game marked playing. - if (rom.value.rom_user && auth.scopes.includes("roms.user.write")) { - applyLaunchStatus(rom.value.rom_user); - romApi.updateUserRomProps({ - romId: rom.value.id, - data: rom.value.rom_user, - updateLastPlayed: true, - }); + if (auth.scopes.includes("roms.user.write")) { + recordLaunch(rom.value); } if (player.fullscreenEnabled && fullscreenOnPlay.value) { diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index 5a3967875..8a7605fde 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -30,7 +30,7 @@ import GameCover from "@/v2/components/shared/GameCover.vue"; import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; -import { applyLaunchStatus } from "@/v2/utils/romStatus"; +import { recordLaunch } from "@/v2/utils/romStatus"; type PlayerState = "idle" | "loading" | "playing" | "error" | "exited"; type ErrorType = @@ -287,15 +287,10 @@ async function handlePlay(): Promise { containerHost.value = session.host; playerState.value = "playing"; - // Mark the game "now playing" and refresh last_played on launch (protected - // statuses are left untouched by applyLaunchStatus). - if (rom.value.rom_user && auth.scopes.includes("roms.user.write")) { - applyLaunchStatus(rom.value.rom_user); - romApi.updateUserRomProps({ - romId: rom.value.id, - data: rom.value.rom_user, - updateLastPlayed: true, - }); + // Mark the game "now playing" and refresh last_played on launch; protected + // statuses are left untouched and a failed write reverts locally. + if (auth.scopes.includes("roms.user.write")) { + recordLaunch(rom.value); } // Wait for the DOM to update and the iframe to exist. From ccb4a3986ac9c8702a3b39f29597d64379c8290a Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 21 Jul 2026 09:04:50 -0400 Subject: [PATCH 5/9] fix(v2): decouple stream launch-status write from the claim transaction Move recordLaunch out of the claimSession try/catch and run it after a successful claim (gated on playerState === "playing"). The launch-status write is incidental metadata, so keeping it inside the launch transaction risked coupling it to the claimed-session lifecycle; running it afterward ensures it can never affect play or leave a claimed session needing cleanup. Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/src/v2/views/Player/Stream.vue | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index 8a7605fde..e19bb24b5 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -287,12 +287,6 @@ async function handlePlay(): Promise { containerHost.value = session.host; playerState.value = "playing"; - // Mark the game "now playing" and refresh last_played on launch; protected - // statuses are left untouched and a failed write reverts locally. - if (auth.scopes.includes("roms.user.write")) { - recordLaunch(rom.value); - } - // Wait for the DOM to update and the iframe to exist. attachTimeouts.forEach((id) => clearTimeout(id)); attachTimeouts = []; @@ -331,6 +325,16 @@ async function handlePlay(): Promise { errorMessage.value = error.message ?? t("play.stream-error-generic"); } } + + // Record the launch outside the claim transaction: this is an incidental + // status write, so it must never abort a successfully claimed session. + if ( + rom.value && + playerState.value === "playing" && + auth.scopes.includes("roms.user.write") + ) { + recordLaunch(rom.value); + } } async function handleStop(): Promise { From 58ec1c4aa809252a74701096a01ce5d540a7a819 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 21 Jul 2026 15:56:28 -0400 Subject: [PATCH 6/9] feat(v2): drive rom_user status from play sessions, not launch write Move the per-play status update (last_played, now_playing, and the finished/empty -> incomplete rewind) off the optimistic launch-time write and onto play-session ingest, so it reflects real play and is recorded once. Backend: ingest now updates rom_user status when a session is the newest play, leaving deliberate statuses (completed_100 / retired / never_playing) untouched and skipping backfilled older sessions so they can't resurrect now_playing. Frontend: new usePlaySession composable records a session and ingests it on exit; wired into Ruffle and Stream. EmulatorJS already ingests via the embedded v1 Player, so its launch-time recordLaunch is dropped. The dead recordLaunch / applyLaunchStatus helpers are removed. Co-Authored-By: Claude Opus 4.8 (1M context) --- backend/handler/play_session_handler.py | 21 +++- backend/tests/endpoints/test_play_sessions.py | 100 +++++++++++++++- .../composables/usePlaySession/index.test.ts | 103 ++++++++++++++++ .../v2/composables/usePlaySession/index.ts | 62 ++++++++++ frontend/src/v2/utils/romStatus.test.ts | 111 ------------------ frontend/src/v2/utils/romStatus.ts | 37 +----- frontend/src/v2/views/Player/EmulatorJS.vue | 10 +- frontend/src/v2/views/Player/Ruffle.vue | 17 +-- frontend/src/v2/views/Player/Stream.vue | 21 ++-- 9 files changed, 302 insertions(+), 180 deletions(-) create mode 100644 frontend/src/v2/composables/usePlaySession/index.test.ts create mode 100644 frontend/src/v2/composables/usePlaySession/index.ts delete mode 100644 frontend/src/v2/utils/romStatus.test.ts diff --git a/backend/handler/play_session_handler.py b/backend/handler/play_session_handler.py index 5ae356e21..1bfd0b891 100644 --- a/backend/handler/play_session_handler.py +++ b/backend/handler/play_session_handler.py @@ -6,6 +6,7 @@ from pydash import compact from handler.database import db_device_handler, db_play_session_handler, db_rom_handler from logger.logger import log from models.play_session import PlaySession +from models.rom import RomUserStatus from utils.datetime import to_utc @@ -37,7 +38,7 @@ def _resolve_device(device_id: str | None, user_id: int) -> str | None: return device_id if device is not None else None -def _update_rom_user_last_played( +def _apply_play_to_rom_user( rom_user_updates: dict[int, datetime], user_id: int ) -> None: for rom_id, latest_end_time in rom_user_updates.items(): @@ -46,10 +47,18 @@ def _update_rom_user_last_played( rom_user = db_rom_handler.add_rom_user(rom_id=rom_id, user_id=user_id) current = to_utc(rom_user.last_played) if rom_user.last_played else None - if current is None or latest_end_time > current: - db_rom_handler.update_rom_user( - rom_user.id, {"last_played": latest_end_time} - ) + # Only the newest play advances state. A backfilled or device-synced + # older session must not resurrect "now playing" or rewind the status. + if current is not None and latest_end_time <= current: + continue + + updates: dict = {"last_played": latest_end_time, "now_playing": True} + # Playing again counts as active: rewind an empty or "finished" status + # to "incomplete", but leave statuses the user set on purpose + # (completed_100 / retired / never_playing) untouched. + if rom_user.status in (None, RomUserStatus.FINISHED): + updates["status"] = RomUserStatus.INCOMPLETE + db_rom_handler.update_rom_user(rom_user.id, updates) def ingest_play_sessions( @@ -138,7 +147,7 @@ def ingest_play_sessions( rom_user_updates[resolved_rom_id] = ps.end_time # Phase 4: Side effects - _update_rom_user_last_played(rom_user_updates, user_id) + _apply_play_to_rom_user(rom_user_updates, user_id) if resolved_device_id is not None: db_device_handler.update_last_seen( diff --git a/backend/tests/endpoints/test_play_sessions.py b/backend/tests/endpoints/test_play_sessions.py index cdc39b345..0a1ca83af 100644 --- a/backend/tests/endpoints/test_play_sessions.py +++ b/backend/tests/endpoints/test_play_sessions.py @@ -11,7 +11,7 @@ from handler.auth import oauth_handler from handler.database import db_device_handler, db_play_session_handler, db_rom_handler from models.device import Device from models.platform import Platform -from models.rom import Rom +from models.rom import Rom, RomUserStatus from models.user import User from utils.datetime import to_utc @@ -68,6 +68,14 @@ def _ingest(device_id=None, sessions=None): return {"device_id": device_id, "sessions": sessions or []} +def _prime_rom_user(rom_id, user_id, **fields): + """Fetch (or create) the rom_user and seed it with the given fields.""" + rom_user = db_rom_handler.get_rom_user(rom_id=rom_id, user_id=user_id) + if rom_user is None: + rom_user = db_rom_handler.add_rom_user(rom_id=rom_id, user_id=user_id) + return db_rom_handler.update_rom_user(rom_user.id, fields) + + class TestPlaySessionIngest: def test_single_session(self, client, access_token: str, device: Device, rom: Rom): payload = _ingest(device_id=device.id, sessions=[_session(rom_id=rom.id)]) @@ -472,6 +480,96 @@ class TestPlaySessionRomUserUpdates: last_played_utc = to_utc(rom_user.last_played) assert abs((last_played_utc - expected_latest).total_seconds()) < 2 + def test_now_playing_set_on_ingest( + self, client, access_token: str, admin_user: User, rom: Rom + ): + payload = _ingest(sessions=[_session(rom_id=rom.id)]) + client.post( + "/api/play-sessions", + json=payload, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user is not None + assert rom_user.now_playing is True + + def test_empty_status_rewound_to_incomplete( + self, client, access_token: str, admin_user: User, rom: Rom + ): + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user.status == RomUserStatus.INCOMPLETE + + def test_finished_status_rewound_to_incomplete( + self, client, access_token: str, admin_user: User, rom: Rom + ): + _prime_rom_user(rom.id, admin_user.id, status=RomUserStatus.FINISHED) + + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user.status == RomUserStatus.INCOMPLETE + + @pytest.mark.parametrize( + "protected_status", + [ + RomUserStatus.COMPLETED_100, + RomUserStatus.RETIRED, + RomUserStatus.NEVER_PLAYING, + ], + ) + def test_deliberate_status_preserved( + self, client, access_token, admin_user, rom, protected_status + ): + _prime_rom_user(rom.id, admin_user.id, status=protected_status) + + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + # now_playing is orthogonal, so it still flips on... + assert rom_user.now_playing is True + # ...but the deliberate enum status is left untouched. + assert rom_user.status == protected_status + + def test_older_session_does_not_resurrect_now_playing( + self, client, access_token: str, admin_user: User, rom: Rom + ): + # A recent play sets last_played and now_playing. + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id, start_offset_hours=-1)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + db_rom_handler.update_rom_user( + rom_user.id, {"now_playing": False, "status": RomUserStatus.FINISHED} + ) + + # Backfilling an older session must not advance state. + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id, start_offset_hours=-10)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user.now_playing is False + assert rom_user.status == RomUserStatus.FINISHED + def test_rom_user_created_if_not_exists( self, client, access_token: str, admin_user: User, platform: Platform ): diff --git a/frontend/src/v2/composables/usePlaySession/index.test.ts b/frontend/src/v2/composables/usePlaySession/index.test.ts new file mode 100644 index 000000000..8dcbd73c6 --- /dev/null +++ b/frontend/src/v2/composables/usePlaySession/index.test.ts @@ -0,0 +1,103 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import playSessionApi from "@/services/api/play-session"; +import type { SimpleRom } from "@/stores/roms"; +import { usePlaySession } from "./index"; + +vi.mock("@/services/api/play-session", () => ({ + default: { ingestPlaySessions: vi.fn() }, +})); + +// Controllable auth stand-in: tests tweak scopes / user between cases. +const authState = { + scopes: ["roms.user.write"] as string[], + user: { current_device_id: "device-1" } as { + current_device_id: string; + } | null, +}; +vi.mock("@/stores/auth", () => ({ + default: () => authState, +})); + +const ingest = vi.mocked(playSessionApi.ingestPlaySessions); + +function makeRom(id = 7): SimpleRom { + return { id } as unknown as SimpleRom; +} + +beforeEach(() => { + ingest.mockReset(); + ingest.mockResolvedValue({} as never); + authState.scopes = ["roms.user.write"]; + authState.user = { current_device_id: "device-1" }; + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-07-21T10:00:00.000Z")); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("usePlaySession", () => { + it("ingests a session with real start/end/duration on flush", () => { + const { start, flush } = usePlaySession(); + start(makeRom(42)); + vi.advanceTimersByTime(90_000); + flush(); + + expect(ingest).toHaveBeenCalledTimes(1); + expect(ingest).toHaveBeenCalledWith({ + deviceId: "device-1", + sessions: [ + { + rom_id: 42, + start_time: "2026-07-21T10:00:00.000Z", + end_time: "2026-07-21T10:01:30.000Z", + duration_ms: 90_000, + }, + ], + }); + }); + + it("does nothing without a write scope", () => { + authState.scopes = ["roms.user.read"]; + const { start, flush } = usePlaySession(); + start(makeRom()); + vi.advanceTimersByTime(90_000); + flush(); + expect(ingest).not.toHaveBeenCalled(); + }); + + it("drops sub-second sessions", () => { + const { start, flush } = usePlaySession(); + start(makeRom()); + vi.advanceTimersByTime(500); + flush(); + expect(ingest).not.toHaveBeenCalled(); + }); + + it("is idempotent — a second flush does not resubmit", () => { + const { start, flush } = usePlaySession(); + start(makeRom()); + vi.advanceTimersByTime(90_000); + flush(); + flush(); + expect(ingest).toHaveBeenCalledTimes(1); + }); + + it("flush without a prior start is a no-op", () => { + const { flush } = usePlaySession(); + flush(); + expect(ingest).not.toHaveBeenCalled(); + }); + + it("sends a null device id when the user has none", () => { + authState.user = null; + const { start, flush } = usePlaySession(); + start(makeRom()); + vi.advanceTimersByTime(90_000); + flush(); + expect(ingest).toHaveBeenCalledWith( + expect.objectContaining({ deviceId: null }), + ); + }); +}); diff --git a/frontend/src/v2/composables/usePlaySession/index.ts b/frontend/src/v2/composables/usePlaySession/index.ts new file mode 100644 index 000000000..5a28fe16d --- /dev/null +++ b/frontend/src/v2/composables/usePlaySession/index.ts @@ -0,0 +1,62 @@ +// usePlaySession — records a single play session's wall-clock and ingests it +// on flush. The session is what drives the server-side rom_user update +// (last_played + now_playing + status), replacing the old optimistic +// launch-time write. +// +// Fire-and-forget: entering or leaving gameplay must never block on the +// network. flush() is idempotent, so the several exit paths a player has +// (stop button, save-and-exit, back navigation, unmount) can each call it +// without risking a double submission. +import playSessionApi from "@/services/api/play-session"; +import storeAuth from "@/stores/auth"; +import type { SimpleRom } from "@/stores/roms"; + +// Sessions shorter than a second carry no meaningful playtime and would be +// rejected anyway: the backend floors timestamps to whole seconds and +// requires end_time > start_time. A tap-Play-then-quit is dropped. +const MIN_SESSION_MS = 1000; + +export function usePlaySession(): { + start: (rom: SimpleRom) => void; + flush: () => void; +} { + const auth = storeAuth(); + let startTime: Date | null = null; + let romId: number | null = null; + + function start(rom: SimpleRom): void { + // Recording is gated on the same scope the ingest endpoint requires. + if (!auth.scopes.includes("roms.user.write")) return; + startTime = new Date(); + romId = rom.id; + } + + function flush(): void { + if (startTime === null || romId === null) return; + const sessionStart = startTime; + const sessionRomId = romId; + // Clear before the async call so a second flush is a no-op. + startTime = null; + romId = null; + + const endTime = new Date(); + const durationMs = endTime.getTime() - sessionStart.getTime(); + if (durationMs < MIN_SESSION_MS) return; + + playSessionApi + .ingestPlaySessions({ + deviceId: auth.user?.current_device_id ?? null, + sessions: [ + { + rom_id: sessionRomId, + start_time: sessionStart.toISOString(), + end_time: endTime.toISOString(), + duration_ms: durationMs, + }, + ], + }) + .catch((err) => console.error("Failed to submit play session:", err)); + } + + return { start, flush }; +} diff --git a/frontend/src/v2/utils/romStatus.test.ts b/frontend/src/v2/utils/romStatus.test.ts deleted file mode 100644 index 2f96c393f..000000000 --- a/frontend/src/v2/utils/romStatus.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { RomUserSchema } from "@/__generated__"; -import romApi from "@/services/api/rom"; -import type { SimpleRom } from "@/stores/roms"; -import { applyLaunchStatus, recordLaunch } from "./romStatus"; - -vi.mock("@/services/api/rom", () => ({ - default: { updateUserRomProps: vi.fn() }, -})); - -const updateUserRomProps = vi.mocked(romApi.updateUserRomProps); - -// Minimal RomUserSchema factory — only the fields the launch helpers read -// matter, the rest are filled with representative defaults. -function makeRomUser(overrides: Partial = {}): RomUserSchema { - return { - id: 1, - user_id: 1, - rom_id: 1, - created_at: "", - updated_at: "", - last_played: null, - is_main_sibling: false, - backlogged: false, - now_playing: false, - hidden: false, - rating: 0, - difficulty: 0, - completion: 0, - status: null, - ...overrides, - }; -} - -describe("applyLaunchStatus", () => { - it("marks the game now playing", () => { - const ru = makeRomUser({ now_playing: false }); - applyLaunchStatus(ru); - expect(ru.now_playing).toBe(true); - }); - - it("fills an empty status with incomplete", () => { - const ru = makeRomUser({ status: null }); - applyLaunchStatus(ru); - expect(ru.status).toBe("incomplete"); - }); - - it("rewinds a finished game to incomplete", () => { - const ru = makeRomUser({ status: "finished" }); - applyLaunchStatus(ru); - expect(ru.status).toBe("incomplete"); - }); - - it("leaves an in-progress status untouched", () => { - const ru = makeRomUser({ status: "incomplete" }); - applyLaunchStatus(ru); - expect(ru.status).toBe("incomplete"); - }); - - it.each(["completed_100", "retired", "never_playing"] as const)( - "protects the %s status the user set on purpose", - (status) => { - const ru = makeRomUser({ status }); - applyLaunchStatus(ru); - // now_playing is a separate orthogonal flag, so it still flips on, - // but the deliberate enum status is preserved. - expect(ru.now_playing).toBe(true); - expect(ru.status).toBe(status); - }, - ); -}); - -function makeRom(romUser: RomUserSchema): SimpleRom { - return { id: 1, rom_user: romUser } as unknown as SimpleRom; -} - -describe("recordLaunch", () => { - beforeEach(() => { - updateUserRomProps.mockReset(); - }); - - it("applies the launch status and persists it with last_played", () => { - updateUserRomProps.mockResolvedValue({} as never); - const ru = makeRomUser({ status: null }); - recordLaunch(makeRom(ru)); - - expect(ru.now_playing).toBe(true); - expect(ru.status).toBe("incomplete"); - expect(updateUserRomProps).toHaveBeenCalledWith({ - romId: 1, - data: ru, - updateLastPlayed: true, - }); - }); - - it("reverts the local mutation when the write fails", async () => { - updateUserRomProps.mockRejectedValue(new Error("boom")); - const ru = makeRomUser({ status: "finished", now_playing: false }); - recordLaunch(makeRom(ru)); - - // Optimistic update is visible synchronously... - expect(ru.now_playing).toBe(true); - expect(ru.status).toBe("incomplete"); - - // ...then reverted once the rejected write settles. - await vi.waitFor(() => { - expect(ru.now_playing).toBe(false); - expect(ru.status).toBe("finished"); - }); - }); -}); diff --git a/frontend/src/v2/utils/romStatus.ts b/frontend/src/v2/utils/romStatus.ts index 9113bcb78..c8dff8cad 100644 --- a/frontend/src/v2/utils/romStatus.ts +++ b/frontend/src/v2/utils/romStatus.ts @@ -4,44 +4,9 @@ // surfaces present the same options, in the same order, with the same // icons. v2-only: v1 still reads `romStatusMap`'s emoji from // `@/utils`, so that map stays untouched. -import type { RomUserSchema, RomUserStatus } from "@/__generated__"; -import romApi from "@/services/api/rom"; -import type { SimpleRom } from "@/stores/roms"; +import type { RomUserStatus } from "@/__generated__"; import type { PlayingStatus } from "@/utils"; -// Advance a ROM's per-user status for a launch. Mutates in place so the -// caller can persist the same object it already sends to the props endpoint. -// The game becomes "now playing"; an empty or "finished" status rewinds to -// "incomplete" (they're playing again). Statuses the user set on purpose -// (completed 100% / retired / never playing) are left untouched. -export function applyLaunchStatus(romUser: RomUserSchema): void { - romUser.now_playing = true; - if (romUser.status === null || romUser.status === "finished") { - romUser.status = "incomplete"; - } -} - -// Persist a launch: optimistically apply the launch status and bump -// last_played, reverting the local mutation if the write fails so client -// state never drifts from the server. Fire-and-forget by design (the caller -// is entering gameplay), but the rejection is handled rather than left to -// surface as an unhandled promise. -export function recordLaunch(rom: SimpleRom): void { - const romUser = rom.rom_user; - const before = { now_playing: romUser.now_playing, status: romUser.status }; - applyLaunchStatus(romUser); - romApi - .updateUserRomProps({ - romId: rom.id, - data: romUser, - updateLastPlayed: true, - }) - .catch((err) => { - Object.assign(romUser, before); - console.error("Failed to record play status:", err); - }); -} - // Icon map covering both the enum statuses and the orthogonal boolean // flags (now_playing / backlogged / hidden) so a single menu can present // them together. diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index ed9cf33b6..8f5a6153f 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -50,7 +50,6 @@ import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; import { useInputModality } from "@/v2/composables/useInputModality"; import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; -import { recordLaunch } from "@/v2/utils/romStatus"; import { installIOSFullscreenShim } from "@/views/Player/EmulatorJS/utils"; // Reuse v1's heavy emulator integration — do NOT rewrite this. Lazy so the @@ -226,12 +225,9 @@ async function onPlay() { removeIOSFullscreenShim.value?.(); removeIOSFullscreenShim.value = installIOSFullscreenShim(); - if (rom.value && auth.scopes.includes("roms.user.write")) { - // Marks the game "now playing" and bumps last_played on launch; protected - // statuses are left untouched and a failed write reverts locally. - recordLaunch(rom.value); - } - + // last_played / now_playing / status are updated server-side when the + // embedded ingests the play session on exit, so no launch-time + // write is made here. gameRunning.value = true; window.EJS_fullscreenOnLoaded = fullscreenOnPlay.value; fullScreen.value = fullscreenOnPlay.value; diff --git a/frontend/src/v2/views/Player/Ruffle.vue b/frontend/src/v2/views/Player/Ruffle.vue index 5905fe466..dbc56e085 100644 --- a/frontend/src/v2/views/Player/Ruffle.vue +++ b/frontend/src/v2/views/Player/Ruffle.vue @@ -16,7 +16,6 @@ import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; import { ROUTES } from "@/plugins/router"; import romApi from "@/services/api/rom"; -import storeAuth from "@/stores/auth"; import storePlaying from "@/stores/playing"; import storeRoms, { type DetailedRom, type SimpleRom } from "@/stores/roms"; import type { RuffleSourceAPI } from "@/types/ruffle"; @@ -24,9 +23,9 @@ import { getDownloadPath } from "@/utils"; import GameCover from "@/v2/components/shared/GameCover.vue"; import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; +import { usePlaySession } from "@/v2/composables/usePlaySession"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; import { colorCanvas } from "@/v2/tokens"; -import { recordLaunch } from "@/v2/utils/romStatus"; const RUFFLE_VERSION = "0.2.0-nightly.2025.8.14"; const DEFAULT_BACKGROUND_COLOR = colorCanvas.bgDeep; @@ -36,7 +35,7 @@ const route = useRoute(); const router = useRouter(); const { fullscreenOnPlay } = useFullscreenPref(); const playingStore = storePlaying(); -const auth = storeAuth(); +const playSession = usePlaySession(); const rom = ref(null); const gameRunning = ref(false); @@ -145,11 +144,10 @@ function onPlay() { player.style.width = "100%"; player.style.height = "100%"; - // Record the launch only once playback is actually under way, so a - // failed player creation / load doesn't leave the game marked playing. - if (auth.scopes.includes("roms.user.write")) { - recordLaunch(rom.value); - } + // Start timing the session only once playback is actually under way, so a + // failed player creation / load records nothing. The session is ingested + // on unmount, which is what updates last_played / now_playing / status. + playSession.start(rom.value); if (player.fullscreenEnabled && fullscreenOnPlay.value) { player.enterFullscreen(); @@ -205,6 +203,9 @@ onMounted(async () => { }); onBeforeUnmount(() => { + // Every exit path (Quit, back links, route change) unmounts the view, so + // this is the single choke point for recording the session. + playSession.flush(); // Hand the keyboard and gamepad back to the UI on any exit path. playingStore.setPlaying(false); }); diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index e19bb24b5..7c57bca2b 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -22,15 +22,14 @@ import { useRoute, useRouter } from "vue-router"; import { ROUTES } from "@/plugins/router"; import romApi from "@/services/api/rom"; import streamingApi from "@/services/api/streaming"; -import storeAuth from "@/stores/auth"; import storePlaying from "@/stores/playing"; import storeRoms, { type DetailedRom, type SimpleRom } from "@/stores/roms"; import { useStreamingStore } from "@/stores/streaming"; import GameCover from "@/v2/components/shared/GameCover.vue"; import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; +import { usePlaySession } from "@/v2/composables/usePlaySession"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; -import { recordLaunch } from "@/v2/utils/romStatus"; type PlayerState = "idle" | "loading" | "playing" | "error" | "exited"; type ErrorType = @@ -46,7 +45,7 @@ const setBgArt = useBackgroundArt(); const romsStore = storeRoms(); const galleryRoms = storeGalleryRoms(); const playingStore = storePlaying(); -const auth = storeAuth(); +const playSession = usePlaySession(); const rom = ref(null); const playerState = ref("idle"); @@ -188,6 +187,9 @@ onBeforeUnmount(() => { iframeLoadCleanup = null; contentWindowCleanup?.(); contentWindowCleanup = null; + // Every exit path (Stop, Save & Exit, back nav) unmounts the view, so this + // is the single choke point for recording the session. + playSession.flush(); // Hand controller input back to the UI regardless of how we leave. playingStore.setPlaying(false); if (playerState.value === "exited") { @@ -326,14 +328,11 @@ async function handlePlay(): Promise { } } - // Record the launch outside the claim transaction: this is an incidental - // status write, so it must never abort a successfully claimed session. - if ( - rom.value && - playerState.value === "playing" && - auth.scopes.includes("roms.user.write") - ) { - recordLaunch(rom.value); + // Start timing the session once the claim succeeds and playback is live. + // The session is ingested on unmount, which updates last_played / + // now_playing / status server-side. + if (rom.value && playerState.value === "playing") { + playSession.start(rom.value); } } From b720781f87ee677142c7a19d6c063b7f7a0ea0bf Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 21 Jul 2026 16:15:02 -0400 Subject: [PATCH 7/9] more cleanup --- frontend/src/composables/useUISettings.ts | 6 +----- frontend/src/v2/views/Player/EmulatorJS.vue | 3 --- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/frontend/src/composables/useUISettings.ts b/frontend/src/composables/useUISettings.ts index 15e23b107..a0b55811d 100644 --- a/frontend/src/composables/useUISettings.ts +++ b/frontend/src/composables/useUISettings.ts @@ -15,8 +15,7 @@ export const UI_SETTINGS_KEYS = { // NOTE: uiVersion is intentionally NOT tracked here. It's owned by the // singleton in composables/useUiVersion.ts so a write propagates reactively - // to the RomM.vue gate without a reload. When v2 graduates we can move it - // into this map and pick up backend sync. + // to the RomM.vue gate without a reload. // Home section showStats: { key: "settings.showStats", default: true }, @@ -82,9 +81,6 @@ export const UI_SETTINGS_KEYS = { boxartStyle: { key: "settings.boxartStyle", default: "cover_path" }, // Gameplay - // Ask for confirmation before launching a game the user deliberately - // shelved (Retired / Never Playing) so an accidental Play doesn't - // silently reactivate it. confirmProtectedLaunch: { key: "settings.confirmProtectedLaunch", default: true, diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index 8f5a6153f..6b3cf160e 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -225,9 +225,6 @@ async function onPlay() { removeIOSFullscreenShim.value?.(); removeIOSFullscreenShim.value = installIOSFullscreenShim(); - // last_played / now_playing / status are updated server-side when the - // embedded ingests the play session on exit, so no launch-time - // write is made here. gameRunning.value = true; window.EJS_fullscreenOnLoaded = fullscreenOnPlay.value; fullScreen.value = fullscreenOnPlay.value; From 2cc8c02101e9ea2cc7193065acf08e09062003d8 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 21 Jul 2026 16:32:39 -0400 Subject: [PATCH 8/9] feat(v2): record EmulatorJS play sessions in the v2 shell, not v1 Player Wire usePlaySession into the v2 EmulatorJS view so a session is recorded on any exit path (in-emulator Exit/Save & Quit, back nav, or route change), starting when the game goes live and flushing on unmount. flush() is idempotent so overlapping exit paths can't double-submit. Remove the play-session ingest from the shared v1 Player component so there is a single source of truth and no double-recording. immediateExit now only navigates back to the game details view. Note: Player.vue is also mounted by the v1 EmulatorJS view, which no longer records sessions as a result; acceptable while v1 is frozen and slated for removal. Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/src/v2/views/Player/EmulatorJS.vue | 8 +++- .../src/views/Player/EmulatorJS/Player.vue | 41 +++---------------- 2 files changed, 13 insertions(+), 36 deletions(-) diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index 6b3cf160e..e2b2c9395 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -48,6 +48,7 @@ import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; import { useCoverArt } from "@/v2/composables/useCoverArt"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; import { useInputModality } from "@/v2/composables/useInputModality"; +import { usePlaySession } from "@/v2/composables/usePlaySession"; import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; import { installIOSFullscreenShim } from "@/views/Player/EmulatorJS/utils"; @@ -68,6 +69,7 @@ const configStore = storeConfig(); const { playing, fullScreen } = storeToRefs(playingStore); const { fullscreenOnPlay } = useFullscreenPref(); const { modality } = useInputModality(); +const playSession = usePlaySession(); // Ref the Play CTA so we can imperatively focus it on enter (and again // when the user comes back from a running session). RBtn forwards to @@ -437,10 +439,12 @@ onMounted(async () => { // to Play on exit so a Start-Play loop stays on the pad. watch(gameRunning, (running, prev) => { if (running && !prev) { + if (rom.value) playSession.start(rom.value); emitActivityStart(); startActivityHeartbeat(); } if (prev && !running) { + playSession.flush(); stopActivityHeartbeat(); emitActivityStop(); nextTick(focusPlayButton); @@ -457,7 +461,9 @@ function onGamepadButton(e: CustomEvent<{ name?: string }>) { onBeforeUnmount(() => { // Leaving the player (back nav / route change) ends the session even if - // the user never exited the game to the config screen first. + // the user never exited the game to the config screen first. flush() is + // idempotent, so an exit that already flushed via the watch is a no-op. + playSession.flush(); stopActivityHeartbeat(); emitActivityStop(); // Hand the keyboard and gamepad back to the UI; the flag otherwise diff --git a/frontend/src/views/Player/EmulatorJS/Player.vue b/frontend/src/views/Player/EmulatorJS/Player.vue index a4f9eb6d4..0ac44ff47 100644 --- a/frontend/src/views/Player/EmulatorJS/Player.vue +++ b/frontend/src/views/Player/EmulatorJS/Player.vue @@ -11,7 +11,6 @@ import type { NetplayICEServer, } from "@/__generated__"; import { ROUTES } from "@/plugins/router"; -import playSessionApi from "@/services/api/play-session"; import { saveApi as api } from "@/services/api/save"; import storeAuth from "@/stores/auth"; import storeConfig from "@/stores/config"; @@ -55,7 +54,6 @@ const props = defineProps<{ }>(); const romRef = ref(props.rom); const saveRef = ref(props.save); -const sessionStartTime = ref(null); const deviceIDRef = ref(authStore.user?.current_device_id ?? undefined); const theme = useTheme(); const emitter = inject>("emitter"); @@ -385,8 +383,6 @@ window.EJS_onSaveState = async function ({ }; window.EJS_onGameStart = async () => { - sessionStartTime.value = new Date(); - // Install netplay overrides synchronously, before any await below, so they // are in place before room polling or a Create/Join action can start. const netplay = window.EJS_emulator?.netplay; @@ -501,37 +497,12 @@ window.EJS_onGameStart = async () => { }; function immediateExit() { - if (!sessionStartTime.value) { - return router - .push({ name: ROUTES.ROM, params: { rom: romRef.value.id } }) - .catch((error) => { - console.error("Error navigating to console rom", error); - }); - } - - const endTime = new Date(); - const durationMs = endTime.getTime() - sessionStartTime.value.getTime(); - - playSessionApi - .ingestPlaySessions({ - deviceId: deviceIDRef.value, - sessions: [ - { - rom_id: romRef.value.id, - start_time: sessionStartTime.value.toISOString(), - end_time: endTime.toISOString(), - duration_ms: durationMs, - }, - ], - }) - .catch((err) => console.error("Failed to submit play session:", err)) - .finally(() => { - sessionStartTime.value = null; - router - .push({ name: ROUTES.ROM, params: { rom: romRef.value.id } }) - .catch((error) => { - console.error("Error navigating to console rom", error); - }); + // Play-session recording is owned by the v2 player shell (usePlaySession); + // this only returns to the game details view. + router + .push({ name: ROUTES.ROM, params: { rom: romRef.value.id } }) + .catch((error) => { + console.error("Error navigating to console rom", error); }); } From e87571d7f56b7b67632a719acd9073a4552e7676 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 21 Jul 2026 16:51:57 -0400 Subject: [PATCH 9/9] fix(v2): send exit-time play session with keepalive so it survives reload Leaving EmulatorJS triggers a full page reload (to reset COOP/COEP) that aborts the in-flight play-session POST. Add an ingestPlaySessionsKeepalive variant using fetch with keepalive (plus the session cookie and CSRF header), and have usePlaySession.flush() use it so the session is recorded even as the document unloads. Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/src/services/api/play-session.ts | 36 +++++++++++++++---- .../composables/usePlaySession/index.test.ts | 5 ++- .../v2/composables/usePlaySession/index.ts | 24 ++++++------- 3 files changed, 42 insertions(+), 23 deletions(-) diff --git a/frontend/src/services/api/play-session.ts b/frontend/src/services/api/play-session.ts index 60374f821..3b86b78e0 100644 --- a/frontend/src/services/api/play-session.ts +++ b/frontend/src/services/api/play-session.ts @@ -1,16 +1,19 @@ +import Cookies from "js-cookie"; import api from "@/services/api"; +interface PlaySessionEntry { + rom_id: number; + start_time: string; + end_time: string; + duration_ms: number; +} + async function ingestPlaySessions({ deviceId = null, sessions, }: { deviceId?: string | null; - sessions: { - rom_id: number; - start_time: string; - end_time: string; - duration_ms: number; - }[]; + sessions: PlaySessionEntry[]; }) { return api.post("/play-sessions", { device_id: deviceId, @@ -18,4 +21,23 @@ async function ingestPlaySessions({ }); } -export default { ingestPlaySessions }; +function ingestPlaySessionsKeepalive({ + deviceId = null, + sessions, +}: { + deviceId?: string | null; + sessions: PlaySessionEntry[]; +}): void { + void fetch("/api/play-sessions", { + method: "POST", + keepalive: true, + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + "x-csrftoken": Cookies.get("romm_csrftoken") ?? "", + }, + body: JSON.stringify({ device_id: deviceId, sessions }), + }).catch((err) => console.error("Failed to submit play session:", err)); +} + +export default { ingestPlaySessions, ingestPlaySessionsKeepalive }; diff --git a/frontend/src/v2/composables/usePlaySession/index.test.ts b/frontend/src/v2/composables/usePlaySession/index.test.ts index 8dcbd73c6..44448f3e9 100644 --- a/frontend/src/v2/composables/usePlaySession/index.test.ts +++ b/frontend/src/v2/composables/usePlaySession/index.test.ts @@ -4,7 +4,7 @@ import type { SimpleRom } from "@/stores/roms"; import { usePlaySession } from "./index"; vi.mock("@/services/api/play-session", () => ({ - default: { ingestPlaySessions: vi.fn() }, + default: { ingestPlaySessionsKeepalive: vi.fn() }, })); // Controllable auth stand-in: tests tweak scopes / user between cases. @@ -18,7 +18,7 @@ vi.mock("@/stores/auth", () => ({ default: () => authState, })); -const ingest = vi.mocked(playSessionApi.ingestPlaySessions); +const ingest = vi.mocked(playSessionApi.ingestPlaySessionsKeepalive); function makeRom(id = 7): SimpleRom { return { id } as unknown as SimpleRom; @@ -26,7 +26,6 @@ function makeRom(id = 7): SimpleRom { beforeEach(() => { ingest.mockReset(); - ingest.mockResolvedValue({} as never); authState.scopes = ["roms.user.write"]; authState.user = { current_device_id: "device-1" }; vi.useFakeTimers(); diff --git a/frontend/src/v2/composables/usePlaySession/index.ts b/frontend/src/v2/composables/usePlaySession/index.ts index 5a28fe16d..eafa6d07b 100644 --- a/frontend/src/v2/composables/usePlaySession/index.ts +++ b/frontend/src/v2/composables/usePlaySession/index.ts @@ -43,19 +43,17 @@ export function usePlaySession(): { const durationMs = endTime.getTime() - sessionStart.getTime(); if (durationMs < MIN_SESSION_MS) return; - playSessionApi - .ingestPlaySessions({ - deviceId: auth.user?.current_device_id ?? null, - sessions: [ - { - rom_id: sessionRomId, - start_time: sessionStart.toISOString(), - end_time: endTime.toISOString(), - duration_ms: durationMs, - }, - ], - }) - .catch((err) => console.error("Failed to submit play session:", err)); + playSessionApi.ingestPlaySessionsKeepalive({ + deviceId: auth.user?.current_device_id ?? null, + sessions: [ + { + rom_id: sessionRomId, + start_time: sessionStart.toISOString(), + end_time: endTime.toISOString(), + duration_ms: durationMs, + }, + ], + }); } return { start, flush };